html.form.class.php 433 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456
  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), 'dayhour' or 'datehourpicker' '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 reposition" 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 'datehourpicker', '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 on action href URL parameter
  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 'tzuserrel' or 'tzserver' (when $typeofdata is a date)
  190. * @param array $moreoptions Array with more options. For example array('addnowlink'=>1)
  191. * @return string HTML edit field
  192. */
  193. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id', $gm = 'auto', $moreoptions = array())
  194. {
  195. global $conf, $langs;
  196. $ret = '';
  197. // Check parameters
  198. if (empty($typeofdata)) {
  199. return 'ErrorBadParameter typeofdata is empty';
  200. }
  201. // Clean paramater $typeofdata
  202. if ($typeofdata == 'datetime') {
  203. $typeofdata = 'dayhour';
  204. }
  205. $reg = array();
  206. if (preg_match('/^(\w+)\((\d+)\)$/', $typeofdata, $reg)) {
  207. if ($reg[1] == 'varchar') {
  208. $typeofdata = 'string';
  209. } elseif ($reg[1] == 'int') {
  210. $typeofdata = 'numeric';
  211. } else {
  212. return 'ErrorBadParameter '.$typeofdata;
  213. }
  214. }
  215. // When option to edit inline is activated
  216. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  217. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  218. } else {
  219. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  220. if ($editmode) {
  221. $ret .= "\n";
  222. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  223. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  224. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  225. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  226. if (empty($notabletag)) {
  227. $ret .= '<table class="nobordernopadding centpercent">';
  228. }
  229. if (empty($notabletag)) {
  230. $ret .= '<tr><td>';
  231. }
  232. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  233. $tmp = explode(':', $typeofdata);
  234. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
  235. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  236. $tmp = explode(':', $typeofdata);
  237. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  238. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.$valuetoshow.'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
  239. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  240. $tmp = explode(':', $typeofdata);
  241. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  242. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
  243. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  244. $tmp = explode(':', $typeofdata);
  245. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
  246. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  247. $tmp = explode(':', $typeofdata);
  248. $cols = (empty($tmp[2]) ? '' : $tmp[2]);
  249. $morealt = '';
  250. if (preg_match('/%/', $cols)) {
  251. $morealt = ' style="width: '.$cols.'"';
  252. $cols = '';
  253. }
  254. $valuetoshow = ($editvalue ? $editvalue : $value);
  255. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.(empty($tmp[1]) ? '20' : $tmp[1]).'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  256. // textarea convert automatically entities chars into simple chars.
  257. // 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.
  258. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  259. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  260. $ret .= '</textarea>';
  261. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  262. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  263. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, $addnowlink, 0, '', '', '', '', 1, '', '', $gm);
  264. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  265. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  266. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, $addnowlink, 0, '', '', '', '', 1, '', '', $gm);
  267. } elseif (preg_match('/^select;/', $typeofdata)) {
  268. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  269. $arraylist = array();
  270. foreach ($arraydata as $val) {
  271. $tmp = explode(':', $val);
  272. $tmpkey = str_replace('|', ':', $tmp[0]);
  273. $arraylist[$tmpkey] = $tmp[1];
  274. }
  275. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  276. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  277. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  278. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  279. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), (empty($tmp[2]) ? '' : $tmp[2]), (empty($tmp[3]) ? '100' : $tmp[3]), (empty($tmp[1]) ? 'dolibarr_notes' : $tmp[1]), 'In', (empty($tmp[5]) ? 0 : $tmp[5]), (isset($tmp[8]) ? ($tmp[8] ? true : false) : true), true, (empty($tmp[6]) ? '20' : $tmp[6]), (empty($tmp[7]) ? '100' : $tmp[7]));
  280. $ret .= $doleditor->Create(1);
  281. }
  282. if (empty($notabletag)) {
  283. $ret .= '</td>';
  284. }
  285. // Button save-cancel
  286. if (empty($notabletag)) {
  287. $ret .= '<td class="left">';
  288. }
  289. //else $ret.='<div class="clearboth"></div>';
  290. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  291. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  292. $ret .= '<br>'."\n";
  293. }
  294. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  295. if (empty($notabletag)) {
  296. $ret .= '</td>';
  297. }
  298. if (empty($notabletag)) {
  299. $ret .= '</tr></table>'."\n";
  300. }
  301. $ret .= '</form>'."\n";
  302. } else {
  303. if (preg_match('/^(email)/', $typeofdata)) {
  304. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  305. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  306. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  307. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  308. $tmp = explode(':', $typeofdata);
  309. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  310. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  311. $ret .= dol_htmlentitiesbr($value);
  312. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  313. $ret .= dol_string_onlythesehtmltags($value);
  314. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  315. $ret .= dol_string_onlythesehtmltags($value);
  316. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  317. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day', $gm).'</span>';
  318. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  319. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour', $gm).'</span>';
  320. } elseif (preg_match('/^select;/', $typeofdata)) {
  321. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  322. $arraylist = array();
  323. foreach ($arraydata as $val) {
  324. $tmp = explode(':', $val);
  325. $arraylist[$tmp[0]] = $tmp[1];
  326. }
  327. $ret .= $arraylist[$value];
  328. if ($htmlname == 'fk_product_type') {
  329. if ($value == 0) {
  330. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  331. } else {
  332. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  333. }
  334. }
  335. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  336. $tmpcontent = dol_htmlentitiesbr($value);
  337. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  338. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  339. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  340. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  341. }
  342. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  343. // clean data from some dangerous html
  344. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  345. } else {
  346. $ret .= dol_escape_htmltag($value);
  347. }
  348. if ($formatfunc && method_exists($object, $formatfunc)) {
  349. $ret = $object->$formatfunc($ret);
  350. }
  351. }
  352. }
  353. return $ret;
  354. }
  355. /**
  356. * Output edit in place form
  357. *
  358. * @param string $fieldname Name of the field
  359. * @param object $object Object
  360. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  361. * @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]'...)
  362. * @param string $check Same coe than $check parameter of GETPOST()
  363. * @param string $morecss More CSS
  364. * @return string HTML code for the edit of alternative language
  365. */
  366. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  367. {
  368. global $conf, $langs, $extralanguages;
  369. $result = '';
  370. // List of extra languages
  371. $arrayoflangcode = array();
  372. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  373. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  374. }
  375. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  376. if (!is_object($extralanguages)) {
  377. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  378. $extralanguages = new ExtraLanguages($this->db);
  379. }
  380. $extralanguages->fetch_name_extralanguages('societe');
  381. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  382. return ''; // No extralang field to show
  383. }
  384. $result .= '<!-- Widget for translation -->'."\n";
  385. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  386. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  387. $result .= $s;
  388. $result .= '</div>';
  389. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  390. $resultforextrlang = '';
  391. foreach ($arrayoflangcode as $langcode) {
  392. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  393. if (empty($valuetoshow)) {
  394. $object->fetchValuesForExtraLanguages();
  395. //var_dump($object->array_languages);
  396. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  397. }
  398. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  399. $resultforextrlang .= $s;
  400. // TODO Use the showInputField() method of ExtraLanguages object
  401. if ($typeofdata == 'textarea') {
  402. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  403. $resultforextrlang .= $valuetoshow;
  404. $resultforextrlang .= '</textarea>';
  405. } else {
  406. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  407. }
  408. }
  409. $result .= $resultforextrlang;
  410. $result .= '</div>';
  411. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  412. }
  413. return $result;
  414. }
  415. /**
  416. * Output edit in place form
  417. *
  418. * @param object $object Object
  419. * @param string $value Value to show/edit
  420. * @param string $htmlname DIV ID (field name)
  421. * @param int $condition Condition to edit
  422. * @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')
  423. * @param string $editvalue When in edit mode, use this value as $value instead of value
  424. * @param object $extObject External object
  425. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  426. * @return string HTML edit in place
  427. */
  428. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  429. {
  430. global $conf;
  431. $out = '';
  432. // Check parameters
  433. if (preg_match('/^text/', $inputType)) {
  434. $value = dol_nl2br($value);
  435. } elseif (preg_match('/^numeric/', $inputType)) {
  436. $value = price($value);
  437. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  438. $value = dol_print_date($value, 'day');
  439. }
  440. if ($condition) {
  441. $element = false;
  442. $table_element = false;
  443. $fk_element = false;
  444. $loadmethod = false;
  445. $savemethod = false;
  446. $ext_element = false;
  447. $button_only = false;
  448. $inputOption = '';
  449. $rows = '';
  450. $cols = '';
  451. if (is_object($object)) {
  452. $element = $object->element;
  453. $table_element = $object->table_element;
  454. $fk_element = $object->id;
  455. }
  456. if (is_object($extObject)) {
  457. $ext_element = $extObject->element;
  458. }
  459. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  460. $tmp = explode(':', $inputType);
  461. $inputType = $tmp[0];
  462. if (!empty($tmp[1])) {
  463. $inputOption = $tmp[1];
  464. }
  465. if (!empty($tmp[2])) {
  466. $savemethod = $tmp[2];
  467. }
  468. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  469. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  470. $tmp = explode(':', $inputType);
  471. $inputType = $tmp[0];
  472. if (!empty($tmp[1])) {
  473. $inputOption = $tmp[1];
  474. }
  475. if (!empty($tmp[2])) {
  476. $savemethod = $tmp[2];
  477. }
  478. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  479. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  480. $tmp = explode(':', $inputType);
  481. $inputType = $tmp[0];
  482. $loadmethod = $tmp[1];
  483. if (!empty($tmp[2])) {
  484. $savemethod = $tmp[2];
  485. }
  486. if (!empty($tmp[3])) {
  487. $button_only = true;
  488. }
  489. } elseif (preg_match('/^textarea/', $inputType)) {
  490. $tmp = explode(':', $inputType);
  491. $inputType = $tmp[0];
  492. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  493. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  494. } elseif (preg_match('/^ckeditor/', $inputType)) {
  495. $tmp = explode(':', $inputType);
  496. $inputType = $tmp[0];
  497. $toolbar = $tmp[1];
  498. if (!empty($tmp[2])) {
  499. $width = $tmp[2];
  500. }
  501. if (!empty($tmp[3])) {
  502. $heigth = $tmp[3];
  503. }
  504. if (!empty($tmp[4])) {
  505. $savemethod = $tmp[4];
  506. }
  507. if (isModEnabled('fckeditor')) {
  508. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  509. } else {
  510. $inputType = 'textarea';
  511. }
  512. }
  513. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  514. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  515. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  516. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  517. if (!empty($savemethod)) {
  518. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  519. }
  520. if (!empty($ext_element)) {
  521. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  522. }
  523. if (!empty($custommsg)) {
  524. if (is_array($custommsg)) {
  525. if (!empty($custommsg['success'])) {
  526. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  527. }
  528. if (!empty($custommsg['error'])) {
  529. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  530. }
  531. } else {
  532. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  533. }
  534. }
  535. if ($inputType == 'textarea') {
  536. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  537. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  538. }
  539. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  540. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  541. } else {
  542. $out = $value;
  543. }
  544. return $out;
  545. }
  546. /**
  547. * Show a text and picto with tooltip on text or picto.
  548. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  549. *
  550. * @param string $text Text to show
  551. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  552. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  553. * @param int $direction -1=image is before, 0=no image, 1=image is after
  554. * @param string $img Html code for image (use img_xxx() function to get it)
  555. * @param string $extracss Add a CSS style to td tags
  556. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  557. * @param string $incbefore Include code before the text
  558. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  559. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  560. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  561. * @return string Code html du tooltip (texte+picto)
  562. * @see textwithpicto() Use thisfunction if you can.
  563. */
  564. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  565. {
  566. if ($incbefore) {
  567. $text = $incbefore.$text;
  568. }
  569. if (!$htmltext) {
  570. return $text;
  571. }
  572. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  573. $tag = 'td';
  574. if ($notabs == 2) {
  575. $tag = 'div';
  576. }
  577. if ($notabs == 3) {
  578. $tag = 'span';
  579. }
  580. // Sanitize tooltip
  581. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  582. $extrastyle = '';
  583. if ($direction < 0) {
  584. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  585. $extrastyle = 'padding: 0px; padding-left: 3px;';
  586. }
  587. if ($direction > 0) {
  588. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  589. $extrastyle = 'padding: 0px; padding-right: 3px;';
  590. }
  591. $classfortooltip = 'classfortooltip';
  592. $s = '';
  593. $textfordialog = '';
  594. if ($tooltiptrigger == '') {
  595. $htmltext = str_replace('"', '&quot;', $htmltext);
  596. } else {
  597. $classfortooltip = 'classfortooltiponclick';
  598. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  599. }
  600. if ($tooltipon == 2 || $tooltipon == 3) {
  601. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  602. if ($tooltiptrigger == '') {
  603. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  604. } else {
  605. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  606. }
  607. } else {
  608. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  609. }
  610. if ($tooltipon == 1 || $tooltipon == 3) {
  611. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  612. if ($tooltiptrigger == '') {
  613. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  614. } else {
  615. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  616. }
  617. } else {
  618. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  619. }
  620. if (empty($notabs)) {
  621. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  622. } elseif ($notabs == 2) {
  623. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  624. }
  625. // Define value if value is before
  626. if ($direction < 0) {
  627. $s .= '<'.$tag.$paramfortooltipimg;
  628. if ($tag == 'td') {
  629. $s .= ' class="valigntop" width="14"';
  630. }
  631. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  632. }
  633. // Use another method to help avoid having a space in value in order to use this value with jquery
  634. // Define label
  635. if ((string) $text != '') {
  636. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  637. }
  638. // Define value if value is after
  639. if ($direction > 0) {
  640. $s .= '<'.$tag.$paramfortooltipimg;
  641. if ($tag == 'td') {
  642. $s .= ' class="valignmiddle" width="14"';
  643. }
  644. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  645. }
  646. if (empty($notabs)) {
  647. $s .= '</tr></table>';
  648. } elseif ($notabs == 2) {
  649. $s .= '</div>';
  650. }
  651. return $s;
  652. }
  653. /**
  654. * Show a text with a picto and a tooltip on picto
  655. *
  656. * @param string $text Text to show
  657. * @param string $htmltext Content of tooltip
  658. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  659. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  660. * @param string $extracss Add a CSS style to td, div or span tag
  661. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  662. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  663. * @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')
  664. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  665. * @return string HTML code of text, picto, tooltip
  666. */
  667. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  668. {
  669. global $conf, $langs;
  670. $alt = '';
  671. if ($tooltiptrigger) {
  672. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  673. }
  674. //For backwards compatibility
  675. if ($type == '0') {
  676. $type = 'info';
  677. } elseif ($type == '1') {
  678. $type = 'help';
  679. }
  680. // If info or help with no javascript, show only text
  681. if (empty($conf->use_javascript_ajax)) {
  682. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  683. return $text;
  684. } else {
  685. $alt = $htmltext;
  686. $htmltext = '';
  687. }
  688. }
  689. // If info or help with smartphone, show only text (tooltip hover can't works)
  690. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  691. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  692. return $text;
  693. }
  694. }
  695. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  696. //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
  697. //{
  698. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  699. //}
  700. $img = '';
  701. if ($type == 'info') {
  702. $img = img_help(0, $alt);
  703. } elseif ($type == 'help') {
  704. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  705. } elseif ($type == 'helpclickable') {
  706. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  707. } elseif ($type == 'superadmin') {
  708. $img = img_picto($alt, 'redstar');
  709. } elseif ($type == 'admin') {
  710. $img = img_picto($alt, 'star');
  711. } elseif ($type == 'warning') {
  712. $img = img_warning($alt);
  713. } elseif ($type != 'none') {
  714. $img = img_picto($alt, $type); // $type can be an image path
  715. }
  716. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  717. }
  718. /**
  719. * Generate select HTML to choose massaction
  720. *
  721. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  722. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  723. * @param int $alwaysvisible 1=select button always visible
  724. * @param string $name Name for massaction
  725. * @param string $cssclass CSS class used to check for select
  726. * @return string|void Select list
  727. */
  728. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  729. {
  730. global $conf, $langs, $hookmanager;
  731. $disabled = 0;
  732. $ret = '<div class="centpercent center">';
  733. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  734. // 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.
  735. $parameters = array();
  736. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  737. // check if there is a mass action
  738. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  739. return;
  740. }
  741. if (empty($reshook)) {
  742. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  743. foreach ($arrayofaction as $code => $label) {
  744. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  745. }
  746. }
  747. $ret .= $hookmanager->resPrint;
  748. $ret .= '</select>';
  749. if (empty($conf->dol_optimize_smallscreen)) {
  750. $ret .= ajax_combobox('.'.$name.'select');
  751. }
  752. // 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
  753. $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.
  754. $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")).'">';
  755. $ret .= '</div>';
  756. if (!empty($conf->use_javascript_ajax)) {
  757. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  758. <script>
  759. 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 */
  760. {
  761. atleastoneselected=0;
  762. jQuery("."+cssclass).each(function( index ) {
  763. /* console.log( index + ": " + $( this ).text() ); */
  764. if ($(this).is(\':checked\')) atleastoneselected++;
  765. });
  766. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  767. if (atleastoneselected || '.$alwaysvisible.')
  768. {
  769. jQuery("."+name).show();
  770. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  771. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  772. }
  773. else
  774. {
  775. jQuery("."+name).hide();
  776. jQuery("."+name+"other").hide();
  777. }
  778. }
  779. jQuery(document).ready(function () {
  780. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  781. jQuery(".' . $cssclass.'").click(function() {
  782. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  783. });
  784. jQuery(".' . $name.'select").change(function() {
  785. var massaction = $( this ).val();
  786. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  787. if (massaction == "builddoc")
  788. {
  789. urlform = urlform + "#show_files";
  790. }
  791. $( this ).closest("form").attr("action", urlform);
  792. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  793. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  794. if ($(this).val() != \'0\')
  795. {
  796. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  797. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  798. jQuery(".' . $name.'"+massaction).show();
  799. }
  800. else
  801. {
  802. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  803. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  804. }
  805. });
  806. });
  807. </script>
  808. ';
  809. }
  810. return $ret;
  811. }
  812. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  813. /**
  814. * Return combo list of activated countries, into language of user
  815. *
  816. * @param string $selected Id or Code or Label of preselected country
  817. * @param string $htmlname Name of html select object
  818. * @param string $htmloption More html options on select object
  819. * @param integer $maxlength Max length for labels (0=no limit)
  820. * @param string $morecss More css class
  821. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  822. * @param int|string $showempty Show empty choice
  823. * @param int $disablefavorites 1=Disable favorites,
  824. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  825. * @param array $exclude_country_code Array of country code (iso2) to exclude
  826. * @param int $hideflags Hide flags
  827. * @return string HTML string with select
  828. */
  829. 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)
  830. {
  831. // phpcs:enable
  832. global $conf, $langs, $mysoc;
  833. $langs->load("dict");
  834. $out = '';
  835. $countryArray = array();
  836. $favorite = array();
  837. $label = array();
  838. $atleastonefavorite = 0;
  839. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  840. $sql .= " FROM ".$this->db->prefix()."c_country";
  841. $sql .= " WHERE active > 0";
  842. //$sql.= " ORDER BY code ASC";
  843. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  844. $resql = $this->db->query($sql);
  845. if ($resql) {
  846. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  847. $num = $this->db->num_rows($resql);
  848. $i = 0;
  849. if ($num) {
  850. while ($i < $num) {
  851. $obj = $this->db->fetch_object($resql);
  852. $countryArray[$i]['rowid'] = $obj->rowid;
  853. $countryArray[$i]['code_iso'] = $obj->code_iso;
  854. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  855. $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 : ''));
  856. $countryArray[$i]['favorite'] = $obj->favorite;
  857. $countryArray[$i]['eec'] = $obj->eec;
  858. $favorite[$i] = $obj->favorite;
  859. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  860. $i++;
  861. }
  862. if (empty($disablefavorites)) {
  863. $array1_sort_order = SORT_DESC;
  864. $array2_sort_order = SORT_ASC;
  865. array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
  866. } else {
  867. $countryArray = dol_sort_array($countryArray, 'label');
  868. }
  869. if ($showempty) {
  870. if (is_numeric($showempty)) {
  871. $out .= '<option value="">&nbsp;</option>'."\n";
  872. } else {
  873. $out .= '<option value="">'.$langs->trans($showempty).'</option>'."\n";
  874. }
  875. }
  876. if ($addspecialentries) { // Add dedicated entries for groups of countries
  877. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  878. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  879. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  880. if ($mysoc->isInEEC()) {
  881. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  882. }
  883. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  884. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  885. }
  886. foreach ($countryArray as $row) {
  887. //if (empty($showempty) && empty($row['rowid'])) continue;
  888. if (empty($row['rowid'])) {
  889. continue;
  890. }
  891. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  892. continue; // exclude some countries
  893. }
  894. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  895. $atleastonefavorite++;
  896. }
  897. if (empty($row['favorite']) && $atleastonefavorite) {
  898. $atleastonefavorite = 0;
  899. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  900. }
  901. $labeltoshow = '';
  902. if ($row['label']) {
  903. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  904. } else {
  905. $labeltoshow .= '&nbsp;';
  906. }
  907. if ($row['code_iso']) {
  908. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  909. if (empty($hideflags)) {
  910. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  911. $labeltoshow = $tmpflag.' '.$labeltoshow;
  912. }
  913. }
  914. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  915. $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']).'">';
  916. } else {
  917. $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']).'">';
  918. }
  919. $out .= $labeltoshow;
  920. $out .= '</option>'."\n";
  921. }
  922. }
  923. $out .= '</select>';
  924. } else {
  925. dol_print_error($this->db);
  926. }
  927. // Make select dynamic
  928. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  929. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  930. return $out;
  931. }
  932. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  933. /**
  934. * Return select list of incoterms
  935. *
  936. * @param string $selected Id or Code of preselected incoterm
  937. * @param string $location_incoterms Value of input location
  938. * @param string $page Defined the form action
  939. * @param string $htmlname Name of html select object
  940. * @param string $htmloption Options html on select object
  941. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  942. * @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')))
  943. * @param array $disableautocomplete Disable autocomplete
  944. * @return string HTML string with select and input
  945. */
  946. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  947. {
  948. // phpcs:enable
  949. global $conf, $langs;
  950. $langs->load("dict");
  951. $out = '';
  952. $moreattrib = '';
  953. $incotermArray = array();
  954. $sql = "SELECT rowid, code";
  955. $sql .= " FROM ".$this->db->prefix()."c_incoterms";
  956. $sql .= " WHERE active > 0";
  957. $sql .= " ORDER BY code ASC";
  958. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  959. $resql = $this->db->query($sql);
  960. if ($resql) {
  961. if ($conf->use_javascript_ajax && !$forcecombo) {
  962. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  963. $out .= ajax_combobox($htmlname, $events);
  964. }
  965. if (!empty($page)) {
  966. $out .= '<form method="post" action="'.$page.'">';
  967. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  968. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  969. }
  970. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  971. $out .= '<option value="0">&nbsp;</option>';
  972. $num = $this->db->num_rows($resql);
  973. $i = 0;
  974. if ($num) {
  975. while ($i < $num) {
  976. $obj = $this->db->fetch_object($resql);
  977. $incotermArray[$i]['rowid'] = $obj->rowid;
  978. $incotermArray[$i]['code'] = $obj->code;
  979. $i++;
  980. }
  981. foreach ($incotermArray as $row) {
  982. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  983. $out .= '<option value="'.$row['rowid'].'" selected>';
  984. } else {
  985. $out .= '<option value="'.$row['rowid'].'">';
  986. }
  987. if ($row['code']) {
  988. $out .= $row['code'];
  989. }
  990. $out .= '</option>';
  991. }
  992. }
  993. $out .= '</select>';
  994. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  995. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  996. $moreattrib .= ' autocomplete="off"';
  997. }
  998. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  999. if (!empty($page)) {
  1000. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  1001. }
  1002. } else {
  1003. dol_print_error($this->db);
  1004. }
  1005. return $out;
  1006. }
  1007. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1008. /**
  1009. * Return list of types of lines (product or service)
  1010. * Example: 0=product, 1=service, 9=other (for external module)
  1011. *
  1012. * @param string $selected Preselected type
  1013. * @param string $htmlname Name of field in html form
  1014. * @param int $showempty Add an empty field
  1015. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  1016. * @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')
  1017. * @return void
  1018. */
  1019. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  1020. {
  1021. // phpcs:enable
  1022. global $langs, $conf;
  1023. // If product & services are enabled or both disabled.
  1024. if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
  1025. || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
  1026. if (empty($hidetext)) {
  1027. print $langs->trans("Type").': ';
  1028. }
  1029. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  1030. if ($showempty) {
  1031. print '<option value="-1"';
  1032. if ($selected == -1) {
  1033. print ' selected';
  1034. }
  1035. print '>&nbsp;</option>';
  1036. }
  1037. print '<option value="0"';
  1038. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1039. print ' selected';
  1040. }
  1041. print '>'.$langs->trans("Product");
  1042. print '<option value="1"';
  1043. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1044. print ' selected';
  1045. }
  1046. print '>'.$langs->trans("Service");
  1047. print '</select>';
  1048. print ajax_combobox('select_'.$htmlname);
  1049. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1050. }
  1051. if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
  1052. print $langs->trans("Service");
  1053. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1054. }
  1055. if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
  1056. print $langs->trans("Product");
  1057. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1058. }
  1059. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1060. 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
  1061. }
  1062. }
  1063. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1064. /**
  1065. * Load into cache cache_types_fees, array of types of fees
  1066. *
  1067. * @return int Nb of lines loaded, <0 if KO
  1068. */
  1069. public function load_cache_types_fees()
  1070. {
  1071. // phpcs:enable
  1072. global $langs;
  1073. $num = count($this->cache_types_fees);
  1074. if ($num > 0) {
  1075. return 0; // Cache already loaded
  1076. }
  1077. dol_syslog(__METHOD__, LOG_DEBUG);
  1078. $langs->load("trips");
  1079. $sql = "SELECT c.code, c.label";
  1080. $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
  1081. $sql .= " WHERE active > 0";
  1082. $resql = $this->db->query($sql);
  1083. if ($resql) {
  1084. $num = $this->db->num_rows($resql);
  1085. $i = 0;
  1086. while ($i < $num) {
  1087. $obj = $this->db->fetch_object($resql);
  1088. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1089. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1090. $this->cache_types_fees[$obj->code] = $label;
  1091. $i++;
  1092. }
  1093. asort($this->cache_types_fees);
  1094. return $num;
  1095. } else {
  1096. dol_print_error($this->db);
  1097. return -1;
  1098. }
  1099. }
  1100. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1101. /**
  1102. * Return list of types of notes
  1103. *
  1104. * @param string $selected Preselected type
  1105. * @param string $htmlname Name of field in form
  1106. * @param int $showempty Add an empty field
  1107. * @return void
  1108. */
  1109. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1110. {
  1111. // phpcs:enable
  1112. global $user, $langs;
  1113. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1114. $this->load_cache_types_fees();
  1115. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1116. if ($showempty) {
  1117. print '<option value="-1"';
  1118. if ($selected == -1) {
  1119. print ' selected';
  1120. }
  1121. print '>&nbsp;</option>';
  1122. }
  1123. foreach ($this->cache_types_fees as $key => $value) {
  1124. print '<option value="'.$key.'"';
  1125. if ($key == $selected) {
  1126. print ' selected';
  1127. }
  1128. print '>';
  1129. print $value;
  1130. print '</option>';
  1131. }
  1132. print '</select>';
  1133. if ($user->admin) {
  1134. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1135. }
  1136. }
  1137. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1138. /**
  1139. * Output html form to select a third party
  1140. *
  1141. * @param string $selected Preselected type
  1142. * @param string $htmlname Name of field in form
  1143. * @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)')
  1144. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1145. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1146. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1147. * @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')))
  1148. * @param int $limit Maximum number of elements
  1149. * @param string $morecss Add more css styles to the SELECT component
  1150. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1151. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1152. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1153. * @param array $ajaxoptions Options for ajax_autocompleter
  1154. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1155. * @param array $excludeids Exclude IDs from the select combo
  1156. * @param int $showcode Show code
  1157. * @return string HTML string with select box for thirdparty.
  1158. */
  1159. public function select_company($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $limit = 0, $morecss = 'minwidth100', $moreparam = '', $selected_input_value = '', $hidelabel = 1, $ajaxoptions = array(), $multiple = false, $excludeids = array(), $showcode = 0)
  1160. {
  1161. // phpcs:enable
  1162. global $conf, $user, $langs;
  1163. $out = '';
  1164. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1165. if (is_null($ajaxoptions)) {
  1166. $ajaxoptions = array();
  1167. }
  1168. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1169. // No immediate load of all database
  1170. $placeholder = '';
  1171. if ($selected && empty($selected_input_value)) {
  1172. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1173. $societetmp = new Societe($this->db);
  1174. $societetmp->fetch($selected);
  1175. $selected_input_value = $societetmp->name;
  1176. unset($societetmp);
  1177. }
  1178. // mode 1
  1179. $urloption = 'htmlname='.urlencode(str_replace('.', '_', $htmlname)).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '').($showcode ? '&showcode='.urlencode($showcode) : '');
  1180. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1181. if (empty($hidelabel)) {
  1182. print $langs->trans("RefOrLabel").' : ';
  1183. } elseif ($hidelabel > 1) {
  1184. $placeholder = $langs->trans("RefOrLabel");
  1185. if ($hidelabel == 2) {
  1186. $out .= img_picto($langs->trans("Search"), 'search');
  1187. }
  1188. }
  1189. $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' : '').' />';
  1190. if ($hidelabel == 3) {
  1191. $out .= img_picto($langs->trans("Search"), 'search');
  1192. }
  1193. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1194. } else {
  1195. // Immediate load of all database
  1196. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1197. }
  1198. return $out;
  1199. }
  1200. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1201. /**
  1202. * Output html form to select a third party.
  1203. * 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.
  1204. *
  1205. * @param string $selected Preselected type
  1206. * @param string $htmlname Name of field in form
  1207. * @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.
  1208. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1209. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1210. * @param int $forcecombo Force to use standard HTML select component without beautification
  1211. * @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')))
  1212. * @param string $filterkey Filter on key value
  1213. * @param int $outputmode 0=HTML select string, 1=Array
  1214. * @param int $limit Limit number of answers
  1215. * @param string $morecss Add more css styles to the SELECT component
  1216. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1217. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1218. * @param array $excludeids Exclude IDs from the select combo
  1219. * @param int $showcode Show code in list
  1220. * @return string HTML string with
  1221. */
  1222. public function select_thirdparty_list($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $filterkey = '', $outputmode = 0, $limit = 0, $morecss = 'minwidth100', $moreparam = '', $multiple = false, $excludeids = array(), $showcode = 0)
  1223. {
  1224. // phpcs:enable
  1225. global $conf, $user, $langs;
  1226. global $hookmanager;
  1227. $out = '';
  1228. $num = 0;
  1229. $outarray = array();
  1230. if ($selected === '') {
  1231. $selected = array();
  1232. } elseif (!is_array($selected)) {
  1233. $selected = array($selected);
  1234. }
  1235. // Clean $filter that may contains sql conditions so sql code
  1236. if (function_exists('testSqlAndScriptInject')) {
  1237. if (testSqlAndScriptInject($filter, 3) > 0) {
  1238. $filter = '';
  1239. }
  1240. }
  1241. // We search companies
  1242. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1243. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1244. $sql .= ", s.address, s.zip, s.town";
  1245. $sql .= ", dictp.code as country_code";
  1246. }
  1247. $sql .= " FROM ".$this->db->prefix()."societe as s";
  1248. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1249. $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
  1250. }
  1251. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1252. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  1253. }
  1254. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1255. if (!empty($user->socid)) {
  1256. $sql .= " AND s.rowid = ".((int) $user->socid);
  1257. }
  1258. if ($filter) {
  1259. $sql .= " AND (".$filter.")";
  1260. }
  1261. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1262. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1263. }
  1264. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1265. $sql .= " AND s.status <> 0";
  1266. }
  1267. if (!empty($excludeids)) {
  1268. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1269. }
  1270. // Add where from hooks
  1271. $parameters = array();
  1272. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1273. $sql .= $hookmanager->resPrint;
  1274. // Add criteria
  1275. if ($filterkey && $filterkey != '') {
  1276. $sql .= " AND (";
  1277. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1278. // For natural search
  1279. $scrit = explode(' ', $filterkey);
  1280. $i = 0;
  1281. if (count($scrit) > 1) {
  1282. $sql .= "(";
  1283. }
  1284. foreach ($scrit as $crit) {
  1285. if ($i > 0) {
  1286. $sql .= " AND ";
  1287. }
  1288. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1289. $i++;
  1290. }
  1291. if (count($scrit) > 1) {
  1292. $sql .= ")";
  1293. }
  1294. if (isModEnabled('barcode')) {
  1295. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1296. }
  1297. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1298. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1299. $sql .= ")";
  1300. }
  1301. $sql .= $this->db->order("nom", "ASC");
  1302. $sql .= $this->db->plimit($limit, 0);
  1303. // Build output string
  1304. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1305. $resql = $this->db->query($sql);
  1306. if ($resql) {
  1307. if (!$forcecombo) {
  1308. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1309. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1310. }
  1311. // Construct $out and $outarray
  1312. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1313. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1314. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1315. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1316. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1317. if ($showempty && !is_numeric($showempty)) {
  1318. $textifempty = $langs->trans($showempty);
  1319. } else {
  1320. $textifempty .= $langs->trans("All");
  1321. }
  1322. }
  1323. if ($showempty) {
  1324. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1325. }
  1326. $companytemp = new Societe($this->db);
  1327. $num = $this->db->num_rows($resql);
  1328. $i = 0;
  1329. if ($num) {
  1330. while ($i < $num) {
  1331. $obj = $this->db->fetch_object($resql);
  1332. $label = '';
  1333. if ($showcode || !empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) {
  1334. if (($obj->client) && (!empty($obj->code_client))) {
  1335. $label = $obj->code_client.' - ';
  1336. }
  1337. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1338. $label .= $obj->code_fournisseur.' - ';
  1339. }
  1340. $label .= ' '.$obj->name;
  1341. } else {
  1342. $label = $obj->name;
  1343. }
  1344. if (!empty($obj->name_alias)) {
  1345. $label .= ' ('.$obj->name_alias.')';
  1346. }
  1347. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1348. $label .= ' - '.$obj->tva_intra;
  1349. }
  1350. $labelhtml = $label;
  1351. if ($showtype) {
  1352. $companytemp->id = $obj->rowid;
  1353. $companytemp->client = $obj->client;
  1354. $companytemp->fournisseur = $obj->fournisseur;
  1355. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1356. if ($tmptype) {
  1357. $labelhtml .= ' '.$tmptype;
  1358. }
  1359. if ($obj->client || $obj->fournisseur) {
  1360. $label .= ' (';
  1361. }
  1362. if ($obj->client == 1 || $obj->client == 3) {
  1363. $label .= $langs->trans("Customer");
  1364. }
  1365. if ($obj->client == 2 || $obj->client == 3) {
  1366. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1367. }
  1368. if ($obj->fournisseur) {
  1369. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1370. }
  1371. if ($obj->client || $obj->fournisseur) {
  1372. $label .= ')';
  1373. }
  1374. }
  1375. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1376. $s = ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1377. if (!empty($obj->country_code)) {
  1378. $s .= ', '.$langs->trans('Country'.$obj->country_code);
  1379. }
  1380. $label .= $s;
  1381. $labelhtml .= $s;
  1382. }
  1383. if (empty($outputmode)) {
  1384. if (in_array($obj->rowid, $selected)) {
  1385. $out .= '<option value="'.$obj->rowid.'" selected data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
  1386. } else {
  1387. $out .= '<option value="'.$obj->rowid.'" data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
  1388. }
  1389. } else {
  1390. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label, 'labelhtml'=>$labelhtml));
  1391. }
  1392. $i++;
  1393. if (($i % 10) == 0) {
  1394. $out .= "\n";
  1395. }
  1396. }
  1397. }
  1398. $out .= '</select>'."\n";
  1399. } else {
  1400. dol_print_error($this->db);
  1401. }
  1402. $this->result = array('nbofthirdparties'=>$num);
  1403. if ($outputmode) {
  1404. return $outarray;
  1405. }
  1406. return $out;
  1407. }
  1408. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1409. /**
  1410. * Return HTML combo list of absolute discounts
  1411. *
  1412. * @param string $selected Id remise fixe pre-selectionnee
  1413. * @param string $htmlname Nom champ formulaire
  1414. * @param string $filter Criteres optionnels de filtre
  1415. * @param int $socid Id of thirdparty
  1416. * @param int $maxvalue Max value for lines that can be selected
  1417. * @return int Return number of qualifed lines in list
  1418. */
  1419. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1420. {
  1421. // phpcs:enable
  1422. global $langs, $conf;
  1423. // On recherche les remises
  1424. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1425. $sql .= " re.description, re.fk_facture_source";
  1426. $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
  1427. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1428. $sql .= " AND re.entity = ".$conf->entity;
  1429. if ($filter) {
  1430. $sql .= " AND ".$filter;
  1431. }
  1432. $sql .= " ORDER BY re.description ASC";
  1433. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1434. $resql = $this->db->query($sql);
  1435. if ($resql) {
  1436. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1437. $num = $this->db->num_rows($resql);
  1438. $qualifiedlines = $num;
  1439. $i = 0;
  1440. if ($num) {
  1441. print '<option value="0">&nbsp;</option>';
  1442. while ($i < $num) {
  1443. $obj = $this->db->fetch_object($resql);
  1444. $desc = dol_trunc($obj->description, 40);
  1445. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1446. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1447. }
  1448. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1449. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1450. }
  1451. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1452. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1453. }
  1454. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1455. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1456. }
  1457. $selectstring = '';
  1458. if ($selected > 0 && $selected == $obj->rowid) {
  1459. $selectstring = ' selected';
  1460. }
  1461. $disabled = '';
  1462. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1463. $qualifiedlines--;
  1464. $disabled = ' disabled';
  1465. }
  1466. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1467. $tmpfac = new Facture($this->db);
  1468. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1469. $desc = $desc.' - '.$tmpfac->ref;
  1470. }
  1471. }
  1472. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1473. $i++;
  1474. }
  1475. }
  1476. print '</select>';
  1477. print ajax_combobox('select_'.$htmlname);
  1478. return $qualifiedlines;
  1479. } else {
  1480. dol_print_error($this->db);
  1481. return -1;
  1482. }
  1483. }
  1484. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1485. /**
  1486. * Return list of all contacts (for a third party or all)
  1487. *
  1488. * @param int $socid Id ot third party or 0 for all
  1489. * @param string $selected Id contact pre-selectionne
  1490. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1491. * @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
  1492. * @param string $exclude List of contacts id to exclude
  1493. * @param string $limitto Disable answers that are not id in this array list
  1494. * @param integer $showfunction Add function into label
  1495. * @param string $morecss Add more class to class style
  1496. * @param integer $showsoc Add company into label
  1497. * @param int $forcecombo Force to use combo box
  1498. * @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')))
  1499. * @param bool $options_only Return options only (for ajax treatment)
  1500. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1501. * @param string $htmlid Html id to use instead of htmlname
  1502. * @return int <0 if KO, Nb of contact in list if OK
  1503. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1504. */
  1505. 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 = '')
  1506. {
  1507. // phpcs:enable
  1508. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1509. return $this->num;
  1510. }
  1511. /**
  1512. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1513. * This also set the number of contacts found into $this->num
  1514. *
  1515. * @since 9.0 Add afterSelectContactOptions hook
  1516. *
  1517. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1518. * @param array|int $selected Array of ID of pre-selected contact id
  1519. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1520. * @param int|string $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
  1521. * @param string $exclude List of contacts id to exclude
  1522. * @param string $limitto Disable answers that are not id in this array list
  1523. * @param integer $showfunction Add function into label
  1524. * @param string $morecss Add more class to class style
  1525. * @param bool $options_only Return options only (for ajax treatment)
  1526. * @param integer $showsoc Add company into label
  1527. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1528. * @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')))
  1529. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1530. * @param string $htmlid Html id to use instead of htmlname
  1531. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1532. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1533. * @return int|string <0 if KO, HTML with select string if OK.
  1534. */
  1535. 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)
  1536. {
  1537. global $conf, $langs, $hookmanager, $action;
  1538. $langs->load('companies');
  1539. if (empty($htmlid)) {
  1540. $htmlid = $htmlname;
  1541. }
  1542. $num = 0;
  1543. if ($selected === '') {
  1544. $selected = array();
  1545. } elseif (!is_array($selected)) {
  1546. $selected = array($selected);
  1547. }
  1548. $out = '';
  1549. if (!is_object($hookmanager)) {
  1550. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1551. $hookmanager = new HookManager($this->db);
  1552. }
  1553. // We search third parties
  1554. $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";
  1555. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1556. $sql .= ", s.nom as company, s.town AS company_town";
  1557. }
  1558. $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
  1559. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1560. $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
  1561. }
  1562. $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
  1563. if ($socid > 0 || $socid == -1) {
  1564. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1565. }
  1566. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1567. $sql .= " AND sp.statut <> 0";
  1568. }
  1569. // Add where from hooks
  1570. $parameters = array();
  1571. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1572. $sql .= $hookmanager->resPrint;
  1573. $sql .= " ORDER BY sp.lastname ASC";
  1574. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1575. $resql = $this->db->query($sql);
  1576. if ($resql) {
  1577. $num = $this->db->num_rows($resql);
  1578. if ($htmlname != 'none' && !$options_only) {
  1579. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1580. }
  1581. if ($showempty && ! is_numeric($showempty)) {
  1582. $textforempty = $showempty;
  1583. $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
  1584. } else {
  1585. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1586. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1587. }
  1588. if ($showempty == 2) {
  1589. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1590. }
  1591. }
  1592. $i = 0;
  1593. if ($num) {
  1594. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1595. $contactstatic = new Contact($this->db);
  1596. while ($i < $num) {
  1597. $obj = $this->db->fetch_object($resql);
  1598. // Set email (or phones) and town extended infos
  1599. $extendedInfos = '';
  1600. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1601. $extendedInfos = array();
  1602. $email = trim($obj->email);
  1603. if (!empty($email)) {
  1604. $extendedInfos[] = $email;
  1605. } else {
  1606. $phone = trim($obj->phone);
  1607. $phone_perso = trim($obj->phone_perso);
  1608. $phone_mobile = trim($obj->phone_mobile);
  1609. if (!empty($phone)) {
  1610. $extendedInfos[] = $phone;
  1611. }
  1612. if (!empty($phone_perso)) {
  1613. $extendedInfos[] = $phone_perso;
  1614. }
  1615. if (!empty($phone_mobile)) {
  1616. $extendedInfos[] = $phone_mobile;
  1617. }
  1618. }
  1619. $contact_town = trim($obj->contact_town);
  1620. $company_town = trim($obj->company_town);
  1621. if (!empty($contact_town)) {
  1622. $extendedInfos[] = $contact_town;
  1623. } elseif (!empty($company_town)) {
  1624. $extendedInfos[] = $company_town;
  1625. }
  1626. $extendedInfos = implode(' - ', $extendedInfos);
  1627. if (!empty($extendedInfos)) {
  1628. $extendedInfos = ' - '.$extendedInfos;
  1629. }
  1630. }
  1631. $contactstatic->id = $obj->rowid;
  1632. $contactstatic->lastname = $obj->lastname;
  1633. $contactstatic->firstname = $obj->firstname;
  1634. if ($obj->statut == 1) {
  1635. if ($htmlname != 'none') {
  1636. $disabled = 0;
  1637. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1638. $disabled = 1;
  1639. }
  1640. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1641. $disabled = 1;
  1642. }
  1643. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1644. $out .= '<option value="'.$obj->rowid.'"';
  1645. if ($disabled) {
  1646. $out .= ' disabled';
  1647. }
  1648. $out .= ' selected>';
  1649. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1650. if ($showfunction && $obj->poste) {
  1651. $out .= ' ('.$obj->poste.')';
  1652. }
  1653. if (($showsoc > 0) && $obj->company) {
  1654. $out .= ' - ('.$obj->company.')';
  1655. }
  1656. $out .= '</option>';
  1657. } else {
  1658. $out .= '<option value="'.$obj->rowid.'"';
  1659. if ($disabled) {
  1660. $out .= ' disabled';
  1661. }
  1662. $out .= '>';
  1663. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1664. if ($showfunction && $obj->poste) {
  1665. $out .= ' ('.$obj->poste.')';
  1666. }
  1667. if (($showsoc > 0) && $obj->company) {
  1668. $out .= ' - ('.$obj->company.')';
  1669. }
  1670. $out .= '</option>';
  1671. }
  1672. } else {
  1673. if (in_array($obj->rowid, $selected)) {
  1674. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1675. if ($showfunction && $obj->poste) {
  1676. $out .= ' ('.$obj->poste.')';
  1677. }
  1678. if (($showsoc > 0) && $obj->company) {
  1679. $out .= ' - ('.$obj->company.')';
  1680. }
  1681. }
  1682. }
  1683. }
  1684. $i++;
  1685. }
  1686. } else {
  1687. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1688. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1689. $out .= $labeltoshow;
  1690. $out .= '</option>';
  1691. }
  1692. $parameters = array(
  1693. 'socid'=>$socid,
  1694. 'htmlname'=>$htmlname,
  1695. 'resql'=>$resql,
  1696. 'out'=>&$out,
  1697. 'showfunction'=>$showfunction,
  1698. 'showsoc'=>$showsoc,
  1699. );
  1700. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1701. if ($htmlname != 'none' && !$options_only) {
  1702. $out .= '</select>';
  1703. }
  1704. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1705. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1706. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1707. }
  1708. $this->num = $num;
  1709. return $out;
  1710. } else {
  1711. dol_print_error($this->db);
  1712. return -1;
  1713. }
  1714. }
  1715. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1716. /**
  1717. * Return the HTML select list of users
  1718. *
  1719. * @param string $selected Id user preselected
  1720. * @param string $htmlname Field name in form
  1721. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1722. * @param array $exclude Array list of users id to exclude
  1723. * @param int $disabled If select list must be disabled
  1724. * @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
  1725. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1726. * @param string $force_entity '0' or Ids of environment to force
  1727. * @return void
  1728. * @deprecated Use select_dolusers instead
  1729. * @see select_dolusers()
  1730. */
  1731. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1732. {
  1733. // phpcs:enable
  1734. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1735. }
  1736. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1737. /**
  1738. * Return select list of users
  1739. *
  1740. * @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)
  1741. * @param string $htmlname Field name in form
  1742. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1743. * @param array $exclude Array list of users id to exclude
  1744. * @param int $disabled If select list must be disabled
  1745. * @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
  1746. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1747. * @param string $force_entity '0' or Ids of environment to force
  1748. * @param int $maxlength Maximum length of string into list (0=no limit)
  1749. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1750. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1751. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1752. * @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.
  1753. * @param string $morecss More css
  1754. * @param int $notdisabled Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1755. * @param int $outputmode 0=HTML select string, 1=Array
  1756. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1757. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1758. * @return string HTML select string
  1759. * @see select_dolgroups()
  1760. */
  1761. 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 = '', $notdisabled = 0, $outputmode = 0, $multiple = false, $forcecombo = 0)
  1762. {
  1763. // phpcs:enable
  1764. global $conf, $user, $langs, $hookmanager;
  1765. global $action;
  1766. // If no preselected user defined, we take current user
  1767. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1768. $selected = $user->id;
  1769. }
  1770. if ($selected === '') {
  1771. $selected = array();
  1772. } elseif (!is_array($selected)) {
  1773. $selected = array($selected);
  1774. }
  1775. $excludeUsers = null;
  1776. $includeUsers = null;
  1777. // Permettre l'exclusion d'utilisateurs
  1778. if (is_array($exclude)) {
  1779. $excludeUsers = implode(",", $exclude);
  1780. }
  1781. // Permettre l'inclusion d'utilisateurs
  1782. if (is_array($include)) {
  1783. $includeUsers = implode(",", $include);
  1784. } elseif ($include == 'hierarchy') {
  1785. // Build list includeUsers to have only hierarchy
  1786. $includeUsers = implode(",", $user->getAllChildIds(0));
  1787. } elseif ($include == 'hierarchyme') {
  1788. // Build list includeUsers to have only hierarchy and current user
  1789. $includeUsers = implode(",", $user->getAllChildIds(1));
  1790. }
  1791. $out = '';
  1792. $outarray = array();
  1793. // Forge request to select users
  1794. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1795. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1796. $sql .= ", e.label";
  1797. }
  1798. $sql .= " FROM ".$this->db->prefix()."user as u";
  1799. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1800. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
  1801. if ($force_entity) {
  1802. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1803. } else {
  1804. $sql .= " WHERE u.entity IS NOT NULL";
  1805. }
  1806. } else {
  1807. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1808. $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
  1809. $sql .= " ON ug.fk_user = u.rowid";
  1810. $sql .= " WHERE ug.entity = ".$conf->entity;
  1811. } else {
  1812. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1813. }
  1814. }
  1815. if (!empty($user->socid)) {
  1816. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1817. }
  1818. if (is_array($exclude) && $excludeUsers) {
  1819. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1820. }
  1821. if ($includeUsers) {
  1822. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1823. }
  1824. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $notdisabled) {
  1825. $sql .= " AND u.statut <> 0";
  1826. }
  1827. if (!empty($morefilter)) {
  1828. $sql .= " ".$morefilter;
  1829. }
  1830. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1831. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1832. if (!empty($reshook)) {
  1833. $sql .= $hookmanager->resPrint;
  1834. }
  1835. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1836. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1837. } else {
  1838. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1839. }
  1840. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1841. $resql = $this->db->query($sql);
  1842. if ($resql) {
  1843. $num = $this->db->num_rows($resql);
  1844. $i = 0;
  1845. if ($num) {
  1846. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1847. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1848. if ($show_empty && !$multiple) {
  1849. $textforempty = ' ';
  1850. if (!empty($conf->use_javascript_ajax)) {
  1851. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1852. }
  1853. if (!is_numeric($show_empty)) {
  1854. $textforempty = $show_empty;
  1855. }
  1856. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1857. }
  1858. if ($show_every) {
  1859. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1860. }
  1861. $userstatic = new User($this->db);
  1862. while ($i < $num) {
  1863. $obj = $this->db->fetch_object($resql);
  1864. $userstatic->id = $obj->rowid;
  1865. $userstatic->lastname = $obj->lastname;
  1866. $userstatic->firstname = $obj->firstname;
  1867. $userstatic->photo = $obj->photo;
  1868. $userstatic->statut = $obj->status;
  1869. $userstatic->entity = $obj->entity;
  1870. $userstatic->admin = $obj->admin;
  1871. $disableline = '';
  1872. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1873. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1874. }
  1875. $labeltoshow = ''; $labeltoshowhtml = '';
  1876. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1877. $fullNameMode = 0;
  1878. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1879. $fullNameMode = 1; //Firstname+lastname
  1880. }
  1881. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1882. $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1883. if (empty($obj->firstname) && empty($obj->lastname)) {
  1884. $labeltoshow .= $obj->login;
  1885. $labeltoshowhtml .= $obj->login;
  1886. }
  1887. // Complete name with a more info string like: ' (info1 - info2 - ...)'
  1888. $moreinfo = ''; $moreinfohtml = '';
  1889. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1890. $moreinfo .= ($moreinfo ? ' - ' : ' (');
  1891. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
  1892. $moreinfo .= $obj->login;
  1893. $moreinfohtml .= $obj->login;
  1894. }
  1895. if ($showstatus >= 0) {
  1896. if ($obj->status == 1 && $showstatus == 1) {
  1897. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1898. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans('Enabled');
  1899. }
  1900. if ($obj->status == 0 && $showstatus == 1) {
  1901. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1902. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans('Disabled');
  1903. }
  1904. }
  1905. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1906. if (!$obj->entity) {
  1907. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1908. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans("AllEntities");
  1909. } else {
  1910. if ($obj->entity != $conf->entity) {
  1911. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1912. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1913. }
  1914. }
  1915. }
  1916. $moreinfo .= ($moreinfo ? ')' : '');
  1917. $moreinfohtml .= ($moreinfohtml ? ')' : '');
  1918. if ($disableline && $disableline != '1') {
  1919. // Add text from $enableonlytext parameter
  1920. $moreinfo .= ' - '.$disableline;
  1921. $moreinfohtml .= ' - '.$disableline;
  1922. }
  1923. $labeltoshow .= $moreinfo;
  1924. $labeltoshowhtml .= $moreinfohtml;
  1925. $out .= '<option value="'.$obj->rowid.'"';
  1926. if ($disableline) {
  1927. $out .= ' disabled';
  1928. }
  1929. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1930. $out .= ' selected';
  1931. }
  1932. $out .= ' data-html="';
  1933. $outhtml = '';
  1934. // if (!empty($obj->photo)) {
  1935. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1936. // }
  1937. if ($showstatus >= 0 && $obj->status == 0) {
  1938. $outhtml .= '<strike class="opacitymediumxxx">';
  1939. }
  1940. $outhtml .= $labeltoshowhtml;
  1941. if ($showstatus >= 0 && $obj->status == 0) {
  1942. $outhtml .= '</strike>';
  1943. }
  1944. $out .= dol_escape_htmltag($outhtml);
  1945. $out .= '">';
  1946. $out .= $labeltoshow;
  1947. $out .= '</option>';
  1948. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1949. $i++;
  1950. }
  1951. } else {
  1952. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1953. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1954. }
  1955. $out .= '</select>';
  1956. if ($num && !$forcecombo) {
  1957. // Enhance with select2
  1958. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1959. $out .= ajax_combobox($htmlname);
  1960. }
  1961. } else {
  1962. dol_print_error($this->db);
  1963. }
  1964. if ($outputmode) {
  1965. return $outarray;
  1966. }
  1967. return $out;
  1968. }
  1969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1970. /**
  1971. * Return select list of users. Selected users are stored into session.
  1972. * List of users are provided into $_SESSION['assignedtouser'].
  1973. *
  1974. * @param string $action Value for $action
  1975. * @param string $htmlname Field name in form
  1976. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1977. * @param array $exclude Array list of users id to exclude
  1978. * @param int $disabled If select list must be disabled
  1979. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1980. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1981. * @param int $force_entity '0' or Ids of environment to force
  1982. * @param int $maxlength Maximum length of string into list (0=no limit)
  1983. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1984. * @param string $morefilter Add more filters into sql request
  1985. * @param int $showproperties Show properties of each attendees
  1986. * @param array $listofuserid Array with properties of each user
  1987. * @param array $listofcontactid Array with properties of each contact
  1988. * @param array $listofotherid Array with properties of each other contact
  1989. * @return string HTML select string
  1990. * @see select_dolgroups()
  1991. */
  1992. 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())
  1993. {
  1994. // phpcs:enable
  1995. global $conf, $user, $langs;
  1996. $userstatic = new User($this->db);
  1997. $out = '';
  1998. $assignedtouser = array();
  1999. if (!empty($_SESSION['assignedtouser'])) {
  2000. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  2001. }
  2002. $nbassignetouser = count($assignedtouser);
  2003. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  2004. if ($nbassignetouser) {
  2005. $out .= '<ul class="attendees">';
  2006. }
  2007. $i = 0;
  2008. $ownerid = 0;
  2009. foreach ($assignedtouser as $key => $value) {
  2010. if ($value['id'] == $ownerid) {
  2011. continue;
  2012. }
  2013. $out .= '<li>';
  2014. $userstatic->fetch($value['id']);
  2015. $out .= $userstatic->getNomUrl(-1);
  2016. if ($i == 0) {
  2017. $ownerid = $value['id'];
  2018. $out .= ' ('.$langs->trans("Owner").')';
  2019. }
  2020. if ($nbassignetouser > 1 && $action != 'view') {
  2021. $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.'">';
  2022. }
  2023. // Show my availability
  2024. if ($showproperties) {
  2025. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  2026. $out .= '<div class="myavailability inline-block">';
  2027. $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>';
  2028. $out .= '</div>';
  2029. }
  2030. }
  2031. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2032. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2033. $out .= '</li>';
  2034. $i++;
  2035. }
  2036. if ($nbassignetouser) {
  2037. $out .= '</ul>';
  2038. }
  2039. // Method with no ajax
  2040. if ($action != 'view') {
  2041. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2042. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  2043. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2044. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2045. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  2046. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  2047. $out .= '});';
  2048. $out .= '})</script>';
  2049. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2050. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  2051. $out .= '<br>';
  2052. }
  2053. return $out;
  2054. }
  2055. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2056. /**
  2057. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2058. *
  2059. * @param int $selected Preselected products
  2060. * @param string $htmlname Name of HTML select field (must be unique in page).
  2061. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2062. * @param int $limit Limit on number of returned lines
  2063. * @param int $price_level Level of price to show
  2064. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2065. * @param int $finished 2=all, 1=finished, 0=raw material
  2066. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2067. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2068. * @param array $ajaxoptions Options for ajax_autocompleter
  2069. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2070. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2071. * @param int $forcecombo Force to use combo box
  2072. * @param string $morecss Add more css on select
  2073. * @param int $hidepriceinlabel 1=Hide prices in label
  2074. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2075. * 'warehouseopen' = count products from open warehouses,
  2076. * 'warehouseclosed' = count products from closed warehouses,
  2077. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2078. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2079. * @param string $nooutput No print, return the output into a string
  2080. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2081. * @return void|string
  2082. */
  2083. 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)
  2084. {
  2085. // phpcs:enable
  2086. global $langs, $conf;
  2087. $out = '';
  2088. // check parameters
  2089. $price_level = (!empty($price_level) ? $price_level : 0);
  2090. if (is_null($ajaxoptions)) {
  2091. $ajaxoptions = array();
  2092. }
  2093. if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
  2094. if (isModEnabled("product") && !isModEnabled('service')) {
  2095. $filtertype = '0';
  2096. } elseif (!isModEnabled('product') && isModEnabled("service")) {
  2097. $filtertype = '1';
  2098. }
  2099. }
  2100. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2101. $placeholder = '';
  2102. if ($selected && empty($selected_input_value)) {
  2103. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2104. $producttmpselect = new Product($this->db);
  2105. $producttmpselect->fetch($selected);
  2106. $selected_input_value = $producttmpselect->ref;
  2107. unset($producttmpselect);
  2108. }
  2109. // handle case where product or service module is disabled + no filter specified
  2110. if ($filtertype == '') {
  2111. if (!isModEnabled('product')) { // when product module is disabled, show services only
  2112. $filtertype = 1;
  2113. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2114. $filtertype = 0;
  2115. }
  2116. }
  2117. // mode=1 means customers products
  2118. $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;
  2119. //Price by customer
  2120. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2121. $urloption .= '&socid='.$socid;
  2122. }
  2123. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2124. if (isModEnabled('variants') && is_array($selected_combinations)) {
  2125. // Code to automatically insert with javascript the select of attributes under the select of product
  2126. // when a parent of variant has been selected.
  2127. $out .= '
  2128. <!-- script to auto show attributes select tags if a variant was selected -->
  2129. <script>
  2130. // auto show attributes fields
  2131. selected = '.json_encode($selected_combinations).';
  2132. combvalues = {};
  2133. jQuery(document).ready(function () {
  2134. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2135. if (jQuery(this).val() == \'free\') {
  2136. jQuery(\'div#attributes_box\').empty();
  2137. }
  2138. });
  2139. jQuery("input#'.$htmlname.'").change(function () {
  2140. if (!jQuery(this).val()) {
  2141. jQuery(\'div#attributes_box\').empty();
  2142. return;
  2143. }
  2144. console.log("A change has started. We get variants fields to inject html select");
  2145. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2146. id: jQuery(this).val()
  2147. }, function (data) {
  2148. jQuery(\'div#attributes_box\').empty();
  2149. jQuery.each(data, function (key, val) {
  2150. combvalues[val.id] = val.values;
  2151. var span = jQuery(document.createElement(\'div\')).css({
  2152. \'display\': \'table-row\'
  2153. });
  2154. span.append(
  2155. jQuery(document.createElement(\'div\')).text(val.label).css({
  2156. \'font-weight\': \'bold\',
  2157. \'display\': \'table-cell\'
  2158. })
  2159. );
  2160. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2161. \'margin-left\': \'15px\',
  2162. \'white-space\': \'pre\'
  2163. }).append(
  2164. jQuery(document.createElement(\'option\')).val(\'\')
  2165. );
  2166. jQuery.each(combvalues[val.id], function (key, val) {
  2167. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2168. if (selected[val.fk_product_attribute] == val.id) {
  2169. tag.attr(\'selected\', \'selected\');
  2170. }
  2171. html.append(tag);
  2172. });
  2173. span.append(html);
  2174. jQuery(\'div#attributes_box\').append(span);
  2175. });
  2176. })
  2177. });
  2178. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2179. });
  2180. </script>
  2181. ';
  2182. }
  2183. if (empty($hidelabel)) {
  2184. $out .= $langs->trans("RefOrLabel").' : ';
  2185. } elseif ($hidelabel > 1) {
  2186. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2187. if ($hidelabel == 2) {
  2188. $out .= img_picto($langs->trans("Search"), 'search');
  2189. }
  2190. }
  2191. $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' : '').' />';
  2192. if ($hidelabel == 3) {
  2193. $out .= img_picto($langs->trans("Search"), 'search');
  2194. }
  2195. } else {
  2196. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2197. }
  2198. if (empty($nooutput)) {
  2199. print $out;
  2200. } else {
  2201. return $out;
  2202. }
  2203. }
  2204. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2205. /**
  2206. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2207. *
  2208. * @param int $selected Preselected BOM id
  2209. * @param string $htmlname Name of HTML select field (must be unique in page).
  2210. * @param int $limit Limit on number of returned lines
  2211. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2212. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2213. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2214. * @param string $morecss Add more css on select
  2215. * @param string $nooutput No print, return the output into a string
  2216. * @param int $forcecombo Force to use combo box
  2217. * @param array $TProducts Add filter on a defined product
  2218. * @return void|string
  2219. */
  2220. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2221. {
  2222. // phpcs:enable
  2223. global $conf, $user, $langs, $db;
  2224. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2225. $error = 0;
  2226. $out = '';
  2227. if (!$forcecombo) {
  2228. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2229. $events = array();
  2230. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2231. }
  2232. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2233. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2234. $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
  2235. $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
  2236. if (!empty($status)) $sql.= ' AND status = '. (int) $status;
  2237. if (!empty($type)) $sql.= ' AND bomtype = '. (int) $type;
  2238. if (!empty($TProducts)) $sql .= ' AND fk_product IN ('.$this->db->sanitize(implode(',', $TProducts)).')';
  2239. if (!empty($limit)) $sql.= ' LIMIT '. (int) $limit;
  2240. $resql = $db->query($sql);
  2241. if ($resql) {
  2242. if ($showempty) {
  2243. $out .= '<option value="-1"';
  2244. if (empty($selected)) $out .= ' selected';
  2245. $out .= '>&nbsp;</option>';
  2246. }
  2247. while ($obj = $db->fetch_object($resql)) {
  2248. $product = new Product($db);
  2249. $res = $product->fetch($obj->fk_product);
  2250. $out .= '<option value="'.$obj->rowid.'"';
  2251. if ($obj->rowid == $selected) $out .= 'selected';
  2252. $out .= '>'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
  2253. }
  2254. } else {
  2255. $error++;
  2256. dol_print_error($db);
  2257. }
  2258. if (empty($nooutput)) {
  2259. print $out;
  2260. } else {
  2261. return $out;
  2262. }
  2263. }
  2264. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2265. /**
  2266. * Return list of products for a customer.
  2267. * Called by select_produits.
  2268. *
  2269. * @param int $selected Preselected product
  2270. * @param string $htmlname Name of select html
  2271. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2272. * @param int $limit Limit on number of returned lines
  2273. * @param int $price_level Level of price to show
  2274. * @param string $filterkey Filter on product
  2275. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2276. * @param int $finished Filter on finished field: 2=No filter
  2277. * @param int $outputmode 0=HTML select string, 1=Array
  2278. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2279. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2280. * @param int $forcecombo Force to use combo box
  2281. * @param string $morecss Add more css on select
  2282. * @param int $hidepriceinlabel 1=Hide prices in label
  2283. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2284. * 'warehouseopen' = count products from open warehouses,
  2285. * 'warehouseclosed' = count products from closed warehouses,
  2286. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2287. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2288. * @return array|string Array of keys for json
  2289. */
  2290. 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)
  2291. {
  2292. // phpcs:enable
  2293. global $langs, $conf;
  2294. global $hookmanager;
  2295. $out = '';
  2296. $outarray = array();
  2297. // Units
  2298. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2299. $langs->load('other');
  2300. }
  2301. $warehouseStatusArray = array();
  2302. if (!empty($warehouseStatus)) {
  2303. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2304. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2305. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2306. }
  2307. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2308. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2309. }
  2310. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2311. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2312. }
  2313. }
  2314. $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";
  2315. if (count($warehouseStatusArray)) {
  2316. $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
  2317. } else {
  2318. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2319. }
  2320. $sql = "SELECT ";
  2321. $sql .= $selectFields.$selectFieldsGrouped;
  2322. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2323. //Product category
  2324. $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
  2325. FROM ".$this->db->prefix()."categorie_product
  2326. WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
  2327. LIMIT 1
  2328. ) AS categorie_product_id ";
  2329. }
  2330. //Price by customer
  2331. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2332. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2333. $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';
  2334. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2335. }
  2336. // Units
  2337. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2338. $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";
  2339. $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';
  2340. }
  2341. // Multilang : we add translation
  2342. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2343. $sql .= ", pl.label as label_translated";
  2344. $sql .= ", pl.description as description_translated";
  2345. $selectFields .= ", label_translated";
  2346. $selectFields .= ", description_translated";
  2347. }
  2348. // Price by quantity
  2349. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2350. $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
  2351. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2352. $sql .= " AND price_level = ".((int) $price_level);
  2353. }
  2354. $sql .= " ORDER BY date_price";
  2355. $sql .= " DESC LIMIT 1) as price_rowid";
  2356. $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
  2357. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2358. $sql .= " AND price_level = ".((int) $price_level);
  2359. }
  2360. $sql .= " ORDER BY date_price";
  2361. $sql .= " DESC LIMIT 1) as price_by_qty";
  2362. $selectFields .= ", price_rowid, price_by_qty";
  2363. }
  2364. $sql .= " FROM ".$this->db->prefix()."product as p";
  2365. if (count($warehouseStatusArray)) {
  2366. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
  2367. $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2368. $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.
  2369. }
  2370. // include search in supplier ref
  2371. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2372. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2373. }
  2374. //Price by customer
  2375. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2376. $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2377. }
  2378. // Units
  2379. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2380. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2381. }
  2382. // Multilang : we add translation
  2383. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2384. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
  2385. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2386. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2387. $soc = new Societe($this->db);
  2388. $result = $soc->fetch($socid);
  2389. if ($result > 0 && !empty($soc->default_lang)) {
  2390. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2391. } else {
  2392. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2393. }
  2394. } else {
  2395. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2396. }
  2397. }
  2398. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2399. $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2400. }
  2401. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2402. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2403. $sql .= " AND pac.rowid IS NULL";
  2404. }
  2405. if ($finished == 0) {
  2406. $sql .= " AND p.finished = ".((int) $finished);
  2407. } elseif ($finished == 1) {
  2408. $sql .= " AND p.finished = ".((int) $finished);
  2409. if ($status >= 0) {
  2410. $sql .= " AND p.tosell = ".((int) $status);
  2411. }
  2412. } elseif ($status >= 0) {
  2413. $sql .= " AND p.tosell = ".((int) $status);
  2414. }
  2415. if ($status_purchase >= 0) {
  2416. $sql .= " AND p.tobuy = ".((int) $status_purchase);
  2417. }
  2418. // Filter by product type
  2419. if (strval($filtertype) != '') {
  2420. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2421. } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
  2422. $sql .= " AND p.fk_product_type = 1";
  2423. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2424. $sql .= " AND p.fk_product_type = 0";
  2425. }
  2426. // Add where from hooks
  2427. $parameters = array();
  2428. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2429. $sql .= $hookmanager->resPrint;
  2430. // Add criteria on ref/label
  2431. if ($filterkey != '') {
  2432. $sql .= ' AND (';
  2433. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2434. // For natural search
  2435. $scrit = explode(' ', $filterkey);
  2436. $i = 0;
  2437. if (count($scrit) > 1) {
  2438. $sql .= "(";
  2439. }
  2440. foreach ($scrit as $crit) {
  2441. if ($i > 0) {
  2442. $sql .= " AND ";
  2443. }
  2444. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2445. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2446. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2447. }
  2448. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2449. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2450. }
  2451. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2452. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2453. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2454. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2455. }
  2456. }
  2457. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2458. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2459. }
  2460. $sql .= ")";
  2461. $i++;
  2462. }
  2463. if (count($scrit) > 1) {
  2464. $sql .= ")";
  2465. }
  2466. if (isModEnabled('barcode')) {
  2467. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2468. }
  2469. $sql .= ')';
  2470. }
  2471. if (count($warehouseStatusArray)) {
  2472. $sql .= " GROUP BY ".$selectFields;
  2473. }
  2474. //Sort by category
  2475. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2476. $sql .= " ORDER BY categorie_product_id ";
  2477. //ASC OR DESC order
  2478. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2479. } else {
  2480. $sql .= $this->db->order("p.ref");
  2481. }
  2482. $sql .= $this->db->plimit($limit, 0);
  2483. // Build output string
  2484. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2485. $result = $this->db->query($sql);
  2486. if ($result) {
  2487. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2488. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2489. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2490. $num = $this->db->num_rows($result);
  2491. $events = null;
  2492. if (!$forcecombo) {
  2493. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2494. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2495. }
  2496. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2497. $textifempty = '';
  2498. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2499. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2500. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2501. if ($showempty && !is_numeric($showempty)) {
  2502. $textifempty = $langs->trans($showempty);
  2503. } else {
  2504. $textifempty .= $langs->trans("All");
  2505. }
  2506. } else {
  2507. if ($showempty && !is_numeric($showempty)) {
  2508. $textifempty = $langs->trans($showempty);
  2509. }
  2510. }
  2511. if ($showempty) {
  2512. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2513. }
  2514. $i = 0;
  2515. while ($num && $i < $num) {
  2516. $opt = '';
  2517. $optJson = array();
  2518. $objp = $this->db->fetch_object($result);
  2519. 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
  2520. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2521. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2522. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2523. $sql .= " ORDER BY quantity ASC";
  2524. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2525. $result2 = $this->db->query($sql);
  2526. if ($result2) {
  2527. $nb_prices = $this->db->num_rows($result2);
  2528. $j = 0;
  2529. while ($nb_prices && $j < $nb_prices) {
  2530. $objp2 = $this->db->fetch_object($result2);
  2531. $objp->price_by_qty_rowid = $objp2->rowid;
  2532. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2533. $objp->price_by_qty_quantity = $objp2->quantity;
  2534. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2535. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2536. // For backward compatibility
  2537. $objp->quantity = $objp2->quantity;
  2538. $objp->price = $objp2->price;
  2539. $objp->unitprice = $objp2->unitprice;
  2540. $objp->remise_percent = $objp2->remise_percent;
  2541. //$objp->tva_tx is not overwritten by $objp2 value
  2542. //$objp->default_vat_code is not overwritten by $objp2 value
  2543. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2544. $j++;
  2545. // Add new entry
  2546. // "key" value of json key array is used by jQuery automatically as selected value
  2547. // "label" value of json key array is used by jQuery automatically as text for combo box
  2548. $out .= $opt;
  2549. array_push($outarray, $optJson);
  2550. }
  2551. }
  2552. } else {
  2553. if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
  2554. $price_product = new Product($this->db);
  2555. $price_product->fetch($objp->rowid, '', '', 1);
  2556. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2557. $priceparser = new PriceParser($this->db);
  2558. $price_result = $priceparser->parseProduct($price_product);
  2559. if ($price_result >= 0) {
  2560. $objp->price = $price_result;
  2561. $objp->unitprice = $price_result;
  2562. //Calculate the VAT
  2563. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2564. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2565. }
  2566. }
  2567. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2568. // Add new entry
  2569. // "key" value of json key array is used by jQuery automatically as selected value
  2570. // "label" value of json key array is used by jQuery automatically as text for combo box
  2571. $out .= $opt;
  2572. array_push($outarray, $optJson);
  2573. }
  2574. $i++;
  2575. }
  2576. $out .= '</select>';
  2577. $this->db->free($result);
  2578. if (empty($outputmode)) {
  2579. return $out;
  2580. }
  2581. return $outarray;
  2582. } else {
  2583. dol_print_error($this->db);
  2584. }
  2585. return '';
  2586. }
  2587. /**
  2588. * Function to forge the string with OPTIONs of SELECT.
  2589. * This define value for &$opt and &$optJson.
  2590. * This function is called by select_produits_list().
  2591. *
  2592. * @param object $objp Resultset of fetch
  2593. * @param string $opt Option (var used for returned value in string option format)
  2594. * @param string $optJson Option (var used for returned value in json format)
  2595. * @param int $price_level Price level
  2596. * @param string $selected Preselected value
  2597. * @param int $hidepriceinlabel Hide price in label
  2598. * @param string $filterkey Filter key to highlight
  2599. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2600. * @return void
  2601. */
  2602. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2603. {
  2604. global $langs, $conf, $user;
  2605. $outkey = '';
  2606. $outval = '';
  2607. $outref = '';
  2608. $outlabel = '';
  2609. $outlabel_translated = '';
  2610. $outdesc = '';
  2611. $outdesc_translated = '';
  2612. $outbarcode = '';
  2613. $outorigin = '';
  2614. $outtype = '';
  2615. $outprice_ht = '';
  2616. $outprice_ttc = '';
  2617. $outpricebasetype = '';
  2618. $outtva_tx = '';
  2619. $outdefault_vat_code = '';
  2620. $outqty = 1;
  2621. $outdiscount = 0;
  2622. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2623. $label = $objp->label;
  2624. if (!empty($objp->label_translated)) {
  2625. $label = $objp->label_translated;
  2626. }
  2627. if (!empty($filterkey) && $filterkey != '') {
  2628. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2629. }
  2630. $outkey = $objp->rowid;
  2631. $outref = $objp->ref;
  2632. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2633. $outlabel = $objp->label;
  2634. $outdesc = $objp->description;
  2635. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2636. $outlabel_translated = $objp->label_translated;
  2637. $outdesc_translated = $objp->description_translated;
  2638. }
  2639. $outbarcode = $objp->barcode;
  2640. $outorigin = $objp->fk_country;
  2641. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2642. $outtype = $objp->fk_product_type;
  2643. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2644. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2645. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2646. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2647. }
  2648. // Units
  2649. $outvalUnits = '';
  2650. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2651. if (!empty($objp->unit_short)) {
  2652. $outvalUnits .= ' - '.$objp->unit_short;
  2653. }
  2654. }
  2655. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2656. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2657. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2658. $outvalUnits .= ' - '.$unitToShow;
  2659. }
  2660. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2661. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2662. $outvalUnits .= ' - '.$unitToShow;
  2663. }
  2664. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2665. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2666. $outvalUnits .= ' - '.$unitToShow;
  2667. }
  2668. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2669. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2670. $outvalUnits .= ' - '.$unitToShow;
  2671. }
  2672. }
  2673. if ($outdurationvalue && $outdurationunit) {
  2674. $da = array(
  2675. 'h' => $langs->trans('Hour'),
  2676. 'd' => $langs->trans('Day'),
  2677. 'w' => $langs->trans('Week'),
  2678. 'm' => $langs->trans('Month'),
  2679. 'y' => $langs->trans('Year')
  2680. );
  2681. if (isset($da[$outdurationunit])) {
  2682. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2683. }
  2684. }
  2685. $opt = '<option value="'.$objp->rowid.'"';
  2686. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2687. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2688. $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.'"';
  2689. }
  2690. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2691. if (!empty($user->rights->stock->lire)) {
  2692. if ($objp->stock > 0) {
  2693. $opt .= ' class="product_line_stock_ok"';
  2694. } elseif ($objp->stock <= 0) {
  2695. $opt .= ' class="product_line_stock_too_low"';
  2696. }
  2697. }
  2698. }
  2699. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2700. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2701. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2702. }
  2703. $opt .= '>';
  2704. $opt .= $objp->ref;
  2705. if (!empty($objp->custref)) {
  2706. $opt.= ' (' . $objp->custref . ')';
  2707. }
  2708. if ($outbarcode) {
  2709. $opt .= ' ('.$outbarcode.')';
  2710. }
  2711. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2712. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2713. $opt .= ' ('.getCountry($outorigin, 1).')';
  2714. }
  2715. $objRef = $objp->ref;
  2716. if (!empty($objp->custref)) {
  2717. $objRef .= ' (' . $objp->custref . ')';
  2718. }
  2719. if (!empty($filterkey) && $filterkey != '') {
  2720. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2721. }
  2722. $outval .= $objRef;
  2723. if ($outbarcode) {
  2724. $outval .= ' ('.$outbarcode.')';
  2725. }
  2726. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2727. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2728. $outval .= ' ('.getCountry($outorigin, 1).')';
  2729. }
  2730. // Units
  2731. $opt .= $outvalUnits;
  2732. $outval .= $outvalUnits;
  2733. $found = 0;
  2734. // Multiprice
  2735. // If we need a particular price level (from 1 to n)
  2736. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2737. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2738. $sql .= " FROM ".$this->db->prefix()."product_price";
  2739. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2740. $sql .= " AND entity IN (".getEntity('productprice').")";
  2741. $sql .= " AND price_level = ".((int) $price_level);
  2742. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2743. $sql .= " LIMIT 1";
  2744. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2745. $result2 = $this->db->query($sql);
  2746. if ($result2) {
  2747. $objp2 = $this->db->fetch_object($result2);
  2748. if ($objp2) {
  2749. $found = 1;
  2750. if ($objp2->price_base_type == 'HT') {
  2751. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2752. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2753. } else {
  2754. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2755. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2756. }
  2757. $outprice_ht = price($objp2->price);
  2758. $outprice_ttc = price($objp2->price_ttc);
  2759. $outpricebasetype = $objp2->price_base_type;
  2760. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2761. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2762. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2763. } else {
  2764. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2765. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2766. }
  2767. }
  2768. } else {
  2769. dol_print_error($this->db);
  2770. }
  2771. }
  2772. // Price by quantity
  2773. 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))) {
  2774. $found = 1;
  2775. $outqty = $objp->quantity;
  2776. $outdiscount = $objp->remise_percent;
  2777. if ($objp->quantity == 1) {
  2778. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2779. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2780. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2781. $outval .= $langs->transnoentities("Unit");
  2782. } else {
  2783. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2784. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2785. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2786. $outval .= $langs->transnoentities("Units");
  2787. }
  2788. $outprice_ht = price($objp->unitprice);
  2789. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2790. $outpricebasetype = $objp->price_base_type;
  2791. $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
  2792. $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
  2793. }
  2794. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2795. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2796. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2797. }
  2798. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2799. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2800. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2801. }
  2802. // Price by customer
  2803. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2804. if (!empty($objp->idprodcustprice)) {
  2805. $found = 1;
  2806. if ($objp->custprice_base_type == 'HT') {
  2807. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2808. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2809. } else {
  2810. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2811. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2812. }
  2813. $outprice_ht = price($objp->custprice);
  2814. $outprice_ttc = price($objp->custprice_ttc);
  2815. $outpricebasetype = $objp->custprice_base_type;
  2816. $outtva_tx = $objp->custtva_tx;
  2817. $outdefault_vat_code = $objp->custdefault_vat_code;
  2818. }
  2819. }
  2820. // If level no defined or multiprice not found, we used the default price
  2821. if (empty($hidepriceinlabel) && !$found) {
  2822. if ($objp->price_base_type == 'HT') {
  2823. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2824. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2825. } else {
  2826. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2827. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2828. }
  2829. $outprice_ht = price($objp->price);
  2830. $outprice_ttc = price($objp->price_ttc);
  2831. $outpricebasetype = $objp->price_base_type;
  2832. $outtva_tx = $objp->tva_tx;
  2833. $outdefault_vat_code = $objp->default_vat_code;
  2834. }
  2835. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2836. if (!empty($user->rights->stock->lire)) {
  2837. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2838. if ($objp->stock > 0) {
  2839. $outval .= ' - <span class="product_line_stock_ok">';
  2840. } elseif ($objp->stock <= 0) {
  2841. $outval .= ' - <span class="product_line_stock_too_low">';
  2842. }
  2843. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2844. $outval .= '</span>';
  2845. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2846. $langs->load("stocks");
  2847. $tmpproduct = new Product($this->db);
  2848. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2849. $tmpproduct->load_virtual_stock();
  2850. $virtualstock = $tmpproduct->stock_theorique;
  2851. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2852. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2853. if ($virtualstock > 0) {
  2854. $outval .= '<span class="product_line_stock_ok">';
  2855. } elseif ($virtualstock <= 0) {
  2856. $outval .= '<span class="product_line_stock_too_low">';
  2857. }
  2858. $outval .= $virtualstock;
  2859. $outval .= '</span>';
  2860. unset($tmpproduct);
  2861. }
  2862. }
  2863. }
  2864. $opt .= "</option>\n";
  2865. $optJson = array(
  2866. 'key'=>$outkey,
  2867. 'value'=>$outref,
  2868. 'label'=>$outval,
  2869. 'label2'=>$outlabel,
  2870. 'desc'=>$outdesc,
  2871. 'type'=>$outtype,
  2872. 'price_ht'=>price2num($outprice_ht),
  2873. 'price_ttc'=>price2num($outprice_ttc),
  2874. 'price_ht_locale'=>price(price2num($outprice_ht)),
  2875. 'price_ttc_locale'=>price(price2num($outprice_ttc)),
  2876. 'pricebasetype'=>$outpricebasetype,
  2877. 'tva_tx'=>$outtva_tx,
  2878. 'default_vat_code'=>$outdefault_vat_code,
  2879. 'qty'=>$outqty,
  2880. 'discount'=>$outdiscount,
  2881. 'duration_value'=>$outdurationvalue,
  2882. 'duration_unit'=>$outdurationunit,
  2883. 'pbq'=>$outpbq,
  2884. 'labeltrans'=>$outlabel_translated,
  2885. 'desctrans'=>$outdesc_translated,
  2886. 'ref_customer'=>$outrefcust
  2887. );
  2888. }
  2889. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2890. /**
  2891. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2892. *
  2893. * @param int $socid Id third party
  2894. * @param string $selected Preselected product
  2895. * @param string $htmlname Name of HTML Select
  2896. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2897. * @param string $filtre For a SQL filter
  2898. * @param array $ajaxoptions Options for ajax_autocompleter
  2899. * @param int $hidelabel Hide label (0=no, 1=yes)
  2900. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2901. * @param string $morecss More CSS
  2902. * @param string $placeholder Placeholder
  2903. * @return void
  2904. */
  2905. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2906. {
  2907. // phpcs:enable
  2908. global $langs, $conf;
  2909. global $price_level, $status, $finished;
  2910. if (!isset($status)) {
  2911. $status = 1;
  2912. }
  2913. $selected_input_value = '';
  2914. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2915. if ($selected > 0) {
  2916. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2917. $producttmpselect = new Product($this->db);
  2918. $producttmpselect->fetch($selected);
  2919. $selected_input_value = $producttmpselect->ref;
  2920. unset($producttmpselect);
  2921. }
  2922. // mode=2 means suppliers products
  2923. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2924. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2925. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2926. } else {
  2927. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2928. }
  2929. }
  2930. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2931. /**
  2932. * Return list of suppliers products
  2933. *
  2934. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2935. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2936. * @param string $htmlname Name of HTML select
  2937. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2938. * @param string $filtre Generic filter. Data must not come from user input.
  2939. * @param string $filterkey Filter of produdts
  2940. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2941. * @param int $outputmode 0=HTML select string, 1=Array
  2942. * @param int $limit Limit of line number
  2943. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2944. * @param string $morecss Add more CSS
  2945. * @param int $showstockinlist Show stock information (slower).
  2946. * @param string $placeholder Placeholder
  2947. * @return array|string Array of keys for json
  2948. */
  2949. 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 = '')
  2950. {
  2951. // phpcs:enable
  2952. global $langs, $conf, $user;
  2953. global $hookmanager;
  2954. $out = '';
  2955. $outarray = array();
  2956. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2957. $langs->load('stocks');
  2958. // Units
  2959. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2960. $langs->load('other');
  2961. }
  2962. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock, p.tva_tx as tva_tx_sale, p.default_vat_code as default_vat_code_sale,";
  2963. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2964. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2965. $sql .= " pfp.supplier_reputation";
  2966. // if we use supplier description of the products
  2967. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2968. $sql .= ", pfp.desc_fourn as description";
  2969. } else {
  2970. $sql .= ", p.description";
  2971. }
  2972. // Units
  2973. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2974. $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";
  2975. }
  2976. if (isModEnabled('barcode')) {
  2977. $sql .= ", pfp.barcode";
  2978. }
  2979. $sql .= " FROM ".$this->db->prefix()."product as p";
  2980. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2981. if ($socid > 0) {
  2982. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2983. }
  2984. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  2985. // Units
  2986. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2987. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2988. }
  2989. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2990. if ($statut != -1) {
  2991. $sql .= " AND p.tobuy = ".((int) $statut);
  2992. }
  2993. if (strval($filtertype) != '') {
  2994. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2995. }
  2996. if (!empty($filtre)) {
  2997. $sql .= " ".$filtre;
  2998. }
  2999. // Add where from hooks
  3000. $parameters = array();
  3001. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3002. $sql .= $hookmanager->resPrint;
  3003. // Add criteria on ref/label
  3004. if ($filterkey != '') {
  3005. $sql .= ' AND (';
  3006. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  3007. // For natural search
  3008. $scrit = explode(' ', $filterkey);
  3009. $i = 0;
  3010. if (count($scrit) > 1) {
  3011. $sql .= "(";
  3012. }
  3013. foreach ($scrit as $crit) {
  3014. if ($i > 0) {
  3015. $sql .= " AND ";
  3016. }
  3017. $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)."%'";
  3018. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  3019. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  3020. }
  3021. $sql .= ")";
  3022. $i++;
  3023. }
  3024. if (count($scrit) > 1) {
  3025. $sql .= ")";
  3026. }
  3027. if (isModEnabled('barcode')) {
  3028. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  3029. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  3030. }
  3031. $sql .= ')';
  3032. }
  3033. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3034. $sql .= $this->db->plimit($limit, 0);
  3035. // Build output string
  3036. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  3037. $result = $this->db->query($sql);
  3038. if ($result) {
  3039. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3040. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  3041. $num = $this->db->num_rows($result);
  3042. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3043. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  3044. if (!$selected) {
  3045. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  3046. } else {
  3047. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  3048. }
  3049. $i = 0;
  3050. while ($i < $num) {
  3051. $objp = $this->db->fetch_object($result);
  3052. if (is_null($objp->idprodfournprice)) {
  3053. // There is no supplier price found, we will use the vat rate for sale
  3054. $objp->tva_tx = $objp->tva_tx_sale;
  3055. $objp->default_vat_code = $objp->default_vat_code_sale;
  3056. }
  3057. $outkey = $objp->idprodfournprice; // id in table of price
  3058. if (!$outkey && $alsoproductwithnosupplierprice) {
  3059. $outkey = 'idprod_'.$objp->rowid; // id of product
  3060. }
  3061. $outref = $objp->ref;
  3062. $outbarcode = $objp->barcode;
  3063. $outqty = 1;
  3064. $outdiscount = 0;
  3065. $outtype = $objp->fk_product_type;
  3066. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3067. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  3068. // Units
  3069. $outvalUnits = '';
  3070. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3071. if (!empty($objp->unit_short)) {
  3072. $outvalUnits .= ' - '.$objp->unit_short;
  3073. }
  3074. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3075. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3076. $outvalUnits .= ' - '.$unitToShow;
  3077. }
  3078. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3079. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  3080. $outvalUnits .= ' - '.$unitToShow;
  3081. }
  3082. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3083. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3084. $outvalUnits .= ' - '.$unitToShow;
  3085. }
  3086. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3087. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3088. $outvalUnits .= ' - '.$unitToShow;
  3089. }
  3090. if ($outdurationvalue && $outdurationunit) {
  3091. $da = array(
  3092. 'h' => $langs->trans('Hour'),
  3093. 'd' => $langs->trans('Day'),
  3094. 'w' => $langs->trans('Week'),
  3095. 'm' => $langs->trans('Month'),
  3096. 'y' => $langs->trans('Year')
  3097. );
  3098. if (isset($da[$outdurationunit])) {
  3099. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  3100. }
  3101. }
  3102. }
  3103. $objRef = $objp->ref;
  3104. if ($filterkey && $filterkey != '') {
  3105. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  3106. }
  3107. $objRefFourn = $objp->ref_fourn;
  3108. if ($filterkey && $filterkey != '') {
  3109. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3110. }
  3111. $label = $objp->label;
  3112. if ($filterkey && $filterkey != '') {
  3113. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  3114. }
  3115. $optlabel = $objp->ref;
  3116. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3117. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  3118. }
  3119. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3120. $optlabel .= ' ('.$outbarcode.')';
  3121. }
  3122. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3123. $outvallabel = $objRef;
  3124. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3125. $outvallabel .= ' ('.$objRefFourn.')';
  3126. }
  3127. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3128. $outvallabel .= ' ('.$outbarcode.')';
  3129. }
  3130. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3131. // Units
  3132. $optlabel .= $outvalUnits;
  3133. $outvallabel .= $outvalUnits;
  3134. if (!empty($objp->idprodfournprice)) {
  3135. $outqty = $objp->quantity;
  3136. $outdiscount = $objp->remise_percent;
  3137. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3138. $prod_supplier = new ProductFournisseur($this->db);
  3139. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3140. $prod_supplier->id = $objp->fk_product;
  3141. $prod_supplier->fourn_qty = $objp->quantity;
  3142. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3143. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3144. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3145. $priceparser = new PriceParser($this->db);
  3146. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3147. if ($price_result >= 0) {
  3148. $objp->fprice = $price_result;
  3149. if ($objp->quantity >= 1) {
  3150. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3151. }
  3152. }
  3153. }
  3154. if ($objp->quantity == 1) {
  3155. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3156. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3157. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3158. $outvallabel .= $langs->transnoentities("Unit");
  3159. } else {
  3160. $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;
  3161. $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;
  3162. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3163. $outvallabel .= ' '.$langs->transnoentities("Units");
  3164. }
  3165. if ($objp->quantity > 1) {
  3166. $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
  3167. $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
  3168. }
  3169. if ($objp->remise_percent >= 1) {
  3170. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3171. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3172. }
  3173. if ($objp->duration) {
  3174. $optlabel .= " - ".$objp->duration;
  3175. $outvallabel .= " - ".$objp->duration;
  3176. }
  3177. if (!$socid) {
  3178. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3179. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3180. }
  3181. if ($objp->supplier_reputation) {
  3182. //TODO dictionary
  3183. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3184. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3185. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3186. }
  3187. } else {
  3188. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3189. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3190. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3191. } else // No supplier price defined for product, even on other suppliers
  3192. {
  3193. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3194. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3195. }
  3196. }
  3197. if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3198. $novirtualstock = ($showstockinlist == 2);
  3199. if (!empty($user->rights->stock->lire)) {
  3200. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3201. if ($objp->stock > 0) {
  3202. $optlabel .= ' - <span class="product_line_stock_ok">';
  3203. } elseif ($objp->stock <= 0) {
  3204. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3205. }
  3206. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3207. $optlabel .= '</span>';
  3208. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3209. $langs->load("stocks");
  3210. $tmpproduct = new Product($this->db);
  3211. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3212. $tmpproduct->load_virtual_stock();
  3213. $virtualstock = $tmpproduct->stock_theorique;
  3214. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3215. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3216. if ($virtualstock > 0) {
  3217. $optlabel .= '<span class="product_line_stock_ok">';
  3218. } elseif ($virtualstock <= 0) {
  3219. $optlabel .= '<span class="product_line_stock_too_low">';
  3220. }
  3221. $optlabel .= $virtualstock;
  3222. $optlabel .= '</span>';
  3223. unset($tmpproduct);
  3224. }
  3225. }
  3226. }
  3227. $optstart = '<option value="'.$outkey.'"';
  3228. if ($selected && $selected == $objp->idprodfournprice) {
  3229. $optstart .= ' selected';
  3230. }
  3231. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3232. $optstart .= ' disabled';
  3233. }
  3234. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3235. $optstart .= ' data-product-id="'.dol_escape_htmltag($objp->rowid).'"';
  3236. $optstart .= ' data-price-id="'.dol_escape_htmltag($objp->idprodfournprice).'"';
  3237. $optstart .= ' data-qty="'.dol_escape_htmltag($objp->quantity).'"';
  3238. $optstart .= ' data-up="'.dol_escape_htmltag(price2num($objp->unitprice)).'"';
  3239. $optstart .= ' data-up-locale="'.dol_escape_htmltag(price($objp->unitprice)).'"';
  3240. $optstart .= ' data-discount="'.dol_escape_htmltag($outdiscount).'"';
  3241. $optstart .= ' data-tvatx="'.dol_escape_htmltag(price2num($objp->tva_tx)).'"';
  3242. $optstart .= ' data-tvatx-formated="'.dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)).'"';
  3243. $optstart .= ' data-default-vat-code="'.dol_escape_htmltag($objp->default_vat_code).'"';
  3244. }
  3245. $optstart .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3246. $outarrayentry = array(
  3247. 'key' => $outkey,
  3248. 'value' => $outref,
  3249. 'label' => $outvallabel,
  3250. 'qty' => $outqty,
  3251. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3252. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3253. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3254. 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
  3255. 'tva_tx' => price2num($objp->tva_tx),
  3256. 'default_vat_code' => $objp->default_vat_code,
  3257. 'discount' => $outdiscount,
  3258. 'type' => $outtype,
  3259. 'duration_value' => $outdurationvalue,
  3260. 'duration_unit' => $outdurationunit,
  3261. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3262. 'description' => $objp->description
  3263. );
  3264. $parameters = array(
  3265. 'objp' => &$objp,
  3266. 'optstart' => &$optstart,
  3267. 'optlabel' => &$optlabel,
  3268. 'outvallabel' => &$outvallabel,
  3269. 'outarrayentry' => &$outarrayentry
  3270. );
  3271. $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
  3272. // Add new entry
  3273. // "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
  3274. // "label" value of json key array is used by jQuery automatically as text for combo box
  3275. $out .= $optstart . ' data-html="'.dol_escape_htmltag($optlabel).'">' . $optlabel . "</option>\n";
  3276. array_push(
  3277. $outarray,
  3278. array('key'=>$outkey,
  3279. 'value'=>$outref,
  3280. 'label'=>$outvallabel,
  3281. 'qty'=>$outqty,
  3282. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3283. 'price_qty_ht_locale'=>price($objp->fprice),
  3284. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3285. 'price_unit_ht_locale'=>price($objp->unitprice),
  3286. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3287. 'tva_tx_formated' => price($objp->tva_tx),
  3288. 'tva_tx'=>price2num($objp->tva_tx),
  3289. 'default_vat_code'=>$objp->default_vat_code,
  3290. 'discount'=>$outdiscount,
  3291. 'type'=>$outtype,
  3292. 'duration_value'=>$outdurationvalue,
  3293. 'duration_unit'=>$outdurationunit,
  3294. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3295. 'description'=>$objp->description
  3296. )
  3297. );
  3298. // Exemple of var_dump $outarray
  3299. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3300. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3301. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3302. //}
  3303. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3304. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3305. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3306. $i++;
  3307. }
  3308. $out .= '</select>';
  3309. $this->db->free($result);
  3310. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3311. $out .= ajax_combobox($htmlname);
  3312. if (empty($outputmode)) {
  3313. return $out;
  3314. }
  3315. return $outarray;
  3316. } else {
  3317. dol_print_error($this->db);
  3318. }
  3319. return '';
  3320. }
  3321. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3322. /**
  3323. * Return list of suppliers prices for a product
  3324. *
  3325. * @param int $productid Id of product
  3326. * @param string $htmlname Name of HTML field
  3327. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3328. * @return string
  3329. */
  3330. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3331. {
  3332. // phpcs:enable
  3333. global $langs, $conf;
  3334. $langs->load('stocks');
  3335. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3336. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3337. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3338. $sql .= " FROM ".$this->db->prefix()."product as p";
  3339. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3340. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  3341. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3342. $sql .= " AND p.tobuy = 1";
  3343. $sql .= " AND s.fournisseur = 1";
  3344. $sql .= " AND p.rowid = ".((int) $productid);
  3345. if (empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED)) {
  3346. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3347. } else {
  3348. $sql .= " ORDER BY pfp.unitprice ASC";
  3349. }
  3350. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3351. $result = $this->db->query($sql);
  3352. if ($result) {
  3353. $num = $this->db->num_rows($result);
  3354. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3355. if (!$num) {
  3356. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3357. } else {
  3358. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3359. $form .= '<option value="0">&nbsp;</option>';
  3360. $i = 0;
  3361. while ($i < $num) {
  3362. $objp = $this->db->fetch_object($result);
  3363. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3364. //if there is only one supplier, preselect it
  3365. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && !empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED))) {
  3366. $opt .= ' selected';
  3367. }
  3368. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3369. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3370. $prod_supplier = new ProductFournisseur($this->db);
  3371. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3372. $prod_supplier->id = $productid;
  3373. $prod_supplier->fourn_qty = $objp->quantity;
  3374. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3375. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3376. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3377. $priceparser = new PriceParser($this->db);
  3378. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3379. if ($price_result >= 0) {
  3380. $objp->fprice = $price_result;
  3381. if ($objp->quantity >= 1) {
  3382. $objp->unitprice = $objp->fprice / $objp->quantity;
  3383. }
  3384. }
  3385. }
  3386. if ($objp->quantity == 1) {
  3387. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3388. }
  3389. $opt .= $objp->quantity.' ';
  3390. if ($objp->quantity == 1) {
  3391. $opt .= $langs->trans("Unit");
  3392. } else {
  3393. $opt .= $langs->trans("Units");
  3394. }
  3395. if ($objp->quantity > 1) {
  3396. $opt .= " - ";
  3397. $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");
  3398. }
  3399. if ($objp->duration) {
  3400. $opt .= " - ".$objp->duration;
  3401. }
  3402. $opt .= "</option>\n";
  3403. $form .= $opt;
  3404. $i++;
  3405. }
  3406. }
  3407. $form .= '</select>';
  3408. $this->db->free($result);
  3409. return $form;
  3410. } else {
  3411. dol_print_error($this->db);
  3412. return '';
  3413. }
  3414. }
  3415. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3416. /**
  3417. * Return list of delivery address
  3418. *
  3419. * @param string $selected Id contact pre-selectionn
  3420. * @param int $socid Id of company
  3421. * @param string $htmlname Name of HTML field
  3422. * @param int $showempty Add an empty field
  3423. * @return integer|null
  3424. */
  3425. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3426. {
  3427. // phpcs:enable
  3428. // looking for users
  3429. $sql = "SELECT a.rowid, a.label";
  3430. $sql .= " FROM ".$this->db->prefix()."societe_address as a";
  3431. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3432. $sql .= " ORDER BY a.label ASC";
  3433. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3434. $resql = $this->db->query($sql);
  3435. if ($resql) {
  3436. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3437. if ($showempty) {
  3438. print '<option value="0">&nbsp;</option>';
  3439. }
  3440. $num = $this->db->num_rows($resql);
  3441. $i = 0;
  3442. if ($num) {
  3443. while ($i < $num) {
  3444. $obj = $this->db->fetch_object($resql);
  3445. if ($selected && $selected == $obj->rowid) {
  3446. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3447. } else {
  3448. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3449. }
  3450. $i++;
  3451. }
  3452. }
  3453. print '</select>';
  3454. return $num;
  3455. } else {
  3456. dol_print_error($this->db);
  3457. return;
  3458. }
  3459. }
  3460. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3461. /**
  3462. * Load into cache list of payment terms
  3463. *
  3464. * @return int Nb of lines loaded, <0 if KO
  3465. */
  3466. public function load_cache_conditions_paiements()
  3467. {
  3468. // phpcs:enable
  3469. global $langs;
  3470. $num = count($this->cache_conditions_paiements);
  3471. if ($num > 0) {
  3472. return 0; // Cache already loaded
  3473. }
  3474. dol_syslog(__METHOD__, LOG_DEBUG);
  3475. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3476. $sql .= " FROM ".$this->db->prefix().'c_payment_term';
  3477. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3478. $sql .= " AND active > 0";
  3479. $sql .= " ORDER BY sortorder";
  3480. $resql = $this->db->query($sql);
  3481. if ($resql) {
  3482. $num = $this->db->num_rows($resql);
  3483. $i = 0;
  3484. while ($i < $num) {
  3485. $obj = $this->db->fetch_object($resql);
  3486. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3487. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3488. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3489. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3490. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3491. $i++;
  3492. }
  3493. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3494. return $num;
  3495. } else {
  3496. dol_print_error($this->db);
  3497. return -1;
  3498. }
  3499. }
  3500. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3501. /**
  3502. * Load int a cache property th elist of possible delivery delays.
  3503. *
  3504. * @return int Nb of lines loaded, <0 if KO
  3505. */
  3506. public function load_cache_availability()
  3507. {
  3508. // phpcs:enable
  3509. global $langs;
  3510. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3511. if ($num > 0) {
  3512. return 0; // Cache already loaded
  3513. }
  3514. dol_syslog(__METHOD__, LOG_DEBUG);
  3515. $langs->load('propal');
  3516. $sql = "SELECT rowid, code, label, position";
  3517. $sql .= " FROM ".$this->db->prefix().'c_availability';
  3518. $sql .= " WHERE active > 0";
  3519. $resql = $this->db->query($sql);
  3520. if ($resql) {
  3521. $num = $this->db->num_rows($resql);
  3522. $i = 0;
  3523. while ($i < $num) {
  3524. $obj = $this->db->fetch_object($resql);
  3525. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3526. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3527. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3528. $this->cache_availability[$obj->rowid]['label'] = $label;
  3529. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3530. $i++;
  3531. }
  3532. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3533. return $num;
  3534. } else {
  3535. dol_print_error($this->db);
  3536. return -1;
  3537. }
  3538. }
  3539. /**
  3540. * Retourne la liste des types de delais de livraison possibles
  3541. *
  3542. * @param int $selected Id du type de delais pre-selectionne
  3543. * @param string $htmlname Nom de la zone select
  3544. * @param string $filtertype To add a filter
  3545. * @param int $addempty Add empty entry
  3546. * @param string $morecss More CSS
  3547. * @return void
  3548. */
  3549. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3550. {
  3551. global $langs, $user;
  3552. $this->load_cache_availability();
  3553. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3554. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3555. if ($addempty) {
  3556. print '<option value="0">&nbsp;</option>';
  3557. }
  3558. foreach ($this->cache_availability as $id => $arrayavailability) {
  3559. if ($selected == $id) {
  3560. print '<option value="'.$id.'" selected>';
  3561. } else {
  3562. print '<option value="'.$id.'">';
  3563. }
  3564. print dol_escape_htmltag($arrayavailability['label']);
  3565. print '</option>';
  3566. }
  3567. print '</select>';
  3568. if ($user->admin) {
  3569. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3570. }
  3571. print ajax_combobox($htmlname);
  3572. }
  3573. /**
  3574. * Load into cache cache_demand_reason, array of input reasons
  3575. *
  3576. * @return int Nb of lines loaded, <0 if KO
  3577. */
  3578. public function loadCacheInputReason()
  3579. {
  3580. global $langs;
  3581. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3582. if ($num > 0) {
  3583. return 0; // Cache already loaded
  3584. }
  3585. $sql = "SELECT rowid, code, label";
  3586. $sql .= " FROM ".$this->db->prefix().'c_input_reason';
  3587. $sql .= " WHERE active > 0";
  3588. $resql = $this->db->query($sql);
  3589. if ($resql) {
  3590. $num = $this->db->num_rows($resql);
  3591. $i = 0;
  3592. $tmparray = array();
  3593. while ($i < $num) {
  3594. $obj = $this->db->fetch_object($resql);
  3595. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3596. $label = ($obj->label != '-' ? $obj->label : '');
  3597. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3598. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3599. }
  3600. if ($langs->trans($obj->code) != $obj->code) {
  3601. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3602. }
  3603. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3604. $tmparray[$obj->rowid]['code'] = $obj->code;
  3605. $tmparray[$obj->rowid]['label'] = $label;
  3606. $i++;
  3607. }
  3608. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3609. unset($tmparray);
  3610. return $num;
  3611. } else {
  3612. dol_print_error($this->db);
  3613. return -1;
  3614. }
  3615. }
  3616. /**
  3617. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3618. * List found into table c_input_reason loaded by loadCacheInputReason
  3619. *
  3620. * @param int $selected Id or code of type origin to select by default
  3621. * @param string $htmlname Nom de la zone select
  3622. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3623. * @param int $addempty Add an empty entry
  3624. * @param string $morecss Add more css to the HTML select component
  3625. * @param int $notooltip Do not show the tooltip for admin
  3626. * @return void
  3627. */
  3628. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3629. {
  3630. global $langs, $user;
  3631. $this->loadCacheInputReason();
  3632. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3633. if ($addempty) {
  3634. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3635. }
  3636. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3637. if ($arraydemandreason['code'] == $exclude) {
  3638. continue;
  3639. }
  3640. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3641. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3642. } else {
  3643. print '<option value="'.$arraydemandreason['id'].'">';
  3644. }
  3645. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3646. print $langs->trans($label);
  3647. print '</option>';
  3648. }
  3649. print '</select>';
  3650. if ($user->admin && empty($notooltip)) {
  3651. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3652. }
  3653. print ajax_combobox('select_'.$htmlname);
  3654. }
  3655. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3656. /**
  3657. * Charge dans cache la liste des types de paiements possibles
  3658. *
  3659. * @return int Nb of lines loaded, <0 if KO
  3660. */
  3661. public function load_cache_types_paiements()
  3662. {
  3663. // phpcs:enable
  3664. global $langs;
  3665. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3666. if ($num > 0) {
  3667. return $num; // Cache already loaded
  3668. }
  3669. dol_syslog(__METHOD__, LOG_DEBUG);
  3670. $this->cache_types_paiements = array();
  3671. $sql = "SELECT id, code, libelle as label, type, active";
  3672. $sql .= " FROM ".$this->db->prefix()."c_paiement";
  3673. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3674. $resql = $this->db->query($sql);
  3675. if ($resql) {
  3676. $num = $this->db->num_rows($resql);
  3677. $i = 0;
  3678. while ($i < $num) {
  3679. $obj = $this->db->fetch_object($resql);
  3680. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3681. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3682. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3683. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3684. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3685. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3686. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3687. $i++;
  3688. }
  3689. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3690. return $num;
  3691. } else {
  3692. dol_print_error($this->db);
  3693. return -1;
  3694. }
  3695. }
  3696. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3697. /**
  3698. * print list of payment modes.
  3699. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3700. * See instead to force the default value by the caller.
  3701. *
  3702. * @param int $selected Id of payment term to preselect by default
  3703. * @param string $htmlname Nom de la zone select
  3704. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3705. * @param int $addempty Add an empty entry
  3706. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3707. * @param string $morecss Add more CSS on select tag
  3708. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3709. * 0 : use default deposit percentage from entry
  3710. * > 0 : force deposit percentage (for example, from company object)
  3711. * @return void
  3712. * @deprecated
  3713. */
  3714. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3715. {
  3716. // phpcs:enable
  3717. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent = -1);
  3718. }
  3719. /**
  3720. * Return list of payment modes.
  3721. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3722. * See instead to force the default value by the caller.
  3723. *
  3724. * @param int $selected Id of payment term to preselect by default
  3725. * @param string $htmlname Nom de la zone select
  3726. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3727. * @param int $addempty Add an empty entry
  3728. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3729. * @param string $morecss Add more CSS on select tag
  3730. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3731. * 0 : use default deposit percentage from entry
  3732. * > 0 : force deposit percentage (for example, from company object)
  3733. * @return string String for the HTML select component
  3734. */
  3735. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3736. {
  3737. global $langs, $user, $conf;
  3738. $out = '';
  3739. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3740. $this->load_cache_conditions_paiements();
  3741. // Set default value if not already set by caller
  3742. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3743. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3744. }
  3745. $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3746. if ($addempty) {
  3747. $out.= '<option value="0">&nbsp;</option>';
  3748. }
  3749. $selectedDepositPercent = null;
  3750. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3751. if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
  3752. continue;
  3753. }
  3754. if ($selected == $id) {
  3755. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3756. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3757. } else {
  3758. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3759. }
  3760. $label = $arrayconditions['label'];
  3761. if (!empty($arrayconditions['deposit_percent'])) {
  3762. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3763. }
  3764. $out.= $label;
  3765. $out.= '</option>';
  3766. }
  3767. $out.= '</select>';
  3768. if ($user->admin && empty($noinfoadmin)) {
  3769. $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3770. }
  3771. $out.= ajax_combobox($htmlname);
  3772. if ($deposit_percent >= 0) {
  3773. $out .= ' <span id="'.$htmlname.'_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3774. $out .= $langs->trans('DepositPercent') . ' : ';
  3775. $out .= '<input id="'.$htmlname.'_deposit_percent" name="'.$htmlname.'_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
  3776. $out .= '</span>';
  3777. $out .= '
  3778. <script>
  3779. $(document).ready(function () {
  3780. $("#' . $htmlname . '").change(function () {
  3781. let $selected = $(this).find("option:selected");
  3782. let depositPercent = $selected.attr("data-deposit_percent");
  3783. if (depositPercent.length > 0) {
  3784. $("#'.$htmlname.'_deposit_percent_container").show().find("#'.$htmlname.'_deposit_percent").val(depositPercent);
  3785. } else {
  3786. $("#'.$htmlname.'_deposit_percent_container").hide();
  3787. }
  3788. return true;
  3789. });
  3790. });
  3791. </script>';
  3792. }
  3793. return $out;
  3794. }
  3795. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3796. /**
  3797. * Return list of payment methods
  3798. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3799. *
  3800. * @param string $selected Id or code or preselected payment mode
  3801. * @param string $htmlname Name of select field
  3802. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3803. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3804. * @param int $empty 1=can be empty, 0 otherwise
  3805. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3806. * @param int $maxlength Max length of label
  3807. * @param int $active Active or not, -1 = all
  3808. * @param string $morecss Add more CSS on select tag
  3809. * @param int $nooutput 1=Return string, do not send to output
  3810. * @return string|void String for the HTML select component
  3811. */
  3812. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3813. {
  3814. // phpcs:enable
  3815. global $langs, $user, $conf;
  3816. $out = '';
  3817. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3818. $filterarray = array();
  3819. if ($filtertype == 'CRDT') {
  3820. $filterarray = array(0, 2, 3);
  3821. } elseif ($filtertype == 'DBIT') {
  3822. $filterarray = array(1, 2, 3);
  3823. } elseif ($filtertype != '' && $filtertype != '-1') {
  3824. $filterarray = explode(',', $filtertype);
  3825. }
  3826. $this->load_cache_types_paiements();
  3827. // Set default value if not already set by caller
  3828. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3829. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3830. }
  3831. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3832. if ($empty) {
  3833. $out .= '<option value="">&nbsp;</option>';
  3834. }
  3835. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3836. // If not good status
  3837. if ($active >= 0 && $arraytypes['active'] != $active) {
  3838. continue;
  3839. }
  3840. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3841. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3842. continue;
  3843. }
  3844. // We discard empty line if showempty is on because an empty line has already been output.
  3845. if ($empty && empty($arraytypes['code'])) {
  3846. continue;
  3847. }
  3848. if ($format == 0) {
  3849. $out .= '<option value="'.$id.'"';
  3850. } elseif ($format == 1) {
  3851. $out .= '<option value="'.$arraytypes['code'].'"';
  3852. } elseif ($format == 2) {
  3853. $out .= '<option value="'.$arraytypes['code'].'"';
  3854. } elseif ($format == 3) {
  3855. $out .= '<option value="'.$id.'"';
  3856. }
  3857. // Print attribute selected or not
  3858. if ($format == 1 || $format == 2) {
  3859. if ($selected == $arraytypes['code']) {
  3860. $out .= ' selected';
  3861. }
  3862. } else {
  3863. if ($selected == $id) {
  3864. $out .= ' selected';
  3865. }
  3866. }
  3867. $out .= '>';
  3868. $value = '';
  3869. if ($format == 0) {
  3870. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3871. } elseif ($format == 1) {
  3872. $value = $arraytypes['code'];
  3873. } elseif ($format == 2) {
  3874. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3875. } elseif ($format == 3) {
  3876. $value = $arraytypes['code'];
  3877. }
  3878. $out .= $value ? $value : '&nbsp;';
  3879. $out .= '</option>';
  3880. }
  3881. $out .= '</select>';
  3882. if ($user->admin && !$noadmininfo) {
  3883. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3884. }
  3885. $out .= ajax_combobox('select'.$htmlname);
  3886. if (empty($nooutput)) {
  3887. print $out;
  3888. } else {
  3889. return $out;
  3890. }
  3891. }
  3892. /**
  3893. * Selection HT or TTC
  3894. *
  3895. * @param string $selected Id pre-selectionne
  3896. * @param string $htmlname Nom de la zone select
  3897. * @param string $addjscombo Add js combo
  3898. * @return string Code of HTML select to chose tax or not
  3899. */
  3900. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3901. {
  3902. global $langs;
  3903. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3904. $options = array(
  3905. 'HT'=>$langs->trans("HT"),
  3906. 'TTC'=>$langs->trans("TTC")
  3907. );
  3908. foreach ($options as $id => $value) {
  3909. if ($selected == $id) {
  3910. $return .= '<option value="'.$id.'" selected>'.$value;
  3911. } else {
  3912. $return .= '<option value="'.$id.'">'.$value;
  3913. }
  3914. $return .= '</option>';
  3915. }
  3916. $return .= '</select>';
  3917. if ($addjscombo) {
  3918. $return .= ajax_combobox('select_'.$htmlname);
  3919. }
  3920. return $return;
  3921. }
  3922. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3923. /**
  3924. * Load in cache list of transport mode
  3925. *
  3926. * @return int Nb of lines loaded, <0 if KO
  3927. */
  3928. public function load_cache_transport_mode()
  3929. {
  3930. // phpcs:enable
  3931. global $langs;
  3932. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3933. if ($num > 0) {
  3934. return $num; // Cache already loaded
  3935. }
  3936. dol_syslog(__METHOD__, LOG_DEBUG);
  3937. $this->cache_transport_mode = array();
  3938. $sql = "SELECT rowid, code, label, active";
  3939. $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
  3940. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3941. $resql = $this->db->query($sql);
  3942. if ($resql) {
  3943. $num = $this->db->num_rows($resql);
  3944. $i = 0;
  3945. while ($i < $num) {
  3946. $obj = $this->db->fetch_object($resql);
  3947. // If traduction exist, we use it else we take the default label
  3948. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3949. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3950. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3951. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3952. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3953. $i++;
  3954. }
  3955. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3956. return $num;
  3957. } else {
  3958. dol_print_error($this->db);
  3959. return -1;
  3960. }
  3961. }
  3962. /**
  3963. * Return list of transport mode for intracomm report
  3964. *
  3965. * @param string $selected Id of the transport mode pre-selected
  3966. * @param string $htmlname Name of the select field
  3967. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3968. * @param int $empty 1=can be empty, 0 else
  3969. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3970. * @param int $maxlength Max length of label
  3971. * @param int $active Active or not, -1 = all
  3972. * @param string $morecss Add more CSS on select tag
  3973. * @return void
  3974. */
  3975. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3976. {
  3977. global $langs, $user;
  3978. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3979. $this->load_cache_transport_mode();
  3980. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3981. if ($empty) {
  3982. print '<option value="">&nbsp;</option>';
  3983. }
  3984. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3985. // If not good status
  3986. if ($active >= 0 && $arraytypes['active'] != $active) {
  3987. continue;
  3988. }
  3989. // We discard empty line if showempty is on because an empty line has already been output.
  3990. if ($empty && empty($arraytypes['code'])) {
  3991. continue;
  3992. }
  3993. if ($format == 0) {
  3994. print '<option value="'.$id.'"';
  3995. } elseif ($format == 1) {
  3996. print '<option value="'.$arraytypes['code'].'"';
  3997. } elseif ($format == 2) {
  3998. print '<option value="'.$arraytypes['code'].'"';
  3999. } elseif ($format == 3) {
  4000. print '<option value="'.$id.'"';
  4001. }
  4002. // If text is selected, we compare with code, else with id
  4003. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  4004. print ' selected';
  4005. } elseif ($selected == $id) {
  4006. print ' selected';
  4007. }
  4008. print '>';
  4009. $value = '';
  4010. if ($format == 0) {
  4011. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4012. } elseif ($format == 1) {
  4013. $value = $arraytypes['code'];
  4014. } elseif ($format == 2) {
  4015. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4016. } elseif ($format == 3) {
  4017. $value = $arraytypes['code'];
  4018. }
  4019. print $value ? $value : '&nbsp;';
  4020. print '</option>';
  4021. }
  4022. print '</select>';
  4023. if ($user->admin && !$noadmininfo) {
  4024. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4025. }
  4026. }
  4027. /**
  4028. * Return a HTML select list of shipping mode
  4029. *
  4030. * @param string $selected Id shipping mode pre-selected
  4031. * @param string $htmlname Name of select zone
  4032. * @param string $filtre To filter list. This parameter must not come from input of users
  4033. * @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.
  4034. * @param string $moreattrib To add more attribute on select
  4035. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  4036. * @param string $morecss More CSS
  4037. * @return void
  4038. */
  4039. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  4040. {
  4041. global $langs, $conf, $user;
  4042. $langs->load("admin");
  4043. $langs->load("deliveries");
  4044. $sql = "SELECT rowid, code, libelle as label";
  4045. $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
  4046. $sql .= " WHERE active > 0";
  4047. if ($filtre) {
  4048. $sql .= " AND ".$filtre;
  4049. }
  4050. $sql .= " ORDER BY libelle ASC";
  4051. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  4052. $result = $this->db->query($sql);
  4053. if ($result) {
  4054. $num = $this->db->num_rows($result);
  4055. $i = 0;
  4056. if ($num) {
  4057. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4058. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4059. print '<option value="-1">&nbsp;</option>';
  4060. }
  4061. while ($i < $num) {
  4062. $obj = $this->db->fetch_object($result);
  4063. if ($selected == $obj->rowid) {
  4064. print '<option value="'.$obj->rowid.'" selected>';
  4065. } else {
  4066. print '<option value="'.$obj->rowid.'">';
  4067. }
  4068. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  4069. print '</option>';
  4070. $i++;
  4071. }
  4072. print "</select>";
  4073. if ($user->admin && empty($noinfoadmin)) {
  4074. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4075. }
  4076. print ajax_combobox('select'.$htmlname);
  4077. } else {
  4078. print $langs->trans("NoShippingMethodDefined");
  4079. }
  4080. } else {
  4081. dol_print_error($this->db);
  4082. }
  4083. }
  4084. /**
  4085. * Display form to select shipping mode
  4086. *
  4087. * @param string $page Page
  4088. * @param int $selected Id of shipping mode
  4089. * @param string $htmlname Name of select html field
  4090. * @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.
  4091. * @return void
  4092. */
  4093. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4094. {
  4095. global $langs;
  4096. $langs->load("deliveries");
  4097. if ($htmlname != "none") {
  4098. print '<form method="POST" action="'.$page.'">';
  4099. print '<input type="hidden" name="action" value="setshippingmethod">';
  4100. print '<input type="hidden" name="token" value="'.newToken().'">';
  4101. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4102. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4103. print '</form>';
  4104. } else {
  4105. if ($selected) {
  4106. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4107. print $langs->trans("SendingMethod".strtoupper($code));
  4108. } else {
  4109. print "&nbsp;";
  4110. }
  4111. }
  4112. }
  4113. /**
  4114. * Creates HTML last in cycle situation invoices selector
  4115. *
  4116. * @param string $selected Preselected ID
  4117. * @param int $socid Company ID
  4118. *
  4119. * @return string HTML select
  4120. */
  4121. public function selectSituationInvoices($selected = '', $socid = 0)
  4122. {
  4123. global $langs;
  4124. $langs->load('bills');
  4125. $opt = '<option value="" selected></option>';
  4126. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4127. $sql .= ' FROM '.$this->db->prefix().'facture';
  4128. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  4129. $sql .= ' AND situation_counter >= 1';
  4130. $sql .= ' AND fk_soc = '.(int) $socid;
  4131. $sql .= ' AND type <> 2';
  4132. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4133. $resql = $this->db->query($sql);
  4134. if ($resql && $this->db->num_rows($resql) > 0) {
  4135. // Last seen cycle
  4136. $ref = 0;
  4137. while ($obj = $this->db->fetch_object($resql)) {
  4138. //Same cycle ?
  4139. if ($obj->situation_cycle_ref != $ref) {
  4140. // Just seen this cycle
  4141. $ref = $obj->situation_cycle_ref;
  4142. //not final ?
  4143. if ($obj->situation_final != 1) {
  4144. //Not prov?
  4145. if (substr($obj->ref, 1, 4) != 'PROV') {
  4146. if ($selected == $obj->rowid) {
  4147. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  4148. } else {
  4149. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  4150. }
  4151. }
  4152. }
  4153. }
  4154. }
  4155. } else {
  4156. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4157. }
  4158. if ($opt == '<option value ="" selected></option>') {
  4159. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  4160. }
  4161. return $opt;
  4162. }
  4163. /**
  4164. * Creates HTML units selector (code => label)
  4165. *
  4166. * @param string $selected Preselected Unit ID
  4167. * @param string $htmlname Select name
  4168. * @param int $showempty Add a nempty line
  4169. * @param string $unit_type Restrict to one given unit type
  4170. * @return string HTML select
  4171. */
  4172. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4173. {
  4174. global $langs;
  4175. $langs->load('products');
  4176. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  4177. $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
  4178. $sql .= ' WHERE active > 0';
  4179. if (!empty($unit_type)) {
  4180. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  4181. }
  4182. $sql .= " ORDER BY sortorder";
  4183. $resql = $this->db->query($sql);
  4184. if ($resql && $this->db->num_rows($resql) > 0) {
  4185. if ($showempty) {
  4186. $return .= '<option value="none"></option>';
  4187. }
  4188. while ($res = $this->db->fetch_object($resql)) {
  4189. $unitLabel = $res->label;
  4190. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  4191. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  4192. }
  4193. if ($selected == $res->rowid) {
  4194. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  4195. } else {
  4196. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  4197. }
  4198. }
  4199. $return .= '</select>';
  4200. }
  4201. return $return;
  4202. }
  4203. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4204. /**
  4205. * Return a HTML select list of bank accounts
  4206. *
  4207. * @param string $selected Id account pre-selected
  4208. * @param string $htmlname Name of select zone
  4209. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4210. * @param string $filtre To filter list. This parameter must not come from input of users
  4211. * @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.
  4212. * @param string $moreattrib To add more attribute on select
  4213. * @param int $showcurrency Show currency in label
  4214. * @param string $morecss More CSS
  4215. * @param int $nooutput 1=Return string, do not send to output
  4216. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4217. */
  4218. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4219. {
  4220. // phpcs:enable
  4221. global $langs, $conf;
  4222. $out = '';
  4223. $langs->load("admin");
  4224. $num = 0;
  4225. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4226. $sql .= " FROM ".$this->db->prefix()."bank_account";
  4227. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  4228. if ($status != 2) {
  4229. $sql .= " AND clos = ".(int) $status;
  4230. }
  4231. if ($filtre) {
  4232. $sql .= " AND ".$filtre;
  4233. }
  4234. $sql .= " ORDER BY label";
  4235. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  4236. $result = $this->db->query($sql);
  4237. if ($result) {
  4238. $num = $this->db->num_rows($result);
  4239. $i = 0;
  4240. if ($num) {
  4241. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4242. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4243. $out .= '<option value="-1">&nbsp;</option>';
  4244. }
  4245. while ($i < $num) {
  4246. $obj = $this->db->fetch_object($result);
  4247. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4248. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  4249. } else {
  4250. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  4251. }
  4252. $out .= trim($obj->label);
  4253. if ($showcurrency) {
  4254. $out .= ' ('.$obj->currency_code.')';
  4255. }
  4256. if ($status == 2 && $obj->status == 1) {
  4257. $out .= ' ('.$langs->trans("Closed").')';
  4258. }
  4259. $out .= '</option>';
  4260. $i++;
  4261. }
  4262. $out .= "</select>";
  4263. $out .= ajax_combobox('select'.$htmlname);
  4264. } else {
  4265. if ($status == 0) {
  4266. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4267. } else {
  4268. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4269. }
  4270. }
  4271. } else {
  4272. dol_print_error($this->db);
  4273. }
  4274. // Output or return
  4275. if (empty($nooutput)) {
  4276. print $out;
  4277. } else {
  4278. return $out;
  4279. }
  4280. return $num;
  4281. }
  4282. /**
  4283. * Return a HTML select list of establishment
  4284. *
  4285. * @param string $selected Id establishment pre-selected
  4286. * @param string $htmlname Name of select zone
  4287. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4288. * @param string $filtre To filter list. This parameter must not come from input of users
  4289. * @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.
  4290. * @param string $moreattrib To add more attribute on select
  4291. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4292. */
  4293. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4294. {
  4295. global $langs, $conf;
  4296. $langs->load("admin");
  4297. $num = 0;
  4298. $sql = "SELECT rowid, name, fk_country, status, entity";
  4299. $sql .= " FROM ".$this->db->prefix()."establishment";
  4300. $sql .= " WHERE 1=1";
  4301. if ($status != 2) {
  4302. $sql .= " AND status = ".(int) $status;
  4303. }
  4304. if ($filtre) {
  4305. $sql .= " AND ".$filtre;
  4306. }
  4307. $sql .= " ORDER BY name";
  4308. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4309. $result = $this->db->query($sql);
  4310. if ($result) {
  4311. $num = $this->db->num_rows($result);
  4312. $i = 0;
  4313. if ($num) {
  4314. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4315. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4316. print '<option value="-1">&nbsp;</option>';
  4317. }
  4318. while ($i < $num) {
  4319. $obj = $this->db->fetch_object($result);
  4320. if ($selected == $obj->rowid) {
  4321. print '<option value="'.$obj->rowid.'" selected>';
  4322. } else {
  4323. print '<option value="'.$obj->rowid.'">';
  4324. }
  4325. print trim($obj->name);
  4326. if ($status == 2 && $obj->status == 1) {
  4327. print ' ('.$langs->trans("Closed").')';
  4328. }
  4329. print '</option>';
  4330. $i++;
  4331. }
  4332. print "</select>";
  4333. } else {
  4334. if ($status == 0) {
  4335. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4336. } else {
  4337. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4338. }
  4339. }
  4340. } else {
  4341. dol_print_error($this->db);
  4342. return -1;
  4343. }
  4344. }
  4345. /**
  4346. * Display form to select bank account
  4347. *
  4348. * @param string $page Page
  4349. * @param int $selected Id of bank account
  4350. * @param string $htmlname Name of select html field
  4351. * @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.
  4352. * @return void
  4353. */
  4354. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4355. {
  4356. global $langs;
  4357. if ($htmlname != "none") {
  4358. print '<form method="POST" action="'.$page.'">';
  4359. print '<input type="hidden" name="action" value="setbankaccount">';
  4360. print '<input type="hidden" name="token" value="'.newToken().'">';
  4361. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4362. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4363. if ($nbaccountfound > 0) {
  4364. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4365. }
  4366. print '</form>';
  4367. } else {
  4368. $langs->load('banks');
  4369. if ($selected) {
  4370. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4371. $bankstatic = new Account($this->db);
  4372. $result = $bankstatic->fetch($selected);
  4373. if ($result) {
  4374. print $bankstatic->getNomUrl(1);
  4375. }
  4376. } else {
  4377. print "&nbsp;";
  4378. }
  4379. }
  4380. }
  4381. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4382. /**
  4383. * Return list of categories having choosed type
  4384. *
  4385. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4386. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4387. * @param string $htmlname HTML field name
  4388. * @param int $maxlength Maximum length for labels
  4389. * @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.
  4390. * $markafterid can be an :
  4391. * - int (id of category)
  4392. * - string (categories ids seprated by comma)
  4393. * - array (list of categories ids)
  4394. * @param int $outputmode 0=HTML select string, 1=Array, 2=Array extended
  4395. * @param int $include [=0] Removed or 1=Keep only
  4396. * @param string $morecss More CSS
  4397. * @return string|array
  4398. * @see select_categories()
  4399. */
  4400. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4401. {
  4402. // phpcs:enable
  4403. global $conf, $langs;
  4404. $langs->load("categories");
  4405. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4406. // For backward compatibility
  4407. if (is_numeric($type)) {
  4408. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4409. }
  4410. if ($type === Categorie::TYPE_BANK_LINE) {
  4411. // TODO Move this into common category feature
  4412. $cate_arbo = array();
  4413. $sql = "SELECT c.label, c.rowid";
  4414. $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
  4415. $sql .= " WHERE entity = ".$conf->entity;
  4416. $sql .= " ORDER BY c.label";
  4417. $result = $this->db->query($sql);
  4418. if ($result) {
  4419. $num = $this->db->num_rows($result);
  4420. $i = 0;
  4421. while ($i < $num) {
  4422. $objp = $this->db->fetch_object($result);
  4423. if ($objp) {
  4424. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label, 'color'=>'', 'picto'=>'category');
  4425. }
  4426. $i++;
  4427. }
  4428. $this->db->free($result);
  4429. } else {
  4430. dol_print_error($this->db);
  4431. }
  4432. } else {
  4433. $cat = new Categorie($this->db);
  4434. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4435. }
  4436. $outarray = array();
  4437. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4438. if (is_array($cate_arbo)) {
  4439. if (!count($cate_arbo)) {
  4440. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4441. } else {
  4442. $output .= '<option value="-1">&nbsp;</option>';
  4443. foreach ($cate_arbo as $key => $value) {
  4444. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4445. $add = 'selected ';
  4446. } else {
  4447. $add = '';
  4448. }
  4449. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'"';
  4450. $output .= ' data-html="'.dol_escape_htmltag(img_picto('', 'category', 'class="pictofixedwidth" style="color: #'.$cate_arbo[$key]['color'].'"').dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle')).'"';
  4451. $output .= '>';
  4452. $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4453. $output .= '</option>';
  4454. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4455. }
  4456. }
  4457. }
  4458. $output .= '</select>';
  4459. $output .= "\n";
  4460. if ($outputmode == 2) {
  4461. return $cate_arbo;
  4462. } elseif ($outputmode) {
  4463. return $outarray;
  4464. }
  4465. return $output;
  4466. }
  4467. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4468. /**
  4469. * Show a confirmation HTML form or AJAX popup
  4470. *
  4471. * @param string $page Url of page to call if confirmation is OK
  4472. * @param string $title Title
  4473. * @param string $question Question
  4474. * @param string $action Action
  4475. * @param array $formquestion An array with forms complementary inputs
  4476. * @param string $selectedchoice "" or "no" or "yes"
  4477. * @param int|string $useajax 0=No, 1=Yes use Ajax to show the popup, 2=Yes and also submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4478. * @param int $height Force height of box
  4479. * @param int $width Force width of box
  4480. * @return void
  4481. * @deprecated
  4482. * @see formconfirm()
  4483. */
  4484. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4485. {
  4486. // phpcs:enable
  4487. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4488. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4489. }
  4490. /**
  4491. * Show a confirmation HTML form or AJAX popup.
  4492. * Easiest way to use this is with useajax=1.
  4493. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4494. * just after calling this method. For example:
  4495. * print '<script type="text/javascript">'."\n";
  4496. * print 'jQuery(document).ready(function() {'."\n";
  4497. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4498. * print '});'."\n";
  4499. * print '</script>'."\n";
  4500. *
  4501. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4502. * @param string $title Title
  4503. * @param string $question Question
  4504. * @param string $action Action
  4505. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...'))
  4506. * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'select', 'multiselect', 'morecss',
  4507. * 'other', 'onecolumn' or 'hidden'...
  4508. * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0
  4509. * @param int|string $useajax 0=No, 1=Yes use Ajax to show the popup, 2=Yes and also submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4510. * @param int|string $height Force height of box (0 = auto)
  4511. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4512. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4513. * @param string $labelbuttonyes Label for Yes
  4514. * @param string $labelbuttonno Label for No
  4515. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4516. */
  4517. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4518. {
  4519. global $langs, $conf;
  4520. $more = '<!-- formconfirm - before call, page='.dol_escape_htmltag($page).' -->';
  4521. $formconfirm = '';
  4522. $inputok = array();
  4523. $inputko = array();
  4524. // Clean parameters
  4525. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4526. if ($conf->browser->layout == 'phone') {
  4527. $width = '95%';
  4528. }
  4529. // Set height automatically if not defined
  4530. if (empty($height)) {
  4531. $height = 220;
  4532. if (is_array($formquestion) && count($formquestion) > 2) {
  4533. $height += ((count($formquestion) - 2) * 24);
  4534. }
  4535. }
  4536. if (is_array($formquestion) && !empty($formquestion)) {
  4537. // First add hidden fields and value
  4538. foreach ($formquestion as $key => $input) {
  4539. if (is_array($input) && !empty($input)) {
  4540. if ($input['type'] == 'hidden') {
  4541. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4542. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4543. $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'" class="'.$morecss.'"'.$moreattr.'>'."\n";
  4544. }
  4545. }
  4546. }
  4547. // Now add questions
  4548. $moreonecolumn = '';
  4549. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4550. foreach ($formquestion as $key => $input) {
  4551. if (is_array($input) && !empty($input)) {
  4552. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4553. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4554. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4555. if ($input['type'] == 'text') {
  4556. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="text" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.(empty($input['value']) ? '' : $input['value']).'"'.$moreattr.' /></div></div>'."\n";
  4557. } elseif ($input['type'] == 'password') {
  4558. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="password" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.(empty($input['value']) ? '' : $input['value']).'"'.$moreattr.' /></div></div>'."\n";
  4559. } elseif ($input['type'] == 'textarea') {
  4560. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4561. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4562. $more .= $input['value'];
  4563. $more .= '</textarea>';
  4564. $more .= '</div></div>'."\n";*/
  4565. $moreonecolumn .= '<div class="margintoponly">';
  4566. $moreonecolumn .= $input['label'].'<br>';
  4567. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4568. $moreonecolumn .= $input['value'];
  4569. $moreonecolumn .= '</textarea>';
  4570. $moreonecolumn .= '</div>';
  4571. } elseif (in_array($input['type'], ['select', 'multiselect'])) {
  4572. if (empty($morecss)) {
  4573. $morecss = 'minwidth100';
  4574. }
  4575. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4576. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4577. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4578. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4579. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4580. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4581. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4582. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4583. if (!empty($input['label'])) {
  4584. $more .= $input['label'].'</div><div class="tagtd left">';
  4585. }
  4586. if ($input['type'] == 'select') {
  4587. $more .= $this->selectarray($input['name'], $input['values'], !empty($input['default']) ? $input['default'] : '-1', $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4588. } else {
  4589. $more .= $this->multiselectarray($input['name'], $input['values'], is_array($input['default']) ? $input['default'] : [$input['default']], $key_in_label, $value_as_key, $morecss, $translate, $maxlen, $moreattr);
  4590. }
  4591. $more .= '</div></div>'."\n";
  4592. } elseif ($input['type'] == 'checkbox') {
  4593. $more .= '<div class="tagtr">';
  4594. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4595. $more .= '<input type="checkbox" class="flat'.($morecss ? ' '.$morecss : '').'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4596. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4597. $more .= ' checked';
  4598. }
  4599. if (is_bool($input['value']) && $input['value']) {
  4600. $more .= ' checked';
  4601. }
  4602. if (isset($input['disabled'])) {
  4603. $more .= ' disabled';
  4604. }
  4605. $more .= ' /></div>';
  4606. $more .= '</div>'."\n";
  4607. } elseif ($input['type'] == 'radio') {
  4608. $i = 0;
  4609. foreach ($input['values'] as $selkey => $selval) {
  4610. $more .= '<div class="tagtr">';
  4611. if ($i == 0) {
  4612. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4613. } else {
  4614. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4615. }
  4616. $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;
  4617. if (!empty($input['disabled'])) {
  4618. $more .= ' disabled';
  4619. }
  4620. if (isset($input['default']) && $input['default'] === $selkey) {
  4621. $more .= ' checked="checked"';
  4622. }
  4623. $more .= ' /> ';
  4624. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'" class="valignmiddle">'.$selval.'</label>';
  4625. $more .= '</div></div>'."\n";
  4626. $i++;
  4627. }
  4628. } elseif ($input['type'] == 'date') {
  4629. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4630. $more .= '<div class="tagtd">';
  4631. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4632. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4633. $more .= '</div></div>'."\n";
  4634. $formquestion[] = array('name'=>$input['name'].'day');
  4635. $formquestion[] = array('name'=>$input['name'].'month');
  4636. $formquestion[] = array('name'=>$input['name'].'year');
  4637. $formquestion[] = array('name'=>$input['name'].'hour');
  4638. $formquestion[] = array('name'=>$input['name'].'min');
  4639. } elseif ($input['type'] == 'other') {
  4640. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4641. if (!empty($input['label'])) {
  4642. $more .= $input['label'].'</div><div class="tagtd">';
  4643. }
  4644. $more .= $input['value'];
  4645. $more .= '</div></div>'."\n";
  4646. } elseif ($input['type'] == 'onecolumn') {
  4647. $moreonecolumn .= '<div class="margintoponly">';
  4648. $moreonecolumn .= $input['value'];
  4649. $moreonecolumn .= '</div>'."\n";
  4650. } elseif ($input['type'] == 'hidden') {
  4651. // Do nothing more, already added by a previous loop
  4652. } elseif ($input['type'] == 'separator') {
  4653. $more .= '<br>';
  4654. } else {
  4655. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4656. }
  4657. }
  4658. }
  4659. $more .= '</div>'."\n";
  4660. $more .= $moreonecolumn;
  4661. }
  4662. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4663. // 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
  4664. // See page product/card.php for example
  4665. if (!empty($conf->dol_use_jmobile)) {
  4666. $useajax = 0;
  4667. }
  4668. if (empty($conf->use_javascript_ajax)) {
  4669. $useajax = 0;
  4670. }
  4671. if ($useajax) {
  4672. $autoOpen = true;
  4673. $dialogconfirm = 'dialog-confirm';
  4674. $button = '';
  4675. if (!is_numeric($useajax)) {
  4676. $button = $useajax;
  4677. $useajax = 1;
  4678. $autoOpen = false;
  4679. $dialogconfirm .= '-'.$button;
  4680. }
  4681. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=yes';
  4682. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=no' : '');
  4683. // Add input fields into list of fields to read during submit (inputok and inputko)
  4684. if (is_array($formquestion)) {
  4685. foreach ($formquestion as $key => $input) {
  4686. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4687. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4688. if (is_array($input) && isset($input['name'])) {
  4689. if (strpos($input['name'], ',') > 0) {
  4690. $inputok = array_merge($inputok, explode(',', $input['name']));
  4691. } else {
  4692. array_push($inputok, $input['name']);
  4693. }
  4694. }
  4695. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4696. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4697. array_push($inputko, $input['name']);
  4698. }
  4699. }
  4700. }
  4701. // Show JQuery confirm box.
  4702. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4703. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4704. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4705. }
  4706. if (!empty($more)) {
  4707. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4708. }
  4709. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4710. $formconfirm .= '</div>'."\n";
  4711. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4712. $formconfirm .= '<script type="text/javascript">'."\n";
  4713. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4714. $formconfirm .= 'jQuery(document).ready(function() {
  4715. $(function() {
  4716. $( "#'.$dialogconfirm.'" ).dialog(
  4717. {
  4718. autoOpen: '.($autoOpen ? "true" : "false").',';
  4719. if ($newselectedchoice == 'no') {
  4720. $formconfirm .= '
  4721. open: function() {
  4722. $(this).parent().find("button.ui-button:eq(2)").focus();
  4723. },';
  4724. }
  4725. $jsforcursor = '';
  4726. if ($useajax == 1) {
  4727. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor'."\n";
  4728. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");'."\n";
  4729. }
  4730. $postconfirmas = 'GET';
  4731. $formconfirm .= '
  4732. resizable: false,
  4733. height: "'.$height.'",
  4734. width: "'.$width.'",
  4735. modal: true,
  4736. closeOnEscape: false,
  4737. buttons: {
  4738. "'.dol_escape_js($langs->transnoentities($labelbuttonyes)).'": function() {
  4739. var options = "token='.urlencode(newToken()).'";
  4740. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4741. var page = "'.dol_escape_js(!empty($page) ? $page : '').'";
  4742. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4743. if (inputok.length > 0) {
  4744. $.each(inputok, function(i, inputname) {
  4745. var more = "";
  4746. var inputvalue;
  4747. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4748. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4749. } else {
  4750. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4751. inputvalue = $("#" + inputname + more).val();
  4752. }
  4753. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4754. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4755. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4756. });
  4757. }
  4758. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
  4759. if (pageyes.length > 0) {';
  4760. if ($postconfirmas == 'GET') {
  4761. $formconfirm .= 'location.href = urljump;';
  4762. } else {
  4763. $formconfirm .= $jsforcursor;
  4764. $formconfirm .= 'var post = $.post(
  4765. pageyes,
  4766. options,
  4767. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4768. );';
  4769. }
  4770. $formconfirm .= '
  4771. console.log("after post ok");
  4772. }
  4773. $(this).dialog("close");
  4774. },
  4775. "'.dol_escape_js($langs->transnoentities($labelbuttonno)).'": function() {
  4776. var options = "token='.urlencode(newToken()).'";
  4777. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4778. var page = "'.dol_escape_js(!empty($page) ? $page : '').'";
  4779. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4780. if (inputko.length > 0) {
  4781. $.each(inputko, function(i, inputname) {
  4782. var more = "";
  4783. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4784. var inputvalue = $("#" + inputname + more).val();
  4785. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4786. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4787. });
  4788. }
  4789. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
  4790. //alert(urljump);
  4791. if (pageno.length > 0) {';
  4792. if ($postconfirmas == 'GET') {
  4793. $formconfirm .= 'location.href = urljump;';
  4794. } else {
  4795. $formconfirm .= $jsforcursor;
  4796. $formconfirm .= 'var post = $.post(
  4797. pageno,
  4798. options,
  4799. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4800. );';
  4801. }
  4802. $formconfirm .= '
  4803. console.log("after post ko");
  4804. }
  4805. $(this).dialog("close");
  4806. }
  4807. }
  4808. }
  4809. );
  4810. var button = "'.$button.'";
  4811. if (button.length > 0) {
  4812. $( "#" + button ).click(function() {
  4813. $("#'.$dialogconfirm.'").dialog("open");
  4814. });
  4815. }
  4816. });
  4817. });
  4818. </script>';
  4819. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4820. } else {
  4821. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4822. if (empty($disableformtag)) {
  4823. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4824. }
  4825. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4826. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4827. $formconfirm .= '<table class="valid centpercent">'."\n";
  4828. // Line title
  4829. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4830. $formconfirm .= img_picto('', 'recent').' '.$title;
  4831. $formconfirm .= '</td></tr>'."\n";
  4832. // Line text
  4833. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4834. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4835. }
  4836. // Line form fields
  4837. if ($more) {
  4838. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4839. $formconfirm .= $more;
  4840. $formconfirm .= '</td></tr>'."\n";
  4841. }
  4842. // Line with question
  4843. $formconfirm .= '<tr class="valid">';
  4844. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4845. $formconfirm .= '<td class="valid center">';
  4846. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  4847. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
  4848. $formconfirm .= '</td>';
  4849. $formconfirm .= '</tr>'."\n";
  4850. $formconfirm .= '</table>'."\n";
  4851. if (empty($disableformtag)) {
  4852. $formconfirm .= "</form>\n";
  4853. }
  4854. $formconfirm .= '<br>';
  4855. if (!empty($conf->use_javascript_ajax)) {
  4856. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4857. $formconfirm .= '<script type="text/javascript">'."\n";
  4858. $formconfirm .= '
  4859. $(document).ready(function () {
  4860. $(".confirmvalidatebutton").on("click", function() {
  4861. console.log("We click on button");
  4862. $(this).attr("disabled", "disabled");
  4863. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4864. //console.log($(this).closest("form"));
  4865. $(this).closest("form").submit();
  4866. });
  4867. });
  4868. ';
  4869. $formconfirm .= '</script>'."\n";
  4870. }
  4871. $formconfirm .= "<!-- end formconfirm -->\n";
  4872. }
  4873. return $formconfirm;
  4874. }
  4875. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4876. /**
  4877. * Show a form to select a project
  4878. *
  4879. * @param int $page Page
  4880. * @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)
  4881. * @param int $selected Id pre-selected project
  4882. * @param string $htmlname Name of select field
  4883. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4884. * @param int $maxlength Max length
  4885. * @param int $forcefocus Force focus on field (works with javascript only)
  4886. * @param int $nooutput No print is done. String is returned.
  4887. * @param string $textifnoproject Text to show if no project
  4888. * @return string Return html content
  4889. */
  4890. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '')
  4891. {
  4892. // phpcs:enable
  4893. global $langs;
  4894. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4895. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4896. $out = '';
  4897. $formproject = new FormProjets($this->db);
  4898. $langs->load("project");
  4899. if ($htmlname != "none") {
  4900. $out .= '<form method="post" action="'.$page.'">';
  4901. $out .= '<input type="hidden" name="action" value="classin">';
  4902. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4903. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4904. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4905. $out .= '</form>';
  4906. } else {
  4907. $out .= '<span class="project_head_block">';
  4908. if ($selected) {
  4909. $projet = new Project($this->db);
  4910. $projet->fetch($selected);
  4911. $out .= $projet->getNomUrl(0, '', 1);
  4912. } else {
  4913. $out .= '<span class="opacitymedium">'.$textifnoproject.'</span>';
  4914. }
  4915. $out .= '</span>';
  4916. }
  4917. if (empty($nooutput)) {
  4918. print $out;
  4919. return '';
  4920. }
  4921. return $out;
  4922. }
  4923. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4924. /**
  4925. * Show a form to select payment conditions
  4926. *
  4927. * @param int $page Page
  4928. * @param string $selected Id condition pre-selectionne
  4929. * @param string $htmlname Name of select html field
  4930. * @param int $addempty Add empty entry
  4931. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4932. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  4933. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  4934. * 0 : use default deposit percentage from entry
  4935. * > 0 : force deposit percentage (for example, from company object)
  4936. * @param int $nooutput No print is done. String is returned.
  4937. * @return string HTML output or ''
  4938. */
  4939. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
  4940. {
  4941. // phpcs:enable
  4942. global $langs;
  4943. $out = '';
  4944. if ($htmlname != "none") {
  4945. $out .= '<form method="POST" action="'.$page.'">';
  4946. $out .= '<input type="hidden" name="action" value="setconditions">';
  4947. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4948. if ($type) {
  4949. $out .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4950. }
  4951. $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  4952. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4953. $out .= '</form>';
  4954. } else {
  4955. if ($selected) {
  4956. $this->load_cache_conditions_paiements();
  4957. if (isset($this->cache_conditions_paiements[$selected])) {
  4958. $label = $this->cache_conditions_paiements[$selected]['label'];
  4959. if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  4960. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  4961. }
  4962. $out .= $label;
  4963. } else {
  4964. $langs->load('errors');
  4965. $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4966. }
  4967. } else {
  4968. $out .= '&nbsp;';
  4969. }
  4970. }
  4971. if (empty($nooutput)) {
  4972. print $out;
  4973. return '';
  4974. }
  4975. return $out;
  4976. }
  4977. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4978. /**
  4979. * Show a form to select a delivery delay
  4980. *
  4981. * @param int $page Page
  4982. * @param string $selected Id condition pre-selectionne
  4983. * @param string $htmlname Name of select html field
  4984. * @param int $addempty Ajoute entree vide
  4985. * @return void
  4986. */
  4987. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4988. {
  4989. // phpcs:enable
  4990. global $langs;
  4991. if ($htmlname != "none") {
  4992. print '<form method="post" action="'.$page.'">';
  4993. print '<input type="hidden" name="action" value="setavailability">';
  4994. print '<input type="hidden" name="token" value="'.newToken().'">';
  4995. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4996. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4997. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4998. print '</form>';
  4999. } else {
  5000. if ($selected) {
  5001. $this->load_cache_availability();
  5002. print $this->cache_availability[$selected]['label'];
  5003. } else {
  5004. print "&nbsp;";
  5005. }
  5006. }
  5007. }
  5008. /**
  5009. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  5010. * List found into table c_input_reason loaded by loadCacheInputReason
  5011. *
  5012. * @param string $page Page
  5013. * @param string $selected Id condition pre-selectionne
  5014. * @param string $htmlname Name of select html field
  5015. * @param int $addempty Add empty entry
  5016. * @return void
  5017. */
  5018. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  5019. {
  5020. global $langs;
  5021. if ($htmlname != "none") {
  5022. print '<form method="post" action="'.$page.'">';
  5023. print '<input type="hidden" name="action" value="setdemandreason">';
  5024. print '<input type="hidden" name="token" value="'.newToken().'">';
  5025. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  5026. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  5027. print '</form>';
  5028. } else {
  5029. if ($selected) {
  5030. $this->loadCacheInputReason();
  5031. foreach ($this->cache_demand_reason as $key => $val) {
  5032. if ($val['id'] == $selected) {
  5033. print $val['label'];
  5034. break;
  5035. }
  5036. }
  5037. } else {
  5038. print "&nbsp;";
  5039. }
  5040. }
  5041. }
  5042. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5043. /**
  5044. * Show a form + html select a date
  5045. *
  5046. * @param string $page Page
  5047. * @param string $selected Date preselected
  5048. * @param string $htmlname Html name of date input fields or 'none'
  5049. * @param int $displayhour Display hour selector
  5050. * @param int $displaymin Display minutes selector
  5051. * @param int $nooutput 1=No print output, return string
  5052. * @param string $type 'direct-debit' or 'bank-transfer'
  5053. * @return string
  5054. * @see selectDate()
  5055. */
  5056. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  5057. {
  5058. // phpcs:enable
  5059. global $langs;
  5060. $ret = '';
  5061. if ($htmlname != "none") {
  5062. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  5063. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  5064. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  5065. if ($type) {
  5066. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  5067. }
  5068. $ret .= '<table class="nobordernopadding">';
  5069. $ret .= '<tr><td>';
  5070. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  5071. $ret .= '</td>';
  5072. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5073. $ret .= '</tr></table></form>';
  5074. } else {
  5075. if ($displayhour) {
  5076. $ret .= dol_print_date($selected, 'dayhour');
  5077. } else {
  5078. $ret .= dol_print_date($selected, 'day');
  5079. }
  5080. }
  5081. if (empty($nooutput)) {
  5082. print $ret;
  5083. }
  5084. return $ret;
  5085. }
  5086. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5087. /**
  5088. * Show a select form to choose a user
  5089. *
  5090. * @param string $page Page
  5091. * @param string $selected Id of user preselected
  5092. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  5093. * @param array $exclude List of users id to exclude
  5094. * @param array $include List of users id to include
  5095. * @return void
  5096. */
  5097. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  5098. {
  5099. // phpcs:enable
  5100. global $langs;
  5101. if ($htmlname != "none") {
  5102. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  5103. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  5104. print '<input type="hidden" name="token" value="'.newToken().'">';
  5105. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5106. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5107. print '</form>';
  5108. } else {
  5109. if ($selected) {
  5110. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  5111. $theuser = new User($this->db);
  5112. $theuser->fetch($selected);
  5113. print $theuser->getNomUrl(1);
  5114. } else {
  5115. print "&nbsp;";
  5116. }
  5117. }
  5118. }
  5119. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5120. /**
  5121. * Show form with payment mode
  5122. *
  5123. * @param string $page Page
  5124. * @param int $selected Id mode pre-selectionne
  5125. * @param string $htmlname Name of select html field
  5126. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5127. * @param int $active Active or not, -1 = all
  5128. * @param int $addempty 1=Add empty entry
  5129. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5130. * @param int $nooutput 1=Return string, no output
  5131. * @return string HTML output or ''
  5132. */
  5133. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
  5134. {
  5135. // phpcs:enable
  5136. global $langs;
  5137. $out = '';
  5138. if ($htmlname != "none") {
  5139. $out .= '<form method="POST" action="'.$page.'">';
  5140. $out .= '<input type="hidden" name="action" value="setmode">';
  5141. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5142. if ($type) {
  5143. $out .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  5144. }
  5145. $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5146. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5147. $out .= '</form>';
  5148. } else {
  5149. if ($selected) {
  5150. $this->load_cache_types_paiements();
  5151. $out .= $this->cache_types_paiements[$selected]['label'];
  5152. } else {
  5153. $out .= "&nbsp;";
  5154. }
  5155. }
  5156. if ($nooutput) {
  5157. return $out;
  5158. } else {
  5159. print $out;
  5160. }
  5161. return '';
  5162. }
  5163. /**
  5164. * Show form with transport mode
  5165. *
  5166. * @param string $page Page
  5167. * @param int $selected Id mode pre-select
  5168. * @param string $htmlname Name of select html field
  5169. * @param int $active Active or not, -1 = all
  5170. * @param int $addempty 1=Add empty entry
  5171. * @return void
  5172. */
  5173. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5174. {
  5175. global $langs;
  5176. if ($htmlname != "none") {
  5177. print '<form method="POST" action="'.$page.'">';
  5178. print '<input type="hidden" name="action" value="settransportmode">';
  5179. print '<input type="hidden" name="token" value="'.newToken().'">';
  5180. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5181. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5182. print '</form>';
  5183. } else {
  5184. if ($selected) {
  5185. $this->load_cache_transport_mode();
  5186. print $this->cache_transport_mode[$selected]['label'];
  5187. } else {
  5188. print "&nbsp;";
  5189. }
  5190. }
  5191. }
  5192. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5193. /**
  5194. * Show form with multicurrency code
  5195. *
  5196. * @param string $page Page
  5197. * @param string $selected code pre-selectionne
  5198. * @param string $htmlname Name of select html field
  5199. * @return void
  5200. */
  5201. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5202. {
  5203. // phpcs:enable
  5204. global $langs;
  5205. if ($htmlname != "none") {
  5206. print '<form method="POST" action="'.$page.'">';
  5207. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5208. print '<input type="hidden" name="token" value="'.newToken().'">';
  5209. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5210. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5211. print '</form>';
  5212. } else {
  5213. dol_include_once('/core/lib/company.lib.php');
  5214. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5215. }
  5216. }
  5217. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5218. /**
  5219. * Show form with multicurrency rate
  5220. *
  5221. * @param string $page Page
  5222. * @param double $rate Current rate
  5223. * @param string $htmlname Name of select html field
  5224. * @param string $currency Currency code to explain the rate
  5225. * @return void
  5226. */
  5227. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5228. {
  5229. // phpcs:enable
  5230. global $langs, $mysoc, $conf;
  5231. if ($htmlname != "none") {
  5232. print '<form method="POST" action="'.$page.'">';
  5233. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5234. print '<input type="hidden" name="token" value="'.newToken().'">';
  5235. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  5236. print '<select name="calculation_mode">';
  5237. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  5238. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  5239. print '</select> ';
  5240. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5241. print '</form>';
  5242. } else {
  5243. if (!empty($rate)) {
  5244. print price($rate, 1, $langs, 1, 0);
  5245. if ($currency && $rate != 1) {
  5246. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  5247. }
  5248. } else {
  5249. print 1;
  5250. }
  5251. }
  5252. }
  5253. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5254. /**
  5255. * Show a select box with available absolute discounts
  5256. *
  5257. * @param string $page Page URL where form is shown
  5258. * @param int $selected Value pre-selected
  5259. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5260. * @param int $socid Third party id
  5261. * @param float $amount Total amount available
  5262. * @param string $filter SQL filter on discounts
  5263. * @param int $maxvalue Max value for lines that can be selected
  5264. * @param string $more More string to add
  5265. * @param int $hidelist 1=Hide list
  5266. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5267. * @return void
  5268. */
  5269. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5270. {
  5271. // phpcs:enable
  5272. global $conf, $langs;
  5273. if ($htmlname != "none") {
  5274. print '<form method="post" action="'.$page.'">';
  5275. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5276. print '<input type="hidden" name="token" value="'.newToken().'">';
  5277. print '<div class="inline-block">';
  5278. if (!empty($discount_type)) {
  5279. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5280. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5281. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5282. } else {
  5283. $translationKey = 'HasCreditNoteFromSupplier';
  5284. }
  5285. } else {
  5286. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5287. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5288. } else {
  5289. $translationKey = 'HasCreditNoteFromSupplier';
  5290. }
  5291. }
  5292. } else {
  5293. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5294. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5295. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5296. } else {
  5297. $translationKey = 'CompanyHasCreditNote';
  5298. }
  5299. } else {
  5300. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5301. $translationKey = 'CompanyHasAbsoluteDiscount';
  5302. } else {
  5303. $translationKey = 'CompanyHasCreditNote';
  5304. }
  5305. }
  5306. }
  5307. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5308. if (empty($hidelist)) {
  5309. print ' ';
  5310. }
  5311. print '</div>';
  5312. if (empty($hidelist)) {
  5313. print '<div class="inline-block" style="padding-right: 10px">';
  5314. $newfilter = 'discount_type='.intval($discount_type);
  5315. if (!empty($discount_type)) {
  5316. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5317. } else {
  5318. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5319. }
  5320. if ($filter) {
  5321. $newfilter .= ' AND ('.$filter.')';
  5322. }
  5323. // output the combo of discounts
  5324. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5325. if ($nbqualifiedlines > 0) {
  5326. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  5327. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5328. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5329. }
  5330. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5331. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5332. }
  5333. print '>';
  5334. }
  5335. print '</div>';
  5336. }
  5337. if ($more) {
  5338. print '<div class="inline-block">';
  5339. print $more;
  5340. print '</div>';
  5341. }
  5342. print '</form>';
  5343. } else {
  5344. if ($selected) {
  5345. print $selected;
  5346. } else {
  5347. print "0";
  5348. }
  5349. }
  5350. }
  5351. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5352. /**
  5353. * Show forms to select a contact
  5354. *
  5355. * @param string $page Page
  5356. * @param Societe $societe Filter on third party
  5357. * @param int $selected Id contact pre-selectionne
  5358. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5359. * @return void
  5360. */
  5361. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5362. {
  5363. // phpcs:enable
  5364. global $langs, $conf;
  5365. if ($htmlname != "none") {
  5366. print '<form method="post" action="'.$page.'">';
  5367. print '<input type="hidden" name="action" value="set_contact">';
  5368. print '<input type="hidden" name="token" value="'.newToken().'">';
  5369. print '<table class="nobordernopadding">';
  5370. print '<tr><td>';
  5371. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5372. $num = $this->num;
  5373. if ($num == 0) {
  5374. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5375. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5376. }
  5377. print '</td>';
  5378. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5379. print '</tr></table></form>';
  5380. } else {
  5381. if ($selected) {
  5382. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5383. $contact = new Contact($this->db);
  5384. $contact->fetch($selected);
  5385. print $contact->getFullName($langs);
  5386. } else {
  5387. print "&nbsp;";
  5388. }
  5389. }
  5390. }
  5391. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5392. /**
  5393. * Output html select to select thirdparty
  5394. *
  5395. * @param string $page Page
  5396. * @param string $selected Id preselected
  5397. * @param string $htmlname Name of HTML select
  5398. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5399. * @param int $showempty Add an empty field
  5400. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5401. * @param int $forcecombo Force to use combo box
  5402. * @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')))
  5403. * @param int $nooutput No print output. Return it only.
  5404. * @param array $excludeids Exclude IDs from the select combo
  5405. * @param string $textifnothirdparty Text to show if no thirdparty
  5406. * @return string HTML output or ''
  5407. */
  5408. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
  5409. {
  5410. // phpcs:enable
  5411. global $langs;
  5412. $out = '';
  5413. if ($htmlname != "none") {
  5414. $out .= '<form method="post" action="'.$page.'">';
  5415. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5416. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5417. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5418. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5419. $out .= '</form>';
  5420. } else {
  5421. if ($selected) {
  5422. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5423. $soc = new Societe($this->db);
  5424. $soc->fetch($selected);
  5425. $out .= $soc->getNomUrl(0, '');
  5426. } else {
  5427. $out .= '<span class="opacitymedium">'.$textifnothirdparty.'</span>';
  5428. }
  5429. }
  5430. if ($nooutput) {
  5431. return $out;
  5432. } else {
  5433. print $out;
  5434. }
  5435. return '';
  5436. }
  5437. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5438. /**
  5439. * Retourne la liste des devises, dans la langue de l'utilisateur
  5440. *
  5441. * @param string $selected preselected currency code
  5442. * @param string $htmlname name of HTML select list
  5443. * @deprecated
  5444. * @return void
  5445. */
  5446. public function select_currency($selected = '', $htmlname = 'currency_id')
  5447. {
  5448. // phpcs:enable
  5449. print $this->selectCurrency($selected, $htmlname);
  5450. }
  5451. /**
  5452. * Retourne la liste des devises, dans la langue de l'utilisateur
  5453. *
  5454. * @param string $selected preselected currency code
  5455. * @param string $htmlname name of HTML select list
  5456. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5457. * @param string $useempty '1'=Allow empty value
  5458. * @return string
  5459. */
  5460. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5461. {
  5462. global $conf, $langs, $user;
  5463. $langs->loadCacheCurrencies('');
  5464. $out = '';
  5465. if ($selected == 'euro' || $selected == 'euros') {
  5466. $selected = 'EUR'; // Pour compatibilite
  5467. }
  5468. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5469. if ($useempty) {
  5470. $out .= '<option value="-1" selected></option>';
  5471. }
  5472. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5473. $labeltoshow = $currency['label'];
  5474. if ($mode == 1) {
  5475. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5476. } else {
  5477. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5478. }
  5479. if ($selected && $selected == $code_iso) {
  5480. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5481. } else {
  5482. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5483. }
  5484. $out .= $labeltoshow;
  5485. $out .= '</option>';
  5486. }
  5487. $out .= '</select>';
  5488. if ($user->admin) {
  5489. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5490. }
  5491. // Make select dynamic
  5492. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5493. $out .= ajax_combobox($htmlname);
  5494. return $out;
  5495. }
  5496. /**
  5497. * Return array of currencies in user language
  5498. *
  5499. * @param string $selected Preselected currency code
  5500. * @param string $htmlname Name of HTML select list
  5501. * @param integer $useempty 1=Add empty line
  5502. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5503. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5504. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5505. * @param string $morecss More css
  5506. * @return string
  5507. */
  5508. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5509. {
  5510. global $conf, $langs;
  5511. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5512. $TCurrency = array();
  5513. $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
  5514. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5515. if ($filter) {
  5516. $sql .= " AND ".$filter;
  5517. }
  5518. $resql = $this->db->query($sql);
  5519. if ($resql) {
  5520. while ($obj = $this->db->fetch_object($resql)) {
  5521. $TCurrency[$obj->code] = $obj->code;
  5522. }
  5523. }
  5524. $out = '';
  5525. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  5526. if ($useempty) {
  5527. $out .= '<option value="">&nbsp;</option>';
  5528. }
  5529. // If company current currency not in table, we add it into list. Should always be available.
  5530. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5531. $TCurrency[$conf->currency] = $conf->currency;
  5532. }
  5533. if (count($TCurrency) > 0) {
  5534. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5535. if (isset($TCurrency[$code_iso])) {
  5536. if (!empty($selected) && $selected == $code_iso) {
  5537. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5538. } else {
  5539. $out .= '<option value="'.$code_iso.'">';
  5540. }
  5541. $out .= $currency['label'];
  5542. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5543. $out .= '</option>';
  5544. }
  5545. }
  5546. }
  5547. $out .= '</select>';
  5548. // Make select dynamic
  5549. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5550. $out .= ajax_combobox($htmlname);
  5551. return $out;
  5552. }
  5553. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5554. /**
  5555. * Load into the cache vat rates of a country
  5556. *
  5557. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5558. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5559. */
  5560. public function load_cache_vatrates($country_code)
  5561. {
  5562. // phpcs:enable
  5563. global $langs;
  5564. $num = count($this->cache_vatrates);
  5565. if ($num > 0) {
  5566. return $num; // Cache already loaded
  5567. }
  5568. dol_syslog(__METHOD__, LOG_DEBUG);
  5569. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5570. $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
  5571. $sql .= " WHERE t.fk_pays = c.rowid";
  5572. $sql .= " AND t.active > 0";
  5573. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5574. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5575. $resql = $this->db->query($sql);
  5576. if ($resql) {
  5577. $num = $this->db->num_rows($resql);
  5578. if ($num) {
  5579. for ($i = 0; $i < $num; $i++) {
  5580. $obj = $this->db->fetch_object($resql);
  5581. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5582. $this->cache_vatrates[$i]['code'] = $obj->code;
  5583. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5584. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5585. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5586. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5587. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5588. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5589. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5590. $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
  5591. $positiverates = '';
  5592. if ($obj->taux) {
  5593. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5594. }
  5595. if ($obj->localtax1) {
  5596. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5597. }
  5598. if ($obj->localtax2) {
  5599. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5600. }
  5601. if (empty($positiverates)) {
  5602. $positiverates = '0';
  5603. }
  5604. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5605. }
  5606. return $num;
  5607. } else {
  5608. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5609. return -1;
  5610. }
  5611. } else {
  5612. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5613. return -2;
  5614. }
  5615. }
  5616. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5617. /**
  5618. * Output an HTML select vat rate.
  5619. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5620. *
  5621. * @param string $htmlname Name of HTML select field
  5622. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5623. * @param Societe $societe_vendeuse Thirdparty seller
  5624. * @param Societe $societe_acheteuse Thirdparty buyer
  5625. * @param int $idprod Id product. O if unknown of NA.
  5626. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5627. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5628. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5629. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5630. * 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.
  5631. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5632. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5633. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5634. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5635. * @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
  5636. * @return string
  5637. */
  5638. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5639. {
  5640. // phpcs:enable
  5641. global $langs, $conf, $mysoc;
  5642. $langs->load('errors');
  5643. $return = '';
  5644. // Define defaultnpr, defaultttx and defaultcode
  5645. $defaultnpr = ($info_bits & 0x01);
  5646. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5647. $defaulttx = str_replace('*', '', $selectedrate);
  5648. $defaultcode = '';
  5649. $reg = array();
  5650. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5651. $defaultcode = $reg[1];
  5652. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5653. }
  5654. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5655. // Check parameters
  5656. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5657. if ($societe_vendeuse->id == $mysoc->id) {
  5658. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5659. } else {
  5660. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5661. }
  5662. return $return;
  5663. }
  5664. //var_dump($societe_acheteuse);
  5665. //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";
  5666. //exit;
  5667. // Define list of countries to use to search VAT rates to show
  5668. // First we defined code_country to use to find list
  5669. if (is_object($societe_vendeuse)) {
  5670. $code_country = "'".$societe_vendeuse->country_code."'";
  5671. } else {
  5672. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5673. }
  5674. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5675. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5676. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5677. // We also add the buyer
  5678. if (is_numeric($type)) {
  5679. if ($type == 1) { // We know product is a service
  5680. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5681. }
  5682. } elseif (!$idprod) { // We don't know type of product
  5683. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5684. } else {
  5685. $prodstatic = new Product($this->db);
  5686. $prodstatic->fetch($idprod);
  5687. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5688. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5689. }
  5690. }
  5691. }
  5692. }
  5693. // Now we get list
  5694. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5695. if ($num > 0) {
  5696. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5697. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5698. $tmpthirdparty = new Societe($this->db);
  5699. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5700. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5701. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5702. $defaultcode = $reg[1];
  5703. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5704. }
  5705. if (empty($defaulttx)) {
  5706. $defaultnpr = 0;
  5707. }
  5708. }
  5709. // If we fails to find a default vat rate, we take the last one in list
  5710. // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
  5711. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5712. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5713. // We take the last one found in list
  5714. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5715. } else {
  5716. // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
  5717. $defaulttx = '';
  5718. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5719. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5720. }
  5721. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5722. $defaultcode = $reg[1];
  5723. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5724. }
  5725. }
  5726. }
  5727. // Disabled if seller is not subject to VAT
  5728. $disabled = false;
  5729. $title = '';
  5730. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5731. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5732. // of using supplier invoices (this is a very bad idea !)
  5733. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5734. $title = ' title="'.dol_escape_htmltag($langs->trans('VATIsNotUsed')).'"';
  5735. $disabled = true;
  5736. }
  5737. }
  5738. if (!$options_only) {
  5739. $return .= '<select class="flat minwidth50imp maxwidth100" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5740. }
  5741. $selectedfound = false;
  5742. foreach ($this->cache_vatrates as $rate) {
  5743. // Keep only 0 if seller is not subject to VAT
  5744. if ($disabled && $rate['txtva'] != 0) {
  5745. continue;
  5746. }
  5747. // Define key to use into select list
  5748. $key = $rate['txtva'];
  5749. $key .= $rate['nprtva'] ? '*' : '';
  5750. if ($mode > 0 && $rate['code']) {
  5751. $key .= ' ('.$rate['code'].')';
  5752. }
  5753. if ($mode < 0) {
  5754. $key = $rate['rowid'];
  5755. }
  5756. $return .= '<option value="'.$key.'"';
  5757. if (!$selectedfound) {
  5758. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5759. if ($defaultcode == $rate['code']) {
  5760. $return .= ' selected';
  5761. $selectedfound = true;
  5762. }
  5763. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5764. $return .= ' selected';
  5765. $selectedfound = true;
  5766. }
  5767. }
  5768. $return .= '>';
  5769. // Show label of VAT
  5770. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5771. // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
  5772. $return .= $rate['labelpositiverates'];
  5773. } else {
  5774. // Simple label
  5775. $return .= vatrate($rate['label']);
  5776. }
  5777. //$return.=($rate['code']?' '.$rate['code']:'');
  5778. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5779. $return .= '</option>';
  5780. }
  5781. if (!$options_only) {
  5782. $return .= '</select>';
  5783. //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
  5784. }
  5785. } else {
  5786. $return .= $this->error;
  5787. }
  5788. $this->num = $num;
  5789. return $return;
  5790. }
  5791. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5792. /**
  5793. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5794. * Fields are preselected with :
  5795. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5796. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5797. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5798. *
  5799. * @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).
  5800. * @param string $prefix Prefix for fields name
  5801. * @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
  5802. * @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
  5803. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5804. * @param string $form_name Not used
  5805. * @param int $d 1=Show days, month, years
  5806. * @param int $addnowlink Add a link "Now"
  5807. * @param int $nooutput Do not output html string but return it
  5808. * @param int $disabled Disable input fields
  5809. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5810. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5811. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5812. * @return string|void Nothing or string if nooutput is 1
  5813. * @deprecated
  5814. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5815. */
  5816. 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 = '')
  5817. {
  5818. // phpcs:enable
  5819. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5820. if (!empty($nooutput)) {
  5821. return $retstring;
  5822. }
  5823. print $retstring;
  5824. return;
  5825. }
  5826. /**
  5827. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5828. * Fields are preselected with :
  5829. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5830. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5831. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5832. *
  5833. * @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).
  5834. * @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).
  5835. * @param string $prefix Prefix for fields name
  5836. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5837. * @param string $forcenewline Force new line between the 2 dates.
  5838. * @return string Html for selectDate
  5839. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5840. */
  5841. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5842. {
  5843. global $langs;
  5844. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5845. if ($forcenewline) {
  5846. $ret .= '<br>';
  5847. }
  5848. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5849. return $ret;
  5850. }
  5851. /**
  5852. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5853. * Fields are preselected with :
  5854. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5855. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5856. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5857. *
  5858. * @param integer|string $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5859. * @param string $prefix Prefix for fields name
  5860. * @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
  5861. * @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
  5862. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5863. * @param string $form_name Not used
  5864. * @param int $d 1=Show days, month, years
  5865. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5866. * @param int $disabled Disable input fields
  5867. * @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')
  5868. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5869. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5870. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5871. * @param int $stepminutes Specify step for minutes between 1 and 30
  5872. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5873. * @param string $placeholder Placeholder
  5874. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5875. * @return string Html for selectDate
  5876. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5877. */
  5878. 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')
  5879. {
  5880. global $conf, $langs;
  5881. if ($gm === 'auto') {
  5882. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5883. }
  5884. $retstring = '';
  5885. if ($prefix == '') {
  5886. $prefix = 're';
  5887. }
  5888. if ($h == '') {
  5889. $h = 0;
  5890. }
  5891. if ($m == '') {
  5892. $m = 0;
  5893. }
  5894. $emptydate = 0;
  5895. $emptyhours = 0;
  5896. if ($stepminutes <= 0 || $stepminutes > 30) {
  5897. $stepminutes = 1;
  5898. }
  5899. if ($empty == 1) {
  5900. $emptydate = 1;
  5901. $emptyhours = 1;
  5902. }
  5903. if ($empty == 2) {
  5904. $emptydate = 0;
  5905. $emptyhours = 1;
  5906. }
  5907. $orig_set_time = $set_time;
  5908. if ($set_time === '' && $emptydate == 0) {
  5909. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5910. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5911. $set_time = dol_now($gm);
  5912. } else {
  5913. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5914. }
  5915. }
  5916. // Analysis of the pre-selection date
  5917. $reg = array();
  5918. $shour = '';
  5919. $smin = '';
  5920. $ssec = '';
  5921. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5922. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5923. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5924. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5925. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5926. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5927. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5928. } elseif (strval($set_time) != '' && $set_time != -1) {
  5929. // set_time est un timestamps (0 possible)
  5930. $syear = dol_print_date($set_time, "%Y", $gm);
  5931. $smonth = dol_print_date($set_time, "%m", $gm);
  5932. $sday = dol_print_date($set_time, "%d", $gm);
  5933. if ($orig_set_time != '') {
  5934. $shour = dol_print_date($set_time, "%H", $gm);
  5935. $smin = dol_print_date($set_time, "%M", $gm);
  5936. $ssec = dol_print_date($set_time, "%S", $gm);
  5937. }
  5938. } else {
  5939. // Date est '' ou vaut -1
  5940. $syear = '';
  5941. $smonth = '';
  5942. $sday = '';
  5943. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5944. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5945. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5946. }
  5947. if ($h == 3) {
  5948. $shour = '';
  5949. }
  5950. if ($m == 3) {
  5951. $smin = '';
  5952. }
  5953. $nowgmt = dol_now('gmt');
  5954. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5955. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5956. $usecalendar = 'combo';
  5957. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5958. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5959. }
  5960. if ($d) {
  5961. // Show date with popup
  5962. if ($usecalendar != 'combo') {
  5963. $formated_date = '';
  5964. //print "e".$set_time." t ".$conf->format_date_short;
  5965. if (strval($set_time) != '' && $set_time != -1) {
  5966. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5967. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5968. }
  5969. // Calendrier popup version eldy
  5970. if ($usecalendar == "eldy") {
  5971. // Input area to enter date manually
  5972. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5973. $retstring .= ($disabled ? ' disabled' : '');
  5974. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5975. $retstring .= '>';
  5976. // Icon calendar
  5977. $retstringbuttom = '';
  5978. if (!$disabled) {
  5979. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5980. $base = DOL_URL_ROOT.'/core/';
  5981. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5982. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5983. } else {
  5984. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5985. }
  5986. $retstring = $retstringbuttom.$retstring;
  5987. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5988. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5989. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5990. } elseif ($usecalendar == 'jquery') {
  5991. if (!$disabled) {
  5992. // Output javascript for datepicker
  5993. $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (date('Y') - 100));
  5994. $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (date('Y') + 100));
  5995. $retstring .= "<script type='text/javascript'>";
  5996. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5997. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5998. autoclose: true,
  5999. todayHighlight: true,
  6000. yearRange: '".$minYear.":".$maxYear."',";
  6001. if (!empty($conf->dol_use_jmobile)) {
  6002. $retstring .= "
  6003. beforeShow: function (input, datePicker) {
  6004. input.disabled = true;
  6005. },
  6006. onClose: function (dateText, datePicker) {
  6007. this.disabled = false;
  6008. },
  6009. ";
  6010. }
  6011. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  6012. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  6013. $retstring .= "
  6014. showOn: 'button', /* both has problem with autocompletion */
  6015. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  6016. buttonImageOnly: true";
  6017. }
  6018. $retstring .= "
  6019. }) });";
  6020. $retstring .= "</script>";
  6021. }
  6022. // Zone de saisie manuelle de la date
  6023. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  6024. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  6025. $retstring .= ($disabled ? ' disabled' : '');
  6026. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  6027. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6028. $retstring .= '>';
  6029. // Icone calendrier
  6030. if (!$disabled) {
  6031. /* Not required. Managed by option buttonImage of jquery
  6032. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  6033. $retstring.="<script type='text/javascript'>";
  6034. $retstring.="jQuery(document).ready(function() {";
  6035. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  6036. $retstring.=" jQuery('#".$prefix."').focus();";
  6037. $retstring.=' });';
  6038. $retstring.='});';
  6039. $retstring.="</script>";*/
  6040. } else {
  6041. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  6042. $retsring = $retstringbutton.$retstring;
  6043. }
  6044. $retstring .= '</div>';
  6045. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  6046. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  6047. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  6048. } else {
  6049. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  6050. }
  6051. } else {
  6052. // Show date with combo selects
  6053. // Day
  6054. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  6055. if ($emptydate || $set_time == -1) {
  6056. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6057. }
  6058. for ($day = 1; $day <= 31; $day++) {
  6059. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  6060. }
  6061. $retstring .= "</select>";
  6062. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  6063. if ($emptydate || $set_time == -1) {
  6064. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6065. }
  6066. // Month
  6067. for ($month = 1; $month <= 12; $month++) {
  6068. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  6069. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  6070. $retstring .= "</option>";
  6071. }
  6072. $retstring .= "</select>";
  6073. // Year
  6074. if ($emptydate || $set_time == -1) {
  6075. $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.'">';
  6076. } else {
  6077. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  6078. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  6079. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  6080. }
  6081. $retstring .= "</select>\n";
  6082. }
  6083. }
  6084. }
  6085. if ($d && $h) {
  6086. $retstring .= ($h == 2 ? '<br>' : ' ');
  6087. $retstring .= '<span class="nowraponall">';
  6088. }
  6089. if ($h) {
  6090. $hourstart = 0;
  6091. $hourend = 24;
  6092. if ($openinghours != '') {
  6093. $openinghours = explode(',', $openinghours);
  6094. $hourstart = $openinghours[0];
  6095. $hourend = $openinghours[1];
  6096. if ($hourend < $hourstart) {
  6097. $hourend = $hourstart;
  6098. }
  6099. }
  6100. // Show hour
  6101. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  6102. if ($emptyhours) {
  6103. $retstring .= '<option value="-1">&nbsp;</option>';
  6104. }
  6105. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  6106. if (strlen($hour) < 2) {
  6107. $hour = "0".$hour;
  6108. }
  6109. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  6110. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  6111. $retstring .= '</option>';
  6112. }
  6113. $retstring .= '</select>';
  6114. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  6115. if ($m) {
  6116. $retstring .= ":";
  6117. }
  6118. }
  6119. if ($m) {
  6120. // Show minutes
  6121. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  6122. if ($emptyhours) {
  6123. $retstring .= '<option value="-1">&nbsp;</option>';
  6124. }
  6125. for ($min = 0; $min < 60; $min += $stepminutes) {
  6126. if (strlen($min) < 2) {
  6127. $min = "0".$min;
  6128. }
  6129. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  6130. }
  6131. $retstring .= '</select>';
  6132. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  6133. }
  6134. if ($d && $h) {
  6135. $retstring .= '</span>';
  6136. }
  6137. // Add a "Now" link
  6138. if (!empty($conf->use_javascript_ajax) && $addnowlink) {
  6139. // Script which will be inserted in the onClick of the "Now" link
  6140. $reset_scripts = "";
  6141. if ($addnowlink == 2) { // local computer time
  6142. // pad add leading 0 on numbers
  6143. $reset_scripts .= "Number.prototype.pad = function(size) {
  6144. var s = String(this);
  6145. while (s.length < (size || 2)) {s = '0' + s;}
  6146. return s;
  6147. };
  6148. var d = new Date();";
  6149. }
  6150. // Generate the date part, depending on the use or not of the javascript calendar
  6151. if ($addnowlink == 1) { // server time expressed in user time setup
  6152. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  6153. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6154. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6155. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6156. } elseif ($addnowlink == 2) {
  6157. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6158. * This break application for foreign languages.
  6159. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6160. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6161. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6162. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6163. */
  6164. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  6165. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6166. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6167. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6168. }
  6169. /*if ($usecalendar == "eldy")
  6170. {
  6171. $base=DOL_URL_ROOT.'/core/';
  6172. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6173. }
  6174. else
  6175. {
  6176. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6177. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6178. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6179. }*/
  6180. // Update the hour part
  6181. if ($h) {
  6182. if ($fullday) {
  6183. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6184. }
  6185. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6186. if ($addnowlink == 1) {
  6187. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6188. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  6189. } elseif ($addnowlink == 2) {
  6190. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  6191. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  6192. }
  6193. if ($fullday) {
  6194. $reset_scripts .= ' } ';
  6195. }
  6196. }
  6197. // Update the minute part
  6198. if ($m) {
  6199. if ($fullday) {
  6200. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6201. }
  6202. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6203. if ($addnowlink == 1) {
  6204. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6205. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6206. } elseif ($addnowlink == 2) {
  6207. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  6208. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6209. }
  6210. if ($fullday) {
  6211. $reset_scripts .= ' } ';
  6212. }
  6213. }
  6214. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6215. if ($reset_scripts && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6216. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  6217. $retstring .= $langs->trans("Now");
  6218. $retstring .= '</button> ';
  6219. }
  6220. }
  6221. // Add a "Plus one hour" link
  6222. if ($conf->use_javascript_ajax && $addplusone) {
  6223. // Script which will be inserted in the onClick of the "Add plusone" link
  6224. $reset_scripts = "";
  6225. // Generate the date part, depending on the use or not of the javascript calendar
  6226. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  6227. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6228. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6229. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6230. // Update the hour part
  6231. if ($h) {
  6232. if ($fullday) {
  6233. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6234. }
  6235. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6236. if ($fullday) {
  6237. $reset_scripts .= ' } ';
  6238. }
  6239. }
  6240. // Update the minute part
  6241. if ($m) {
  6242. if ($fullday) {
  6243. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6244. }
  6245. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6246. if ($fullday) {
  6247. $reset_scripts .= ' } ';
  6248. }
  6249. }
  6250. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6251. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6252. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  6253. $retstring .= $langs->trans("DateStartPlusOne");
  6254. $retstring .= '</button> ';
  6255. }
  6256. }
  6257. // Add a link to set data
  6258. if ($conf->use_javascript_ajax && $adddateof) {
  6259. $tmparray = dol_getdate($adddateof);
  6260. if (empty($labeladddateof)) {
  6261. $labeladddateof = $langs->trans("DateInvoice");
  6262. }
  6263. $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>';
  6264. }
  6265. return $retstring;
  6266. }
  6267. /**
  6268. * selectTypeDuration
  6269. *
  6270. * @param string $prefix Prefix
  6271. * @param string $selected Selected duration type
  6272. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6273. * @return string HTML select string
  6274. */
  6275. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6276. {
  6277. global $langs;
  6278. $TDurationTypes = array(
  6279. 'y'=>$langs->trans('Years'),
  6280. 'm'=>$langs->trans('Month'),
  6281. 'w'=>$langs->trans('Weeks'),
  6282. 'd'=>$langs->trans('Days'),
  6283. 'h'=>$langs->trans('Hours'),
  6284. 'i'=>$langs->trans('Minutes')
  6285. );
  6286. // Removed undesired duration types
  6287. foreach ($excludetypes as $value) {
  6288. unset($TDurationTypes[$value]);
  6289. }
  6290. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  6291. foreach ($TDurationTypes as $key => $typeduration) {
  6292. $retstring .= '<option value="'.$key.'"';
  6293. if ($key == $selected) {
  6294. $retstring .= " selected";
  6295. }
  6296. $retstring .= ">".$typeduration."</option>";
  6297. }
  6298. $retstring .= "</select>";
  6299. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  6300. return $retstring;
  6301. }
  6302. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6303. /**
  6304. * Function to show a form to select a duration on a page
  6305. *
  6306. * @param string $prefix Prefix for input fields
  6307. * @param int $iSecond Default preselected duration (number of seconds or '')
  6308. * @param int $disabled Disable the combo box
  6309. * @param string $typehour If 'select' then input hour and input min is a combo,
  6310. * If 'text' input hour is in text and input min is a text,
  6311. * If 'textselect' input hour is in text and input min is a combo
  6312. * @param integer $minunderhours If 1, show minutes selection under the hours
  6313. * @param int $nooutput Do not output html string but return it
  6314. * @return string|void
  6315. */
  6316. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6317. {
  6318. // phpcs:enable
  6319. global $langs;
  6320. $retstring = '<span class="nowraponall">';
  6321. $hourSelected = 0;
  6322. $minSelected = 0;
  6323. // Hours
  6324. if ($iSecond != '') {
  6325. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6326. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6327. $minSelected = convertSecondToTime($iSecond, 'min');
  6328. }
  6329. if ($typehour == 'select') {
  6330. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  6331. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6332. $retstring .= '<option value="'.$hour.'"';
  6333. if ($hourSelected == $hour) {
  6334. $retstring .= " selected";
  6335. }
  6336. $retstring .= ">".$hour."</option>";
  6337. }
  6338. $retstring .= "</select>";
  6339. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6340. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  6341. } else {
  6342. return 'BadValueForParameterTypeHour';
  6343. }
  6344. if ($typehour != 'text') {
  6345. $retstring .= ' '.$langs->trans('HourShort');
  6346. } else {
  6347. $retstring .= '<span class="">:</span>';
  6348. }
  6349. // Minutes
  6350. if ($minunderhours) {
  6351. $retstring .= '<br>';
  6352. } else {
  6353. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6354. }
  6355. if ($typehour == 'select' || $typehour == 'textselect') {
  6356. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  6357. for ($min = 0; $min <= 55; $min = $min + 5) {
  6358. $retstring .= '<option value="'.$min.'"';
  6359. if ($minSelected == $min) {
  6360. $retstring .= ' selected';
  6361. }
  6362. $retstring .= '>'.$min.'</option>';
  6363. }
  6364. $retstring .= "</select>";
  6365. } elseif ($typehour == 'text') {
  6366. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6367. }
  6368. if ($typehour != 'text') {
  6369. $retstring .= ' '.$langs->trans('MinuteShort');
  6370. }
  6371. $retstring.="</span>";
  6372. if (!empty($nooutput)) {
  6373. return $retstring;
  6374. }
  6375. print $retstring;
  6376. return;
  6377. }
  6378. /**
  6379. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6380. *
  6381. * @param int $selected Preselected tickets
  6382. * @param string $htmlname Name of HTML select field (must be unique in page).
  6383. * @param string $filtertype To add a filter
  6384. * @param int $limit Limit on number of returned lines
  6385. * @param int $status Ticket status
  6386. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6387. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6388. * @param array $ajaxoptions Options for ajax_autocompleter
  6389. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6390. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6391. * @param int $forcecombo Force to use combo box
  6392. * @param string $morecss Add more css on select
  6393. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6394. * @param string $nooutput No print, return the output into a string
  6395. * @return string
  6396. */
  6397. 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)
  6398. {
  6399. global $langs, $conf;
  6400. $out = '';
  6401. // check parameters
  6402. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6403. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6404. $placeholder = '';
  6405. if ($selected && empty($selected_input_value)) {
  6406. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6407. $tickettmpselect = new Ticket($this->db);
  6408. $tickettmpselect->fetch($selected);
  6409. $selected_input_value = $tickettmpselect->ref;
  6410. unset($tickettmpselect);
  6411. }
  6412. $urloption = '';
  6413. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6414. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6415. elseif ($hidelabel > 1) {
  6416. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6417. if ($hidelabel == 2) {
  6418. $out .= img_picto($langs->trans("Search"), 'search');
  6419. }
  6420. }
  6421. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6422. if ($hidelabel == 3) {
  6423. $out .= img_picto($langs->trans("Search"), 'search');
  6424. }
  6425. } else {
  6426. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6427. }
  6428. if (empty($nooutput)) {
  6429. print $out;
  6430. } else {
  6431. return $out;
  6432. }
  6433. return '';
  6434. }
  6435. /**
  6436. * Return list of tickets.
  6437. * Called by selectTickets.
  6438. *
  6439. * @param int $selected Preselected ticket
  6440. * @param string $htmlname Name of select html
  6441. * @param string $filtertype Filter on ticket type
  6442. * @param int $limit Limit on number of returned lines
  6443. * @param string $filterkey Filter on ticket ref or subject
  6444. * @param int $status Ticket status
  6445. * @param int $outputmode 0=HTML select string, 1=Array
  6446. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6447. * @param int $forcecombo Force to use combo box
  6448. * @param string $morecss Add more css on select
  6449. * @return array Array of keys for json
  6450. */
  6451. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6452. {
  6453. global $langs, $conf;
  6454. $out = '';
  6455. $outarray = array();
  6456. $selectFields = " p.rowid, p.ref, p.message";
  6457. $sql = "SELECT ";
  6458. $sql .= $selectFields;
  6459. $sql .= " FROM ".$this->db->prefix()."ticket as p";
  6460. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6461. // Add criteria on ref/label
  6462. if ($filterkey != '') {
  6463. $sql .= ' AND (';
  6464. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6465. // For natural search
  6466. $scrit = explode(' ', $filterkey);
  6467. $i = 0;
  6468. if (count($scrit) > 1) $sql .= "(";
  6469. foreach ($scrit as $crit) {
  6470. if ($i > 0) $sql .= " AND ";
  6471. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6472. $sql .= ")";
  6473. $i++;
  6474. }
  6475. if (count($scrit) > 1) $sql .= ")";
  6476. $sql .= ')';
  6477. }
  6478. $sql .= $this->db->plimit($limit, 0);
  6479. // Build output string
  6480. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6481. $result = $this->db->query($sql);
  6482. if ($result) {
  6483. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6484. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6485. $num = $this->db->num_rows($result);
  6486. $events = null;
  6487. if (!$forcecombo) {
  6488. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6489. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6490. }
  6491. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6492. $textifempty = '';
  6493. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6494. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6495. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6496. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6497. else $textifempty .= $langs->trans("All");
  6498. } else {
  6499. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6500. }
  6501. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6502. $i = 0;
  6503. while ($num && $i < $num) {
  6504. $opt = '';
  6505. $optJson = array();
  6506. $objp = $this->db->fetch_object($result);
  6507. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6508. // Add new entry
  6509. // "key" value of json key array is used by jQuery automatically as selected value
  6510. // "label" value of json key array is used by jQuery automatically as text for combo box
  6511. $out .= $opt;
  6512. array_push($outarray, $optJson);
  6513. $i++;
  6514. }
  6515. $out .= '</select>';
  6516. $this->db->free($result);
  6517. if (empty($outputmode)) {
  6518. return $out;
  6519. }
  6520. return $outarray;
  6521. } else {
  6522. dol_print_error($this->db);
  6523. }
  6524. return array();
  6525. }
  6526. /**
  6527. * constructTicketListOption.
  6528. * This define value for &$opt and &$optJson.
  6529. *
  6530. * @param object $objp Result set of fetch
  6531. * @param string $opt Option (var used for returned value in string option format)
  6532. * @param string $optJson Option (var used for returned value in json format)
  6533. * @param string $selected Preselected value
  6534. * @param string $filterkey Filter key to highlight
  6535. * @return void
  6536. */
  6537. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6538. {
  6539. $outkey = '';
  6540. $outref = '';
  6541. $outtype = '';
  6542. $outkey = $objp->rowid;
  6543. $outref = $objp->ref;
  6544. $outtype = $objp->fk_product_type;
  6545. $opt = '<option value="'.$objp->rowid.'"';
  6546. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6547. $opt .= '>';
  6548. $opt .= $objp->ref;
  6549. $objRef = $objp->ref;
  6550. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6551. $opt .= "</option>\n";
  6552. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6553. }
  6554. /**
  6555. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6556. *
  6557. * @param int $selected Preselected tickets
  6558. * @param string $htmlname Name of HTML select field (must be unique in page).
  6559. * @param string $filtertype To add a filter
  6560. * @param int $limit Limit on number of returned lines
  6561. * @param int $status Ticket status
  6562. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6563. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6564. * @param array $ajaxoptions Options for ajax_autocompleter
  6565. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6566. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6567. * @param int $forcecombo Force to use combo box
  6568. * @param string $morecss Add more css on select
  6569. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6570. * @param string $nooutput No print, return the output into a string
  6571. * @return string
  6572. */
  6573. 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)
  6574. {
  6575. global $langs, $conf;
  6576. $out = '';
  6577. // check parameters
  6578. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6579. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6580. $placeholder = '';
  6581. if ($selected && empty($selected_input_value)) {
  6582. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6583. $projecttmpselect = new Project($this->db);
  6584. $projecttmpselect->fetch($selected);
  6585. $selected_input_value = $projecttmpselect->ref;
  6586. unset($projecttmpselect);
  6587. }
  6588. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6589. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6590. elseif ($hidelabel > 1) {
  6591. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6592. if ($hidelabel == 2) {
  6593. $out .= img_picto($langs->trans("Search"), 'search');
  6594. }
  6595. }
  6596. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6597. if ($hidelabel == 3) {
  6598. $out .= img_picto($langs->trans("Search"), 'search');
  6599. }
  6600. } else {
  6601. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6602. }
  6603. if (empty($nooutput)) {
  6604. print $out;
  6605. } else {
  6606. return $out;
  6607. }
  6608. return '';
  6609. }
  6610. /**
  6611. * Return list of projects.
  6612. * Called by selectProjects.
  6613. *
  6614. * @param int $selected Preselected project
  6615. * @param string $htmlname Name of select html
  6616. * @param string $filtertype Filter on project type
  6617. * @param int $limit Limit on number of returned lines
  6618. * @param string $filterkey Filter on project ref or subject
  6619. * @param int $status Ticket status
  6620. * @param int $outputmode 0=HTML select string, 1=Array
  6621. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6622. * @param int $forcecombo Force to use combo box
  6623. * @param string $morecss Add more css on select
  6624. * @return array Array of keys for json
  6625. */
  6626. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6627. {
  6628. global $langs, $conf;
  6629. $out = '';
  6630. $outarray = array();
  6631. $selectFields = " p.rowid, p.ref";
  6632. $sql = "SELECT ";
  6633. $sql .= $selectFields;
  6634. $sql .= " FROM ".$this->db->prefix()."projet as p";
  6635. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6636. // Add criteria on ref/label
  6637. if ($filterkey != '') {
  6638. $sql .= ' AND (';
  6639. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6640. // For natural search
  6641. $scrit = explode(' ', $filterkey);
  6642. $i = 0;
  6643. if (count($scrit) > 1) $sql .= "(";
  6644. foreach ($scrit as $crit) {
  6645. if ($i > 0) $sql .= " AND ";
  6646. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6647. $sql .= "";
  6648. $i++;
  6649. }
  6650. if (count($scrit) > 1) $sql .= ")";
  6651. $sql .= ')';
  6652. }
  6653. $sql .= $this->db->plimit($limit, 0);
  6654. // Build output string
  6655. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6656. $result = $this->db->query($sql);
  6657. if ($result) {
  6658. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6659. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6660. $num = $this->db->num_rows($result);
  6661. $events = null;
  6662. if (!$forcecombo) {
  6663. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6664. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6665. }
  6666. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6667. $textifempty = '';
  6668. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6669. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6670. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6671. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6672. else $textifempty .= $langs->trans("All");
  6673. } else {
  6674. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6675. }
  6676. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6677. $i = 0;
  6678. while ($num && $i < $num) {
  6679. $opt = '';
  6680. $optJson = array();
  6681. $objp = $this->db->fetch_object($result);
  6682. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6683. // Add new entry
  6684. // "key" value of json key array is used by jQuery automatically as selected value
  6685. // "label" value of json key array is used by jQuery automatically as text for combo box
  6686. $out .= $opt;
  6687. array_push($outarray, $optJson);
  6688. $i++;
  6689. }
  6690. $out .= '</select>';
  6691. $this->db->free($result);
  6692. if (empty($outputmode)) {
  6693. return $out;
  6694. }
  6695. return $outarray;
  6696. } else {
  6697. dol_print_error($this->db);
  6698. }
  6699. return array();
  6700. }
  6701. /**
  6702. * constructProjectListOption.
  6703. * This define value for &$opt and &$optJson.
  6704. *
  6705. * @param object $objp Result set of fetch
  6706. * @param string $opt Option (var used for returned value in string option format)
  6707. * @param string $optJson Option (var used for returned value in json format)
  6708. * @param string $selected Preselected value
  6709. * @param string $filterkey Filter key to highlight
  6710. * @return void
  6711. */
  6712. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6713. {
  6714. $outkey = '';
  6715. $outref = '';
  6716. $outtype = '';
  6717. $label = $objp->label;
  6718. $outkey = $objp->rowid;
  6719. $outref = $objp->ref;
  6720. $outlabel = $objp->label;
  6721. $outtype = $objp->fk_product_type;
  6722. $opt = '<option value="'.$objp->rowid.'"';
  6723. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6724. $opt .= '>';
  6725. $opt .= $objp->ref;
  6726. $objRef = $objp->ref;
  6727. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6728. $opt .= "</option>\n";
  6729. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6730. }
  6731. /**
  6732. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6733. *
  6734. * @param int $selected Preselected tickets
  6735. * @param string $htmlname Name of HTML select field (must be unique in page).
  6736. * @param string $filtertype To add a filter
  6737. * @param int $limit Limit on number of returned lines
  6738. * @param int $status Ticket status
  6739. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6740. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6741. * @param array $ajaxoptions Options for ajax_autocompleter
  6742. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6743. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6744. * @param int $forcecombo Force to use combo box
  6745. * @param string $morecss Add more css on select
  6746. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6747. * @param string $nooutput No print, return the output into a string
  6748. * @return string
  6749. */
  6750. 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)
  6751. {
  6752. global $langs, $conf;
  6753. $out = '';
  6754. // check parameters
  6755. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6756. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6757. $placeholder = '';
  6758. $urloption = '';
  6759. if ($selected && empty($selected_input_value)) {
  6760. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6761. $adherenttmpselect = new Adherent($this->db);
  6762. $adherenttmpselect->fetch($selected);
  6763. $selected_input_value = $adherenttmpselect->ref;
  6764. unset($adherenttmpselect);
  6765. }
  6766. $urloption = '';
  6767. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6768. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6769. elseif ($hidelabel > 1) {
  6770. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6771. if ($hidelabel == 2) {
  6772. $out .= img_picto($langs->trans("Search"), 'search');
  6773. }
  6774. }
  6775. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6776. if ($hidelabel == 3) {
  6777. $out .= img_picto($langs->trans("Search"), 'search');
  6778. }
  6779. } else {
  6780. $filterkey = '';
  6781. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6782. }
  6783. if (empty($nooutput)) {
  6784. print $out;
  6785. } else {
  6786. return $out;
  6787. }
  6788. return '';
  6789. }
  6790. /**
  6791. * Return list of adherents.
  6792. * Called by selectMembers.
  6793. *
  6794. * @param int $selected Preselected adherent
  6795. * @param string $htmlname Name of select html
  6796. * @param string $filtertype Filter on adherent type
  6797. * @param int $limit Limit on number of returned lines
  6798. * @param string $filterkey Filter on member status
  6799. * @param int $status Member status
  6800. * @param int $outputmode 0=HTML select string, 1=Array
  6801. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6802. * @param int $forcecombo Force to use combo box
  6803. * @param string $morecss Add more css on select
  6804. * @return array Array of keys for json
  6805. */
  6806. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6807. {
  6808. global $langs, $conf;
  6809. $out = '';
  6810. $outarray = array();
  6811. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6812. $sql = "SELECT ";
  6813. $sql .= $selectFields;
  6814. $sql .= " FROM ".$this->db->prefix()."adherent as p";
  6815. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6816. // Add criteria on ref/label
  6817. if ($filterkey != '') {
  6818. $sql .= ' AND (';
  6819. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6820. // For natural search
  6821. $scrit = explode(' ', $filterkey);
  6822. $i = 0;
  6823. if (count($scrit) > 1) $sql .= "(";
  6824. foreach ($scrit as $crit) {
  6825. if ($i > 0) $sql .= " AND ";
  6826. $sql .= "(p.firstname LIKE '".$this->db->escape($prefix.$crit)."%'";
  6827. $sql .= " OR p.lastname LIKE '".$this->db->escape($prefix.$crit)."%')";
  6828. $i++;
  6829. }
  6830. if (count($scrit) > 1) $sql .= ")";
  6831. $sql .= ')';
  6832. }
  6833. if ($status != -1) {
  6834. $sql .= ' AND statut = '.((int) $status);
  6835. }
  6836. $sql .= $this->db->plimit($limit, 0);
  6837. // Build output string
  6838. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6839. $result = $this->db->query($sql);
  6840. if ($result) {
  6841. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6842. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6843. $num = $this->db->num_rows($result);
  6844. $events = null;
  6845. if (!$forcecombo) {
  6846. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6847. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6848. }
  6849. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6850. $textifempty = '';
  6851. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6852. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6853. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6854. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6855. else $textifempty .= $langs->trans("All");
  6856. } else {
  6857. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6858. }
  6859. if ($showempty) {
  6860. $out .= '<option value="-1" selected>'.$textifempty.'</option>';
  6861. }
  6862. $i = 0;
  6863. while ($num && $i < $num) {
  6864. $opt = '';
  6865. $optJson = array();
  6866. $objp = $this->db->fetch_object($result);
  6867. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6868. // Add new entry
  6869. // "key" value of json key array is used by jQuery automatically as selected value
  6870. // "label" value of json key array is used by jQuery automatically as text for combo box
  6871. $out .= $opt;
  6872. array_push($outarray, $optJson);
  6873. $i++;
  6874. }
  6875. $out .= '</select>';
  6876. $this->db->free($result);
  6877. if (empty($outputmode)) {
  6878. return $out;
  6879. }
  6880. return $outarray;
  6881. } else {
  6882. dol_print_error($this->db);
  6883. }
  6884. return array();
  6885. }
  6886. /**
  6887. * constructMemberListOption.
  6888. * This define value for &$opt and &$optJson.
  6889. *
  6890. * @param object $objp Result set of fetch
  6891. * @param string $opt Option (var used for returned value in string option format)
  6892. * @param string $optJson Option (var used for returned value in json format)
  6893. * @param string $selected Preselected value
  6894. * @param string $filterkey Filter key to highlight
  6895. * @return void
  6896. */
  6897. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6898. {
  6899. $outkey = '';
  6900. $outlabel = '';
  6901. $outtype = '';
  6902. $outkey = $objp->rowid;
  6903. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6904. $outtype = $objp->fk_adherent_type;
  6905. $opt = '<option value="'.$objp->rowid.'"';
  6906. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6907. $opt .= '>';
  6908. if (!empty($filterkey) && $filterkey != '') {
  6909. $outlabel = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $outlabel, 1);
  6910. }
  6911. $opt .= $outlabel;
  6912. $opt .= "</option>\n";
  6913. $optJson = array('key'=>$outkey, 'value'=>$outlabel, 'type'=>$outtype);
  6914. }
  6915. /**
  6916. * Generic method to select a component from a combo list.
  6917. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6918. * This is the generic method that will replace all specific existing methods.
  6919. *
  6920. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6921. * @param string $htmlname Name of HTML select component
  6922. * @param int $preselectedvalue Preselected value (ID of element)
  6923. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6924. * @param string $searchkey Search criteria
  6925. * @param string $placeholder Place holder
  6926. * @param string $morecss More CSS
  6927. * @param string $moreparams More params provided to ajax call
  6928. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6929. * @param int $disabled 1=Html component is disabled
  6930. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6931. * @return string Return HTML string
  6932. * @see selectForFormsList() select_thirdparty_list()
  6933. */
  6934. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6935. {
  6936. global $conf, $user;
  6937. $objecttmp = null;
  6938. // Example of value for $objectdec:
  6939. // Bom:bom/class/bom.class.php:0:t.status=1
  6940. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6941. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6942. $InfoFieldList = explode(":", $objectdesc, 4);
  6943. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  6944. $reg = array();
  6945. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6946. $InfoFieldList[4] = $reg[1]; // take the sort field
  6947. }
  6948. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6949. $classname = $InfoFieldList[0];
  6950. $classpath = $InfoFieldList[1];
  6951. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6952. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6953. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6954. if (!empty($classpath)) {
  6955. dol_include_once($classpath);
  6956. if ($classname && class_exists($classname)) {
  6957. $objecttmp = new $classname($this->db);
  6958. // Make some replacement
  6959. $sharedentities = getEntity(strtolower($classname));
  6960. $filter = str_replace(
  6961. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6962. array($conf->entity, $sharedentities, $user->id),
  6963. $filter
  6964. );
  6965. }
  6966. }
  6967. if (!is_object($objecttmp)) {
  6968. dol_syslog('Error bad setup of type for field '.join(',', $InfoFieldList), LOG_WARNING);
  6969. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6970. }
  6971. //var_dump($filter);
  6972. $prefixforautocompletemode = $objecttmp->element;
  6973. if ($prefixforautocompletemode == 'societe') {
  6974. $prefixforautocompletemode = 'company';
  6975. }
  6976. if ($prefixforautocompletemode == 'product') {
  6977. $prefixforautocompletemode = 'produit';
  6978. }
  6979. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6980. dol_syslog(get_class($this)."::selectForForms filter=".$filter, LOG_DEBUG);
  6981. $out = '';
  6982. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6983. // No immediate load of all database
  6984. $placeholder = '';
  6985. if ($preselectedvalue && empty($selected_input_value)) {
  6986. $objecttmp->fetch($preselectedvalue);
  6987. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6988. //unset($objecttmp);
  6989. }
  6990. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6991. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6992. // No immediate load of all database
  6993. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6994. // Activate the auto complete using ajax call.
  6995. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6996. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6997. $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).'"' : '') .' />';
  6998. } else {
  6999. // Immediate load of table record.
  7000. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
  7001. }
  7002. return $out;
  7003. }
  7004. /**
  7005. * Function to forge a SQL criteria
  7006. *
  7007. * @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"
  7008. * @return string Forged criteria. Example: "t.field like 'abc%'"
  7009. */
  7010. protected static function forgeCriteriaCallback($matches)
  7011. {
  7012. global $db;
  7013. //dol_syslog("Convert matches ".$matches[1]);
  7014. if (empty($matches[1])) {
  7015. return '';
  7016. }
  7017. $tmp = explode(':', $matches[1]);
  7018. if (count($tmp) < 3) {
  7019. return '';
  7020. }
  7021. $tmpescaped = $tmp[2];
  7022. $regbis = array();
  7023. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  7024. $tmpescaped = "'".$db->escape($regbis[1])."'";
  7025. } else {
  7026. $tmpescaped = $db->escape($tmpescaped);
  7027. }
  7028. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  7029. }
  7030. /**
  7031. * Output html form to select an object.
  7032. * Note, this function is called by selectForForms or by ajax selectobject.php
  7033. *
  7034. * @param Object $objecttmp Object to knwo the table to scan for combo.
  7035. * @param string $htmlname Name of HTML select component
  7036. * @param int $preselectedvalue Preselected value (ID of element)
  7037. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7038. * @param string $searchkey Search value
  7039. * @param string $placeholder Place holder
  7040. * @param string $morecss More CSS
  7041. * @param string $moreparams More params provided to ajax call
  7042. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7043. * @param int $outputmode 0=HTML select string, 1=Array
  7044. * @param int $disabled 1=Html component is disabled
  7045. * @param string $sortfield Sort field
  7046. * @param string $filter Add more filter
  7047. * @return string|array Return HTML string
  7048. * @see selectForForms()
  7049. */
  7050. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '')
  7051. {
  7052. global $conf, $langs, $user, $hookmanager;
  7053. //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
  7054. $prefixforautocompletemode = $objecttmp->element;
  7055. if ($prefixforautocompletemode == 'societe') {
  7056. $prefixforautocompletemode = 'company';
  7057. }
  7058. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7059. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  7060. $tmpfieldstoshow = '';
  7061. foreach ($objecttmp->fields as $key => $val) {
  7062. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  7063. continue;
  7064. }
  7065. if (!empty($val['showoncombobox'])) {
  7066. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  7067. }
  7068. }
  7069. if ($tmpfieldstoshow) {
  7070. $fieldstoshow = $tmpfieldstoshow;
  7071. }
  7072. } else {
  7073. // For backward compatibility
  7074. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  7075. }
  7076. if (empty($fieldstoshow)) {
  7077. if (isset($objecttmp->fields['ref'])) {
  7078. $fieldstoshow = 't.ref';
  7079. } else {
  7080. $langs->load("errors");
  7081. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  7082. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  7083. }
  7084. }
  7085. $out = '';
  7086. $outarray = array();
  7087. $tmparray = array();
  7088. $num = 0;
  7089. // Search data
  7090. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".$this->db->prefix().$objecttmp->table_element." as t";
  7091. if (isset($objecttmp->ismultientitymanaged)) {
  7092. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7093. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  7094. $sql .= " INNER JOIN ".$this->db->prefix().$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  7095. }
  7096. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7097. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7098. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  7099. }
  7100. }
  7101. }
  7102. // Add where from hooks
  7103. $parameters = array();
  7104. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  7105. if (!empty($hookmanager->resPrint)) {
  7106. $sql .= $hookmanager->resPrint;
  7107. } else {
  7108. $sql .= " WHERE 1=1";
  7109. if (isset($objecttmp->ismultientitymanaged)) {
  7110. if ($objecttmp->ismultientitymanaged == 1) {
  7111. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  7112. }
  7113. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7114. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  7115. }
  7116. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  7117. if ($objecttmp->element == 'societe') {
  7118. $sql .= " AND t.rowid = ".((int) $user->socid);
  7119. } else {
  7120. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  7121. }
  7122. }
  7123. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7124. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7125. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  7126. }
  7127. }
  7128. }
  7129. if ($searchkey != '') {
  7130. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  7131. }
  7132. if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  7133. /*if (! DolibarrApi::_checkFilters($filter))
  7134. {
  7135. throw new RestException(503, 'Error when validating parameter sqlfilters '.$filter);
  7136. }*/
  7137. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  7138. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $filter).")";
  7139. }
  7140. }
  7141. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7142. //$sql.=$this->db->plimit($limit, 0);
  7143. //print $sql;
  7144. // Build output string
  7145. $resql = $this->db->query($sql);
  7146. if ($resql) {
  7147. // Construct $out and $outarray
  7148. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  7149. // 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
  7150. $textifempty = '&nbsp;';
  7151. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7152. if (!empty($conf->global->$confkeyforautocompletemode)) {
  7153. if ($showempty && !is_numeric($showempty)) {
  7154. $textifempty = $langs->trans($showempty);
  7155. } else {
  7156. $textifempty .= $langs->trans("All");
  7157. }
  7158. }
  7159. if ($showempty) {
  7160. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  7161. }
  7162. $num = $this->db->num_rows($resql);
  7163. $i = 0;
  7164. if ($num) {
  7165. while ($i < $num) {
  7166. $obj = $this->db->fetch_object($resql);
  7167. $label = '';
  7168. $tmparray = explode(',', $fieldstoshow);
  7169. $oldvalueforshowoncombobox = 0;
  7170. foreach ($tmparray as $key => $val) {
  7171. $val = preg_replace('/t\./', '', $val);
  7172. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7173. $label .= $obj->$val;
  7174. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  7175. }
  7176. if (empty($outputmode)) {
  7177. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7178. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  7179. } else {
  7180. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  7181. }
  7182. } else {
  7183. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  7184. }
  7185. $i++;
  7186. if (($i % 10) == 0) {
  7187. $out .= "\n";
  7188. }
  7189. }
  7190. }
  7191. $out .= '</select>'."\n";
  7192. if (!$forcecombo) {
  7193. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7194. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  7195. }
  7196. } else {
  7197. dol_print_error($this->db);
  7198. }
  7199. $this->result = array('nbofelement'=>$num);
  7200. if ($outputmode) {
  7201. return $outarray;
  7202. }
  7203. return $out;
  7204. }
  7205. /**
  7206. * Return a HTML select string, built from an array of key+value.
  7207. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7208. *
  7209. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7210. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7211. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7212. * @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.
  7213. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7214. * @param int $value_as_key 1 to use value as key
  7215. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7216. * @param int $translate 1=Translate and encode value
  7217. * @param int $maxlen Length maximum for labels
  7218. * @param int $disabled Html select box is disabled
  7219. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7220. * @param string $morecss Add more class to css styles
  7221. * @param int $addjscombo Add js combo
  7222. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7223. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7224. * @param int $nohtmlescape No html escaping.
  7225. * @return string HTML select string.
  7226. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7227. */
  7228. public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = 'minwidth75', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  7229. {
  7230. global $conf, $langs;
  7231. // Do we want a multiselect ?
  7232. //$jsbeautify = 0;
  7233. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7234. $jsbeautify = 1;
  7235. if ($value_as_key) {
  7236. $array = array_combine($array, $array);
  7237. }
  7238. $out = '';
  7239. if ($addjscombo < 0) {
  7240. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7241. $addjscombo = 1;
  7242. } else {
  7243. $addjscombo = 0;
  7244. }
  7245. }
  7246. $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
  7247. $out .= '<select id="'.preg_replace('/^\./', '', $idname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  7248. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  7249. $out .= '>';
  7250. if ($show_empty) {
  7251. $textforempty = ' ';
  7252. if (!empty($conf->use_javascript_ajax)) {
  7253. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7254. }
  7255. if (!is_numeric($show_empty)) {
  7256. $textforempty = $show_empty;
  7257. }
  7258. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  7259. }
  7260. if (is_array($array)) {
  7261. // Translate
  7262. if ($translate) {
  7263. foreach ($array as $key => $value) {
  7264. if (!is_array($value)) {
  7265. $array[$key] = $langs->trans($value);
  7266. } else {
  7267. $array[$key]['label'] = $langs->trans($value['label']);
  7268. }
  7269. }
  7270. }
  7271. // Sort
  7272. if ($sort == 'ASC') {
  7273. asort($array);
  7274. } elseif ($sort == 'DESC') {
  7275. arsort($array);
  7276. }
  7277. foreach ($array as $key => $tmpvalue) {
  7278. if (is_array($tmpvalue)) {
  7279. $value = $tmpvalue['label'];
  7280. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7281. $style = empty($tmpvalue['css']) ? '' : ' class="'.$tmpvalue['css'].'"';
  7282. } else {
  7283. $value = $tmpvalue;
  7284. $disabled = '';
  7285. $style = '';
  7286. }
  7287. if (!empty($disablebademail)) {
  7288. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7289. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7290. $disabled = ' disabled';
  7291. $style = ' class="warning"';
  7292. }
  7293. }
  7294. if ($key_in_label) {
  7295. if (empty($nohtmlescape)) {
  7296. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  7297. } else {
  7298. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  7299. }
  7300. } else {
  7301. if (empty($nohtmlescape)) {
  7302. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  7303. } else {
  7304. $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
  7305. }
  7306. if ($value == '' || $value == '-') {
  7307. $selectOptionValue = '&nbsp;';
  7308. }
  7309. }
  7310. $out .= '<option value="'.$key.'"';
  7311. $out .= $style.$disabled;
  7312. if (is_array($id)) {
  7313. if (in_array($key, $id) && !$disabled) {
  7314. $out .= ' selected'; // To preselect a value
  7315. }
  7316. } else {
  7317. $id = (string) $id; // if $id = 0, then $id = '0'
  7318. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7319. $out .= ' selected'; // To preselect a value
  7320. }
  7321. }
  7322. if ($nohtmlescape) {
  7323. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  7324. }
  7325. if (is_array($tmpvalue)) {
  7326. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7327. if (preg_match('/^data-/', $keyforvalue)) {
  7328. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  7329. }
  7330. }
  7331. }
  7332. $out .= '>';
  7333. //var_dump($selectOptionValue);
  7334. $out .= $selectOptionValue;
  7335. $out .= "</option>\n";
  7336. }
  7337. }
  7338. $out .= "</select>";
  7339. // Add code for jquery to use multiselect
  7340. if ($addjscombo && $jsbeautify) {
  7341. // Enhance with select2
  7342. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7343. $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', ($show_empty < 0 ? (string) $show_empty : '-1'), $morecss);
  7344. }
  7345. return $out;
  7346. }
  7347. /**
  7348. * 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.
  7349. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7350. *
  7351. * @param string $htmlname Name of html select area
  7352. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7353. * @param string $id Preselected key
  7354. * @param string $moreparam Add more parameters onto the select tag
  7355. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7356. * @param int $disabled Html select box is disabled
  7357. * @param int $minimumInputLength Minimum Input Length
  7358. * @param string $morecss Add more class to css styles
  7359. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7360. * @param string $placeholder String to use as placeholder
  7361. * @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)
  7362. * @return string HTML select string
  7363. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7364. */
  7365. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7366. {
  7367. global $conf, $langs;
  7368. global $delayedhtmlcontent; // Will be used later outside of this function
  7369. // TODO Use an internal dolibarr component instead of select2
  7370. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7371. return '';
  7372. }
  7373. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  7374. $outdelayed = '';
  7375. if (!empty($conf->use_javascript_ajax)) {
  7376. $tmpplugin = 'select2';
  7377. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7378. <script>
  7379. $(document).ready(function () {
  7380. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  7381. $(".'.$htmlname.'").select2({
  7382. ajax: {
  7383. dir: "ltr",
  7384. url: "'.$url.'",
  7385. dataType: \'json\',
  7386. delay: 250,
  7387. data: function (params) {
  7388. return {
  7389. q: params.term, // search term
  7390. page: params.page
  7391. };
  7392. },
  7393. processResults: function (data) {
  7394. // parse the results into the format expected by Select2.
  7395. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7396. //console.log(data);
  7397. saveRemoteData = data;
  7398. /* format json result for select2 */
  7399. result = []
  7400. $.each( data, function( key, value ) {
  7401. result.push({id: key, text: value.text});
  7402. });
  7403. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7404. //console.log(result);
  7405. return {results: result, more: false}
  7406. },
  7407. cache: true
  7408. },
  7409. language: select2arrayoflanguage,
  7410. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7411. placeholder: "'.dol_escape_js($placeholder).'",
  7412. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7413. minimumInputLength: '.$minimumInputLength.',
  7414. formatResult: function(result, container, query, escapeMarkup) {
  7415. return escapeMarkup(result.text);
  7416. },
  7417. });
  7418. '.($callurlonselect ? '
  7419. /* Code to execute a GET when we select a value */
  7420. $(".'.$htmlname.'").change(function() {
  7421. var selected = $(".'.$htmlname.'").val();
  7422. console.log("We select in selectArrayAjax the entry "+selected)
  7423. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7424. $.each( saveRemoteData, function( key, value ) {
  7425. if (key == selected)
  7426. {
  7427. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7428. location.assign(value.url);
  7429. }
  7430. });
  7431. });' : '').'
  7432. });
  7433. </script>';
  7434. }
  7435. if ($acceptdelayedhtml) {
  7436. $delayedhtmlcontent .= $outdelayed;
  7437. } else {
  7438. $out .= $outdelayed;
  7439. }
  7440. return $out;
  7441. }
  7442. /**
  7443. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7444. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7445. *
  7446. * @param string $htmlname Name of html select area
  7447. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7448. * @param string $id Preselected key
  7449. * @param string $moreparam Add more parameters onto the select tag
  7450. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7451. * @param int $disabled Html select box is disabled
  7452. * @param int $minimumInputLength Minimum Input Length
  7453. * @param string $morecss Add more class to css styles
  7454. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7455. * @param string $placeholder String to use as placeholder
  7456. * @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)
  7457. * @return string HTML select string
  7458. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7459. */
  7460. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7461. {
  7462. global $conf, $langs;
  7463. global $delayedhtmlcontent; // Will be used later outside of this function
  7464. // TODO Use an internal dolibarr component instead of select2
  7465. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7466. return '';
  7467. }
  7468. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7469. $formattedarrayresult = array();
  7470. foreach ($array as $key => $value) {
  7471. $o = new stdClass();
  7472. $o->id = $key;
  7473. $o->text = $value['text'];
  7474. $o->url = $value['url'];
  7475. $formattedarrayresult[] = $o;
  7476. }
  7477. $outdelayed = '';
  7478. if (!empty($conf->use_javascript_ajax)) {
  7479. $tmpplugin = 'select2';
  7480. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7481. <script>
  7482. $(document).ready(function () {
  7483. var data = '.json_encode($formattedarrayresult).';
  7484. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7485. $(".'.$htmlname.'").select2({
  7486. data: data,
  7487. language: select2arrayoflanguage,
  7488. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7489. placeholder: "'.dol_escape_js($placeholder).'",
  7490. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7491. minimumInputLength: '.$minimumInputLength.',
  7492. formatResult: function(result, container, query, escapeMarkup) {
  7493. return escapeMarkup(result.text);
  7494. },
  7495. matcher: function (params, data) {
  7496. if(! data.id) return null;';
  7497. if ($callurlonselect) {
  7498. // We forge the url with 'sall='
  7499. $outdelayed .= '
  7500. var urlBase = data.url;
  7501. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7502. /* console.log("params.term="+params.term); */
  7503. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7504. saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7505. }
  7506. if (!$disableFiltering) {
  7507. $outdelayed .= '
  7508. if(data.text.match(new RegExp(params.term))) {
  7509. return data;
  7510. }
  7511. return null;';
  7512. } else {
  7513. $outdelayed .= '
  7514. return data;';
  7515. }
  7516. $outdelayed .= '
  7517. }
  7518. });
  7519. '.($callurlonselect ? '
  7520. /* Code to execute a GET when we select a value */
  7521. $(".'.$htmlname.'").change(function() {
  7522. var selected = $(".'.$htmlname.'").val();
  7523. console.log("We select "+selected)
  7524. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7525. $.each( saveRemoteData, function( key, value ) {
  7526. if (key == selected)
  7527. {
  7528. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7529. location.assign(value.url);
  7530. }
  7531. });
  7532. });' : '').'
  7533. });
  7534. </script>';
  7535. }
  7536. if ($acceptdelayedhtml) {
  7537. $delayedhtmlcontent .= $outdelayed;
  7538. } else {
  7539. $out .= $outdelayed;
  7540. }
  7541. return $out;
  7542. }
  7543. /**
  7544. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7545. *
  7546. * @param string $htmlname Name of select
  7547. * @param array $array Array(key=>value) or Array(key=>array('id'=> , 'label'=> ))
  7548. * @param array $selected Array of keys preselected
  7549. * @param int $key_in_label 1 to show key like in "[key] value"
  7550. * @param int $value_as_key 1 to use value as key
  7551. * @param string $morecss Add more css style
  7552. * @param int $translate Translate and encode value
  7553. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7554. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7555. * @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.
  7556. * @param string $placeholder String to use as placeholder
  7557. * @param int $addjscombo Add js combo
  7558. * @return string HTML multiselect string
  7559. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7560. */
  7561. 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)
  7562. {
  7563. global $conf, $langs;
  7564. $out = '';
  7565. if ($addjscombo < 0) {
  7566. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7567. $addjscombo = 1;
  7568. } else {
  7569. $addjscombo = 0;
  7570. }
  7571. }
  7572. // Try also magic suggest
  7573. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  7574. if (is_array($array) && !empty($array)) {
  7575. if ($value_as_key) {
  7576. $array = array_combine($array, $array);
  7577. }
  7578. if (!empty($array)) {
  7579. foreach ($array as $key => $value) {
  7580. $tmpkey = $key;
  7581. $tmpvalue = $value;
  7582. $tmpcolor = '';
  7583. $tmppicto = '';
  7584. if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
  7585. $tmpkey = $value['id'];
  7586. $tmpvalue = $value['label'];
  7587. $tmpcolor = $value['color'];
  7588. $tmppicto = $value['picto'];
  7589. }
  7590. $newval = ($translate ? $langs->trans($tmpvalue) : $tmpvalue);
  7591. $newval = ($key_in_label ? $tmpkey.' - '.$newval : $newval);
  7592. $out .= '<option value="'.$tmpkey.'"';
  7593. if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
  7594. $out .= ' selected';
  7595. }
  7596. $out .= ' data-html="'.dol_escape_htmltag(($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #'.$tmpcolor.'"') : '').$newval).'"';
  7597. $out .= '>';
  7598. $out .= dol_htmlentitiesbr($newval);
  7599. $out .= '</option>'."\n";
  7600. }
  7601. }
  7602. }
  7603. $out .= '</select>'."\n";
  7604. // Add code for jquery to use multiselect
  7605. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7606. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7607. $out .= "\n".'<script>'."\n";
  7608. if ($addjscombo == 1) {
  7609. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7610. $out .= 'function formatResult(record, container) {'."\n";
  7611. $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";
  7612. $out .= ' return record.text;';
  7613. $out .= '};'."\n";
  7614. $out .= 'function formatSelection(record) {'."\n";
  7615. if ($elemtype == 'category') {
  7616. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7617. } else {
  7618. $out .= 'return record.text;';
  7619. }
  7620. $out .= '};'."\n";
  7621. $out .= '$(document).ready(function () {
  7622. $(\'#'.$htmlname.'\').'.$tmpplugin.'({';
  7623. if ($placeholder) {
  7624. $out .= '
  7625. placeholder: {
  7626. id: \'-1\',
  7627. text: \''.dol_escape_js($placeholder).'\'
  7628. },';
  7629. }
  7630. $out .= ' dir: \'ltr\',
  7631. // Specify format function for dropdown item
  7632. formatResult: formatResult,
  7633. templateResult: formatResult, /* For 4.0 */
  7634. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7635. // Specify format function for selected item
  7636. formatSelection: formatSelection,
  7637. templateSelection: formatSelection /* For 4.0 */
  7638. });
  7639. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7640. the size only if component is not hidden by default on load */
  7641. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7642. });'."\n";
  7643. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7644. // Add other js lib
  7645. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7646. // ...
  7647. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7648. $out .= '$(document).ready(function () {
  7649. $(\'#'.$htmlname.'\').multiSelect({
  7650. containerHTML: \'<div class="multi-select-container">\',
  7651. menuHTML: \'<div class="multi-select-menu">\',
  7652. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7653. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7654. activeClass: \'multi-select-container--open\',
  7655. noneText: \''.$placeholder.'\'
  7656. });
  7657. })';
  7658. }
  7659. $out .= '</script>';
  7660. }
  7661. return $out;
  7662. }
  7663. /**
  7664. * 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.
  7665. *
  7666. * @param string $htmlname Name of HTML field
  7667. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7668. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7669. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7670. * @return string HTML multiselect string
  7671. * @see selectarray()
  7672. */
  7673. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7674. {
  7675. global $conf, $langs, $user, $extrafields;
  7676. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7677. return '';
  7678. }
  7679. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7680. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7681. $tmparray = explode(',', $user->conf->$tmpvar);
  7682. foreach ($array as $key => $val) {
  7683. //var_dump($key);
  7684. //var_dump($tmparray);
  7685. if (in_array($key, $tmparray)) {
  7686. $array[$key]['checked'] = 1;
  7687. } else {
  7688. $array[$key]['checked'] = 0;
  7689. }
  7690. }
  7691. } else { // There is no list of fields already customized for user
  7692. foreach ($array as $key => $val) {
  7693. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7694. $array[$key]['checked'] = 0;
  7695. }
  7696. }
  7697. }
  7698. $listoffieldsforselection = '';
  7699. $listcheckedstring = '';
  7700. foreach ($array as $key => $val) {
  7701. // var_dump($val);
  7702. // var_dump(array_key_exists('enabled', $val));
  7703. // var_dump(!$val['enabled']);
  7704. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7705. unset($array[$key]); // We don't want this field
  7706. continue;
  7707. }
  7708. if (!empty($val['type']) && $val['type'] == 'separate') {
  7709. // Field remains in array but we don't add it into $listoffieldsforselection
  7710. //$listoffieldsforselection .= '<li>-----</li>';
  7711. continue;
  7712. }
  7713. if ($val['label']) {
  7714. if (!empty($val['langfile']) && is_object($langs)) {
  7715. $langs->load($val['langfile']);
  7716. }
  7717. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7718. $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>';
  7719. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7720. }
  7721. }
  7722. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7723. <dl class="dropdown">
  7724. <dt>
  7725. <a href="#'.$htmlname.'">
  7726. '.img_picto('', 'list').'
  7727. </a>
  7728. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7729. </dt>
  7730. <dd class="dropdowndd">
  7731. <div class="multiselectcheckbox'.$htmlname.'">
  7732. <ul class="'.$htmlname.($pos == '1' ? 'left' : '').'">
  7733. '.$listoffieldsforselection.'
  7734. </ul>
  7735. </div>
  7736. </dd>
  7737. </dl>
  7738. <script type="text/javascript">
  7739. jQuery(document).ready(function () {
  7740. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7741. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7742. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7743. var title = $(this).val() + ",";
  7744. if ($(this).is(\':checked\')) {
  7745. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7746. }
  7747. else {
  7748. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7749. }
  7750. // Now, we submit page
  7751. //$(this).parents(\'form:first\').submit();
  7752. });
  7753. });
  7754. </script>
  7755. ';
  7756. return $out;
  7757. }
  7758. /**
  7759. * Render list of categories linked to object with id $id and type $type
  7760. *
  7761. * @param int $id Id of object
  7762. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7763. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7764. * @param int $nolink 1=Do not add html links
  7765. * @return string String with categories
  7766. */
  7767. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7768. {
  7769. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7770. $cat = new Categorie($this->db);
  7771. $categories = $cat->containing($id, $type);
  7772. if ($rendermode == 1) {
  7773. $toprint = array();
  7774. foreach ($categories as $c) {
  7775. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7776. foreach ($ways as $way) {
  7777. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7778. }
  7779. }
  7780. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7781. }
  7782. if ($rendermode == 0) {
  7783. $arrayselected = array();
  7784. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7785. foreach ($categories as $c) {
  7786. $arrayselected[] = $c->id;
  7787. }
  7788. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7789. }
  7790. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7791. }
  7792. /**
  7793. * Show linked object block.
  7794. *
  7795. * @param CommonObject $object Object we want to show links to
  7796. * @param string $morehtmlright More html to show on right of title
  7797. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7798. * @param string $title Title
  7799. * @return int <0 if KO, >=0 if OK
  7800. */
  7801. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false, $title = 'RelatedObjects')
  7802. {
  7803. global $conf, $langs, $hookmanager;
  7804. global $bc, $action;
  7805. $object->fetchObjectLinked();
  7806. // Bypass the default method
  7807. $hookmanager->initHooks(array('commonobject'));
  7808. $parameters = array(
  7809. 'morehtmlright' => $morehtmlright,
  7810. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7811. );
  7812. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7813. if (empty($reshook)) {
  7814. $nbofdifferenttypes = count($object->linkedObjects);
  7815. print '<!-- showLinkedObjectBlock -->';
  7816. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7817. print '<div class="div-table-responsive-no-min">';
  7818. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7819. print '<tr class="liste_titre">';
  7820. print '<td>'.$langs->trans("Type").'</td>';
  7821. print '<td>'.$langs->trans("Ref").'</td>';
  7822. print '<td class="center"></td>';
  7823. print '<td class="center">'.$langs->trans("Date").'</td>';
  7824. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7825. print '<td class="right">'.$langs->trans("Status").'</td>';
  7826. print '<td></td>';
  7827. print '</tr>';
  7828. $nboftypesoutput = 0;
  7829. foreach ($object->linkedObjects as $objecttype => $objects) {
  7830. $tplpath = $element = $subelement = $objecttype;
  7831. // to display inport button on tpl
  7832. $showImportButton = false;
  7833. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7834. $showImportButton = true;
  7835. }
  7836. $regs = array();
  7837. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7838. $element = $regs[1];
  7839. $subelement = $regs[2];
  7840. $tplpath = $element.'/'.$subelement;
  7841. }
  7842. $tplname = 'linkedobjectblock';
  7843. // To work with non standard path
  7844. if ($objecttype == 'facture') {
  7845. $tplpath = 'compta/'.$element;
  7846. if (!isModEnabled('facture')) {
  7847. continue; // Do not show if module disabled
  7848. }
  7849. } elseif ($objecttype == 'facturerec') {
  7850. $tplpath = 'compta/facture';
  7851. $tplname = 'linkedobjectblockForRec';
  7852. if (!isModEnabled('facture')) {
  7853. continue; // Do not show if module disabled
  7854. }
  7855. } elseif ($objecttype == 'propal') {
  7856. $tplpath = 'comm/'.$element;
  7857. if (!isModEnabled('propal')) {
  7858. continue; // Do not show if module disabled
  7859. }
  7860. } elseif ($objecttype == 'supplier_proposal') {
  7861. if (!isModEnabled('supplier_proposal')) {
  7862. continue; // Do not show if module disabled
  7863. }
  7864. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
  7865. $tplpath = 'expedition';
  7866. if (!isModEnabled('expedition')) {
  7867. continue; // Do not show if module disabled
  7868. }
  7869. } elseif ($objecttype == 'reception') {
  7870. $tplpath = 'reception';
  7871. if (!isModEnabled('reception')) {
  7872. continue; // Do not show if module disabled
  7873. }
  7874. } elseif ($objecttype == 'delivery') {
  7875. $tplpath = 'delivery';
  7876. if (!isModEnabled('expedition')) {
  7877. continue; // Do not show if module disabled
  7878. }
  7879. } elseif ($objecttype == 'ficheinter') {
  7880. $tplpath = 'fichinter';
  7881. if (!isModEnabled('ficheinter')) {
  7882. continue; // Do not show if module disabled
  7883. }
  7884. } elseif ($objecttype == 'invoice_supplier') {
  7885. $tplpath = 'fourn/facture';
  7886. } elseif ($objecttype == 'order_supplier') {
  7887. $tplpath = 'fourn/commande';
  7888. } elseif ($objecttype == 'expensereport') {
  7889. $tplpath = 'expensereport';
  7890. } elseif ($objecttype == 'subscription') {
  7891. $tplpath = 'adherents';
  7892. } elseif ($objecttype == 'conferenceorbooth') {
  7893. $tplpath = 'eventorganization';
  7894. } elseif ($objecttype == 'conferenceorboothattendee') {
  7895. $tplpath = 'eventorganization';
  7896. } elseif ($objecttype == 'mo') {
  7897. $tplpath = 'mrp';
  7898. if (!isModEnabled('mrp')) {
  7899. continue; // Do not show if module disabled
  7900. }
  7901. }
  7902. global $linkedObjectBlock;
  7903. $linkedObjectBlock = $objects;
  7904. // Output template part (modules that overwrite templates must declare this into descriptor)
  7905. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7906. foreach ($dirtpls as $reldir) {
  7907. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7908. global $noMoreLinkedObjectBlockAfter;
  7909. $noMoreLinkedObjectBlockAfter = 1;
  7910. }
  7911. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7912. if ($res) {
  7913. $nboftypesoutput++;
  7914. break;
  7915. }
  7916. }
  7917. }
  7918. if (!$nboftypesoutput) {
  7919. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7920. }
  7921. print '</table>';
  7922. if (!empty($compatibleImportElementsList)) {
  7923. $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
  7924. }
  7925. print '</div>';
  7926. return $nbofdifferenttypes;
  7927. }
  7928. }
  7929. /**
  7930. * Show block with links to link to other objects.
  7931. *
  7932. * @param CommonObject $object Object we want to show links to
  7933. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7934. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7935. * @return string <0 if KO, >0 if OK
  7936. */
  7937. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7938. {
  7939. global $conf, $langs, $hookmanager;
  7940. global $action;
  7941. $linktoelem = '';
  7942. $linktoelemlist = '';
  7943. $listofidcompanytoscan = '';
  7944. if (!is_object($object->thirdparty)) {
  7945. $object->fetch_thirdparty();
  7946. }
  7947. $possiblelinks = array();
  7948. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7949. $listofidcompanytoscan = $object->thirdparty->id;
  7950. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7951. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7952. }
  7953. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7954. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7955. $tmpproject = new Project($this->db);
  7956. $tmpproject->fetch($object->fk_project);
  7957. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7958. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7959. }
  7960. unset($tmpproject);
  7961. }
  7962. $possiblelinks = array(
  7963. 'propal'=>array(
  7964. 'enabled'=>isModEnabled('propal'),
  7965. 'perms'=>1,
  7966. 'label'=>'LinkToProposal',
  7967. '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').')'),
  7968. 'shipping'=>array(
  7969. 'enabled'=>isModEnabled('expedition'),
  7970. 'perms'=>1,
  7971. 'label'=>'LinkToExpedition',
  7972. 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix()."expedition as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('shipping').')'),
  7973. 'order'=>array(
  7974. 'enabled'=>isModEnabled('commande'),
  7975. 'perms'=>1,
  7976. 'label'=>'LinkToOrder',
  7977. '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').')'),
  7978. 'invoice'=>array(
  7979. 'enabled'=>isModEnabled('facture'),
  7980. 'perms'=>1,
  7981. 'label'=>'LinkToInvoice',
  7982. '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').')'),
  7983. 'invoice_template'=>array(
  7984. 'enabled'=>isModEnabled('facture'),
  7985. 'perms'=>1,
  7986. 'label'=>'LinkToTemplateInvoice',
  7987. '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').')'),
  7988. 'contrat'=>array(
  7989. 'enabled'=>isModEnabled('contrat'),
  7990. 'perms'=>1,
  7991. 'label'=>'LinkToContract',
  7992. '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
  7993. 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'
  7994. ),
  7995. 'fichinter'=>array(
  7996. 'enabled'=>isModEnabled('ficheinter'),
  7997. 'perms'=>1,
  7998. 'label'=>'LinkToIntervention',
  7999. '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').')'),
  8000. 'supplier_proposal'=>array(
  8001. 'enabled'=>(isModEnabled('supplier_proposal') ? $conf->supplier_proposal->enabled : 0),
  8002. 'perms'=>1,
  8003. 'label'=>'LinkToSupplierProposal',
  8004. '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').')'),
  8005. 'order_supplier'=>array(
  8006. 'enabled'=>(isModEnabled("supplier_order") ? $conf->supplier_order->enabled : 0),
  8007. 'perms'=>1,
  8008. 'label'=>'LinkToSupplierOrder',
  8009. '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').')'),
  8010. 'invoice_supplier'=>array(
  8011. 'enabled'=>(isModEnabled("supplier_invoice") ? $conf->supplier_invoice->enabled : 0),
  8012. 'perms'=>1, 'label'=>'LinkToSupplierInvoice',
  8013. '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').')'),
  8014. 'ticket'=>array(
  8015. 'enabled'=>isModEnabled('ticket'),
  8016. 'perms'=>1,
  8017. 'label'=>'LinkToTicket',
  8018. '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').')'),
  8019. 'mo'=>array(
  8020. 'enabled'=>isModEnabled('mrp'),
  8021. 'perms'=>1,
  8022. 'label'=>'LinkToMo',
  8023. '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').')')
  8024. );
  8025. }
  8026. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  8027. // Can complete the possiblelink array
  8028. $hookmanager->initHooks(array('commonobject'));
  8029. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  8030. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8031. }
  8032. if (empty($reshook)) {
  8033. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8034. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  8035. }
  8036. } elseif ($reshook > 0) {
  8037. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8038. $possiblelinks = $hookmanager->resArray;
  8039. }
  8040. }
  8041. foreach ($possiblelinks as $key => $possiblelink) {
  8042. $num = 0;
  8043. if (empty($possiblelink['enabled'])) {
  8044. continue;
  8045. }
  8046. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  8047. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  8048. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8049. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  8050. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8051. print '<input type="hidden" name="action" value="addlinkbyref">';
  8052. print '<input type="hidden" name="token" value="'.newToken().'">';
  8053. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8054. print '<table class="noborder">';
  8055. print '<tr>';
  8056. print '<td>' . $langs->trans("Ref") . '</td>';
  8057. 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>';
  8058. print '</tr>';
  8059. print '</table>';
  8060. print '</form>';
  8061. }
  8062. $sql = $possiblelink['sql'];
  8063. $resqllist = $this->db->query($sql);
  8064. if ($resqllist) {
  8065. $num = $this->db->num_rows($resqllist);
  8066. $i = 0;
  8067. print '<br>';
  8068. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  8069. print '<input type="hidden" name="action" value="addlink">';
  8070. print '<input type="hidden" name="token" value="'.newToken().'">';
  8071. print '<input type="hidden" name="id" value="'.$object->id.'">';
  8072. print '<input type="hidden" name="addlink" value="'.$key.'">';
  8073. print '<table class="noborder">';
  8074. print '<tr class="liste_titre">';
  8075. print '<td class="nowrap"></td>';
  8076. print '<td class="center">'.$langs->trans("Ref").'</td>';
  8077. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  8078. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  8079. print '<td class="left">'.$langs->trans("Company").'</td>';
  8080. print '</tr>';
  8081. while ($i < $num) {
  8082. $objp = $this->db->fetch_object($resqllist);
  8083. print '<tr class="oddeven">';
  8084. print '<td class="left">';
  8085. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  8086. print '</td>';
  8087. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  8088. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  8089. print '<td class="right">';
  8090. if ($possiblelink['label'] == 'LinkToContract') {
  8091. $form = new Form($this->db);
  8092. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  8093. }
  8094. print '<span class="amount">'.(isset($objp->total_ht) ? price($objp->total_ht) : '').'</span>';
  8095. print '</td>';
  8096. print '<td>'.$objp->name.'</td>';
  8097. print '</tr>';
  8098. $i++;
  8099. }
  8100. print '</table>';
  8101. print '<div class="center">';
  8102. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  8103. if (empty($conf->use_javascript_ajax)) {
  8104. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  8105. } else {
  8106. 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>';
  8107. }
  8108. print '</form>';
  8109. $this->db->free($resqllist);
  8110. } else {
  8111. dol_print_error($this->db);
  8112. }
  8113. print '</div>';
  8114. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  8115. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8116. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  8117. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  8118. } else {
  8119. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  8120. }
  8121. }
  8122. }
  8123. if ($linktoelemlist) {
  8124. $linktoelem = '
  8125. <dl class="dropdown" id="linktoobjectname">
  8126. ';
  8127. if (!empty($conf->use_javascript_ajax)) {
  8128. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  8129. }
  8130. $linktoelem .= '<dd>
  8131. <div class="multiselectlinkto">
  8132. <ul class="ulselectedfields">'.$linktoelemlist.'
  8133. </ul>
  8134. </div>
  8135. </dd>
  8136. </dl>';
  8137. } else {
  8138. $linktoelem = '';
  8139. }
  8140. if (!empty($conf->use_javascript_ajax)) {
  8141. print '<!-- Add js to show linkto box -->
  8142. <script>
  8143. jQuery(document).ready(function() {
  8144. jQuery(".linkto").click(function() {
  8145. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  8146. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  8147. });
  8148. });
  8149. </script>
  8150. ';
  8151. }
  8152. return $linktoelem;
  8153. }
  8154. /**
  8155. * Return an html string with a select combo box to choose yes or no
  8156. *
  8157. * @param string $htmlname Name of html select field
  8158. * @param string $value Pre-selected value
  8159. * @param int $option 0 return yes/no, 1 return 1/0
  8160. * @param bool $disabled true or false
  8161. * @param int $useempty 1=Add empty line
  8162. * @param int $addjscombo 1=Add js beautifier on combo box
  8163. * @param string $morecss More CSS
  8164. * @param string $labelyes Label for Yes
  8165. * @param string $labelno Label for No
  8166. * @return string See option
  8167. */
  8168. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8169. {
  8170. global $langs;
  8171. $yes = "yes";
  8172. $no = "no";
  8173. if ($option) {
  8174. $yes = "1";
  8175. $no = "0";
  8176. }
  8177. $disabled = ($disabled ? ' disabled' : '');
  8178. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  8179. if ($useempty) {
  8180. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8181. }
  8182. if (("$value" == 'yes') || ($value == 1)) {
  8183. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans($labelyes).'</option>'."\n";
  8184. $resultyesno .= '<option value="'.$no.'">'.$langs->trans($labelno).'</option>'."\n";
  8185. } else {
  8186. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8187. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans($labelyes).'</option>'."\n";
  8188. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans($labelno).'</option>'."\n";
  8189. }
  8190. $resultyesno .= '</select>'."\n";
  8191. if ($addjscombo) {
  8192. $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
  8193. }
  8194. return $resultyesno;
  8195. }
  8196. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8197. /**
  8198. * Return list of export templates
  8199. *
  8200. * @param string $selected Id modele pre-selectionne
  8201. * @param string $htmlname Name of HTML select
  8202. * @param string $type Type of searched templates
  8203. * @param int $useempty Affiche valeur vide dans liste
  8204. * @return void
  8205. */
  8206. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8207. {
  8208. // phpcs:enable
  8209. $sql = "SELECT rowid, label";
  8210. $sql .= " FROM ".$this->db->prefix()."export_model";
  8211. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  8212. $sql .= " ORDER BY rowid";
  8213. $result = $this->db->query($sql);
  8214. if ($result) {
  8215. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  8216. if ($useempty) {
  8217. print '<option value="-1">&nbsp;</option>';
  8218. }
  8219. $num = $this->db->num_rows($result);
  8220. $i = 0;
  8221. while ($i < $num) {
  8222. $obj = $this->db->fetch_object($result);
  8223. if ($selected == $obj->rowid) {
  8224. print '<option value="'.$obj->rowid.'" selected>';
  8225. } else {
  8226. print '<option value="'.$obj->rowid.'">';
  8227. }
  8228. print $obj->label;
  8229. print '</option>';
  8230. $i++;
  8231. }
  8232. print "</select>";
  8233. } else {
  8234. dol_print_error($this->db);
  8235. }
  8236. }
  8237. /**
  8238. * Return a HTML area with the reference of object and a navigation bar for a business object
  8239. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8240. *
  8241. * @param object $object Object to show.
  8242. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8243. * @param string $morehtml More html content to output just before the nav bar.
  8244. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8245. * @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.
  8246. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8247. * @param string $morehtmlref More html to show after ref.
  8248. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8249. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8250. * @param string $morehtmlleft More html code to show before ref.
  8251. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8252. * @param string $morehtmlright More html code to show after ref.
  8253. * @return string Portion HTML with ref + navigation buttons
  8254. */
  8255. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8256. {
  8257. global $conf, $langs, $hookmanager, $extralanguages;
  8258. $ret = '';
  8259. if (empty($fieldid)) {
  8260. $fieldid = 'rowid';
  8261. }
  8262. if (empty($fieldref)) {
  8263. $fieldref = 'ref';
  8264. }
  8265. // Preparing gender's display if there is one
  8266. $addgendertxt = '';
  8267. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8268. $addgendertxt = ' ';
  8269. switch ($object->gender) {
  8270. case 'man':
  8271. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8272. break;
  8273. case 'woman':
  8274. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8275. break;
  8276. case 'other':
  8277. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8278. break;
  8279. }
  8280. }
  8281. /*
  8282. $addadmin = '';
  8283. if (property_exists($object, 'admin')) {
  8284. if (isModEnabled('multicompany') && !empty($object->admin) && empty($object->entity)) {
  8285. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8286. } elseif (!empty($object->admin)) {
  8287. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8288. }
  8289. }*/
  8290. // Add where from hooks
  8291. if (is_object($hookmanager)) {
  8292. $parameters = array('showrefnav' => true);
  8293. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8294. $object->next_prev_filter .= $hookmanager->resPrint;
  8295. }
  8296. $previous_ref = $next_ref = '';
  8297. if ($shownav) {
  8298. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8299. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8300. $navurl = $_SERVER["PHP_SELF"];
  8301. // Special case for project/task page
  8302. if ($paramid == 'project_ref') {
  8303. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8304. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8305. $paramid = 'ref';
  8306. }
  8307. }
  8308. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8309. // accesskey is for Mac: CTRL + key for all browsers
  8310. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8311. if ($conf->browser->name == 'chrome') {
  8312. $stringforfirstkey .= ' ALT +';
  8313. } elseif ($conf->browser->name == 'firefox') {
  8314. $stringforfirstkey .= ' ALT + SHIFT +';
  8315. } else {
  8316. $stringforfirstkey .= ' CTL +';
  8317. }
  8318. $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>';
  8319. $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>';
  8320. }
  8321. //print "xx".$previous_ref."x".$next_ref;
  8322. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8323. // Right part of banner
  8324. if ($morehtmlright) {
  8325. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  8326. }
  8327. if ($previous_ref || $next_ref || $morehtml) {
  8328. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8329. }
  8330. if ($morehtml) {
  8331. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  8332. }
  8333. if ($shownav && ($previous_ref || $next_ref)) {
  8334. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  8335. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  8336. }
  8337. if ($previous_ref || $next_ref || $morehtml) {
  8338. $ret .= '</ul></div>';
  8339. }
  8340. $parameters = array();
  8341. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8342. if (empty($reshook)) {
  8343. $morehtmlstatus .= $hookmanager->resPrint;
  8344. } else {
  8345. $morehtmlstatus = $hookmanager->resPrint;
  8346. }
  8347. if ($morehtmlstatus) {
  8348. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  8349. }
  8350. $parameters = array();
  8351. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8352. if (empty($reshook)) {
  8353. $morehtmlref .= $hookmanager->resPrint;
  8354. } elseif ($reshook > 0) {
  8355. $morehtmlref = $hookmanager->resPrint;
  8356. }
  8357. // Left part of banner
  8358. if ($morehtmlleft) {
  8359. if ($conf->browser->layout == 'phone') {
  8360. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  8361. } else {
  8362. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  8363. }
  8364. }
  8365. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8366. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  8367. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8368. if ($object->element == 'societe') {
  8369. $ret .= dol_htmlentities($object->name);
  8370. // List of extra languages
  8371. $arrayoflangcode = array();
  8372. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8373. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8374. }
  8375. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8376. if (!is_object($extralanguages)) {
  8377. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  8378. $extralanguages = new ExtraLanguages($this->db);
  8379. }
  8380. $extralanguages->fetch_name_extralanguages('societe');
  8381. if (!empty($extralanguages->attributes['societe']['name'])) {
  8382. $object->fetchValuesForExtraLanguages();
  8383. $htmltext = '';
  8384. // If there is extra languages
  8385. foreach ($arrayoflangcode as $extralangcode) {
  8386. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8387. if ($object->array_languages['name'][$extralangcode]) {
  8388. $htmltext .= $object->array_languages['name'][$extralangcode];
  8389. } else {
  8390. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  8391. }
  8392. }
  8393. $ret .= '<!-- Show translations of name -->'."\n";
  8394. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8395. }
  8396. }
  8397. } elseif ($object->element == 'member') {
  8398. $ret .= $object->ref.'<br>';
  8399. $fullname = $object->getFullName($langs);
  8400. if ($object->morphy == 'mor' && $object->societe) {
  8401. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  8402. } else {
  8403. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  8404. }
  8405. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8406. $ret .= dol_htmlentities($object->getFullName($langs)).$addgendertxt;
  8407. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8408. $ret .= $object->ref.'<br>'.$object->label;
  8409. } elseif (in_array($object->element, array('adherent_type'))) {
  8410. $ret .= $object->label;
  8411. } elseif ($object->element == 'ecm_directories') {
  8412. $ret .= '';
  8413. } elseif ($fieldref != 'none') {
  8414. $ret .= dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "");
  8415. }
  8416. if ($morehtmlref) {
  8417. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8418. if (substr($morehtmlref, 0, 4) != '<div') {
  8419. $ret .= ' ';
  8420. }
  8421. $ret .= $morehtmlref;
  8422. }
  8423. $ret .= '</div>';
  8424. $ret .= '</div><!-- End banner content -->';
  8425. return $ret;
  8426. }
  8427. /**
  8428. * Return HTML code to output a barcode
  8429. *
  8430. * @param Object $object Object containing data to retrieve file name
  8431. * @param int $width Width of photo
  8432. * @param string $morecss More CSS on img of barcode
  8433. * @return string HTML code to output barcode
  8434. */
  8435. public function showbarcode(&$object, $width = 100, $morecss = '')
  8436. {
  8437. global $conf;
  8438. //Check if barcode is filled in the card
  8439. if (empty($object->barcode)) {
  8440. return '';
  8441. }
  8442. // Complete object if not complete
  8443. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8444. $result = $object->fetch_barcode();
  8445. //Check if fetch_barcode() failed
  8446. if ($result < 1) {
  8447. return '<!-- ErrorFetchBarcode -->';
  8448. }
  8449. }
  8450. // Barcode image
  8451. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8452. $out = '<!-- url barcode = '.$url.' -->';
  8453. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8454. return $out;
  8455. }
  8456. /**
  8457. * Return HTML code to output a photo
  8458. *
  8459. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8460. * @param object $object Object containing data to retrieve file name
  8461. * @param int $width Width of photo
  8462. * @param int $height Height of photo (auto if 0)
  8463. * @param int $caneditfield Add edit fields
  8464. * @param string $cssclass CSS name to use on img for photo
  8465. * @param string $imagesize 'mini', 'small' or '' (original)
  8466. * @param int $addlinktofullsize Add link to fullsize image
  8467. * @param int $cache 1=Accept to use image in cache
  8468. * @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 ''.
  8469. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8470. * @return string HTML code to output photo
  8471. */
  8472. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8473. {
  8474. global $conf, $langs;
  8475. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8476. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8477. $ret = '';
  8478. $dir = '';
  8479. $file = '';
  8480. $originalfile = '';
  8481. $altfile = '';
  8482. $email = '';
  8483. $capture = '';
  8484. if ($modulepart == 'societe') {
  8485. $dir = $conf->societe->multidir_output[$entity];
  8486. if (!empty($object->logo)) {
  8487. if (dolIsAllowedForPreview($object->logo)) {
  8488. if ((string) $imagesize == 'mini') {
  8489. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8490. } elseif ((string) $imagesize == 'small') {
  8491. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8492. } else {
  8493. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8494. }
  8495. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8496. }
  8497. }
  8498. $email = $object->email;
  8499. } elseif ($modulepart == 'contact') {
  8500. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8501. if (!empty($object->photo)) {
  8502. if (dolIsAllowedForPreview($object->photo)) {
  8503. if ((string) $imagesize == 'mini') {
  8504. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8505. } elseif ((string) $imagesize == 'small') {
  8506. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8507. } else {
  8508. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8509. }
  8510. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8511. }
  8512. }
  8513. $email = $object->email;
  8514. $capture = 'user';
  8515. } elseif ($modulepart == 'userphoto') {
  8516. $dir = $conf->user->dir_output;
  8517. if (!empty($object->photo)) {
  8518. if (dolIsAllowedForPreview($object->photo)) {
  8519. if ((string) $imagesize == 'mini') {
  8520. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8521. } elseif ((string) $imagesize == 'small') {
  8522. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8523. } else {
  8524. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8525. }
  8526. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8527. }
  8528. }
  8529. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8530. $altfile = $object->id.".jpg"; // For backward compatibility
  8531. }
  8532. $email = $object->email;
  8533. $capture = 'user';
  8534. } elseif ($modulepart == 'memberphoto') {
  8535. $dir = $conf->adherent->dir_output;
  8536. if (!empty($object->photo)) {
  8537. if (dolIsAllowedForPreview($object->photo)) {
  8538. if ((string) $imagesize == 'mini') {
  8539. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8540. } elseif ((string) $imagesize == 'small') {
  8541. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8542. } else {
  8543. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8544. }
  8545. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8546. }
  8547. }
  8548. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8549. $altfile = $object->id.".jpg"; // For backward compatibility
  8550. }
  8551. $email = $object->email;
  8552. $capture = 'user';
  8553. } else {
  8554. // Generic case to show photos
  8555. $dir = $conf->$modulepart->dir_output;
  8556. if (!empty($object->photo)) {
  8557. if (dolIsAllowedForPreview($object->photo)) {
  8558. if ((string) $imagesize == 'mini') {
  8559. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8560. } elseif ((string) $imagesize == 'small') {
  8561. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8562. } else {
  8563. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8564. }
  8565. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8566. }
  8567. }
  8568. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8569. $altfile = $object->id.".jpg"; // For backward compatibility
  8570. }
  8571. $email = $object->email;
  8572. }
  8573. if ($forcecapture) {
  8574. $capture = $forcecapture;
  8575. }
  8576. if ($dir) {
  8577. if ($file && file_exists($dir."/".$file)) {
  8578. if ($addlinktofullsize) {
  8579. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8580. if ($urladvanced) {
  8581. $ret .= '<a href="'.$urladvanced.'">';
  8582. } else {
  8583. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8584. }
  8585. }
  8586. $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.'">';
  8587. if ($addlinktofullsize) {
  8588. $ret .= '</a>';
  8589. }
  8590. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8591. if ($addlinktofullsize) {
  8592. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8593. if ($urladvanced) {
  8594. $ret .= '<a href="'.$urladvanced.'">';
  8595. } else {
  8596. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8597. }
  8598. }
  8599. $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.'">';
  8600. if ($addlinktofullsize) {
  8601. $ret .= '</a>';
  8602. }
  8603. } else {
  8604. $nophoto = '/public/theme/common/nophoto.png';
  8605. $defaultimg = 'identicon'; // For gravatar
  8606. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8607. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8608. $nophoto = 'company';
  8609. } else {
  8610. $nophoto = '/public/theme/common/user_anonymous.png';
  8611. if (!empty($object->gender) && $object->gender == 'man') {
  8612. $nophoto = '/public/theme/common/user_man.png';
  8613. }
  8614. if (!empty($object->gender) && $object->gender == 'woman') {
  8615. $nophoto = '/public/theme/common/user_woman.png';
  8616. }
  8617. }
  8618. }
  8619. if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
  8620. // see https://gravatar.com/site/implement/images/php/
  8621. $ret .= '<!-- Put link to gravatar -->';
  8622. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" 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
  8623. } else {
  8624. if ($nophoto == 'company') {
  8625. $ret .= '<div class="divforspanimg photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'>'.img_picto('', 'company').'</div>';
  8626. $ret .= '<div class="difforspanimgright"></div>';
  8627. } else {
  8628. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8629. }
  8630. }
  8631. }
  8632. if ($caneditfield) {
  8633. if ($object->photo) {
  8634. $ret .= "<br>\n";
  8635. }
  8636. $ret .= '<table class="nobordernopadding centpercent">';
  8637. if ($object->photo) {
  8638. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8639. }
  8640. $ret .= '<tr><td class="tdoverflow">';
  8641. $maxfilesizearray = getMaxFileSizeArray();
  8642. $maxmin = $maxfilesizearray['maxmin'];
  8643. if ($maxmin > 0) {
  8644. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
  8645. }
  8646. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'>';
  8647. $ret .= '</td></tr>';
  8648. $ret .= '</table>';
  8649. }
  8650. } else {
  8651. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8652. }
  8653. return $ret;
  8654. }
  8655. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8656. /**
  8657. * Return select list of groups
  8658. *
  8659. * @param string|object $selected Id group or group preselected
  8660. * @param string $htmlname Field name in form
  8661. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8662. * @param string|array $exclude Array list of groups id to exclude
  8663. * @param int $disabled If select list must be disabled
  8664. * @param string|array $include Array list of groups id to include
  8665. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8666. * @param string $force_entity '0' or Ids of environment to force
  8667. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8668. * @param string $morecss More css to add to html component
  8669. * @return string
  8670. * @see select_dolusers()
  8671. */
  8672. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8673. {
  8674. // phpcs:enable
  8675. global $conf, $user, $langs;
  8676. // Permettre l'exclusion de groupes
  8677. $excludeGroups = null;
  8678. if (is_array($exclude)) {
  8679. $excludeGroups = implode(",", $exclude);
  8680. }
  8681. // Permettre l'inclusion de groupes
  8682. $includeGroups = null;
  8683. if (is_array($include)) {
  8684. $includeGroups = implode(",", $include);
  8685. }
  8686. if (!is_array($selected)) {
  8687. $selected = array($selected);
  8688. }
  8689. $out = '';
  8690. // On recherche les groupes
  8691. $sql = "SELECT ug.rowid, ug.nom as name";
  8692. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8693. $sql .= ", e.label";
  8694. }
  8695. $sql .= " FROM ".$this->db->prefix()."usergroup as ug ";
  8696. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8697. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid=ug.entity";
  8698. if ($force_entity) {
  8699. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8700. } else {
  8701. $sql .= " WHERE ug.entity IS NOT NULL";
  8702. }
  8703. } else {
  8704. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8705. }
  8706. if (is_array($exclude) && $excludeGroups) {
  8707. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8708. }
  8709. if (is_array($include) && $includeGroups) {
  8710. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8711. }
  8712. $sql .= " ORDER BY ug.nom ASC";
  8713. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8714. $resql = $this->db->query($sql);
  8715. if ($resql) {
  8716. // Enhance with select2
  8717. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8718. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8719. $num = $this->db->num_rows($resql);
  8720. $i = 0;
  8721. if ($num) {
  8722. if ($show_empty && !$multiple) {
  8723. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8724. }
  8725. while ($i < $num) {
  8726. $obj = $this->db->fetch_object($resql);
  8727. $disableline = 0;
  8728. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8729. $disableline = 1;
  8730. }
  8731. $out .= '<option value="'.$obj->rowid.'"';
  8732. if ($disableline) {
  8733. $out .= ' disabled';
  8734. }
  8735. if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid) || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
  8736. $out .= ' selected';
  8737. }
  8738. $out .= '>';
  8739. $out .= $obj->name;
  8740. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8741. $out .= " (".$obj->label.")";
  8742. }
  8743. $out .= '</option>';
  8744. $i++;
  8745. }
  8746. } else {
  8747. if ($show_empty) {
  8748. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8749. }
  8750. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8751. }
  8752. $out .= '</select>';
  8753. $out .= ajax_combobox($htmlname);
  8754. } else {
  8755. dol_print_error($this->db);
  8756. }
  8757. return $out;
  8758. }
  8759. /**
  8760. * Return HTML to show the search and clear seach button
  8761. *
  8762. * @param string $pos position colon on liste value left or right
  8763. * @return string
  8764. */
  8765. public function showFilterButtons($pos = '')
  8766. {
  8767. $out = '<div class="nowraponall">';
  8768. if ($pos == 'left') {
  8769. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8770. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8771. } else {
  8772. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8773. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8774. }
  8775. $out .= '</div>';
  8776. return $out;
  8777. }
  8778. /**
  8779. * Return HTML to show the search and clear search button
  8780. *
  8781. * @param string $cssclass CSS class
  8782. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8783. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8784. * @return string
  8785. */
  8786. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8787. {
  8788. global $conf, $langs;
  8789. $out = '';
  8790. if (!empty($conf->use_javascript_ajax)) {
  8791. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8792. }
  8793. $out .= '<script>
  8794. $(document).ready(function() {
  8795. $("#' . $cssclass.'s").click(function() {
  8796. if($(this).is(\':checked\')){
  8797. console.log("We check all '.$cssclass.' and trigger the change method");
  8798. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8799. }
  8800. else
  8801. {
  8802. console.log("We uncheck all");
  8803. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8804. }'."\n";
  8805. if ($calljsfunction) {
  8806. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8807. }
  8808. $out .= ' });
  8809. $(".' . $cssclass.'").change(function() {
  8810. $(this).closest("tr").toggleClass("highlight", this.checked);
  8811. });
  8812. });
  8813. </script>';
  8814. return $out;
  8815. }
  8816. /**
  8817. * Return HTML to show the search and clear seach button
  8818. *
  8819. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8820. * @param string $cssclass CSS class
  8821. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8822. * @param string $massactionname Mass action name
  8823. * @return string
  8824. */
  8825. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8826. {
  8827. $out = $this->showFilterButtons();
  8828. if ($addcheckuncheckall) {
  8829. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8830. }
  8831. return $out;
  8832. }
  8833. /**
  8834. * Return HTML to show the select of expense categories
  8835. *
  8836. * @param string $selected preselected category
  8837. * @param string $htmlname name of HTML select list
  8838. * @param integer $useempty 1=Add empty line
  8839. * @param array $excludeid id to exclude
  8840. * @param string $target htmlname of target select to bind event
  8841. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8842. * @param array $params param to give
  8843. * @param int $info_admin Show the tooltip help picto to setup list
  8844. * @return string
  8845. */
  8846. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8847. {
  8848. global $langs, $user;
  8849. $out = '';
  8850. $sql = "SELECT rowid, label FROM ".$this->db->prefix()."c_exp_tax_cat WHERE active = 1";
  8851. $sql .= " AND entity IN (0,".getEntity('exp_tax_cat').")";
  8852. if (!empty($excludeid)) {
  8853. $sql .= " AND rowid NOT IN (".$this->db->sanitize(implode(',', $excludeid)).")";
  8854. }
  8855. $sql .= " ORDER BY label";
  8856. $resql = $this->db->query($sql);
  8857. if ($resql) {
  8858. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8859. if ($useempty) {
  8860. $out .= '<option value="0">&nbsp;</option>';
  8861. }
  8862. while ($obj = $this->db->fetch_object($resql)) {
  8863. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8864. }
  8865. $out .= '</select>';
  8866. $out .= ajax_combobox('select_'.$htmlname);
  8867. if (!empty($htmlname) && $user->admin && $info_admin) {
  8868. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8869. }
  8870. if (!empty($target)) {
  8871. $sql = "SELECT c.id FROM ".$this->db->prefix()."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8872. $resql = $this->db->query($sql);
  8873. if ($resql) {
  8874. if ($this->db->num_rows($resql) > 0) {
  8875. $obj = $this->db->fetch_object($resql);
  8876. $out .= '<script>
  8877. $(function() {
  8878. $("select[name='.$target.']").on("change", function() {
  8879. var current_val = $(this).val();
  8880. if (current_val == '.$obj->id.') {';
  8881. if (!empty($default_selected) || !empty($selected)) {
  8882. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8883. }
  8884. $out .= '
  8885. $("select[name='.$htmlname.']").change();
  8886. }
  8887. });
  8888. $("select[name='.$htmlname.']").change(function() {
  8889. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8890. // get price of kilometer to fill the unit price
  8891. $.ajax({
  8892. method: "POST",
  8893. dataType: "json",
  8894. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8895. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.join('&', $params)).'",
  8896. }).done(function( data, textStatus, jqXHR ) {
  8897. console.log(data);
  8898. if (typeof data.up != "undefined") {
  8899. $("input[name=value_unit]").val(data.up);
  8900. $("select[name='.$htmlname.']").attr("title", data.title);
  8901. } else {
  8902. $("input[name=value_unit]").val("");
  8903. $("select[name='.$htmlname.']").attr("title", "");
  8904. }
  8905. });
  8906. }
  8907. });
  8908. });
  8909. </script>';
  8910. }
  8911. }
  8912. }
  8913. } else {
  8914. dol_print_error($this->db);
  8915. }
  8916. return $out;
  8917. }
  8918. /**
  8919. * Return HTML to show the select ranges of expense range
  8920. *
  8921. * @param string $selected preselected category
  8922. * @param string $htmlname name of HTML select list
  8923. * @param integer $useempty 1=Add empty line
  8924. * @return string
  8925. */
  8926. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8927. {
  8928. global $conf, $langs;
  8929. $out = '';
  8930. $sql = "SELECT rowid, range_ik FROM ".$this->db->prefix()."c_exp_tax_range";
  8931. $sql .= " WHERE entity = ".$conf->entity." AND active = 1";
  8932. $resql = $this->db->query($sql);
  8933. if ($resql) {
  8934. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8935. if ($useempty) {
  8936. $out .= '<option value="0"></option>';
  8937. }
  8938. while ($obj = $this->db->fetch_object($resql)) {
  8939. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8940. }
  8941. $out .= '</select>';
  8942. } else {
  8943. dol_print_error($this->db);
  8944. }
  8945. return $out;
  8946. }
  8947. /**
  8948. * Return HTML to show a select of expense
  8949. *
  8950. * @param string $selected preselected category
  8951. * @param string $htmlname name of HTML select list
  8952. * @param integer $useempty 1=Add empty choice
  8953. * @param integer $allchoice 1=Add all choice
  8954. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8955. * @return string
  8956. */
  8957. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8958. {
  8959. global $langs;
  8960. $out = '';
  8961. $sql = "SELECT id, code, label FROM ".$this->db->prefix()."c_type_fees";
  8962. $sql .= " WHERE active = 1";
  8963. $resql = $this->db->query($sql);
  8964. if ($resql) {
  8965. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8966. if ($useempty) {
  8967. $out .= '<option value="0"></option>';
  8968. }
  8969. if ($allchoice) {
  8970. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8971. }
  8972. $field = 'code';
  8973. if ($useid) {
  8974. $field = 'id';
  8975. }
  8976. while ($obj = $this->db->fetch_object($resql)) {
  8977. $key = $langs->trans($obj->code);
  8978. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8979. }
  8980. $out .= '</select>';
  8981. } else {
  8982. dol_print_error($this->db);
  8983. }
  8984. return $out;
  8985. }
  8986. /**
  8987. * Output a combo list with invoices qualified for a third party
  8988. *
  8989. * @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)
  8990. * @param int $selected Id invoice preselected
  8991. * @param string $htmlname Name of HTML select
  8992. * @param int $maxlength Maximum length of label
  8993. * @param int $option_only Return only html options lines without the select tag
  8994. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8995. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8996. * @param int $forcefocus Force focus on field (works with javascript only)
  8997. * @param int $disabled Disabled
  8998. * @param string $morecss More css added to the select component
  8999. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  9000. * @param string $showproject 'all' = Show project info, ''=Hide project info
  9001. * @param User $usertofilter User object to use for filtering
  9002. * @return int Nbr of project if OK, <0 if KO
  9003. */
  9004. 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)
  9005. {
  9006. global $user, $conf, $langs;
  9007. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  9008. if (is_null($usertofilter)) {
  9009. $usertofilter = $user;
  9010. }
  9011. $out = '';
  9012. $hideunselectables = false;
  9013. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  9014. $hideunselectables = true;
  9015. }
  9016. if (empty($projectsListId)) {
  9017. if (empty($usertofilter->rights->projet->all->lire)) {
  9018. $projectstatic = new Project($this->db);
  9019. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  9020. }
  9021. }
  9022. // Search all projects
  9023. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  9024. p.title, p.fk_soc, p.fk_statut, p.public,";
  9025. $sql .= ' s.nom as name';
  9026. $sql .= ' FROM '.$this->db->prefix().'projet as p';
  9027. $sql .= ' LEFT JOIN '.$this->db->prefix().'societe as s ON s.rowid = p.fk_soc,';
  9028. $sql .= ' '.$this->db->prefix().'facture as f';
  9029. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  9030. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  9031. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  9032. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  9033. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  9034. $sql .= " ORDER BY p.ref, f.ref ASC";
  9035. $resql = $this->db->query($sql);
  9036. if ($resql) {
  9037. // Use select2 selector
  9038. if (!empty($conf->use_javascript_ajax)) {
  9039. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  9040. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9041. $out .= $comboenhancement;
  9042. $morecss = 'minwidth200imp maxwidth500';
  9043. }
  9044. if (empty($option_only)) {
  9045. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  9046. }
  9047. if (!empty($show_empty)) {
  9048. $out .= '<option value="0" class="optiongrey">';
  9049. if (!is_numeric($show_empty)) {
  9050. $out .= $show_empty;
  9051. } else {
  9052. $out .= '&nbsp;';
  9053. }
  9054. $out .= '</option>';
  9055. }
  9056. $num = $this->db->num_rows($resql);
  9057. $i = 0;
  9058. if ($num) {
  9059. while ($i < $num) {
  9060. $obj = $this->db->fetch_object($resql);
  9061. // 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.
  9062. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  9063. // Do nothing
  9064. } else {
  9065. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  9066. $i++;
  9067. continue;
  9068. }
  9069. $labeltoshow = '';
  9070. if ($showproject == 'all') {
  9071. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  9072. if ($obj->name) {
  9073. $labeltoshow .= ' - '.$obj->name; // Soc name
  9074. }
  9075. $disabled = 0;
  9076. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  9077. $disabled = 1;
  9078. $labeltoshow .= ' - '.$langs->trans("Draft");
  9079. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  9080. if ($discard_closed == 2) {
  9081. $disabled = 1;
  9082. }
  9083. $labeltoshow .= ' - '.$langs->trans("Closed");
  9084. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  9085. $disabled = 1;
  9086. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  9087. }
  9088. }
  9089. if (!empty($selected) && $selected == $obj->rowid) {
  9090. $out .= '<option value="'.$obj->rowid.'" selected';
  9091. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9092. $out .= '>'.$labeltoshow.'</option>';
  9093. } else {
  9094. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  9095. $resultat = '';
  9096. } else {
  9097. $resultat = '<option value="'.$obj->rowid.'"';
  9098. if ($disabled) {
  9099. $resultat .= ' disabled';
  9100. }
  9101. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  9102. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  9103. $resultat .= '>';
  9104. $resultat .= $labeltoshow;
  9105. $resultat .= '</option>';
  9106. }
  9107. $out .= $resultat;
  9108. }
  9109. }
  9110. $i++;
  9111. }
  9112. }
  9113. if (empty($option_only)) {
  9114. $out .= '</select>';
  9115. }
  9116. print $out;
  9117. $this->db->free($resql);
  9118. return $num;
  9119. } else {
  9120. dol_print_error($this->db);
  9121. return -1;
  9122. }
  9123. }
  9124. /**
  9125. * Output a combo list with invoices qualified for a third party
  9126. *
  9127. * @param int $selected Id invoice preselected
  9128. * @param string $htmlname Name of HTML select
  9129. * @param int $maxlength Maximum length of label
  9130. * @param int $option_only Return only html options lines without the select tag
  9131. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9132. * @param int $forcefocus Force focus on field (works with javascript only)
  9133. * @param int $disabled Disabled
  9134. * @param string $morecss More css added to the select component
  9135. * @return int Nbr of project if OK, <0 if KO
  9136. */
  9137. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  9138. {
  9139. global $user, $conf, $langs;
  9140. $out = '';
  9141. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  9142. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  9143. //$sql.= ', el.fk_source';
  9144. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  9145. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  9146. $sql .= " ORDER BY f.titre ASC";
  9147. $resql = $this->db->query($sql);
  9148. if ($resql) {
  9149. // Use select2 selector
  9150. if (!empty($conf->use_javascript_ajax)) {
  9151. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9152. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9153. $out .= $comboenhancement;
  9154. $morecss = 'minwidth200imp maxwidth500';
  9155. }
  9156. if (empty($option_only)) {
  9157. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9158. }
  9159. if (!empty($show_empty)) {
  9160. $out .= '<option value="0" class="optiongrey">';
  9161. if (!is_numeric($show_empty)) {
  9162. $out .= $show_empty;
  9163. } else {
  9164. $out .= '&nbsp;';
  9165. }
  9166. $out .= '</option>';
  9167. }
  9168. $num = $this->db->num_rows($resql);
  9169. if ($num) {
  9170. while ($obj = $this->db->fetch_object($resql)) {
  9171. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9172. $disabled = 0;
  9173. if (!empty($obj->suspended)) {
  9174. $disabled = 1;
  9175. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9176. }
  9177. if (!empty($selected) && $selected == $obj->rowid) {
  9178. $out .= '<option value="' . $obj->rowid . '" selected';
  9179. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9180. $out .= '>' . $labeltoshow . '</option>';
  9181. } else {
  9182. if ($disabled && ($selected != $obj->rowid)) {
  9183. $resultat = '';
  9184. } else {
  9185. $resultat = '<option value="' . $obj->rowid . '"';
  9186. if ($disabled) {
  9187. $resultat .= ' disabled';
  9188. }
  9189. $resultat .= '>';
  9190. $resultat .= $labeltoshow;
  9191. $resultat .= '</option>';
  9192. }
  9193. $out .= $resultat;
  9194. }
  9195. }
  9196. }
  9197. if (empty($option_only)) {
  9198. $out .= '</select>';
  9199. }
  9200. print $out;
  9201. $this->db->free($resql);
  9202. return $num;
  9203. } else {
  9204. $this->errors[]=$this->db->lasterror;
  9205. return -1;
  9206. }
  9207. }
  9208. /**
  9209. * Output the component to make advanced search criteries
  9210. *
  9211. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9212. * @param array $search_component_params Array of selected search criterias
  9213. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9214. * @param string $search_component_params_hidden String with $search_component_params criterias
  9215. * @return string HTML component for advanced search
  9216. */
  9217. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9218. {
  9219. global $langs;
  9220. $ret = '';
  9221. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9222. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  9223. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9224. $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Filters")).'" id="idsubimgproductdistribution"></span>';
  9225. //$ret .= $langs->trans("Filters");
  9226. $ret .= '</a>';
  9227. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9228. // Show select fields as tags.
  9229. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9230. if ($search_component_params_hidden) {
  9231. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9232. $search_component_params_hidden .= '('.$search_component_params_hidden.')';
  9233. }
  9234. $errormessage = '';
  9235. if (!dolCheckFilters($search_component_params_hidden, $errormessage)) {
  9236. print 'ERROR in parsing search string';
  9237. }
  9238. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9239. //var_dump($search_component_params_hidden);
  9240. $htmltags = preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $search_component_params_hidden);
  9241. //var_dump($htmltags);
  9242. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> '.$htmltags.'</span>';
  9243. }
  9244. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9245. //$ret .= search_component_params
  9246. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9247. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9248. $show_search_component_params_hidden = 1;
  9249. if ($show_search_component_params_hidden) {
  9250. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9251. }
  9252. $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%')) -->";
  9253. $ret .= '<input type="hidden" name="search_component_params_hidden" value="'.dol_escape_htmltag($search_component_params_hidden).'">';
  9254. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  9255. foreach ($arrayofcriterias as $criterias) {
  9256. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9257. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9258. continue;
  9259. }
  9260. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9261. continue;
  9262. }
  9263. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9264. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  9265. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  9266. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  9267. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  9268. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  9269. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  9270. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  9271. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  9272. } else {
  9273. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  9274. }
  9275. }
  9276. }
  9277. $ret .= '</div>';
  9278. $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";
  9279. $ret .= '<input type="text" placeholder="'.$langs->trans("Search").'" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9280. $ret .= '</div>';
  9281. $ret .= '</div>';
  9282. return $ret;
  9283. }
  9284. /**
  9285. * selectModelMail
  9286. *
  9287. * @param string $prefix Prefix
  9288. * @param string $modelType Model type
  9289. * @param int $default 1=Show also Default mail template
  9290. * @param int $addjscombo Add js combobox
  9291. * @return string HTML select string
  9292. */
  9293. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9294. {
  9295. global $langs, $user;
  9296. $retstring = '';
  9297. $TModels = array();
  9298. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  9299. $formmail = new FormMail($this->db);
  9300. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9301. if ($default) {
  9302. $TModels[0] = $langs->trans('DefaultMailModel');
  9303. }
  9304. if ($result > 0) {
  9305. foreach ($formmail->lines_model as $model) {
  9306. $TModels[$model->id] = $model->label;
  9307. }
  9308. }
  9309. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  9310. foreach ($TModels as $id_model => $label_model) {
  9311. $retstring .= '<option value="'.$id_model.'"';
  9312. $retstring .= ">".$label_model."</option>";
  9313. }
  9314. $retstring .= "</select>";
  9315. if ($addjscombo) {
  9316. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  9317. }
  9318. return $retstring;
  9319. }
  9320. /**
  9321. * Output the buttons to submit a creation/edit form
  9322. *
  9323. * @param string $save_label Alternative label for save button
  9324. * @param string $cancel_label Alternative label for cancel button
  9325. * @param array $morebuttons Add additional buttons between save and cancel
  9326. * @param bool $withoutdiv Option to remove enclosing centered div
  9327. * @param string $morecss More CSS
  9328. * @param string $dol_openinpopup If the button are shown in a context of a page shown inside a popup, we put here the string name of popup.
  9329. * @return string Html code with the buttons
  9330. */
  9331. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9332. {
  9333. global $langs;
  9334. $buttons = array();
  9335. $save = array(
  9336. 'name' => 'save',
  9337. 'label_key' => $save_label,
  9338. );
  9339. if ($save_label == 'Create' || $save_label == 'Add' ) {
  9340. $save['name'] = 'add';
  9341. } elseif ($save_label == 'Modify') {
  9342. $save['name'] = 'edit';
  9343. }
  9344. $cancel = array(
  9345. 'name' => 'cancel',
  9346. 'label_key' => 'Cancel',
  9347. );
  9348. !empty($save_label) ? $buttons[] = $save : '';
  9349. if (!empty($morebuttons)) {
  9350. $buttons[] = $morebuttons;
  9351. }
  9352. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9353. $retstring = $withoutdiv ? '': '<div class="center">';
  9354. foreach ($buttons as $button) {
  9355. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9356. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  9357. }
  9358. $retstring .= $withoutdiv ? '': '</div>';
  9359. if ($dol_openinpopup) {
  9360. $retstring .= '<!-- buttons are shown into a $dol_openinpopup='.$dol_openinpopup.' context, so we enable the close of dialog on cancel -->'."\n";
  9361. $retstring .= '<script>';
  9362. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9363. e.preventDefault(); console.log(\'We click on cancel in iframe popup '.$dol_openinpopup.'\');
  9364. window.parent.jQuery(\'#idfordialog'.$dol_openinpopup.'\').dialog(\'close\');
  9365. });';
  9366. $retstring .= '</script>';
  9367. }
  9368. return $retstring;
  9369. }
  9370. }