html.form.class.php 443 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603
  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. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  25. *
  26. * This program is free software; you can redistribute it and/or modify
  27. * it under the terms of the GNU General Public License as published by
  28. * the Free Software Foundation; either version 3 of the License, or
  29. * (at your option) any later version.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU General Public License
  37. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  38. */
  39. /**
  40. * \file htdocs/core/class/html.form.class.php
  41. * \ingroup core
  42. * \brief File of class with all html predefined components
  43. */
  44. /**
  45. * Class to manage generation of HTML components
  46. * Only common components must be here.
  47. *
  48. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  49. */
  50. class Form
  51. {
  52. /**
  53. * @var DoliDB Database handler.
  54. */
  55. public $db;
  56. /**
  57. * @var string Error code (or message)
  58. */
  59. public $error = '';
  60. /**
  61. * @var string[] Array of error strings
  62. */
  63. public $errors = array();
  64. public $num;
  65. // Cache arrays
  66. public $cache_types_paiements = array();
  67. public $cache_conditions_paiements = array();
  68. public $cache_transport_mode = array();
  69. public $cache_availability = array();
  70. public $cache_demand_reason = array();
  71. public $cache_types_fees = array();
  72. public $cache_vatrates = array();
  73. /**
  74. * Constructor
  75. *
  76. * @param DoliDB $db Database handler
  77. */
  78. public function __construct($db)
  79. {
  80. $this->db = $db;
  81. }
  82. /**
  83. * Output key field for an editable field
  84. *
  85. * @param string $text Text of label or key to translate
  86. * @param string $htmlname Name of select field ('edit' prefix will be added)
  87. * @param string $preselected Value to show/edit (not used in this function)
  88. * @param object $object Object (on the page we show)
  89. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  90. * @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]'...)
  91. * @param string $moreparam More param to add on a href URL.
  92. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  93. * @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 ' '
  94. * @param string $paramid Key of parameter for id ('id', 'socid')
  95. * @param string $help Tooltip help
  96. * @return string HTML edit field
  97. */
  98. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  99. {
  100. global $conf, $langs;
  101. $ret = '';
  102. // TODO change for compatibility
  103. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  104. if (!empty($perm)) {
  105. $tmp = explode(':', $typeofdata);
  106. $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
  107. if ($fieldrequired) {
  108. $ret .= '<span class="fieldrequired">';
  109. }
  110. if ($help) {
  111. $ret .= $this->textwithpicto($langs->trans($text), $help);
  112. } else {
  113. $ret .= $langs->trans($text);
  114. }
  115. if ($fieldrequired) {
  116. $ret .= '</span>';
  117. }
  118. $ret .= '</div>' . "\n";
  119. } else {
  120. if ($fieldrequired) {
  121. $ret .= '<span class="fieldrequired">';
  122. }
  123. if ($help) {
  124. $ret .= $this->textwithpicto($langs->trans($text), $help);
  125. } else {
  126. $ret .= $langs->trans($text);
  127. }
  128. if ($fieldrequired) {
  129. $ret .= '</span>';
  130. }
  131. }
  132. } else {
  133. if (empty($notabletag) && $perm) {
  134. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  135. }
  136. if ($fieldrequired) {
  137. $ret .= '<span class="fieldrequired">';
  138. }
  139. if ($help) {
  140. $ret .= $this->textwithpicto($langs->trans($text), $help);
  141. } else {
  142. $ret .= $langs->trans($text);
  143. }
  144. if ($fieldrequired) {
  145. $ret .= '</span>';
  146. }
  147. if (!empty($notabletag)) {
  148. $ret .= ' ';
  149. }
  150. if (empty($notabletag) && $perm) {
  151. $ret .= '</td>';
  152. }
  153. if (empty($notabletag) && $perm) {
  154. $ret .= '<td class="right">';
  155. }
  156. if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
  157. $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>';
  158. }
  159. if (!empty($notabletag) && $notabletag == 1) {
  160. if ($text) {
  161. $ret .= ' : ';
  162. } else {
  163. $ret .= ' ';
  164. }
  165. }
  166. if (!empty($notabletag) && $notabletag == 3) {
  167. $ret .= ' ';
  168. }
  169. if (empty($notabletag) && $perm) {
  170. $ret .= '</td>';
  171. }
  172. if (empty($notabletag) && $perm) {
  173. $ret .= '</tr></table>';
  174. }
  175. }
  176. return $ret;
  177. }
  178. /**
  179. * Output value of a field for an editable field
  180. *
  181. * @param string $text Text of label (not used in this function)
  182. * @param string $htmlname Name of select field
  183. * @param string $value Value to show/edit
  184. * @param object $object Object (that we want to show)
  185. * @param boolean $perm Permission to allow button to edit parameter
  186. * @param string $typeofdata Type of data ('string' by default, 'checkbox', '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,...')
  187. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of numeric value, or a select combo). Use '' to use same than $value
  188. * @param object $extObject External object ???
  189. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  190. * @param string $moreparam More param to add on the form on action href URL parameter
  191. * @param int $notabletag Do no output table tags
  192. * @param string $formatfunc Call a specific method of $object->$formatfunc to output field in view mode (For example: 'dol_print_email')
  193. * @param string $paramid Key of parameter for id ('id', 'socid')
  194. * @param string $gm 'auto' or 'tzuser' or 'tzuserrel' or 'tzserver' (when $typeofdata is a date)
  195. * @param array $moreoptions Array with more options. For example array('addnowlink'=>1), array('valuealreadyhtmlescaped'=>1)
  196. * @param string $editaction [=''] use GETPOST default action or set action to edit mode
  197. * @return string HTML edit field
  198. */
  199. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 1, $formatfunc = '', $paramid = 'id', $gm = 'auto', $moreoptions = array(), $editaction = '')
  200. {
  201. global $conf, $langs;
  202. $ret = '';
  203. // Check parameters
  204. if (empty($typeofdata)) {
  205. return 'ErrorBadParameter typeofdata is empty';
  206. }
  207. // Clean paramater $typeofdata
  208. if ($typeofdata == 'datetime') {
  209. $typeofdata = 'dayhour';
  210. }
  211. $reg = array();
  212. if (preg_match('/^(\w+)\((\d+)\)$/', $typeofdata, $reg)) {
  213. if ($reg[1] == 'varchar') {
  214. $typeofdata = 'string';
  215. } elseif ($reg[1] == 'int') {
  216. $typeofdata = 'numeric';
  217. } else {
  218. return 'ErrorBadParameter ' . $typeofdata;
  219. }
  220. }
  221. // When option to edit inline is activated
  222. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  223. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  224. } else {
  225. if ($editaction == '') {
  226. $editaction = GETPOST('action', 'aZ09');
  227. }
  228. $editmode = ($editaction == 'edit' . $htmlname);
  229. if ($editmode) {
  230. $ret .= "\n";
  231. $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
  232. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  233. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  234. $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
  235. if (empty($notabletag)) {
  236. $ret .= '<table class="nobordernopadding centpercent">';
  237. }
  238. if (empty($notabletag)) {
  239. $ret .= '<tr><td>';
  240. }
  241. if (preg_match('/^(string|safehtmlstring|email|url)/', $typeofdata)) {
  242. $tmp = explode(':', $typeofdata);
  243. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  244. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  245. $tmp = explode(':', $typeofdata);
  246. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  247. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $valuetoshow . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  248. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  249. $tmp = explode(':', $typeofdata);
  250. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  251. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  252. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  253. $tmp = explode(':', $typeofdata);
  254. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($value ? $value : 'on') . '"' . ($value ? ' checked' : '') . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
  255. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  256. $tmp = explode(':', $typeofdata);
  257. $cols = (empty($tmp[2]) ? '' : $tmp[2]);
  258. $morealt = '';
  259. if (preg_match('/%/', $cols)) {
  260. $morealt = ' style="width: ' . $cols . '"';
  261. $cols = '';
  262. }
  263. $valuetoshow = ($editvalue ? $editvalue : $value);
  264. $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . (empty($tmp[1]) ? '20' : $tmp[1]) . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '" autofocus>';
  265. // textarea convert automatically entities chars into simple chars.
  266. // 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.
  267. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  268. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  269. $ret .= '</textarea>';
  270. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  271. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  272. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  273. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  274. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  275. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  276. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  277. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  278. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  279. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  280. } elseif (preg_match('/^select;/', $typeofdata)) {
  281. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  282. $arraylist = array();
  283. foreach ($arraydata as $val) {
  284. $tmp = explode(':', $val);
  285. $tmpkey = str_replace('|', ':', $tmp[0]);
  286. $arraylist[$tmpkey] = $tmp[1];
  287. }
  288. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  289. } elseif (preg_match('/^link/', $typeofdata)) {
  290. // TODO Not yet implemented. See code for extrafields
  291. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  292. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  293. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  294. $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]));
  295. $ret .= $doleditor->Create(1);
  296. } elseif ($typeofdata == 'asis') {
  297. $ret .= ($editvalue ? $editvalue : $value);
  298. }
  299. if (empty($notabletag)) {
  300. $ret .= '</td>';
  301. }
  302. // Button save-cancel
  303. if (empty($notabletag)) {
  304. $ret .= '<td>';
  305. }
  306. //else $ret.='<div class="clearboth"></div>';
  307. $ret .= '<input type="submit" class="smallpaddingimp button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Modify") . '">';
  308. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  309. $ret .= '<br>' . "\n";
  310. }
  311. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
  312. if (empty($notabletag)) {
  313. $ret .= '</td>';
  314. }
  315. if (empty($notabletag)) {
  316. $ret .= '</tr></table>' . "\n";
  317. }
  318. $ret .= '</form>' . "\n";
  319. } else {
  320. if (preg_match('/^(email)/', $typeofdata)) {
  321. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  322. } elseif (preg_match('/^url/', $typeofdata)) {
  323. $ret .= dol_print_url($value, '_blank', 32, 1);
  324. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  325. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  326. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  327. $tmp = explode(':', $typeofdata);
  328. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($value ? ' checked' : '') . ($tmp[1] ? $tmp[1] : '') . '/>';
  329. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  330. $ret .= dol_htmlentitiesbr($value);
  331. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  332. $ret .= dol_string_onlythesehtmltags($value);
  333. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  334. $ret .= dol_string_onlythesehtmltags($value);
  335. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  336. $ret .= '<span class="valuedate">' . dol_print_date($value, 'day', $gm) . '</span>';
  337. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  338. $ret .= '<span class="valuedate">' . dol_print_date($value, 'dayhour', $gm) . '</span>';
  339. } elseif (preg_match('/^select;/', $typeofdata)) {
  340. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  341. $arraylist = array();
  342. foreach ($arraydata as $val) {
  343. $tmp = explode(':', $val);
  344. $arraylist[$tmp[0]] = $tmp[1];
  345. }
  346. $ret .= $arraylist[$value];
  347. if ($htmlname == 'fk_product_type') {
  348. if ($value == 0) {
  349. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  350. } else {
  351. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  352. }
  353. }
  354. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  355. $tmpcontent = dol_htmlentitiesbr($value);
  356. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  357. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  358. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  359. $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  360. }
  361. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  362. // clean data from some dangerous html
  363. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  364. } else {
  365. if (empty($moreoptions['valuealreadyhtmlescaped'])) {
  366. $ret .= dol_escape_htmltag($value);
  367. } else {
  368. $ret .= $value; // $value must be already html escaped.
  369. }
  370. }
  371. if ($formatfunc && method_exists($object, $formatfunc)) {
  372. $ret = $object->$formatfunc($ret);
  373. }
  374. }
  375. }
  376. return $ret;
  377. }
  378. /**
  379. * Output edit in place form
  380. *
  381. * @param string $fieldname Name of the field
  382. * @param object $object Object
  383. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  384. * @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]'...)
  385. * @param string $check Same coe than $check parameter of GETPOST()
  386. * @param string $morecss More CSS
  387. * @return string HTML code for the edit of alternative language
  388. */
  389. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  390. {
  391. global $conf, $langs, $extralanguages;
  392. $result = '';
  393. // List of extra languages
  394. $arrayoflangcode = array();
  395. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  396. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  397. }
  398. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  399. if (!is_object($extralanguages)) {
  400. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  401. $extralanguages = new ExtraLanguages($this->db);
  402. }
  403. $extralanguages->fetch_name_extralanguages('societe');
  404. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  405. return ''; // No extralang field to show
  406. }
  407. $result .= '<!-- Widget for translation -->' . "\n";
  408. $result .= '<div class="inline-block paddingleft image-' . $object->element . '-' . $fieldname . '">';
  409. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  410. $result .= $s;
  411. $result .= '</div>';
  412. $result .= '<div class="inline-block hidden field-' . $object->element . '-' . $fieldname . '">';
  413. $resultforextrlang = '';
  414. foreach ($arrayoflangcode as $langcode) {
  415. $valuetoshow = GETPOSTISSET('field-' . $object->element . "-" . $fieldname . "-" . $langcode) ? GETPOST('field-' . $object->element . '-' . $fieldname . "-" . $langcode, $check) : '';
  416. if (empty($valuetoshow)) {
  417. $object->fetchValuesForExtraLanguages();
  418. //var_dump($object->array_languages);
  419. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  420. }
  421. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  422. $resultforextrlang .= $s;
  423. // TODO Use the showInputField() method of ExtraLanguages object
  424. if ($typeofdata == 'textarea') {
  425. $resultforextrlang .= '<textarea name="field-' . $object->element . "-" . $fieldname . "-" . $langcode . '" id="' . $fieldname . "-" . $langcode . '" class="' . $morecss . '" rows="' . ROWS_2 . '" wrap="soft">';
  426. $resultforextrlang .= $valuetoshow;
  427. $resultforextrlang .= '</textarea>';
  428. } else {
  429. $resultforextrlang .= '<input type="text" class="inputfieldforlang ' . ($morecss ? ' ' . $morecss : '') . '" name="field-' . $object->element . '-' . $fieldname . '-' . $langcode . '" value="' . $valuetoshow . '">';
  430. }
  431. }
  432. $result .= $resultforextrlang;
  433. $result .= '</div>';
  434. $result .= '<script nonce="' . getNonce() . '">$(".image-' . $object->element . '-' . $fieldname . '").click(function() { console.log("Toggle lang widget"); jQuery(".field-' . $object->element . '-' . $fieldname . '").toggle(); });</script>';
  435. }
  436. return $result;
  437. }
  438. /**
  439. * Output edit in place form
  440. *
  441. * @param object $object Object
  442. * @param string $value Value to show/edit
  443. * @param string $htmlname DIV ID (field name)
  444. * @param int $condition Condition to edit
  445. * @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')
  446. * @param string $editvalue When in edit mode, use this value as $value instead of value
  447. * @param object $extObject External object
  448. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  449. * @return string HTML edit in place
  450. */
  451. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  452. {
  453. global $conf;
  454. $out = '';
  455. // Check parameters
  456. if (preg_match('/^text/', $inputType)) {
  457. $value = dol_nl2br($value);
  458. } elseif (preg_match('/^numeric/', $inputType)) {
  459. $value = price($value);
  460. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  461. $value = dol_print_date($value, 'day');
  462. }
  463. if ($condition) {
  464. $element = false;
  465. $table_element = false;
  466. $fk_element = false;
  467. $loadmethod = false;
  468. $savemethod = false;
  469. $ext_element = false;
  470. $button_only = false;
  471. $inputOption = '';
  472. $rows = '';
  473. $cols = '';
  474. if (is_object($object)) {
  475. $element = $object->element;
  476. $table_element = $object->table_element;
  477. $fk_element = $object->id;
  478. }
  479. if (is_object($extObject)) {
  480. $ext_element = $extObject->element;
  481. }
  482. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  483. $tmp = explode(':', $inputType);
  484. $inputType = $tmp[0];
  485. if (!empty($tmp[1])) {
  486. $inputOption = $tmp[1];
  487. }
  488. if (!empty($tmp[2])) {
  489. $savemethod = $tmp[2];
  490. }
  491. $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
  492. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  493. $tmp = explode(':', $inputType);
  494. $inputType = $tmp[0];
  495. if (!empty($tmp[1])) {
  496. $inputOption = $tmp[1];
  497. }
  498. if (!empty($tmp[2])) {
  499. $savemethod = $tmp[2];
  500. }
  501. $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
  502. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  503. $tmp = explode(':', $inputType);
  504. $inputType = $tmp[0];
  505. $loadmethod = $tmp[1];
  506. if (!empty($tmp[2])) {
  507. $savemethod = $tmp[2];
  508. }
  509. if (!empty($tmp[3])) {
  510. $button_only = true;
  511. }
  512. } elseif (preg_match('/^textarea/', $inputType)) {
  513. $tmp = explode(':', $inputType);
  514. $inputType = $tmp[0];
  515. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  516. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  517. } elseif (preg_match('/^ckeditor/', $inputType)) {
  518. $tmp = explode(':', $inputType);
  519. $inputType = $tmp[0];
  520. $toolbar = $tmp[1];
  521. if (!empty($tmp[2])) {
  522. $width = $tmp[2];
  523. }
  524. if (!empty($tmp[3])) {
  525. $heigth = $tmp[3];
  526. }
  527. if (!empty($tmp[4])) {
  528. $savemethod = $tmp[4];
  529. }
  530. if (isModEnabled('fckeditor')) {
  531. $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
  532. } else {
  533. $inputType = 'textarea';
  534. }
  535. }
  536. $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
  537. $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
  538. $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
  539. $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
  540. if (!empty($savemethod)) {
  541. $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
  542. }
  543. if (!empty($ext_element)) {
  544. $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
  545. }
  546. if (!empty($custommsg)) {
  547. if (is_array($custommsg)) {
  548. if (!empty($custommsg['success'])) {
  549. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
  550. }
  551. if (!empty($custommsg['error'])) {
  552. $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
  553. }
  554. } else {
  555. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
  556. }
  557. }
  558. if ($inputType == 'textarea') {
  559. $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
  560. $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
  561. }
  562. $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
  563. $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
  564. } else {
  565. $out = $value;
  566. }
  567. return $out;
  568. }
  569. /**
  570. * Show a text and picto with tooltip on text or picto.
  571. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  572. *
  573. * @param string $text Text to show
  574. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  575. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  576. * @param int $direction -1=image is before, 0=no image, 1=image is after
  577. * @param string $img Html code for image (use img_xxx() function to get it)
  578. * @param string $extracss Add a CSS style to td tags
  579. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  580. * @param string $incbefore Include code before the text
  581. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  582. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  583. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  584. * @return string Code html du tooltip (texte+picto)
  585. * @see textwithpicto() Use thisfunction if you can.
  586. */
  587. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  588. {
  589. if ($incbefore) {
  590. $text = $incbefore . $text;
  591. }
  592. if (!$htmltext) {
  593. return $text;
  594. }
  595. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  596. $tag = 'td';
  597. if ($notabs == 2) {
  598. $tag = 'div';
  599. }
  600. if ($notabs == 3) {
  601. $tag = 'span';
  602. }
  603. // Sanitize tooltip
  604. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  605. $extrastyle = '';
  606. if ($direction < 0) {
  607. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  608. $extrastyle = 'padding: 0px; padding-left: 3px;';
  609. }
  610. if ($direction > 0) {
  611. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  612. $extrastyle = 'padding: 0px; padding-right: 3px;';
  613. }
  614. $classfortooltip = 'classfortooltip';
  615. $s = '';
  616. $textfordialog = '';
  617. if ($tooltiptrigger == '') {
  618. $htmltext = str_replace('"', '&quot;', $htmltext);
  619. } else {
  620. $classfortooltip = 'classfortooltiponclick';
  621. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext">' . $htmltext . '</div>';
  622. }
  623. if ($tooltipon == 2 || $tooltipon == 3) {
  624. $paramfortooltipimg = ' class="' . $classfortooltip . ($notabs != 3 ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
  625. if ($tooltiptrigger == '') {
  626. $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on img tag to store tooltip
  627. } else {
  628. $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
  629. }
  630. } else {
  631. $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  632. }
  633. if ($tooltipon == 1 || $tooltipon == 3) {
  634. $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ' inline-block' . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
  635. if ($tooltiptrigger == '') {
  636. $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on td tag to store tooltip
  637. } else {
  638. $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
  639. }
  640. } else {
  641. $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  642. }
  643. if (empty($notabs)) {
  644. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  645. } elseif ($notabs == 2) {
  646. $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
  647. }
  648. // Define value if value is before
  649. if ($direction < 0) {
  650. $s .= '<' . $tag . $paramfortooltipimg;
  651. if ($tag == 'td') {
  652. $s .= ' class="valigntop" width="14"';
  653. }
  654. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  655. }
  656. // Use another method to help avoid having a space in value in order to use this value with jquery
  657. // Define label
  658. if ((string) $text != '') {
  659. $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
  660. }
  661. // Define value if value is after
  662. if ($direction > 0) {
  663. $s .= '<' . $tag . $paramfortooltipimg;
  664. if ($tag == 'td') {
  665. $s .= ' class="valignmiddle" width="14"';
  666. }
  667. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  668. }
  669. if (empty($notabs)) {
  670. $s .= '</tr></table>';
  671. } elseif ($notabs == 2) {
  672. $s .= '</div>';
  673. }
  674. return $s;
  675. }
  676. /**
  677. * Show a text with a picto and a tooltip on picto
  678. *
  679. * @param string $text Text to show
  680. * @param string $htmltext Content of tooltip
  681. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  682. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  683. * @param string $extracss Add a CSS style to td, div or span tag
  684. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  685. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  686. * @param string $tooltiptrigger ''=Tooltip on hover and hidden on smartphone, 'abconsmartphone'=Tooltip on hover and on click on smartphone, 'abc'=Tooltip on click (abc is a unique key, clickable link is on image or on link if param $type='none' or on both if $type='xxxclickable')
  687. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  688. * @return string HTML code of text, picto, tooltip
  689. */
  690. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  691. {
  692. global $conf, $langs;
  693. //For backwards compatibility
  694. if ($type == '0') {
  695. $type = 'info';
  696. } elseif ($type == '1') {
  697. $type = 'help';
  698. }
  699. if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
  700. $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
  701. }
  702. $alt = '';
  703. if ($tooltiptrigger) {
  704. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  705. }
  706. // If info or help with no javascript, show only text
  707. if (empty($conf->use_javascript_ajax)) {
  708. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  709. return $text;
  710. } else {
  711. $alt = $htmltext;
  712. $htmltext = '';
  713. }
  714. }
  715. // If info or help with smartphone, show only text (tooltip hover can't works)
  716. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  717. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  718. return $text;
  719. }
  720. }
  721. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  722. //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
  723. //{
  724. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.'</a>';
  725. //}
  726. $img = '';
  727. if ($type == 'info') {
  728. $img = img_help(0, $alt);
  729. } elseif ($type == 'help') {
  730. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  731. } elseif ($type == 'helpclickable') {
  732. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  733. } elseif ($type == 'superadmin') {
  734. $img = img_picto($alt, 'redstar');
  735. } elseif ($type == 'admin') {
  736. $img = img_picto($alt, 'star');
  737. } elseif ($type == 'warning') {
  738. $img = img_warning($alt);
  739. } elseif ($type != 'none') {
  740. $img = img_picto($alt, $type); // $type can be an image path
  741. }
  742. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  743. }
  744. /**
  745. * Generate select HTML to choose massaction
  746. *
  747. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  748. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  749. * @param int $alwaysvisible 1=select button always visible
  750. * @param string $name Name for massaction
  751. * @param string $cssclass CSS class used to check for select
  752. * @return string|void Select list
  753. */
  754. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  755. {
  756. global $conf, $langs, $hookmanager;
  757. $disabled = 0;
  758. $ret = '<div class="centpercent center">';
  759. $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'select valignmiddle alignstart" id="' . $name . '" name="' . $name . '"' . ($disabled ? ' disabled="disabled"' : '') . '>';
  760. // 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.
  761. $parameters = array();
  762. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  763. // check if there is a mass action
  764. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  765. return;
  766. }
  767. if (empty($reshook)) {
  768. $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
  769. foreach ($arrayofaction as $code => $label) {
  770. $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . ' data-html="' . dol_escape_htmltag($label) . '">' . $label . '</option>';
  771. }
  772. }
  773. $ret .= $hookmanager->resPrint;
  774. $ret .= '</select>';
  775. if (empty($conf->dol_optimize_smallscreen)) {
  776. $ret .= ajax_combobox('.' . $name . 'select');
  777. }
  778. // 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
  779. $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.
  780. $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")) . '">';
  781. $ret .= '</div>';
  782. if (!empty($conf->use_javascript_ajax)) {
  783. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  784. <script nonce="' . getNonce() . '">
  785. 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 */
  786. {
  787. atleastoneselected=0;
  788. jQuery("."+cssclass).each(function( index ) {
  789. /* console.log( index + ": " + $( this ).text() ); */
  790. if ($(this).is(\':checked\')) atleastoneselected++;
  791. });
  792. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  793. if (atleastoneselected || ' . $alwaysvisible . ')
  794. {
  795. jQuery("."+name).show();
  796. ' . ($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("' . $selected . '").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '') . '
  797. ' . ($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '') . '
  798. }
  799. else
  800. {
  801. jQuery("."+name).hide();
  802. jQuery("."+name+"other").hide();
  803. }
  804. }
  805. jQuery(document).ready(function () {
  806. initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
  807. jQuery(".' . $cssclass . '").click(function() {
  808. initCheckForSelect(1, "' . $name . '", "' . $cssclass . '");
  809. });
  810. jQuery(".' . $name . 'select").change(function() {
  811. var massaction = $( this ).val();
  812. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  813. if (massaction == "builddoc")
  814. {
  815. urlform = urlform + "#show_files";
  816. }
  817. $( this ).closest("form").attr("action", urlform);
  818. console.log("we select a mass action name=' . $name . ' massaction="+massaction+" - "+urlform);
  819. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  820. if ($(this).val() != \'0\')
  821. {
  822. jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
  823. jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
  824. jQuery(".' . $name . '"+massaction).show();
  825. }
  826. else
  827. {
  828. jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
  829. jQuery(".' . $name . 'other").hide(); /* To disable any div open */
  830. }
  831. });
  832. });
  833. </script>
  834. ';
  835. }
  836. return $ret;
  837. }
  838. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  839. /**
  840. * Return combo list of activated countries, into language of user
  841. *
  842. * @param string $selected Id or Code or Label of preselected country
  843. * @param string $htmlname Name of html select object
  844. * @param string $htmloption More html options on select object
  845. * @param integer $maxlength Max length for labels (0=no limit)
  846. * @param string $morecss More css class
  847. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  848. * @param int|string $showempty Show empty choice
  849. * @param int $disablefavorites 1=Disable favorites,
  850. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  851. * @param array $exclude_country_code Array of country code (iso2) to exclude
  852. * @param int $hideflags Hide flags
  853. * @return string HTML string with select
  854. */
  855. 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)
  856. {
  857. // phpcs:enable
  858. global $conf, $langs, $mysoc;
  859. $langs->load("dict");
  860. $out = '';
  861. $countryArray = array();
  862. $favorite = array();
  863. $label = array();
  864. $atleastonefavorite = 0;
  865. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  866. $sql .= " FROM " . $this->db->prefix() . "c_country";
  867. $sql .= " WHERE active > 0";
  868. //$sql.= " ORDER BY code ASC";
  869. dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
  870. $resql = $this->db->query($sql);
  871. if ($resql) {
  872. $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
  873. $num = $this->db->num_rows($resql);
  874. $i = 0;
  875. if ($num) {
  876. while ($i < $num) {
  877. $obj = $this->db->fetch_object($resql);
  878. $countryArray[$i]['rowid'] = $obj->rowid;
  879. $countryArray[$i]['code_iso'] = $obj->code_iso;
  880. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  881. $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 : ''));
  882. $countryArray[$i]['favorite'] = $obj->favorite;
  883. $countryArray[$i]['eec'] = $obj->eec;
  884. $favorite[$i] = $obj->favorite;
  885. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  886. $i++;
  887. }
  888. if (empty($disablefavorites)) {
  889. $array1_sort_order = SORT_DESC;
  890. $array2_sort_order = SORT_ASC;
  891. array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
  892. } else {
  893. $countryArray = dol_sort_array($countryArray, 'label');
  894. }
  895. if ($showempty) {
  896. if (is_numeric($showempty)) {
  897. $out .= '<option value="">&nbsp;</option>' . "\n";
  898. } else {
  899. $out .= '<option value="-1">' . $langs->trans($showempty) . '</option>' . "\n";
  900. }
  901. }
  902. if ($addspecialentries) { // Add dedicated entries for groups of countries
  903. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  904. $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  905. $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
  906. if ($mysoc->isInEEC()) {
  907. $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  908. }
  909. $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
  910. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  911. }
  912. foreach ($countryArray as $row) {
  913. //if (empty($showempty) && empty($row['rowid'])) continue;
  914. if (empty($row['rowid'])) {
  915. continue;
  916. }
  917. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  918. continue; // exclude some countries
  919. }
  920. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  921. $atleastonefavorite++;
  922. }
  923. if (empty($row['favorite']) && $atleastonefavorite) {
  924. $atleastonefavorite = 0;
  925. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  926. }
  927. $labeltoshow = '';
  928. if ($row['label']) {
  929. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  930. } else {
  931. $labeltoshow .= '&nbsp;';
  932. }
  933. if ($row['code_iso']) {
  934. $labeltoshow .= ' <span class="opacitymedium">(' . $row['code_iso'] . ')</span>';
  935. if (empty($hideflags)) {
  936. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  937. $labeltoshow = $tmpflag . ' ' . $labeltoshow;
  938. }
  939. }
  940. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  941. $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']) . '">';
  942. } else {
  943. $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']) . '">';
  944. }
  945. $out .= $labeltoshow;
  946. $out .= '</option>' . "\n";
  947. }
  948. }
  949. $out .= '</select>';
  950. } else {
  951. dol_print_error($this->db);
  952. }
  953. // Make select dynamic
  954. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  955. $out .= ajax_combobox('select' . $htmlname, array(), 0, 0, 'resolve');
  956. return $out;
  957. }
  958. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  959. /**
  960. * Return select list of incoterms
  961. *
  962. * @param string $selected Id or Code of preselected incoterm
  963. * @param string $location_incoterms Value of input location
  964. * @param string $page Defined the form action
  965. * @param string $htmlname Name of html select object
  966. * @param string $htmloption Options html on select object
  967. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  968. * @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')))
  969. * @param array $disableautocomplete Disable autocomplete
  970. * @return string HTML string with select and input
  971. */
  972. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  973. {
  974. // phpcs:enable
  975. global $conf, $langs;
  976. $langs->load("dict");
  977. $out = '';
  978. $moreattrib = '';
  979. $incotermArray = array();
  980. $sql = "SELECT rowid, code";
  981. $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
  982. $sql .= " WHERE active > 0";
  983. $sql .= " ORDER BY code ASC";
  984. dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
  985. $resql = $this->db->query($sql);
  986. if ($resql) {
  987. if ($conf->use_javascript_ajax && !$forcecombo) {
  988. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  989. $out .= ajax_combobox($htmlname, $events);
  990. }
  991. if (!empty($page)) {
  992. $out .= '<form method="post" action="' . $page . '">';
  993. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  994. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  995. }
  996. $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
  997. $out .= '<option value="0">&nbsp;</option>';
  998. $num = $this->db->num_rows($resql);
  999. $i = 0;
  1000. if ($num) {
  1001. while ($i < $num) {
  1002. $obj = $this->db->fetch_object($resql);
  1003. $incotermArray[$i]['rowid'] = $obj->rowid;
  1004. $incotermArray[$i]['code'] = $obj->code;
  1005. $i++;
  1006. }
  1007. foreach ($incotermArray as $row) {
  1008. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  1009. $out .= '<option value="' . $row['rowid'] . '" selected>';
  1010. } else {
  1011. $out .= '<option value="' . $row['rowid'] . '">';
  1012. }
  1013. if ($row['code']) {
  1014. $out .= $row['code'];
  1015. }
  1016. $out .= '</option>';
  1017. }
  1018. }
  1019. $out .= '</select>';
  1020. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  1021. $out .= ajax_multiautocompleter('location_incoterms', array(), DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
  1022. $moreattrib .= ' autocomplete="off"';
  1023. }
  1024. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
  1025. if (!empty($page)) {
  1026. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
  1027. }
  1028. } else {
  1029. dol_print_error($this->db);
  1030. }
  1031. return $out;
  1032. }
  1033. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1034. /**
  1035. * Return list of types of lines (product or service)
  1036. * Example: 0=product, 1=service, 9=other (for external module)
  1037. *
  1038. * @param string $selected Preselected type
  1039. * @param string $htmlname Name of field in html form
  1040. * @param int $showempty Add an empty field
  1041. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  1042. * @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')
  1043. * @return void
  1044. */
  1045. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  1046. {
  1047. // phpcs:enable
  1048. global $langs, $conf;
  1049. // If product & services are enabled or both disabled.
  1050. if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
  1051. || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
  1052. if (empty($hidetext)) {
  1053. print $langs->trans("Type") . ': ';
  1054. }
  1055. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  1056. if ($showempty) {
  1057. print '<option value="-1"';
  1058. if ($selected == -1) {
  1059. print ' selected';
  1060. }
  1061. print '>&nbsp;</option>';
  1062. }
  1063. print '<option value="0"';
  1064. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1065. print ' selected';
  1066. }
  1067. print '>' . $langs->trans("Product");
  1068. print '<option value="1"';
  1069. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1070. print ' selected';
  1071. }
  1072. print '>' . $langs->trans("Service");
  1073. print '</select>';
  1074. print ajax_combobox('select_' . $htmlname);
  1075. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1076. }
  1077. if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
  1078. print $langs->trans("Service");
  1079. print '<input type="hidden" name="' . $htmlname . '" value="1">';
  1080. }
  1081. if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
  1082. print $langs->trans("Product");
  1083. print '<input type="hidden" name="' . $htmlname . '" value="0">';
  1084. }
  1085. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1086. 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
  1087. }
  1088. }
  1089. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1090. /**
  1091. * Load into cache cache_types_fees, array of types of fees
  1092. *
  1093. * @return int Nb of lines loaded, <0 if KO
  1094. */
  1095. public function load_cache_types_fees()
  1096. {
  1097. // phpcs:enable
  1098. global $langs;
  1099. $num = count($this->cache_types_fees);
  1100. if ($num > 0) {
  1101. return 0; // Cache already loaded
  1102. }
  1103. dol_syslog(__METHOD__, LOG_DEBUG);
  1104. $langs->load("trips");
  1105. $sql = "SELECT c.code, c.label";
  1106. $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
  1107. $sql .= " WHERE active > 0";
  1108. $resql = $this->db->query($sql);
  1109. if ($resql) {
  1110. $num = $this->db->num_rows($resql);
  1111. $i = 0;
  1112. while ($i < $num) {
  1113. $obj = $this->db->fetch_object($resql);
  1114. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1115. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1116. $this->cache_types_fees[$obj->code] = $label;
  1117. $i++;
  1118. }
  1119. asort($this->cache_types_fees);
  1120. return $num;
  1121. } else {
  1122. dol_print_error($this->db);
  1123. return -1;
  1124. }
  1125. }
  1126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1127. /**
  1128. * Return list of types of notes
  1129. *
  1130. * @param string $selected Preselected type
  1131. * @param string $htmlname Name of field in form
  1132. * @param int $showempty Add an empty field
  1133. * @return void
  1134. */
  1135. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1136. {
  1137. // phpcs:enable
  1138. global $user, $langs;
  1139. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  1140. $this->load_cache_types_fees();
  1141. print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
  1142. if ($showempty) {
  1143. print '<option value="-1"';
  1144. if ($selected == -1) {
  1145. print ' selected';
  1146. }
  1147. print '>&nbsp;</option>';
  1148. }
  1149. foreach ($this->cache_types_fees as $key => $value) {
  1150. print '<option value="' . $key . '"';
  1151. if ($key == $selected) {
  1152. print ' selected';
  1153. }
  1154. print '>';
  1155. print $value;
  1156. print '</option>';
  1157. }
  1158. print '</select>';
  1159. if ($user->admin) {
  1160. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1161. }
  1162. }
  1163. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1164. /**
  1165. * Output html form to select a third party
  1166. *
  1167. * @param string $selected Preselected type
  1168. * @param string $htmlname Name of field in form
  1169. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>()] are allowed here (example: 's.rowid <> x', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1170. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1171. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1172. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1173. * @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')))
  1174. * @param int $limit Maximum number of elements
  1175. * @param string $morecss Add more css styles to the SELECT component
  1176. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1177. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1178. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1179. * @param array $ajaxoptions Options for ajax_autocompleter
  1180. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1181. * @param array $excludeids Exclude IDs from the select combo
  1182. * @param int $showcode Show code
  1183. * @return string HTML string with select box for thirdparty.
  1184. */
  1185. 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)
  1186. {
  1187. // phpcs:enable
  1188. global $conf, $user, $langs;
  1189. $out = '';
  1190. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1191. if (is_null($ajaxoptions)) {
  1192. $ajaxoptions = array();
  1193. }
  1194. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1195. // No immediate load of all database
  1196. $placeholder = '';
  1197. if ($selected && empty($selected_input_value)) {
  1198. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1199. $societetmp = new Societe($this->db);
  1200. $societetmp->fetch($selected);
  1201. $selected_input_value = $societetmp->name;
  1202. unset($societetmp);
  1203. }
  1204. // mode 1
  1205. $urloption = 'htmlname=' . urlencode(str_replace('.', '_', $htmlname)) . '&outjson=1&filter=' . urlencode($filter) . (empty($excludeids) ? '' : '&excludeids=' . join(',', $excludeids)) . ($showtype ? '&showtype=' . urlencode($showtype) : '') . ($showcode ? '&showcode=' . urlencode($showcode) : '');
  1206. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1207. if (empty($hidelabel)) {
  1208. print $langs->trans("RefOrLabel") . ' : ';
  1209. } elseif ($hidelabel > 1) {
  1210. $placeholder = $langs->trans("RefOrLabel");
  1211. if ($hidelabel == 2) {
  1212. $out .= img_picto($langs->trans("Search"), 'search');
  1213. }
  1214. }
  1215. $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' : '') . ' />';
  1216. if ($hidelabel == 3) {
  1217. $out .= img_picto($langs->trans("Search"), 'search');
  1218. }
  1219. $out .= ajax_event($htmlname, $events);
  1220. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1221. } else {
  1222. // Immediate load of all database
  1223. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1224. }
  1225. return $out;
  1226. }
  1227. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1228. /**
  1229. * Output html form to select a third party.
  1230. * 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.
  1231. *
  1232. * @param string $selected Preselected type
  1233. * @param string $htmlname Name of field in form
  1234. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>] are allowed here, example: 's.rowid <> x'
  1235. * If you need parenthesis, use the Universal Filter Syntax, example: '(s.client:in:(1,3))'
  1236. * Do not use a filter coming from input of users.
  1237. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1238. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1239. * @param int $forcecombo Force to use standard HTML select component without beautification
  1240. * @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')))
  1241. * @param string $filterkey Filter on key value
  1242. * @param int $outputmode 0=HTML select string, 1=Array
  1243. * @param int $limit Limit number of answers
  1244. * @param string $morecss Add more css styles to the SELECT component
  1245. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1246. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1247. * @param array $excludeids Exclude IDs from the select combo
  1248. * @param int $showcode Show code in list
  1249. * @return array|string HTML string with
  1250. */
  1251. 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)
  1252. {
  1253. // phpcs:enable
  1254. global $conf, $user, $langs;
  1255. global $hookmanager;
  1256. $out = '';
  1257. $num = 0;
  1258. $outarray = array();
  1259. if ($selected === '') {
  1260. $selected = array();
  1261. } elseif (!is_array($selected)) {
  1262. $selected = array($selected);
  1263. }
  1264. // Clean $filter that may contains sql conditions so sql code
  1265. if (function_exists('testSqlAndScriptInject')) {
  1266. if (testSqlAndScriptInject($filter, 3) > 0) {
  1267. $filter = '';
  1268. return 'SQLInjectionTryDetected';
  1269. }
  1270. }
  1271. if (preg_match('/[\(\)]/', $filter)) {
  1272. // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
  1273. $errormsg = '';
  1274. $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
  1275. // Redo clean $filter that may contains sql conditions so sql code
  1276. if (function_exists('testSqlAndScriptInject')) {
  1277. if (testSqlAndScriptInject($filter, 3) > 0) {
  1278. $filter = '';
  1279. return 'SQLInjectionTryDetected';
  1280. }
  1281. }
  1282. } else {
  1283. // If not, we do nothing. We already no that there is no parenthesis
  1284. // TODO Disallow this case in a future.
  1285. dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Syntax.", LOG_WARNING);
  1286. }
  1287. // We search companies
  1288. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1289. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1290. $sql .= ", s.address, s.zip, s.town";
  1291. $sql .= ", dictp.code as country_code";
  1292. }
  1293. $sql .= " FROM " . $this->db->prefix() . "societe as s";
  1294. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1295. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
  1296. }
  1297. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1298. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  1299. }
  1300. $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
  1301. if (!empty($user->socid)) {
  1302. $sql .= " AND s.rowid = " . ((int) $user->socid);
  1303. }
  1304. if ($filter) {
  1305. // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
  1306. // if not, by testSqlAndScriptInject() only.
  1307. $sql .= " AND (" . $filter . ")";
  1308. }
  1309. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1310. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  1311. }
  1312. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1313. $sql .= " AND s.status <> 0";
  1314. }
  1315. if (!empty($excludeids)) {
  1316. $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(join(',', $excludeids)) . ")";
  1317. }
  1318. // Add where from hooks
  1319. $parameters = array();
  1320. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1321. $sql .= $hookmanager->resPrint;
  1322. // Add criteria
  1323. if ($filterkey && $filterkey != '') {
  1324. $sql .= " AND (";
  1325. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1326. // For natural search
  1327. $scrit = explode(' ', $filterkey);
  1328. $i = 0;
  1329. if (count($scrit) > 1) {
  1330. $sql .= "(";
  1331. }
  1332. foreach ($scrit as $crit) {
  1333. if ($i > 0) {
  1334. $sql .= " AND ";
  1335. }
  1336. $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  1337. $i++;
  1338. }
  1339. if (count($scrit) > 1) {
  1340. $sql .= ")";
  1341. }
  1342. if (isModEnabled('barcode')) {
  1343. $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1344. }
  1345. $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1346. $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1347. $sql .= ")";
  1348. }
  1349. $sql .= $this->db->order("nom", "ASC");
  1350. $sql .= $this->db->plimit($limit, 0);
  1351. // Build output string
  1352. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1353. $resql = $this->db->query($sql);
  1354. if ($resql) {
  1355. if (!$forcecombo) {
  1356. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1357. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1358. }
  1359. // Construct $out and $outarray
  1360. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . '>' . "\n";
  1361. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1362. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1363. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1364. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1365. if ($showempty && !is_numeric($showempty)) {
  1366. $textifempty = $langs->trans($showempty);
  1367. } else {
  1368. $textifempty .= $langs->trans("All");
  1369. }
  1370. }
  1371. if ($showempty) {
  1372. $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
  1373. }
  1374. $companytemp = new Societe($this->db);
  1375. $num = $this->db->num_rows($resql);
  1376. $i = 0;
  1377. if ($num) {
  1378. while ($i < $num) {
  1379. $obj = $this->db->fetch_object($resql);
  1380. $label = '';
  1381. if ($showcode || !empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) {
  1382. if (($obj->client) && (!empty($obj->code_client))) {
  1383. $label = $obj->code_client . ' - ';
  1384. }
  1385. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1386. $label .= $obj->code_fournisseur . ' - ';
  1387. }
  1388. $label .= ' ' . $obj->name;
  1389. } else {
  1390. $label = $obj->name;
  1391. }
  1392. if (!empty($obj->name_alias)) {
  1393. $label .= ' (' . $obj->name_alias . ')';
  1394. }
  1395. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1396. $label .= ' - '.$obj->tva_intra;
  1397. }
  1398. $labelhtml = $label;
  1399. if ($showtype) {
  1400. $companytemp->id = $obj->rowid;
  1401. $companytemp->client = $obj->client;
  1402. $companytemp->fournisseur = $obj->fournisseur;
  1403. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1404. if ($tmptype) {
  1405. $labelhtml .= ' ' . $tmptype;
  1406. }
  1407. if ($obj->client || $obj->fournisseur) {
  1408. $label .= ' (';
  1409. }
  1410. if ($obj->client == 1 || $obj->client == 3) {
  1411. $label .= $langs->trans("Customer");
  1412. }
  1413. if ($obj->client == 2 || $obj->client == 3) {
  1414. $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
  1415. }
  1416. if ($obj->fournisseur) {
  1417. $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
  1418. }
  1419. if ($obj->client || $obj->fournisseur) {
  1420. $label .= ')';
  1421. }
  1422. }
  1423. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1424. $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
  1425. if (!empty($obj->country_code)) {
  1426. $s .= ', ' . $langs->trans('Country' . $obj->country_code);
  1427. }
  1428. $label .= $s;
  1429. $labelhtml .= $s;
  1430. }
  1431. if (empty($outputmode)) {
  1432. if (in_array($obj->rowid, $selected)) {
  1433. $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml) . '">' . $label . '</option>';
  1434. } else {
  1435. $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml) . '">' . $label . '</option>';
  1436. }
  1437. } else {
  1438. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
  1439. }
  1440. $i++;
  1441. if (($i % 10) == 0) {
  1442. $out .= "\n";
  1443. }
  1444. }
  1445. }
  1446. $out .= '</select>' . "\n";
  1447. } else {
  1448. dol_print_error($this->db);
  1449. }
  1450. $this->result = array('nbofthirdparties' => $num);
  1451. if ($outputmode) {
  1452. return $outarray;
  1453. }
  1454. return $out;
  1455. }
  1456. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1457. /**
  1458. * Return HTML combo list of absolute discounts
  1459. *
  1460. * @param string $selected Id remise fixe pre-selectionnee
  1461. * @param string $htmlname Nom champ formulaire
  1462. * @param string $filter Criteres optionnels de filtre
  1463. * @param int $socid Id of thirdparty
  1464. * @param int $maxvalue Max value for lines that can be selected
  1465. * @return int Return number of qualifed lines in list
  1466. */
  1467. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1468. {
  1469. // phpcs:enable
  1470. global $langs, $conf;
  1471. // On recherche les remises
  1472. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1473. $sql .= " re.description, re.fk_facture_source";
  1474. $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
  1475. $sql .= " WHERE re.fk_soc = " . (int) $socid;
  1476. $sql .= " AND re.entity = " . $conf->entity;
  1477. if ($filter) {
  1478. $sql .= " AND " . $filter;
  1479. }
  1480. $sql .= " ORDER BY re.description ASC";
  1481. dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
  1482. $resql = $this->db->query($sql);
  1483. if ($resql) {
  1484. print '<select id="select_' . $htmlname . '" class="flat maxwidthonsmartphone" name="' . $htmlname . '">';
  1485. $num = $this->db->num_rows($resql);
  1486. $qualifiedlines = $num;
  1487. $i = 0;
  1488. if ($num) {
  1489. print '<option value="0">&nbsp;</option>';
  1490. while ($i < $num) {
  1491. $obj = $this->db->fetch_object($resql);
  1492. $desc = dol_trunc($obj->description, 40);
  1493. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1494. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1495. }
  1496. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1497. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1498. }
  1499. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1500. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1501. }
  1502. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1503. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1504. }
  1505. $selectstring = '';
  1506. if ($selected > 0 && $selected == $obj->rowid) {
  1507. $selectstring = ' selected';
  1508. }
  1509. $disabled = '';
  1510. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1511. $qualifiedlines--;
  1512. $disabled = ' disabled';
  1513. }
  1514. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1515. $tmpfac = new Facture($this->db);
  1516. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1517. $desc = $desc . ' - ' . $tmpfac->ref;
  1518. }
  1519. }
  1520. print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  1521. $i++;
  1522. }
  1523. }
  1524. print '</select>';
  1525. print ajax_combobox('select_' . $htmlname);
  1526. return $qualifiedlines;
  1527. } else {
  1528. dol_print_error($this->db);
  1529. return -1;
  1530. }
  1531. }
  1532. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1533. /**
  1534. * Return list of all contacts (for a third party or all)
  1535. *
  1536. * @param int $socid Id ot third party or 0 for all
  1537. * @param string $selected Id contact pre-selectionne
  1538. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1539. * @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
  1540. * @param string $exclude List of contacts id to exclude
  1541. * @param string $limitto Disable answers that are not id in this array list
  1542. * @param integer $showfunction Add function into label
  1543. * @param string $morecss Add more class to class style
  1544. * @param integer $showsoc Add company into label
  1545. * @param int $forcecombo Force to use combo box
  1546. * @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')))
  1547. * @param bool $options_only Return options only (for ajax treatment)
  1548. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1549. * @param string $htmlid Html id to use instead of htmlname
  1550. * @return int <0 if KO, Nb of contact in list if OK
  1551. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1552. */
  1553. 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 = '')
  1554. {
  1555. // phpcs:enable
  1556. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1557. return $this->num;
  1558. }
  1559. /**
  1560. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1561. * This also set the number of contacts found into $this->num
  1562. *
  1563. * @since 9.0 Add afterSelectContactOptions hook
  1564. *
  1565. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1566. * @param array|int $selected Array of ID of pre-selected contact id
  1567. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1568. * @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
  1569. * @param string $exclude List of contacts id to exclude
  1570. * @param string $limitto Disable answers that are not id in this array list
  1571. * @param integer $showfunction Add function into label
  1572. * @param string $morecss Add more class to class style
  1573. * @param bool $options_only Return options only (for ajax treatment)
  1574. * @param integer $showsoc Add company into label
  1575. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1576. * @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')))
  1577. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1578. * @param string $htmlid Html id to use instead of htmlname
  1579. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1580. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1581. * @return int|string <0 if KO, HTML with select string if OK.
  1582. */
  1583. 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)
  1584. {
  1585. global $conf, $langs, $hookmanager, $action;
  1586. $langs->load('companies');
  1587. if (empty($htmlid)) {
  1588. $htmlid = $htmlname;
  1589. }
  1590. $num = 0;
  1591. if ($selected === '') {
  1592. $selected = array();
  1593. } elseif (!is_array($selected)) {
  1594. $selected = array($selected);
  1595. }
  1596. $out = '';
  1597. if (!is_object($hookmanager)) {
  1598. include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  1599. $hookmanager = new HookManager($this->db);
  1600. }
  1601. // We search third parties
  1602. $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";
  1603. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1604. $sql .= ", s.nom as company, s.town AS company_town";
  1605. }
  1606. $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
  1607. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1608. $sql .= " LEFT OUTER JOIN " . $this->db->prefix() . "societe as s ON s.rowid=sp.fk_soc";
  1609. }
  1610. $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
  1611. if ($socid > 0 || $socid == -1) {
  1612. $sql .= " AND sp.fk_soc = " . ((int) $socid);
  1613. }
  1614. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1615. $sql .= " AND sp.statut <> 0";
  1616. }
  1617. // Add where from hooks
  1618. $parameters = array();
  1619. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1620. $sql .= $hookmanager->resPrint;
  1621. $sql .= " ORDER BY sp.lastname ASC";
  1622. dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
  1623. $resql = $this->db->query($sql);
  1624. if ($resql) {
  1625. $num = $this->db->num_rows($resql);
  1626. if ($htmlname != 'none' && !$options_only) {
  1627. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
  1628. }
  1629. if ($showempty && !is_numeric($showempty)) {
  1630. $textforempty = $showempty;
  1631. $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>';
  1632. } else {
  1633. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
  1634. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
  1635. }
  1636. if ($showempty == 2) {
  1637. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
  1638. }
  1639. }
  1640. $i = 0;
  1641. if ($num) {
  1642. include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  1643. $contactstatic = new Contact($this->db);
  1644. while ($i < $num) {
  1645. $obj = $this->db->fetch_object($resql);
  1646. // Set email (or phones) and town extended infos
  1647. $extendedInfos = '';
  1648. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1649. $extendedInfos = array();
  1650. $email = trim($obj->email);
  1651. if (!empty($email)) {
  1652. $extendedInfos[] = $email;
  1653. } else {
  1654. $phone = trim($obj->phone);
  1655. $phone_perso = trim($obj->phone_perso);
  1656. $phone_mobile = trim($obj->phone_mobile);
  1657. if (!empty($phone)) {
  1658. $extendedInfos[] = $phone;
  1659. }
  1660. if (!empty($phone_perso)) {
  1661. $extendedInfos[] = $phone_perso;
  1662. }
  1663. if (!empty($phone_mobile)) {
  1664. $extendedInfos[] = $phone_mobile;
  1665. }
  1666. }
  1667. $contact_town = trim($obj->contact_town);
  1668. $company_town = trim($obj->company_town);
  1669. if (!empty($contact_town)) {
  1670. $extendedInfos[] = $contact_town;
  1671. } elseif (!empty($company_town)) {
  1672. $extendedInfos[] = $company_town;
  1673. }
  1674. $extendedInfos = implode(' - ', $extendedInfos);
  1675. if (!empty($extendedInfos)) {
  1676. $extendedInfos = ' - ' . $extendedInfos;
  1677. }
  1678. }
  1679. $contactstatic->id = $obj->rowid;
  1680. $contactstatic->lastname = $obj->lastname;
  1681. $contactstatic->firstname = $obj->firstname;
  1682. if ($obj->statut == 1) {
  1683. if ($htmlname != 'none') {
  1684. $disabled = 0;
  1685. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1686. $disabled = 1;
  1687. }
  1688. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1689. $disabled = 1;
  1690. }
  1691. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1692. $out .= '<option value="' . $obj->rowid . '"';
  1693. if ($disabled) {
  1694. $out .= ' disabled';
  1695. }
  1696. $out .= ' selected>';
  1697. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1698. if ($showfunction && $obj->poste) {
  1699. $out .= ' (' . $obj->poste . ')';
  1700. }
  1701. if (($showsoc > 0) && $obj->company) {
  1702. $out .= ' - (' . $obj->company . ')';
  1703. }
  1704. $out .= '</option>';
  1705. } else {
  1706. $out .= '<option value="' . $obj->rowid . '"';
  1707. if ($disabled) {
  1708. $out .= ' disabled';
  1709. }
  1710. $out .= '>';
  1711. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1712. if ($showfunction && $obj->poste) {
  1713. $out .= ' (' . $obj->poste . ')';
  1714. }
  1715. if (($showsoc > 0) && $obj->company) {
  1716. $out .= ' - (' . $obj->company . ')';
  1717. }
  1718. $out .= '</option>';
  1719. }
  1720. } else {
  1721. if (in_array($obj->rowid, $selected)) {
  1722. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1723. if ($showfunction && $obj->poste) {
  1724. $out .= ' (' . $obj->poste . ')';
  1725. }
  1726. if (($showsoc > 0) && $obj->company) {
  1727. $out .= ' - (' . $obj->company . ')';
  1728. }
  1729. }
  1730. }
  1731. }
  1732. $i++;
  1733. }
  1734. } else {
  1735. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1736. $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
  1737. $out .= $labeltoshow;
  1738. $out .= '</option>';
  1739. }
  1740. $parameters = array(
  1741. 'socid' => $socid,
  1742. 'htmlname' => $htmlname,
  1743. 'resql' => $resql,
  1744. 'out' => &$out,
  1745. 'showfunction' => $showfunction,
  1746. 'showsoc' => $showsoc,
  1747. );
  1748. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1749. if ($htmlname != 'none' && !$options_only) {
  1750. $out .= '</select>';
  1751. }
  1752. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1753. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1754. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1755. }
  1756. $this->num = $num;
  1757. return $out;
  1758. } else {
  1759. dol_print_error($this->db);
  1760. return -1;
  1761. }
  1762. }
  1763. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1764. /**
  1765. * Return the HTML select list of users
  1766. *
  1767. * @param string $selected Id user preselected
  1768. * @param string $htmlname Field name in form
  1769. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1770. * @param array $exclude Array list of users id to exclude
  1771. * @param int $disabled If select list must be disabled
  1772. * @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
  1773. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1774. * @param string $force_entity '0' or Ids of environment to force
  1775. * @return void
  1776. * @deprecated Use select_dolusers instead
  1777. * @see select_dolusers()
  1778. */
  1779. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1780. {
  1781. // phpcs:enable
  1782. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1783. }
  1784. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1785. /**
  1786. * Return select list of users
  1787. *
  1788. * @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)
  1789. * @param string $htmlname Field name in form
  1790. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1791. * @param array $exclude Array list of users id to exclude
  1792. * @param int $disabled If select list must be disabled
  1793. * @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
  1794. * @param array|string $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1795. * @param string $force_entity '0' or Ids of environment to force
  1796. * @param int $maxlength Maximum length of string into list (0=no limit)
  1797. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1798. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1799. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1800. * @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.
  1801. * @param string $morecss More css
  1802. * @param int $notdisabled Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1803. * @param int $outputmode 0=HTML select string, 1=Array
  1804. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1805. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1806. * @return array|string HTML select string
  1807. * @see select_dolgroups()
  1808. */
  1809. 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)
  1810. {
  1811. // phpcs:enable
  1812. global $conf, $user, $langs, $hookmanager;
  1813. global $action;
  1814. // If no preselected user defined, we take current user
  1815. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1816. $selected = $user->id;
  1817. }
  1818. if ($selected === '') {
  1819. $selected = array();
  1820. } elseif (!is_array($selected)) {
  1821. $selected = array($selected);
  1822. }
  1823. $excludeUsers = null;
  1824. $includeUsers = null;
  1825. // Permettre l'exclusion d'utilisateurs
  1826. if (is_array($exclude)) {
  1827. $excludeUsers = implode(",", $exclude);
  1828. }
  1829. // Permettre l'inclusion d'utilisateurs
  1830. if (is_array($include)) {
  1831. $includeUsers = implode(",", $include);
  1832. } elseif ($include == 'hierarchy') {
  1833. // Build list includeUsers to have only hierarchy
  1834. $includeUsers = implode(",", $user->getAllChildIds(0));
  1835. } elseif ($include == 'hierarchyme') {
  1836. // Build list includeUsers to have only hierarchy and current user
  1837. $includeUsers = implode(",", $user->getAllChildIds(1));
  1838. }
  1839. $out = '';
  1840. $outarray = array();
  1841. $outarray2 = array();
  1842. // Forge request to select users
  1843. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1844. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1845. $sql .= ", e.label";
  1846. }
  1847. $sql .= " FROM " . $this->db->prefix() . "user as u";
  1848. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1849. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
  1850. if ($force_entity) {
  1851. $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
  1852. } else {
  1853. $sql .= " WHERE u.entity IS NOT NULL";
  1854. }
  1855. } else {
  1856. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1857. $sql .= " LEFT JOIN " . $this->db->prefix() . "usergroup_user as ug";
  1858. $sql .= " ON ug.fk_user = u.rowid";
  1859. $sql .= " WHERE ug.entity = " . $conf->entity;
  1860. } else {
  1861. $sql .= " WHERE u.entity IN (0, " . $conf->entity . ")";
  1862. }
  1863. }
  1864. if (!empty($user->socid)) {
  1865. $sql .= " AND u.fk_soc = " . ((int) $user->socid);
  1866. }
  1867. if (is_array($exclude) && $excludeUsers) {
  1868. $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
  1869. }
  1870. if ($includeUsers) {
  1871. $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
  1872. }
  1873. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $notdisabled) {
  1874. $sql .= " AND u.statut <> 0";
  1875. }
  1876. if (!empty($morefilter)) {
  1877. $sql .= " " . $morefilter;
  1878. }
  1879. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1880. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1881. if (!empty($reshook)) {
  1882. $sql .= $hookmanager->resPrint;
  1883. }
  1884. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1885. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1886. } else {
  1887. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1888. }
  1889. dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
  1890. $resql = $this->db->query($sql);
  1891. if ($resql) {
  1892. $num = $this->db->num_rows($resql);
  1893. $i = 0;
  1894. if ($num) {
  1895. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1896. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  1897. if ($show_empty && !$multiple) {
  1898. $textforempty = ' ';
  1899. if (!empty($conf->use_javascript_ajax)) {
  1900. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1901. }
  1902. if (!is_numeric($show_empty)) {
  1903. $textforempty = $show_empty;
  1904. }
  1905. $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  1906. }
  1907. if ($show_every) {
  1908. $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
  1909. }
  1910. $userstatic = new User($this->db);
  1911. while ($i < $num) {
  1912. $obj = $this->db->fetch_object($resql);
  1913. $userstatic->id = $obj->rowid;
  1914. $userstatic->lastname = $obj->lastname;
  1915. $userstatic->firstname = $obj->firstname;
  1916. $userstatic->photo = $obj->photo;
  1917. $userstatic->statut = $obj->status;
  1918. $userstatic->entity = $obj->entity;
  1919. $userstatic->admin = $obj->admin;
  1920. $disableline = '';
  1921. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1922. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1923. }
  1924. $labeltoshow = '';
  1925. $labeltoshowhtml = '';
  1926. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1927. $fullNameMode = 0;
  1928. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1929. $fullNameMode = 1; //Firstname+lastname
  1930. }
  1931. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1932. $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1933. if (empty($obj->firstname) && empty($obj->lastname)) {
  1934. $labeltoshow .= $obj->login;
  1935. $labeltoshowhtml .= $obj->login;
  1936. }
  1937. // Complete name with a more info string like: ' (info1 - info2 - ...)'
  1938. $moreinfo = '';
  1939. $moreinfohtml = '';
  1940. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1941. $moreinfo .= ($moreinfo ? ' - ' : ' (');
  1942. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
  1943. $moreinfo .= $obj->login;
  1944. $moreinfohtml .= $obj->login;
  1945. }
  1946. if ($showstatus >= 0) {
  1947. if ($obj->status == 1 && $showstatus == 1) {
  1948. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
  1949. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
  1950. }
  1951. if ($obj->status == 0 && $showstatus == 1) {
  1952. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
  1953. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
  1954. }
  1955. }
  1956. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1957. if (!$obj->entity) {
  1958. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
  1959. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
  1960. } else {
  1961. if ($obj->entity != $conf->entity) {
  1962. $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1963. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1964. }
  1965. }
  1966. }
  1967. $moreinfo .= ($moreinfo ? ')' : '');
  1968. $moreinfohtml .= ($moreinfohtml ? ')</span>' : '');
  1969. if ($disableline && $disableline != '1') {
  1970. // Add text from $enableonlytext parameter
  1971. $moreinfo .= ' - ' . $disableline;
  1972. $moreinfohtml .= ' - ' . $disableline;
  1973. }
  1974. $labeltoshow .= $moreinfo;
  1975. $labeltoshowhtml .= $moreinfohtml;
  1976. $out .= '<option value="' . $obj->rowid . '"';
  1977. if ($disableline) {
  1978. $out .= ' disabled';
  1979. }
  1980. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1981. $out .= ' selected';
  1982. }
  1983. $out .= ' data-html="';
  1984. $outhtml = $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
  1985. if ($showstatus >= 0 && $obj->status == 0) {
  1986. $outhtml .= '<strike class="opacitymediumxxx">';
  1987. }
  1988. $outhtml .= $labeltoshowhtml;
  1989. if ($showstatus >= 0 && $obj->status == 0) {
  1990. $outhtml .= '</strike>';
  1991. }
  1992. $out .= dol_escape_htmltag($outhtml);
  1993. $out .= '">';
  1994. $out .= $labeltoshow;
  1995. $out .= '</option>';
  1996. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
  1997. $outarray2[$userstatic->id] = array(
  1998. 'id'=>$userstatic->id,
  1999. 'label'=>$labeltoshow,
  2000. 'labelhtml'=>$labeltoshowhtml
  2001. );
  2002. $i++;
  2003. }
  2004. } else {
  2005. $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
  2006. $out .= '<option value="">' . $langs->trans("None") . '</option>';
  2007. }
  2008. $out .= '</select>';
  2009. if ($num && !$forcecombo) {
  2010. // Enhance with select2
  2011. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2012. $out .= ajax_combobox($htmlname);
  2013. }
  2014. } else {
  2015. dol_print_error($this->db);
  2016. }
  2017. if ($outputmode == 2) {
  2018. return $outarray2;
  2019. } elseif ($outputmode) {
  2020. return $outarray;
  2021. }
  2022. return $out;
  2023. }
  2024. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2025. /**
  2026. * Return select list of users. Selected users are stored into session.
  2027. * List of users are provided into $_SESSION['assignedtouser'].
  2028. *
  2029. * @param string $action Value for $action
  2030. * @param string $htmlname Field name in form
  2031. * @param int $show_empty 0=list without the empty value, 1=add empty value
  2032. * @param array $exclude Array list of users id to exclude
  2033. * @param int $disabled If select list must be disabled
  2034. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  2035. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  2036. * @param int $force_entity '0' or Ids of environment to force
  2037. * @param int $maxlength Maximum length of string into list (0=no limit)
  2038. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  2039. * @param string $morefilter Add more filters into sql request
  2040. * @param int $showproperties Show properties of each attendees
  2041. * @param array $listofuserid Array with properties of each user
  2042. * @param array $listofcontactid Array with properties of each contact
  2043. * @param array $listofotherid Array with properties of each other contact
  2044. * @return string HTML select string
  2045. * @see select_dolgroups()
  2046. */
  2047. 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())
  2048. {
  2049. // phpcs:enable
  2050. global $conf, $user, $langs;
  2051. $userstatic = new User($this->db);
  2052. $out = '';
  2053. $assignedtouser = array();
  2054. if (!empty($_SESSION['assignedtouser'])) {
  2055. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  2056. }
  2057. $nbassignetouser = count($assignedtouser);
  2058. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  2059. if ($nbassignetouser) {
  2060. $out .= '<ul class="attendees">';
  2061. }
  2062. $i = 0;
  2063. $ownerid = 0;
  2064. foreach ($assignedtouser as $key => $value) {
  2065. if ($value['id'] == $ownerid) {
  2066. continue;
  2067. }
  2068. $out .= '<li>';
  2069. $userstatic->fetch($value['id']);
  2070. $out .= $userstatic->getNomUrl(-1);
  2071. if ($i == 0) {
  2072. $ownerid = $value['id'];
  2073. $out .= ' (' . $langs->trans("Owner") . ')';
  2074. }
  2075. if ($nbassignetouser > 1 && $action != 'view') {
  2076. $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 . '">';
  2077. }
  2078. // Show my availability
  2079. if ($showproperties) {
  2080. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  2081. $out .= '<div class="myavailability inline-block">';
  2082. $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>';
  2083. $out .= '</div>';
  2084. }
  2085. }
  2086. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2087. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2088. $out .= '</li>';
  2089. $i++;
  2090. }
  2091. if ($nbassignetouser) {
  2092. $out .= '</ul>';
  2093. }
  2094. // Method with no ajax
  2095. if ($action != 'view') {
  2096. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2097. $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
  2098. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2099. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2100. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
  2101. $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
  2102. $out .= '});';
  2103. $out .= '})</script>';
  2104. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2105. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
  2106. $out .= '<br>';
  2107. }
  2108. return $out;
  2109. }
  2110. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2111. /**
  2112. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2113. *
  2114. * @param int $selected Preselected products
  2115. * @param string $htmlname Name of HTML select field (must be unique in page).
  2116. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2117. * @param int $limit Limit on number of returned lines
  2118. * @param int $price_level Level of price to show
  2119. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2120. * @param int $finished 2=all, 1=finished, 0=raw material
  2121. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2122. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2123. * @param array $ajaxoptions Options for ajax_autocompleter
  2124. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2125. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2126. * @param int $forcecombo Force to use combo box
  2127. * @param string $morecss Add more css on select
  2128. * @param int $hidepriceinlabel 1=Hide prices in label
  2129. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2130. * 'warehouseopen' = count products from open warehouses,
  2131. * 'warehouseclosed' = count products from closed warehouses,
  2132. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2133. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2134. * @param string $nooutput No print, return the output into a string
  2135. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2136. * @return void|string
  2137. */
  2138. 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)
  2139. {
  2140. // phpcs:enable
  2141. global $langs, $conf;
  2142. $out = '';
  2143. // check parameters
  2144. $price_level = (!empty($price_level) ? $price_level : 0);
  2145. if (is_null($ajaxoptions)) {
  2146. $ajaxoptions = array();
  2147. }
  2148. if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
  2149. if (isModEnabled("product") && !isModEnabled('service')) {
  2150. $filtertype = '0';
  2151. } elseif (!isModEnabled('product') && isModEnabled("service")) {
  2152. $filtertype = '1';
  2153. }
  2154. }
  2155. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2156. $placeholder = '';
  2157. if ($selected && empty($selected_input_value)) {
  2158. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2159. $producttmpselect = new Product($this->db);
  2160. $producttmpselect->fetch($selected);
  2161. $selected_input_value = $producttmpselect->ref;
  2162. unset($producttmpselect);
  2163. }
  2164. // handle case where product or service module is disabled + no filter specified
  2165. if ($filtertype == '') {
  2166. if (!isModEnabled('product')) { // when product module is disabled, show services only
  2167. $filtertype = 1;
  2168. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2169. $filtertype = 0;
  2170. }
  2171. }
  2172. // mode=1 means customers products
  2173. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=1&status=' . $status . '&status_purchase=' . $status_purchase . '&finished=' . $finished . '&hidepriceinlabel=' . $hidepriceinlabel . '&warehousestatus=' . $warehouseStatus;
  2174. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2175. if (isModEnabled('variants') && is_array($selected_combinations)) {
  2176. // Code to automatically insert with javascript the select of attributes under the select of product
  2177. // when a parent of variant has been selected.
  2178. $out .= '
  2179. <!-- script to auto show attributes select tags if a variant was selected -->
  2180. <script nonce="' . getNonce() . '">
  2181. // auto show attributes fields
  2182. selected = ' . json_encode($selected_combinations) . ';
  2183. combvalues = {};
  2184. jQuery(document).ready(function () {
  2185. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2186. if (jQuery(this).val() == \'free\') {
  2187. jQuery(\'div#attributes_box\').empty();
  2188. }
  2189. });
  2190. jQuery("input#' . $htmlname . '").change(function () {
  2191. if (!jQuery(this).val()) {
  2192. jQuery(\'div#attributes_box\').empty();
  2193. return;
  2194. }
  2195. console.log("A change has started. We get variants fields to inject html select");
  2196. jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
  2197. id: jQuery(this).val()
  2198. }, function (data) {
  2199. jQuery(\'div#attributes_box\').empty();
  2200. jQuery.each(data, function (key, val) {
  2201. combvalues[val.id] = val.values;
  2202. var span = jQuery(document.createElement(\'div\')).css({
  2203. \'display\': \'table-row\'
  2204. });
  2205. span.append(
  2206. jQuery(document.createElement(\'div\')).text(val.label).css({
  2207. \'font-weight\': \'bold\',
  2208. \'display\': \'table-cell\'
  2209. })
  2210. );
  2211. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2212. \'margin-left\': \'15px\',
  2213. \'white-space\': \'pre\'
  2214. }).append(
  2215. jQuery(document.createElement(\'option\')).val(\'\')
  2216. );
  2217. jQuery.each(combvalues[val.id], function (key, val) {
  2218. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2219. if (selected[val.fk_product_attribute] == val.id) {
  2220. tag.attr(\'selected\', \'selected\');
  2221. }
  2222. html.append(tag);
  2223. });
  2224. span.append(html);
  2225. jQuery(\'div#attributes_box\').append(span);
  2226. });
  2227. })
  2228. });
  2229. ' . ($selected ? 'jQuery("input#' . $htmlname . '").change();' : '') . '
  2230. });
  2231. </script>
  2232. ';
  2233. }
  2234. if (empty($hidelabel)) {
  2235. $out .= $langs->trans("RefOrLabel") . ' : ';
  2236. } elseif ($hidelabel > 1) {
  2237. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  2238. if ($hidelabel == 2) {
  2239. $out .= img_picto($langs->trans("Search"), 'search');
  2240. }
  2241. }
  2242. $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' : '') . ' />';
  2243. if ($hidelabel == 3) {
  2244. $out .= img_picto($langs->trans("Search"), 'search');
  2245. }
  2246. } else {
  2247. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2248. }
  2249. if (empty($nooutput)) {
  2250. print $out;
  2251. } else {
  2252. return $out;
  2253. }
  2254. }
  2255. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2256. /**
  2257. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2258. *
  2259. * @param int $selected Preselected BOM id
  2260. * @param string $htmlname Name of HTML select field (must be unique in page).
  2261. * @param int $limit Limit on number of returned lines
  2262. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2263. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2264. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2265. * @param string $morecss Add more css on select
  2266. * @param string $nooutput No print, return the output into a string
  2267. * @param int $forcecombo Force to use combo box
  2268. * @param array $TProducts Add filter on a defined product
  2269. * @return void|string
  2270. */
  2271. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2272. {
  2273. // phpcs:enable
  2274. global $conf, $user, $langs, $db;
  2275. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2276. $error = 0;
  2277. $out = '';
  2278. if (!$forcecombo) {
  2279. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2280. $events = array();
  2281. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2282. }
  2283. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2284. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2285. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'bom_bom as b';
  2286. $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
  2287. if (!empty($status)) $sql .= ' AND status = ' . (int) $status;
  2288. if (!empty($type)) $sql .= ' AND bomtype = ' . (int) $type;
  2289. if (!empty($TProducts)) $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
  2290. if (!empty($limit)) $sql .= ' LIMIT ' . (int) $limit;
  2291. $resql = $db->query($sql);
  2292. if ($resql) {
  2293. if ($showempty) {
  2294. $out .= '<option value="-1"';
  2295. if (empty($selected)) $out .= ' selected';
  2296. $out .= '>&nbsp;</option>';
  2297. }
  2298. while ($obj = $db->fetch_object($resql)) {
  2299. $product = new Product($db);
  2300. $res = $product->fetch($obj->fk_product);
  2301. $out .= '<option value="' . $obj->rowid . '"';
  2302. if ($obj->rowid == $selected) $out .= 'selected';
  2303. $out .= '>' . $obj->ref . ' - ' . $product->label . ' - ' . $obj->label . '</option>';
  2304. }
  2305. } else {
  2306. $error++;
  2307. dol_print_error($db);
  2308. }
  2309. $out .= '</select>';
  2310. if (empty($nooutput)) {
  2311. print $out;
  2312. } else {
  2313. return $out;
  2314. }
  2315. }
  2316. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2317. /**
  2318. * Return list of products for a customer.
  2319. * Called by select_produits.
  2320. *
  2321. * @param int $selected Preselected product
  2322. * @param string $htmlname Name of select html
  2323. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2324. * @param int $limit Limit on number of returned lines
  2325. * @param int $price_level Level of price to show
  2326. * @param string $filterkey Filter on product
  2327. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2328. * @param int $finished Filter on finished field: 2=No filter
  2329. * @param int $outputmode 0=HTML select string, 1=Array
  2330. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2331. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2332. * @param int $forcecombo Force to use combo box
  2333. * @param string $morecss Add more css on select
  2334. * @param int $hidepriceinlabel 1=Hide prices in label
  2335. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2336. * 'warehouseopen' = count products from open warehouses,
  2337. * 'warehouseclosed' = count products from closed warehouses,
  2338. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2339. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2340. * @return array|string Array of keys for json
  2341. */
  2342. 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)
  2343. {
  2344. // phpcs:enable
  2345. global $langs, $conf;
  2346. global $hookmanager;
  2347. $out = '';
  2348. $outarray = array();
  2349. // Units
  2350. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2351. $langs->load('other');
  2352. }
  2353. $warehouseStatusArray = array();
  2354. if (!empty($warehouseStatus)) {
  2355. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2356. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2357. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2358. }
  2359. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2360. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2361. }
  2362. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2363. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2364. }
  2365. }
  2366. $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";
  2367. if (count($warehouseStatusArray)) {
  2368. $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
  2369. } else {
  2370. $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", 0, "p.stock") . " AS stock";
  2371. }
  2372. $sql = "SELECT ";
  2373. // Add select from hooks
  2374. $parameters = array();
  2375. $reshook = $hookmanager->executeHooks('selectProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
  2376. if (empty($reshook)) {
  2377. $sql .= $selectFields.$selectFieldsGrouped.$hookmanager->resPrint;
  2378. } else {
  2379. $sql .= $hookmanager->resPrint;
  2380. }
  2381. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2382. //Product category
  2383. $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
  2384. FROM " . $this->db->prefix() . "categorie_product
  2385. WHERE " . $this->db->prefix() . "categorie_product.fk_product=p.rowid
  2386. LIMIT 1
  2387. ) AS categorie_product_id ";
  2388. }
  2389. //Price by customer
  2390. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2391. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2392. $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';
  2393. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2394. }
  2395. // Units
  2396. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2397. $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";
  2398. $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';
  2399. }
  2400. // Multilang : we add translation
  2401. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2402. $sql .= ", pl.label as label_translated";
  2403. $sql .= ", pl.description as description_translated";
  2404. $selectFields .= ", label_translated";
  2405. $selectFields .= ", description_translated";
  2406. }
  2407. // Price by quantity
  2408. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2409. $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
  2410. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2411. $sql .= " AND price_level = " . ((int) $price_level);
  2412. }
  2413. $sql .= " ORDER BY date_price";
  2414. $sql .= " DESC LIMIT 1) as price_rowid";
  2415. $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
  2416. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2417. $sql .= " AND price_level = " . ((int) $price_level);
  2418. }
  2419. $sql .= " ORDER BY date_price";
  2420. $sql .= " DESC LIMIT 1) as price_by_qty";
  2421. $selectFields .= ", price_rowid, price_by_qty";
  2422. }
  2423. $sql .= " FROM ".$this->db->prefix()."product as p";
  2424. // Add from (left join) from hooks
  2425. $parameters = array();
  2426. $reshook = $hookmanager->executeHooks('selectProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
  2427. $sql .= $hookmanager->resPrint;
  2428. if (count($warehouseStatusArray)) {
  2429. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps on ps.fk_product = p.rowid";
  2430. $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
  2431. $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.
  2432. }
  2433. // include search in supplier ref
  2434. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2435. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2436. }
  2437. //Price by customer
  2438. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2439. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_customer_price as pcp ON pcp.fk_soc=" . ((int) $socid) . " AND pcp.fk_product=p.rowid";
  2440. }
  2441. // Units
  2442. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2443. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  2444. }
  2445. // Multilang : we add translation
  2446. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2447. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid ";
  2448. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2449. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  2450. $soc = new Societe($this->db);
  2451. $result = $soc->fetch($socid);
  2452. if ($result > 0 && !empty($soc->default_lang)) {
  2453. $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
  2454. } else {
  2455. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2456. }
  2457. } else {
  2458. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2459. }
  2460. }
  2461. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2462. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2463. }
  2464. $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
  2465. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2466. $sql .= " AND pac.rowid IS NULL";
  2467. }
  2468. if ($finished == 0) {
  2469. $sql .= " AND p.finished = " . ((int) $finished);
  2470. } elseif ($finished == 1) {
  2471. $sql .= " AND p.finished = " . ((int) $finished);
  2472. if ($status >= 0) {
  2473. $sql .= " AND p.tosell = " . ((int) $status);
  2474. }
  2475. } elseif ($status >= 0) {
  2476. $sql .= " AND p.tosell = " . ((int) $status);
  2477. }
  2478. if ($status_purchase >= 0) {
  2479. $sql .= " AND p.tobuy = " . ((int) $status_purchase);
  2480. }
  2481. // Filter by product type
  2482. if (strval($filtertype) != '') {
  2483. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  2484. } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
  2485. $sql .= " AND p.fk_product_type = 1";
  2486. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2487. $sql .= " AND p.fk_product_type = 0";
  2488. }
  2489. // Add where from hooks
  2490. $parameters = array();
  2491. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2492. $sql .= $hookmanager->resPrint;
  2493. // Add criteria on ref/label
  2494. if ($filterkey != '') {
  2495. $sql .= ' AND (';
  2496. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2497. // For natural search
  2498. $scrit = explode(' ', $filterkey);
  2499. $i = 0;
  2500. if (count($scrit) > 1) {
  2501. $sql .= "(";
  2502. }
  2503. foreach ($scrit as $crit) {
  2504. if ($i > 0) {
  2505. $sql .= " AND ";
  2506. }
  2507. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2508. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2509. $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2510. }
  2511. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2512. $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2513. }
  2514. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2515. $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2516. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2517. $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2518. }
  2519. }
  2520. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2521. $sql .= " OR pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2522. }
  2523. $sql .= ")";
  2524. $i++;
  2525. }
  2526. if (count($scrit) > 1) {
  2527. $sql .= ")";
  2528. }
  2529. if (isModEnabled('barcode')) {
  2530. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  2531. }
  2532. $sql .= ')';
  2533. }
  2534. if (count($warehouseStatusArray)) {
  2535. $sql .= " GROUP BY " . $selectFields;
  2536. }
  2537. //Sort by category
  2538. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2539. $sql .= " ORDER BY categorie_product_id ";
  2540. //ASC OR DESC order
  2541. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2542. } else {
  2543. $sql .= $this->db->order("p.ref");
  2544. }
  2545. $sql .= $this->db->plimit($limit, 0);
  2546. // Build output string
  2547. dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
  2548. $result = $this->db->query($sql);
  2549. if ($result) {
  2550. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2551. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2552. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  2553. $num = $this->db->num_rows($result);
  2554. $events = null;
  2555. if (!$forcecombo) {
  2556. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2557. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2558. }
  2559. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2560. $textifempty = '';
  2561. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2562. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2563. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2564. if ($showempty && !is_numeric($showempty)) {
  2565. $textifempty = $langs->trans($showempty);
  2566. } else {
  2567. $textifempty .= $langs->trans("All");
  2568. }
  2569. } else {
  2570. if ($showempty && !is_numeric($showempty)) {
  2571. $textifempty = $langs->trans($showempty);
  2572. }
  2573. }
  2574. if ($showempty) {
  2575. $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
  2576. }
  2577. $i = 0;
  2578. while ($num && $i < $num) {
  2579. $opt = '';
  2580. $optJson = array();
  2581. $objp = $this->db->fetch_object($result);
  2582. 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
  2583. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2584. $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
  2585. $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
  2586. $sql .= " ORDER BY quantity ASC";
  2587. dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
  2588. $result2 = $this->db->query($sql);
  2589. if ($result2) {
  2590. $nb_prices = $this->db->num_rows($result2);
  2591. $j = 0;
  2592. while ($nb_prices && $j < $nb_prices) {
  2593. $objp2 = $this->db->fetch_object($result2);
  2594. $objp->price_by_qty_rowid = $objp2->rowid;
  2595. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2596. $objp->price_by_qty_quantity = $objp2->quantity;
  2597. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2598. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2599. // For backward compatibility
  2600. $objp->quantity = $objp2->quantity;
  2601. $objp->price = $objp2->price;
  2602. $objp->unitprice = $objp2->unitprice;
  2603. $objp->remise_percent = $objp2->remise_percent;
  2604. //$objp->tva_tx is not overwritten by $objp2 value
  2605. //$objp->default_vat_code is not overwritten by $objp2 value
  2606. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2607. $j++;
  2608. // Add new entry
  2609. // "key" value of json key array is used by jQuery automatically as selected value
  2610. // "label" value of json key array is used by jQuery automatically as text for combo box
  2611. $out .= $opt;
  2612. array_push($outarray, $optJson);
  2613. }
  2614. }
  2615. } else {
  2616. if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
  2617. $price_product = new Product($this->db);
  2618. $price_product->fetch($objp->rowid, '', '', 1);
  2619. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2620. $priceparser = new PriceParser($this->db);
  2621. $price_result = $priceparser->parseProduct($price_product);
  2622. if ($price_result >= 0) {
  2623. $objp->price = $price_result;
  2624. $objp->unitprice = $price_result;
  2625. //Calculate the VAT
  2626. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2627. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2628. }
  2629. }
  2630. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2631. // Add new entry
  2632. // "key" value of json key array is used by jQuery automatically as selected value
  2633. // "label" value of json key array is used by jQuery automatically as text for combo box
  2634. $out .= $opt;
  2635. array_push($outarray, $optJson);
  2636. }
  2637. $i++;
  2638. }
  2639. $out .= '</select>';
  2640. $this->db->free($result);
  2641. if (empty($outputmode)) {
  2642. return $out;
  2643. }
  2644. return $outarray;
  2645. } else {
  2646. dol_print_error($this->db);
  2647. }
  2648. return '';
  2649. }
  2650. /**
  2651. * Function to forge the string with OPTIONs of SELECT.
  2652. * This define value for &$opt and &$optJson.
  2653. * This function is called by select_produits_list().
  2654. *
  2655. * @param object $objp Resultset of fetch
  2656. * @param string $opt Option (var used for returned value in string option format)
  2657. * @param array $optJson Option (var used for returned value in json format)
  2658. * @param int $price_level Price level
  2659. * @param string $selected Preselected value
  2660. * @param int $hidepriceinlabel Hide price in label
  2661. * @param string $filterkey Filter key to highlight
  2662. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2663. * @return void
  2664. */
  2665. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2666. {
  2667. global $langs, $conf, $user;
  2668. global $hookmanager;
  2669. $outkey = '';
  2670. $outval = '';
  2671. $outref = '';
  2672. $outlabel = '';
  2673. $outlabel_translated = '';
  2674. $outdesc = '';
  2675. $outdesc_translated = '';
  2676. $outbarcode = '';
  2677. $outorigin = '';
  2678. $outtype = '';
  2679. $outprice_ht = '';
  2680. $outprice_ttc = '';
  2681. $outpricebasetype = '';
  2682. $outtva_tx = '';
  2683. $outdefault_vat_code = '';
  2684. $outqty = 1;
  2685. $outdiscount = 0;
  2686. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2687. $label = $objp->label;
  2688. if (!empty($objp->label_translated)) {
  2689. $label = $objp->label_translated;
  2690. }
  2691. if (!empty($filterkey) && $filterkey != '') {
  2692. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  2693. }
  2694. $outkey = $objp->rowid;
  2695. $outref = $objp->ref;
  2696. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2697. $outlabel = $objp->label;
  2698. $outdesc = $objp->description;
  2699. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2700. $outlabel_translated = $objp->label_translated;
  2701. $outdesc_translated = $objp->description_translated;
  2702. }
  2703. $outbarcode = $objp->barcode;
  2704. $outorigin = $objp->fk_country;
  2705. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2706. $outtype = $objp->fk_product_type;
  2707. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2708. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  2709. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2710. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2711. }
  2712. // Units
  2713. $outvalUnits = '';
  2714. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2715. if (!empty($objp->unit_short)) {
  2716. $outvalUnits .= ' - ' . $objp->unit_short;
  2717. }
  2718. }
  2719. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2720. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2721. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2722. $outvalUnits .= ' - ' . $unitToShow;
  2723. }
  2724. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2725. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  2726. $outvalUnits .= ' - ' . $unitToShow;
  2727. }
  2728. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2729. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2730. $outvalUnits .= ' - ' . $unitToShow;
  2731. }
  2732. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2733. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2734. $outvalUnits .= ' - ' . $unitToShow;
  2735. }
  2736. }
  2737. if ($outdurationvalue && $outdurationunit) {
  2738. $da = array(
  2739. 'h' => $langs->trans('Hour'),
  2740. 'd' => $langs->trans('Day'),
  2741. 'w' => $langs->trans('Week'),
  2742. 'm' => $langs->trans('Month'),
  2743. 'y' => $langs->trans('Year')
  2744. );
  2745. if (isset($da[$outdurationunit])) {
  2746. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  2747. }
  2748. }
  2749. $opt = '<option value="' . $objp->rowid . '"';
  2750. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2751. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2752. $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 . '"';
  2753. }
  2754. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2755. if (!empty($user->rights->stock->lire)) {
  2756. if ($objp->stock > 0) {
  2757. $opt .= ' class="product_line_stock_ok"';
  2758. } elseif ($objp->stock <= 0) {
  2759. $opt .= ' class="product_line_stock_too_low"';
  2760. }
  2761. }
  2762. }
  2763. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2764. $opt .= ' data-labeltrans="' . $outlabel_translated . '"';
  2765. $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
  2766. }
  2767. $opt .= '>';
  2768. $opt .= $objp->ref;
  2769. if (!empty($objp->custref)) {
  2770. $opt .= ' (' . $objp->custref . ')';
  2771. }
  2772. if ($outbarcode) {
  2773. $opt .= ' (' . $outbarcode . ')';
  2774. }
  2775. $opt .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2776. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2777. $opt .= ' (' . getCountry($outorigin, 1) . ')';
  2778. }
  2779. $objRef = $objp->ref;
  2780. if (!empty($objp->custref)) {
  2781. $objRef .= ' (' . $objp->custref . ')';
  2782. }
  2783. if (!empty($filterkey) && $filterkey != '') {
  2784. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  2785. }
  2786. $outval .= $objRef;
  2787. if ($outbarcode) {
  2788. $outval .= ' (' . $outbarcode . ')';
  2789. }
  2790. $outval .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2791. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2792. $outval .= ' (' . getCountry($outorigin, 1) . ')';
  2793. }
  2794. // Units
  2795. $opt .= $outvalUnits;
  2796. $outval .= $outvalUnits;
  2797. $found = 0;
  2798. // Multiprice
  2799. // If we need a particular price level (from 1 to n)
  2800. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2801. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2802. $sql .= " FROM " . $this->db->prefix() . "product_price";
  2803. $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
  2804. $sql .= " AND entity IN (" . getEntity('productprice') . ")";
  2805. $sql .= " AND price_level = " . ((int) $price_level);
  2806. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2807. $sql .= " LIMIT 1";
  2808. dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level, LOG_DEBUG);
  2809. $result2 = $this->db->query($sql);
  2810. if ($result2) {
  2811. $objp2 = $this->db->fetch_object($result2);
  2812. if ($objp2) {
  2813. $found = 1;
  2814. if ($objp2->price_base_type == 'HT') {
  2815. $opt .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2816. $outval .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2817. } else {
  2818. $opt .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2819. $outval .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2820. }
  2821. $outprice_ht = price($objp2->price);
  2822. $outprice_ttc = price($objp2->price_ttc);
  2823. $outpricebasetype = $objp2->price_base_type;
  2824. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2825. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2826. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2827. } else {
  2828. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2829. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2830. }
  2831. }
  2832. } else {
  2833. dol_print_error($this->db);
  2834. }
  2835. }
  2836. // Price by quantity
  2837. 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))) {
  2838. $found = 1;
  2839. $outqty = $objp->quantity;
  2840. $outdiscount = $objp->remise_percent;
  2841. if ($objp->quantity == 1) {
  2842. $opt .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
  2843. $outval .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
  2844. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2845. $outval .= $langs->transnoentities("Unit");
  2846. } else {
  2847. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2848. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2849. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2850. $outval .= $langs->transnoentities("Units");
  2851. }
  2852. $outprice_ht = price($objp->unitprice);
  2853. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2854. $outpricebasetype = $objp->price_base_type;
  2855. $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
  2856. $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
  2857. }
  2858. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2859. $opt .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2860. $outval .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2861. }
  2862. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2863. $opt .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2864. $outval .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2865. }
  2866. // Price by customer
  2867. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2868. if (!empty($objp->idprodcustprice)) {
  2869. $found = 1;
  2870. if ($objp->custprice_base_type == 'HT') {
  2871. $opt .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2872. $outval .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2873. } else {
  2874. $opt .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2875. $outval .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2876. }
  2877. $outprice_ht = price($objp->custprice);
  2878. $outprice_ttc = price($objp->custprice_ttc);
  2879. $outpricebasetype = $objp->custprice_base_type;
  2880. $outtva_tx = $objp->custtva_tx;
  2881. $outdefault_vat_code = $objp->custdefault_vat_code;
  2882. }
  2883. }
  2884. // If level no defined or multiprice not found, we used the default price
  2885. if (empty($hidepriceinlabel) && !$found) {
  2886. if ($objp->price_base_type == 'HT') {
  2887. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2888. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2889. } else {
  2890. $opt .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2891. $outval .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2892. }
  2893. $outprice_ht = price($objp->price);
  2894. $outprice_ttc = price($objp->price_ttc);
  2895. $outpricebasetype = $objp->price_base_type;
  2896. $outtva_tx = $objp->tva_tx;
  2897. $outdefault_vat_code = $objp->default_vat_code;
  2898. }
  2899. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2900. if (!empty($user->rights->stock->lire)) {
  2901. $opt .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  2902. if ($objp->stock > 0) {
  2903. $outval .= ' - <span class="product_line_stock_ok">';
  2904. } elseif ($objp->stock <= 0) {
  2905. $outval .= ' - <span class="product_line_stock_too_low">';
  2906. }
  2907. $outval .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  2908. $outval .= '</span>';
  2909. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2910. $langs->load("stocks");
  2911. $tmpproduct = new Product($this->db);
  2912. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2913. $tmpproduct->load_virtual_stock();
  2914. $virtualstock = $tmpproduct->stock_theorique;
  2915. $opt .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  2916. $outval .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  2917. if ($virtualstock > 0) {
  2918. $outval .= '<span class="product_line_stock_ok">';
  2919. } elseif ($virtualstock <= 0) {
  2920. $outval .= '<span class="product_line_stock_too_low">';
  2921. }
  2922. $outval .= $virtualstock;
  2923. $outval .= '</span>';
  2924. unset($tmpproduct);
  2925. }
  2926. }
  2927. }
  2928. $parameters = array('objp'=>$objp);
  2929. $reshook = $hookmanager->executeHooks('constructProductListOption', $parameters); // Note that $action and $object may have been modified by hook
  2930. if (empty($reshook)) {
  2931. $opt .= $hookmanager->resPrint;
  2932. } else {
  2933. $opt = $hookmanager->resPrint;
  2934. }
  2935. $opt .= "</option>\n";
  2936. $optJson = array(
  2937. 'key' => $outkey,
  2938. 'value' => $outref,
  2939. 'label' => $outval,
  2940. 'label2' => $outlabel,
  2941. 'desc' => $outdesc,
  2942. 'type' => $outtype,
  2943. 'price_ht' => price2num($outprice_ht),
  2944. 'price_ttc' => price2num($outprice_ttc),
  2945. 'price_ht_locale' => price(price2num($outprice_ht)),
  2946. 'price_ttc_locale' => price(price2num($outprice_ttc)),
  2947. 'pricebasetype' => $outpricebasetype,
  2948. 'tva_tx' => $outtva_tx,
  2949. 'default_vat_code' => $outdefault_vat_code,
  2950. 'qty' => $outqty,
  2951. 'discount' => $outdiscount,
  2952. 'duration_value' => $outdurationvalue,
  2953. 'duration_unit' => $outdurationunit,
  2954. 'pbq' => $outpbq,
  2955. 'labeltrans' => $outlabel_translated,
  2956. 'desctrans' => $outdesc_translated,
  2957. 'ref_customer' => $outrefcust
  2958. );
  2959. }
  2960. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2961. /**
  2962. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2963. *
  2964. * @param int $socid Id third party
  2965. * @param string $selected Preselected product
  2966. * @param string $htmlname Name of HTML Select
  2967. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2968. * @param string $filtre For a SQL filter
  2969. * @param array $ajaxoptions Options for ajax_autocompleter
  2970. * @param int $hidelabel Hide label (0=no, 1=yes)
  2971. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2972. * @param string $morecss More CSS
  2973. * @param string $placeholder Placeholder
  2974. * @return void
  2975. */
  2976. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2977. {
  2978. // phpcs:enable
  2979. global $langs, $conf;
  2980. global $price_level, $status, $finished;
  2981. if (!isset($status)) {
  2982. $status = 1;
  2983. }
  2984. $selected_input_value = '';
  2985. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2986. if ($selected > 0) {
  2987. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2988. $producttmpselect = new Product($this->db);
  2989. $producttmpselect->fetch($selected);
  2990. $selected_input_value = $producttmpselect->ref;
  2991. unset($producttmpselect);
  2992. }
  2993. // mode=2 means suppliers products
  2994. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
  2995. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2996. print ($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="minwidth300" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . '>';
  2997. } else {
  2998. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2999. }
  3000. }
  3001. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3002. /**
  3003. * Return list of suppliers products
  3004. *
  3005. * @param int $socid Id of supplier thirdparty (0 = no filter)
  3006. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  3007. * @param string $htmlname Name of HTML select
  3008. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  3009. * @param string $filtre Generic filter. Data must not come from user input.
  3010. * @param string $filterkey Filter of produdts
  3011. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  3012. * @param int $outputmode 0=HTML select string, 1=Array
  3013. * @param int $limit Limit of line number
  3014. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  3015. * @param string $morecss Add more CSS
  3016. * @param int $showstockinlist Show stock information (slower).
  3017. * @param string $placeholder Placeholder
  3018. * @return array|string Array of keys for json or HTML component
  3019. */
  3020. 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 = '')
  3021. {
  3022. // phpcs:enable
  3023. global $langs, $conf, $user;
  3024. global $hookmanager;
  3025. $out = '';
  3026. $outarray = array();
  3027. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  3028. $langs->load('stocks');
  3029. // Units
  3030. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3031. $langs->load('other');
  3032. }
  3033. $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,";
  3034. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  3035. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  3036. $sql .= " pfp.supplier_reputation";
  3037. // if we use supplier description of the products
  3038. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  3039. $sql .= ", pfp.desc_fourn as description";
  3040. } else {
  3041. $sql .= ", p.description";
  3042. }
  3043. // Units
  3044. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3045. $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";
  3046. }
  3047. if (isModEnabled('barcode')) {
  3048. $sql .= ", pfp.barcode";
  3049. }
  3050. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3051. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
  3052. if ($socid > 0) {
  3053. $sql .= " AND pfp.fk_soc = " . ((int) $socid);
  3054. }
  3055. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3056. // Units
  3057. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3058. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  3059. }
  3060. $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
  3061. if ($statut != -1) {
  3062. $sql .= " AND p.tobuy = " . ((int) $statut);
  3063. }
  3064. if (strval($filtertype) != '') {
  3065. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  3066. }
  3067. if (!empty($filtre)) {
  3068. $sql .= " " . $filtre;
  3069. }
  3070. // Add where from hooks
  3071. $parameters = array();
  3072. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3073. $sql .= $hookmanager->resPrint;
  3074. // Add criteria on ref/label
  3075. if ($filterkey != '') {
  3076. $sql .= ' AND (';
  3077. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  3078. // For natural search
  3079. $scrit = explode(' ', $filterkey);
  3080. $i = 0;
  3081. if (count($scrit) > 1) {
  3082. $sql .= "(";
  3083. }
  3084. foreach ($scrit as $crit) {
  3085. if ($i > 0) {
  3086. $sql .= " AND ";
  3087. }
  3088. $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) . "%'";
  3089. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  3090. $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  3091. }
  3092. $sql .= ")";
  3093. $i++;
  3094. }
  3095. if (count($scrit) > 1) {
  3096. $sql .= ")";
  3097. }
  3098. if (isModEnabled('barcode')) {
  3099. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3100. $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3101. }
  3102. $sql .= ')';
  3103. }
  3104. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3105. $sql .= $this->db->plimit($limit, 0);
  3106. // Build output string
  3107. dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
  3108. $result = $this->db->query($sql);
  3109. if ($result) {
  3110. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3111. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  3112. $num = $this->db->num_rows($result);
  3113. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3114. $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
  3115. if (!$selected) {
  3116. $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3117. } else {
  3118. $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3119. }
  3120. $i = 0;
  3121. while ($i < $num) {
  3122. $objp = $this->db->fetch_object($result);
  3123. if (is_null($objp->idprodfournprice)) {
  3124. // There is no supplier price found, we will use the vat rate for sale
  3125. $objp->tva_tx = $objp->tva_tx_sale;
  3126. $objp->default_vat_code = $objp->default_vat_code_sale;
  3127. }
  3128. $outkey = $objp->idprodfournprice; // id in table of price
  3129. if (!$outkey && $alsoproductwithnosupplierprice) {
  3130. $outkey = 'idprod_' . $objp->rowid; // id of product
  3131. }
  3132. $outref = $objp->ref;
  3133. $outbarcode = $objp->barcode;
  3134. $outqty = 1;
  3135. $outdiscount = 0;
  3136. $outtype = $objp->fk_product_type;
  3137. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3138. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  3139. // Units
  3140. $outvalUnits = '';
  3141. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3142. if (!empty($objp->unit_short)) {
  3143. $outvalUnits .= ' - ' . $objp->unit_short;
  3144. }
  3145. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3146. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3147. $outvalUnits .= ' - ' . $unitToShow;
  3148. }
  3149. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3150. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  3151. $outvalUnits .= ' - ' . $unitToShow;
  3152. }
  3153. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3154. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3155. $outvalUnits .= ' - ' . $unitToShow;
  3156. }
  3157. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3158. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3159. $outvalUnits .= ' - ' . $unitToShow;
  3160. }
  3161. if ($outdurationvalue && $outdurationunit) {
  3162. $da = array(
  3163. 'h' => $langs->trans('Hour'),
  3164. 'd' => $langs->trans('Day'),
  3165. 'w' => $langs->trans('Week'),
  3166. 'm' => $langs->trans('Month'),
  3167. 'y' => $langs->trans('Year')
  3168. );
  3169. if (isset($da[$outdurationunit])) {
  3170. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  3171. }
  3172. }
  3173. }
  3174. $objRef = $objp->ref;
  3175. if ($filterkey && $filterkey != '') {
  3176. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  3177. }
  3178. $objRefFourn = $objp->ref_fourn;
  3179. if ($filterkey && $filterkey != '') {
  3180. $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3181. }
  3182. $label = $objp->label;
  3183. if ($filterkey && $filterkey != '') {
  3184. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  3185. }
  3186. $optlabel = $objp->ref;
  3187. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3188. $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
  3189. }
  3190. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3191. $optlabel .= ' (' . $outbarcode . ')';
  3192. }
  3193. $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3194. $outvallabel = $objRef;
  3195. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3196. $outvallabel .= ' (' . $objRefFourn . ')';
  3197. }
  3198. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3199. $outvallabel .= ' (' . $outbarcode . ')';
  3200. }
  3201. $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3202. // Units
  3203. $optlabel .= $outvalUnits;
  3204. $outvallabel .= $outvalUnits;
  3205. if (!empty($objp->idprodfournprice)) {
  3206. $outqty = $objp->quantity;
  3207. $outdiscount = $objp->remise_percent;
  3208. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3209. $prod_supplier = new ProductFournisseur($this->db);
  3210. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3211. $prod_supplier->id = $objp->fk_product;
  3212. $prod_supplier->fourn_qty = $objp->quantity;
  3213. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3214. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3215. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3216. $priceparser = new PriceParser($this->db);
  3217. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3218. if ($price_result >= 0) {
  3219. $objp->fprice = $price_result;
  3220. if ($objp->quantity >= 1) {
  3221. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3222. }
  3223. }
  3224. }
  3225. if ($objp->quantity == 1) {
  3226. $optlabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3227. $outvallabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
  3228. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3229. $outvallabel .= $langs->transnoentities("Unit");
  3230. } else {
  3231. $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;
  3232. $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;
  3233. $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3234. $outvallabel .= ' ' . $langs->transnoentities("Units");
  3235. }
  3236. if ($objp->quantity > 1) {
  3237. $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
  3238. $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
  3239. }
  3240. if ($objp->remise_percent >= 1) {
  3241. $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3242. $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3243. }
  3244. if ($objp->duration) {
  3245. $optlabel .= " - " . $objp->duration;
  3246. $outvallabel .= " - " . $objp->duration;
  3247. }
  3248. if (!$socid) {
  3249. $optlabel .= " - " . dol_trunc($objp->name, 8);
  3250. $outvallabel .= " - " . dol_trunc($objp->name, 8);
  3251. }
  3252. if ($objp->supplier_reputation) {
  3253. //TODO dictionary
  3254. $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
  3255. $optlabel .= " - " . $reputations[$objp->supplier_reputation];
  3256. $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
  3257. }
  3258. } else {
  3259. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3260. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3261. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3262. } else // No supplier price defined for product, even on other suppliers
  3263. {
  3264. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3265. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3266. }
  3267. }
  3268. if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3269. $novirtualstock = ($showstockinlist == 2);
  3270. if (!empty($user->rights->stock->lire)) {
  3271. $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3272. if ($objp->stock > 0) {
  3273. $optlabel .= ' - <span class="product_line_stock_ok">';
  3274. } elseif ($objp->stock <= 0) {
  3275. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3276. }
  3277. $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
  3278. $optlabel .= '</span>';
  3279. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3280. $langs->load("stocks");
  3281. $tmpproduct = new Product($this->db);
  3282. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3283. $tmpproduct->load_virtual_stock();
  3284. $virtualstock = $tmpproduct->stock_theorique;
  3285. $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  3286. $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  3287. if ($virtualstock > 0) {
  3288. $optlabel .= '<span class="product_line_stock_ok">';
  3289. } elseif ($virtualstock <= 0) {
  3290. $optlabel .= '<span class="product_line_stock_too_low">';
  3291. }
  3292. $optlabel .= $virtualstock;
  3293. $optlabel .= '</span>';
  3294. unset($tmpproduct);
  3295. }
  3296. }
  3297. }
  3298. $optstart = '<option value="' . $outkey . '"';
  3299. if ($selected && $selected == $objp->idprodfournprice) {
  3300. $optstart .= ' selected';
  3301. }
  3302. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3303. $optstart .= ' disabled';
  3304. }
  3305. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3306. $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
  3307. $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
  3308. $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
  3309. $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"';
  3310. $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"';
  3311. $optstart .= ' data-discount="' . dol_escape_htmltag($outdiscount) . '"';
  3312. $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"';
  3313. $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"';
  3314. $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
  3315. }
  3316. $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
  3317. $outarrayentry = array(
  3318. 'key' => $outkey,
  3319. 'value' => $outref,
  3320. 'label' => $outvallabel,
  3321. 'qty' => $outqty,
  3322. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3323. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3324. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3325. 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
  3326. 'tva_tx' => price2num($objp->tva_tx),
  3327. 'default_vat_code' => $objp->default_vat_code,
  3328. 'discount' => $outdiscount,
  3329. 'type' => $outtype,
  3330. 'duration_value' => $outdurationvalue,
  3331. 'duration_unit' => $outdurationunit,
  3332. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3333. 'description' => $objp->description
  3334. );
  3335. $parameters = array(
  3336. 'objp' => &$objp,
  3337. 'optstart' => &$optstart,
  3338. 'optlabel' => &$optlabel,
  3339. 'outvallabel' => &$outvallabel,
  3340. 'outarrayentry' => &$outarrayentry
  3341. );
  3342. $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
  3343. // Add new entry
  3344. // "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
  3345. // "label" value of json key array is used by jQuery automatically as text for combo box
  3346. $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";
  3347. array_push(
  3348. $outarray,
  3349. array('key' => $outkey,
  3350. 'value' => $outref,
  3351. 'label' => $outvallabel,
  3352. 'qty' => $outqty,
  3353. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3354. 'price_qty_ht_locale' => price($objp->fprice),
  3355. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3356. 'price_unit_ht_locale' => price($objp->unitprice),
  3357. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3358. 'tva_tx_formated' => price($objp->tva_tx),
  3359. 'tva_tx' => price2num($objp->tva_tx),
  3360. 'default_vat_code' => $objp->default_vat_code,
  3361. 'discount' => $outdiscount,
  3362. 'type' => $outtype,
  3363. 'duration_value' => $outdurationvalue,
  3364. 'duration_unit' => $outdurationunit,
  3365. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3366. 'description' => $objp->description
  3367. )
  3368. );
  3369. // Exemple of var_dump $outarray
  3370. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3371. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3372. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3373. //}
  3374. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3375. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3376. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3377. $i++;
  3378. }
  3379. $out .= '</select>';
  3380. $this->db->free($result);
  3381. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3382. $out .= ajax_combobox($htmlname);
  3383. } else {
  3384. dol_print_error($this->db);
  3385. }
  3386. if (empty($outputmode)) {
  3387. return $out;
  3388. }
  3389. return $outarray;
  3390. }
  3391. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3392. /**
  3393. * Return list of suppliers prices for a product
  3394. *
  3395. * @param int $productid Id of product
  3396. * @param string $htmlname Name of HTML field
  3397. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3398. * @return string
  3399. */
  3400. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3401. {
  3402. // phpcs:enable
  3403. global $langs, $conf;
  3404. $langs->load('stocks');
  3405. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3406. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3407. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3408. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3409. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3410. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3411. $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
  3412. $sql .= " AND p.tobuy = 1";
  3413. $sql .= " AND s.fournisseur = 1";
  3414. $sql .= " AND p.rowid = " . ((int) $productid);
  3415. if (empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED)) {
  3416. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3417. } else {
  3418. $sql .= " ORDER BY pfp.unitprice ASC";
  3419. }
  3420. dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
  3421. $result = $this->db->query($sql);
  3422. if ($result) {
  3423. $num = $this->db->num_rows($result);
  3424. $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3425. if (!$num) {
  3426. $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
  3427. } else {
  3428. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3429. $form .= '<option value="0">&nbsp;</option>';
  3430. $i = 0;
  3431. while ($i < $num) {
  3432. $objp = $this->db->fetch_object($result);
  3433. $opt = '<option value="' . $objp->idprodfournprice . '"';
  3434. //if there is only one supplier, preselect it
  3435. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && !empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED))) {
  3436. $opt .= ' selected';
  3437. }
  3438. $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
  3439. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3440. $prod_supplier = new ProductFournisseur($this->db);
  3441. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3442. $prod_supplier->id = $productid;
  3443. $prod_supplier->fourn_qty = $objp->quantity;
  3444. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3445. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3446. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3447. $priceparser = new PriceParser($this->db);
  3448. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3449. if ($price_result >= 0) {
  3450. $objp->fprice = $price_result;
  3451. if ($objp->quantity >= 1) {
  3452. $objp->unitprice = $objp->fprice / $objp->quantity;
  3453. }
  3454. }
  3455. }
  3456. if ($objp->quantity == 1) {
  3457. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3458. }
  3459. $opt .= $objp->quantity . ' ';
  3460. if ($objp->quantity == 1) {
  3461. $opt .= $langs->trans("Unit");
  3462. } else {
  3463. $opt .= $langs->trans("Units");
  3464. }
  3465. if ($objp->quantity > 1) {
  3466. $opt .= " - ";
  3467. $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");
  3468. }
  3469. if ($objp->duration) {
  3470. $opt .= " - " . $objp->duration;
  3471. }
  3472. $opt .= "</option>\n";
  3473. $form .= $opt;
  3474. $i++;
  3475. }
  3476. }
  3477. $form .= '</select>';
  3478. $this->db->free($result);
  3479. return $form;
  3480. } else {
  3481. dol_print_error($this->db);
  3482. return '';
  3483. }
  3484. }
  3485. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3486. /**
  3487. * Return list of delivery address
  3488. *
  3489. * @param string $selected Id contact pre-selectionn
  3490. * @param int $socid Id of company
  3491. * @param string $htmlname Name of HTML field
  3492. * @param int $showempty Add an empty field
  3493. * @return integer
  3494. */
  3495. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3496. {
  3497. // phpcs:enable
  3498. // looking for users
  3499. $sql = "SELECT a.rowid, a.label";
  3500. $sql .= " FROM " . $this->db->prefix() . "societe_address as a";
  3501. $sql .= " WHERE a.fk_soc = " . ((int) $socid);
  3502. $sql .= " ORDER BY a.label ASC";
  3503. dol_syslog(get_class($this) . "::select_address", LOG_DEBUG);
  3504. $resql = $this->db->query($sql);
  3505. if ($resql) {
  3506. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3507. if ($showempty) {
  3508. print '<option value="0">&nbsp;</option>';
  3509. }
  3510. $num = $this->db->num_rows($resql);
  3511. $i = 0;
  3512. if ($num) {
  3513. while ($i < $num) {
  3514. $obj = $this->db->fetch_object($resql);
  3515. if ($selected && $selected == $obj->rowid) {
  3516. print '<option value="' . $obj->rowid . '" selected>' . $obj->label . '</option>';
  3517. } else {
  3518. print '<option value="' . $obj->rowid . '">' . $obj->label . '</option>';
  3519. }
  3520. $i++;
  3521. }
  3522. }
  3523. print '</select>';
  3524. return $num;
  3525. } else {
  3526. dol_print_error($this->db);
  3527. return -1;
  3528. }
  3529. }
  3530. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3531. /**
  3532. * Load into cache list of payment terms
  3533. *
  3534. * @return int Nb of lines loaded, <0 if KO
  3535. */
  3536. public function load_cache_conditions_paiements()
  3537. {
  3538. // phpcs:enable
  3539. global $langs;
  3540. $num = count($this->cache_conditions_paiements);
  3541. if ($num > 0) {
  3542. return 0; // Cache already loaded
  3543. }
  3544. dol_syslog(__METHOD__, LOG_DEBUG);
  3545. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3546. $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
  3547. $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
  3548. $sql .= " AND active > 0";
  3549. $sql .= " ORDER BY sortorder";
  3550. $resql = $this->db->query($sql);
  3551. if ($resql) {
  3552. $num = $this->db->num_rows($resql);
  3553. $i = 0;
  3554. while ($i < $num) {
  3555. $obj = $this->db->fetch_object($resql);
  3556. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3557. $label = ($langs->trans("PaymentConditionShort" . $obj->code) != ("PaymentConditionShort" . $obj->code) ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3558. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3559. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3560. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3561. $i++;
  3562. }
  3563. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3564. return $num;
  3565. } else {
  3566. dol_print_error($this->db);
  3567. return -1;
  3568. }
  3569. }
  3570. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3571. /**
  3572. * Load int a cache property th elist of possible delivery delays.
  3573. *
  3574. * @return int Nb of lines loaded, <0 if KO
  3575. */
  3576. public function load_cache_availability()
  3577. {
  3578. // phpcs:enable
  3579. global $langs;
  3580. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3581. if ($num > 0) {
  3582. return 0; // Cache already loaded
  3583. }
  3584. dol_syslog(__METHOD__, LOG_DEBUG);
  3585. $langs->load('propal');
  3586. $sql = "SELECT rowid, code, label, position";
  3587. $sql .= " FROM " . $this->db->prefix() . 'c_availability';
  3588. $sql .= " WHERE active > 0";
  3589. $resql = $this->db->query($sql);
  3590. if ($resql) {
  3591. $num = $this->db->num_rows($resql);
  3592. $i = 0;
  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 = ($langs->trans("AvailabilityType" . $obj->code) != ("AvailabilityType" . $obj->code) ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3597. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3598. $this->cache_availability[$obj->rowid]['label'] = $label;
  3599. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3600. $i++;
  3601. }
  3602. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3603. return $num;
  3604. } else {
  3605. dol_print_error($this->db);
  3606. return -1;
  3607. }
  3608. }
  3609. /**
  3610. * Retourne la liste des types de delais de livraison possibles
  3611. *
  3612. * @param int $selected Id du type de delais pre-selectionne
  3613. * @param string $htmlname Nom de la zone select
  3614. * @param string $filtertype To add a filter
  3615. * @param int $addempty Add empty entry
  3616. * @param string $morecss More CSS
  3617. * @return void
  3618. */
  3619. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3620. {
  3621. global $langs, $user;
  3622. $this->load_cache_availability();
  3623. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3624. print '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3625. if ($addempty) {
  3626. print '<option value="0">&nbsp;</option>';
  3627. }
  3628. foreach ($this->cache_availability as $id => $arrayavailability) {
  3629. if ($selected == $id) {
  3630. print '<option value="' . $id . '" selected>';
  3631. } else {
  3632. print '<option value="' . $id . '">';
  3633. }
  3634. print dol_escape_htmltag($arrayavailability['label']);
  3635. print '</option>';
  3636. }
  3637. print '</select>';
  3638. if ($user->admin) {
  3639. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3640. }
  3641. print ajax_combobox($htmlname);
  3642. }
  3643. /**
  3644. * Load into cache cache_demand_reason, array of input reasons
  3645. *
  3646. * @return int Nb of lines loaded, <0 if KO
  3647. */
  3648. public function loadCacheInputReason()
  3649. {
  3650. global $langs;
  3651. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3652. if ($num > 0) {
  3653. return 0; // Cache already loaded
  3654. }
  3655. $sql = "SELECT rowid, code, label";
  3656. $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
  3657. $sql .= " WHERE active > 0";
  3658. $resql = $this->db->query($sql);
  3659. if ($resql) {
  3660. $num = $this->db->num_rows($resql);
  3661. $i = 0;
  3662. $tmparray = array();
  3663. while ($i < $num) {
  3664. $obj = $this->db->fetch_object($resql);
  3665. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3666. $label = ($obj->label != '-' ? $obj->label : '');
  3667. if ($langs->trans("DemandReasonType" . $obj->code) != ("DemandReasonType" . $obj->code)) {
  3668. $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3669. }
  3670. if ($langs->trans($obj->code) != $obj->code) {
  3671. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3672. }
  3673. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3674. $tmparray[$obj->rowid]['code'] = $obj->code;
  3675. $tmparray[$obj->rowid]['label'] = $label;
  3676. $i++;
  3677. }
  3678. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3679. unset($tmparray);
  3680. return $num;
  3681. } else {
  3682. dol_print_error($this->db);
  3683. return -1;
  3684. }
  3685. }
  3686. /**
  3687. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3688. * List found into table c_input_reason loaded by loadCacheInputReason
  3689. *
  3690. * @param int $selected Id or code of type origin to select by default
  3691. * @param string $htmlname Nom de la zone select
  3692. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3693. * @param int $addempty Add an empty entry
  3694. * @param string $morecss Add more css to the HTML select component
  3695. * @param int $notooltip Do not show the tooltip for admin
  3696. * @return void
  3697. */
  3698. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3699. {
  3700. global $langs, $user;
  3701. $this->loadCacheInputReason();
  3702. print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3703. if ($addempty) {
  3704. print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
  3705. }
  3706. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3707. if ($arraydemandreason['code'] == $exclude) {
  3708. continue;
  3709. }
  3710. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3711. print '<option value="' . $arraydemandreason['id'] . '" selected>';
  3712. } else {
  3713. print '<option value="' . $arraydemandreason['id'] . '">';
  3714. }
  3715. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3716. print $langs->trans($label);
  3717. print '</option>';
  3718. }
  3719. print '</select>';
  3720. if ($user->admin && empty($notooltip)) {
  3721. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3722. }
  3723. print ajax_combobox('select_' . $htmlname);
  3724. }
  3725. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3726. /**
  3727. * Charge dans cache la liste des types de paiements possibles
  3728. *
  3729. * @return int Nb of lines loaded, <0 if KO
  3730. */
  3731. public function load_cache_types_paiements()
  3732. {
  3733. // phpcs:enable
  3734. global $langs;
  3735. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3736. if ($num > 0) {
  3737. return $num; // Cache already loaded
  3738. }
  3739. dol_syslog(__METHOD__, LOG_DEBUG);
  3740. $this->cache_types_paiements = array();
  3741. $sql = "SELECT id, code, libelle as label, type, active";
  3742. $sql .= " FROM " . $this->db->prefix() . "c_paiement";
  3743. $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
  3744. $resql = $this->db->query($sql);
  3745. if ($resql) {
  3746. $num = $this->db->num_rows($resql);
  3747. $i = 0;
  3748. while ($i < $num) {
  3749. $obj = $this->db->fetch_object($resql);
  3750. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3751. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != ("PaymentTypeShort" . $obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3752. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3753. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3754. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3755. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3756. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3757. $i++;
  3758. }
  3759. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3760. return $num;
  3761. } else {
  3762. dol_print_error($this->db);
  3763. return -1;
  3764. }
  3765. }
  3766. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3767. /**
  3768. * print list of payment modes.
  3769. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3770. * See instead to force the default value by the caller.
  3771. *
  3772. * @param int $selected Id of payment term to preselect by default
  3773. * @param string $htmlname Nom de la zone select
  3774. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3775. * @param int $addempty Add an empty entry
  3776. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3777. * @param string $morecss Add more CSS on select tag
  3778. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3779. * 0 : use default deposit percentage from entry
  3780. * > 0 : force deposit percentage (for example, from company object)
  3781. * @return void
  3782. * @deprecated
  3783. */
  3784. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3785. {
  3786. // phpcs:enable
  3787. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
  3788. }
  3789. /**
  3790. * Return list of payment modes.
  3791. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3792. * See instead to force the default value by the caller.
  3793. *
  3794. * @param int $selected Id of payment term to preselect by default
  3795. * @param string $htmlname Nom de la zone select
  3796. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3797. * @param int $addempty Add an empty entry
  3798. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3799. * @param string $morecss Add more CSS on select tag
  3800. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3801. * 0 : use default deposit percentage from entry
  3802. * > 0 : force deposit percentage (for example, from company object)
  3803. * @return string String for the HTML select component
  3804. */
  3805. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3806. {
  3807. global $langs, $user, $conf;
  3808. $out = '';
  3809. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3810. $this->load_cache_conditions_paiements();
  3811. // Set default value if not already set by caller
  3812. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3813. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3814. }
  3815. $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3816. if ($addempty) {
  3817. $out .= '<option value="0">&nbsp;</option>';
  3818. }
  3819. $selectedDepositPercent = null;
  3820. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3821. if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
  3822. continue;
  3823. }
  3824. if ($selected == $id) {
  3825. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3826. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3827. } else {
  3828. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3829. }
  3830. $label = $arrayconditions['label'];
  3831. if (!empty($arrayconditions['deposit_percent'])) {
  3832. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3833. }
  3834. $out .= $label;
  3835. $out .= '</option>';
  3836. }
  3837. $out .= '</select>';
  3838. if ($user->admin && empty($noinfoadmin)) {
  3839. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3840. }
  3841. $out .= ajax_combobox($htmlname);
  3842. if ($deposit_percent >= 0) {
  3843. $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3844. $out .= $langs->trans('DepositPercent') . ' : ';
  3845. $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
  3846. $out .= '</span>';
  3847. $out .= '
  3848. <script nonce="' . getNonce() . '">
  3849. $(document).ready(function () {
  3850. $("#' . $htmlname . '").change(function () {
  3851. let $selected = $(this).find("option:selected");
  3852. let depositPercent = $selected.attr("data-deposit_percent");
  3853. if (depositPercent.length > 0) {
  3854. $("#' . $htmlname . '_deposit_percent_container").show().find("#' . $htmlname . '_deposit_percent").val(depositPercent);
  3855. } else {
  3856. $("#' . $htmlname . '_deposit_percent_container").hide();
  3857. }
  3858. return true;
  3859. });
  3860. });
  3861. </script>';
  3862. }
  3863. return $out;
  3864. }
  3865. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3866. /**
  3867. * Return list of payment methods
  3868. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3869. *
  3870. * @param string $selected Id or code or preselected payment mode
  3871. * @param string $htmlname Name of select field
  3872. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3873. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3874. * @param int $empty 1=can be empty, 0 otherwise
  3875. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3876. * @param int $maxlength Max length of label
  3877. * @param int $active Active or not, -1 = all
  3878. * @param string $morecss Add more CSS on select tag
  3879. * @param int $nooutput 1=Return string, do not send to output
  3880. * @return string|void String for the HTML select component
  3881. */
  3882. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3883. {
  3884. // phpcs:enable
  3885. global $langs, $user, $conf;
  3886. $out = '';
  3887. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
  3888. $filterarray = array();
  3889. if ($filtertype == 'CRDT') {
  3890. $filterarray = array(0, 2, 3);
  3891. } elseif ($filtertype == 'DBIT') {
  3892. $filterarray = array(1, 2, 3);
  3893. } elseif ($filtertype != '' && $filtertype != '-1') {
  3894. $filterarray = explode(',', $filtertype);
  3895. }
  3896. $this->load_cache_types_paiements();
  3897. // Set default value if not already set by caller
  3898. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3899. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3900. }
  3901. $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3902. if ($empty) {
  3903. $out .= '<option value="">&nbsp;</option>';
  3904. }
  3905. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3906. // If not good status
  3907. if ($active >= 0 && $arraytypes['active'] != $active) {
  3908. continue;
  3909. }
  3910. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3911. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3912. continue;
  3913. }
  3914. // We discard empty line if showempty is on because an empty line has already been output.
  3915. if ($empty && empty($arraytypes['code'])) {
  3916. continue;
  3917. }
  3918. if ($format == 0) {
  3919. $out .= '<option value="' . $id . '"';
  3920. } elseif ($format == 1) {
  3921. $out .= '<option value="' . $arraytypes['code'] . '"';
  3922. } elseif ($format == 2) {
  3923. $out .= '<option value="' . $arraytypes['code'] . '"';
  3924. } elseif ($format == 3) {
  3925. $out .= '<option value="' . $id . '"';
  3926. }
  3927. // Print attribute selected or not
  3928. if ($format == 1 || $format == 2) {
  3929. if ($selected == $arraytypes['code']) {
  3930. $out .= ' selected';
  3931. }
  3932. } else {
  3933. if ($selected == $id) {
  3934. $out .= ' selected';
  3935. }
  3936. }
  3937. $out .= '>';
  3938. $value = '';
  3939. if ($format == 0) {
  3940. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3941. } elseif ($format == 1) {
  3942. $value = $arraytypes['code'];
  3943. } elseif ($format == 2) {
  3944. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3945. } elseif ($format == 3) {
  3946. $value = $arraytypes['code'];
  3947. }
  3948. $out .= $value ? $value : '&nbsp;';
  3949. $out .= '</option>';
  3950. }
  3951. $out .= '</select>';
  3952. if ($user->admin && !$noadmininfo) {
  3953. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3954. }
  3955. $out .= ajax_combobox('select' . $htmlname);
  3956. if (empty($nooutput)) {
  3957. print $out;
  3958. } else {
  3959. return $out;
  3960. }
  3961. }
  3962. /**
  3963. * Selection HT or TTC
  3964. *
  3965. * @param string $selected Id pre-selectionne
  3966. * @param string $htmlname Nom de la zone select
  3967. * @param string $addjscombo Add js combo
  3968. * @return string Code of HTML select to chose tax or not
  3969. */
  3970. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3971. {
  3972. global $langs;
  3973. $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3974. $options = array(
  3975. 'HT' => $langs->trans("HT"),
  3976. 'TTC' => $langs->trans("TTC")
  3977. );
  3978. foreach ($options as $id => $value) {
  3979. if ($selected == $id) {
  3980. $return .= '<option value="' . $id . '" selected>' . $value;
  3981. } else {
  3982. $return .= '<option value="' . $id . '">' . $value;
  3983. }
  3984. $return .= '</option>';
  3985. }
  3986. $return .= '</select>';
  3987. if ($addjscombo) {
  3988. $return .= ajax_combobox('select_' . $htmlname);
  3989. }
  3990. return $return;
  3991. }
  3992. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3993. /**
  3994. * Load in cache list of transport mode
  3995. *
  3996. * @return int Nb of lines loaded, <0 if KO
  3997. */
  3998. public function load_cache_transport_mode()
  3999. {
  4000. // phpcs:enable
  4001. global $langs;
  4002. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  4003. if ($num > 0) {
  4004. return $num; // Cache already loaded
  4005. }
  4006. dol_syslog(__METHOD__, LOG_DEBUG);
  4007. $this->cache_transport_mode = array();
  4008. $sql = "SELECT rowid, code, label, active";
  4009. $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
  4010. $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
  4011. $resql = $this->db->query($sql);
  4012. if ($resql) {
  4013. $num = $this->db->num_rows($resql);
  4014. $i = 0;
  4015. while ($i < $num) {
  4016. $obj = $this->db->fetch_object($resql);
  4017. // If traduction exist, we use it else we take the default label
  4018. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != ("PaymentTypeShort" . $obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  4019. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  4020. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  4021. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  4022. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  4023. $i++;
  4024. }
  4025. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  4026. return $num;
  4027. } else {
  4028. dol_print_error($this->db);
  4029. return -1;
  4030. }
  4031. }
  4032. /**
  4033. * Return list of transport mode for intracomm report
  4034. *
  4035. * @param string $selected Id of the transport mode pre-selected
  4036. * @param string $htmlname Name of the select field
  4037. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  4038. * @param int $empty 1=can be empty, 0 else
  4039. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  4040. * @param int $maxlength Max length of label
  4041. * @param int $active Active or not, -1 = all
  4042. * @param string $morecss Add more CSS on select tag
  4043. * @return void
  4044. */
  4045. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  4046. {
  4047. global $langs, $user;
  4048. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
  4049. $this->load_cache_transport_mode();
  4050. print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  4051. if ($empty) {
  4052. print '<option value="">&nbsp;</option>';
  4053. }
  4054. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  4055. // If not good status
  4056. if ($active >= 0 && $arraytypes['active'] != $active) {
  4057. continue;
  4058. }
  4059. // We discard empty line if showempty is on because an empty line has already been output.
  4060. if ($empty && empty($arraytypes['code'])) {
  4061. continue;
  4062. }
  4063. if ($format == 0) {
  4064. print '<option value="' . $id . '"';
  4065. } elseif ($format == 1) {
  4066. print '<option value="' . $arraytypes['code'] . '"';
  4067. } elseif ($format == 2) {
  4068. print '<option value="' . $arraytypes['code'] . '"';
  4069. } elseif ($format == 3) {
  4070. print '<option value="' . $id . '"';
  4071. }
  4072. // If text is selected, we compare with code, else with id
  4073. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  4074. print ' selected';
  4075. } elseif ($selected == $id) {
  4076. print ' selected';
  4077. }
  4078. print '>';
  4079. $value = '';
  4080. if ($format == 0) {
  4081. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4082. } elseif ($format == 1) {
  4083. $value = $arraytypes['code'];
  4084. } elseif ($format == 2) {
  4085. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4086. } elseif ($format == 3) {
  4087. $value = $arraytypes['code'];
  4088. }
  4089. print $value ? $value : '&nbsp;';
  4090. print '</option>';
  4091. }
  4092. print '</select>';
  4093. if ($user->admin && !$noadmininfo) {
  4094. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4095. }
  4096. }
  4097. /**
  4098. * Return a HTML select list of shipping mode
  4099. *
  4100. * @param string $selected Id shipping mode pre-selected
  4101. * @param string $htmlname Name of select zone
  4102. * @param string $filtre To filter list. This parameter must not come from input of users
  4103. * @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.
  4104. * @param string $moreattrib To add more attribute on select
  4105. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  4106. * @param string $morecss More CSS
  4107. * @return void
  4108. */
  4109. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  4110. {
  4111. global $langs, $conf, $user;
  4112. $langs->load("admin");
  4113. $langs->load("deliveries");
  4114. $sql = "SELECT rowid, code, libelle as label";
  4115. $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
  4116. $sql .= " WHERE active > 0";
  4117. if ($filtre) {
  4118. $sql .= " AND " . $filtre;
  4119. }
  4120. $sql .= " ORDER BY libelle ASC";
  4121. dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
  4122. $result = $this->db->query($sql);
  4123. if ($result) {
  4124. $num = $this->db->num_rows($result);
  4125. $i = 0;
  4126. if ($num) {
  4127. print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4128. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4129. print '<option value="-1">&nbsp;</option>';
  4130. }
  4131. while ($i < $num) {
  4132. $obj = $this->db->fetch_object($result);
  4133. if ($selected == $obj->rowid) {
  4134. print '<option value="' . $obj->rowid . '" selected>';
  4135. } else {
  4136. print '<option value="' . $obj->rowid . '">';
  4137. }
  4138. print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
  4139. print '</option>';
  4140. $i++;
  4141. }
  4142. print "</select>";
  4143. if ($user->admin && empty($noinfoadmin)) {
  4144. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4145. }
  4146. print ajax_combobox('select' . $htmlname);
  4147. } else {
  4148. print $langs->trans("NoShippingMethodDefined");
  4149. }
  4150. } else {
  4151. dol_print_error($this->db);
  4152. }
  4153. }
  4154. /**
  4155. * Display form to select shipping mode
  4156. *
  4157. * @param string $page Page
  4158. * @param int $selected Id of shipping mode
  4159. * @param string $htmlname Name of select html field
  4160. * @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.
  4161. * @return void
  4162. */
  4163. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4164. {
  4165. global $langs;
  4166. $langs->load("deliveries");
  4167. if ($htmlname != "none") {
  4168. print '<form method="POST" action="' . $page . '">';
  4169. print '<input type="hidden" name="action" value="setshippingmethod">';
  4170. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4171. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4172. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  4173. print '</form>';
  4174. } else {
  4175. if ($selected) {
  4176. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4177. print $langs->trans("SendingMethod" . strtoupper($code));
  4178. } else {
  4179. print "&nbsp;";
  4180. }
  4181. }
  4182. }
  4183. /**
  4184. * Creates HTML last in cycle situation invoices selector
  4185. *
  4186. * @param string $selected Preselected ID
  4187. * @param int $socid Company ID
  4188. *
  4189. * @return string HTML select
  4190. */
  4191. public function selectSituationInvoices($selected = '', $socid = 0)
  4192. {
  4193. global $langs;
  4194. $langs->load('bills');
  4195. $opt = '<option value="" selected></option>';
  4196. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4197. $sql .= ' FROM ' . $this->db->prefix() . 'facture';
  4198. $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
  4199. $sql .= ' AND situation_counter >= 1';
  4200. $sql .= ' AND fk_soc = ' . (int) $socid;
  4201. $sql .= ' AND type <> 2';
  4202. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4203. $resql = $this->db->query($sql);
  4204. if ($resql && $this->db->num_rows($resql) > 0) {
  4205. // Last seen cycle
  4206. $ref = 0;
  4207. while ($obj = $this->db->fetch_object($resql)) {
  4208. //Same cycle ?
  4209. if ($obj->situation_cycle_ref != $ref) {
  4210. // Just seen this cycle
  4211. $ref = $obj->situation_cycle_ref;
  4212. //not final ?
  4213. if ($obj->situation_final != 1) {
  4214. //Not prov?
  4215. if (substr($obj->ref, 1, 4) != 'PROV') {
  4216. if ($selected == $obj->rowid) {
  4217. $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
  4218. } else {
  4219. $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
  4220. }
  4221. }
  4222. }
  4223. }
  4224. }
  4225. } else {
  4226. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  4227. }
  4228. if ($opt == '<option value ="" selected></option>') {
  4229. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  4230. }
  4231. return $opt;
  4232. }
  4233. /**
  4234. * Creates HTML units selector (code => label)
  4235. *
  4236. * @param string $selected Preselected Unit ID
  4237. * @param string $htmlname Select name
  4238. * @param int $showempty Add a nempty line
  4239. * @param string $unit_type Restrict to one given unit type
  4240. * @return string HTML select
  4241. */
  4242. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4243. {
  4244. global $langs;
  4245. $langs->load('products');
  4246. $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
  4247. $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
  4248. $sql .= ' WHERE active > 0';
  4249. if (!empty($unit_type)) {
  4250. $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
  4251. }
  4252. $sql .= " ORDER BY sortorder";
  4253. $resql = $this->db->query($sql);
  4254. if ($resql && $this->db->num_rows($resql) > 0) {
  4255. if ($showempty) {
  4256. $return .= '<option value="none"></option>';
  4257. }
  4258. while ($res = $this->db->fetch_object($resql)) {
  4259. $unitLabel = $res->label;
  4260. if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
  4261. $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
  4262. }
  4263. if ($selected == $res->rowid) {
  4264. $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
  4265. } else {
  4266. $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
  4267. }
  4268. }
  4269. $return .= '</select>';
  4270. }
  4271. return $return;
  4272. }
  4273. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4274. /**
  4275. * Return a HTML select list of bank accounts
  4276. *
  4277. * @param string $selected Id account pre-selected
  4278. * @param string $htmlname Name of select zone
  4279. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4280. * @param string $filtre To filter list. This parameter must not come from input of users
  4281. * @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.
  4282. * @param string $moreattrib To add more attribute on select
  4283. * @param int $showcurrency Show currency in label
  4284. * @param string $morecss More CSS
  4285. * @param int $nooutput 1=Return string, do not send to output
  4286. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4287. */
  4288. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4289. {
  4290. // phpcs:enable
  4291. global $langs, $conf;
  4292. $out = '';
  4293. $langs->load("admin");
  4294. $num = 0;
  4295. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4296. $sql .= " FROM " . $this->db->prefix() . "bank_account";
  4297. $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
  4298. if ($status != 2) {
  4299. $sql .= " AND clos = " . (int) $status;
  4300. }
  4301. if ($filtre) {
  4302. $sql .= " AND " . $filtre;
  4303. }
  4304. $sql .= " ORDER BY label";
  4305. dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
  4306. $result = $this->db->query($sql);
  4307. if ($result) {
  4308. $num = $this->db->num_rows($result);
  4309. $i = 0;
  4310. if ($num) {
  4311. $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4312. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4313. $out .= '<option value="-1">&nbsp;</option>';
  4314. }
  4315. while ($i < $num) {
  4316. $obj = $this->db->fetch_object($result);
  4317. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4318. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" selected>';
  4319. } else {
  4320. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '">';
  4321. }
  4322. $out .= trim($obj->label);
  4323. if ($showcurrency) {
  4324. $out .= ' (' . $obj->currency_code . ')';
  4325. }
  4326. if ($status == 2 && $obj->status == 1) {
  4327. $out .= ' (' . $langs->trans("Closed") . ')';
  4328. }
  4329. $out .= '</option>';
  4330. $i++;
  4331. }
  4332. $out .= "</select>";
  4333. $out .= ajax_combobox('select' . $htmlname);
  4334. } else {
  4335. if ($status == 0) {
  4336. $out .= '<span class="opacitymedium">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
  4337. } else {
  4338. $out .= '<span class="opacitymedium">' . $langs->trans("NoBankAccountFound") . '</span>';
  4339. }
  4340. }
  4341. } else {
  4342. dol_print_error($this->db);
  4343. }
  4344. // Output or return
  4345. if (empty($nooutput)) {
  4346. print $out;
  4347. } else {
  4348. return $out;
  4349. }
  4350. return $num;
  4351. }
  4352. /**
  4353. * Return a HTML select list of establishment
  4354. *
  4355. * @param string $selected Id establishment pre-selected
  4356. * @param string $htmlname Name of select zone
  4357. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4358. * @param string $filtre To filter list. This parameter must not come from input of users
  4359. * @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.
  4360. * @param string $moreattrib To add more attribute on select
  4361. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4362. */
  4363. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4364. {
  4365. global $langs, $conf;
  4366. $langs->load("admin");
  4367. $num = 0;
  4368. $sql = "SELECT rowid, name, fk_country, status, entity";
  4369. $sql .= " FROM " . $this->db->prefix() . "establishment";
  4370. $sql .= " WHERE 1=1";
  4371. if ($status != 2) {
  4372. $sql .= " AND status = " . (int) $status;
  4373. }
  4374. if ($filtre) {
  4375. $sql .= " AND " . $filtre;
  4376. }
  4377. $sql .= " ORDER BY name";
  4378. dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
  4379. $result = $this->db->query($sql);
  4380. if ($result) {
  4381. $num = $this->db->num_rows($result);
  4382. $i = 0;
  4383. if ($num) {
  4384. print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4385. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4386. print '<option value="-1">&nbsp;</option>';
  4387. }
  4388. while ($i < $num) {
  4389. $obj = $this->db->fetch_object($result);
  4390. if ($selected == $obj->rowid) {
  4391. print '<option value="' . $obj->rowid . '" selected>';
  4392. } else {
  4393. print '<option value="' . $obj->rowid . '">';
  4394. }
  4395. print trim($obj->name);
  4396. if ($status == 2 && $obj->status == 1) {
  4397. print ' (' . $langs->trans("Closed") . ')';
  4398. }
  4399. print '</option>';
  4400. $i++;
  4401. }
  4402. print "</select>";
  4403. } else {
  4404. if ($status == 0) {
  4405. print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
  4406. } else {
  4407. print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
  4408. }
  4409. }
  4410. return $num;
  4411. } else {
  4412. dol_print_error($this->db);
  4413. return -1;
  4414. }
  4415. }
  4416. /**
  4417. * Display form to select bank account
  4418. *
  4419. * @param string $page Page
  4420. * @param int $selected Id of bank account
  4421. * @param string $htmlname Name of select html field
  4422. * @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.
  4423. * @return void
  4424. */
  4425. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4426. {
  4427. global $langs;
  4428. if ($htmlname != "none") {
  4429. print '<form method="POST" action="' . $page . '">';
  4430. print '<input type="hidden" name="action" value="setbankaccount">';
  4431. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4432. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4433. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4434. if ($nbaccountfound > 0) {
  4435. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  4436. }
  4437. print '</form>';
  4438. } else {
  4439. $langs->load('banks');
  4440. if ($selected) {
  4441. require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
  4442. $bankstatic = new Account($this->db);
  4443. $result = $bankstatic->fetch($selected);
  4444. if ($result) {
  4445. print $bankstatic->getNomUrl(1);
  4446. }
  4447. } else {
  4448. print "&nbsp;";
  4449. }
  4450. }
  4451. }
  4452. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4453. /**
  4454. * Return list of categories having choosed type
  4455. *
  4456. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4457. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4458. * @param string $htmlname HTML field name
  4459. * @param int $maxlength Maximum length for labels
  4460. * @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.
  4461. * $markafterid can be an :
  4462. * - int (id of category)
  4463. * - string (categories ids seprated by comma)
  4464. * - array (list of categories ids)
  4465. * @param int $outputmode 0=HTML select string, 1=Array, 2=Array extended
  4466. * @param int $include [=0] Removed or 1=Keep only
  4467. * @param string $morecss More CSS
  4468. * @return string|array
  4469. * @see select_categories()
  4470. */
  4471. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4472. {
  4473. // phpcs:enable
  4474. global $conf, $langs;
  4475. $langs->load("categories");
  4476. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  4477. // For backward compatibility
  4478. if (is_numeric($type)) {
  4479. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4480. }
  4481. if ($type === Categorie::TYPE_BANK_LINE) {
  4482. // TODO Move this into common category feature
  4483. $cate_arbo = array();
  4484. $sql = "SELECT c.label, c.rowid";
  4485. $sql .= " FROM " . $this->db->prefix() . "bank_categ as c";
  4486. $sql .= " WHERE entity = " . $conf->entity;
  4487. $sql .= " ORDER BY c.label";
  4488. $result = $this->db->query($sql);
  4489. if ($result) {
  4490. $num = $this->db->num_rows($result);
  4491. $i = 0;
  4492. while ($i < $num) {
  4493. $objp = $this->db->fetch_object($result);
  4494. if ($objp) {
  4495. $cate_arbo[$objp->rowid] = array('id' => $objp->rowid, 'fulllabel' => $objp->label, 'color' => '', 'picto' => 'category');
  4496. }
  4497. $i++;
  4498. }
  4499. $this->db->free($result);
  4500. } else {
  4501. dol_print_error($this->db);
  4502. }
  4503. } else {
  4504. $cat = new Categorie($this->db);
  4505. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4506. }
  4507. $outarray = array();
  4508. $output = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  4509. if (is_array($cate_arbo)) {
  4510. if (!count($cate_arbo)) {
  4511. $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
  4512. } else {
  4513. $output .= '<option value="-1">&nbsp;</option>';
  4514. foreach ($cate_arbo as $key => $value) {
  4515. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4516. $add = 'selected ';
  4517. } else {
  4518. $add = '';
  4519. }
  4520. $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
  4521. $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')) . '"';
  4522. $output .= '>';
  4523. $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4524. $output .= '</option>';
  4525. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4526. }
  4527. }
  4528. }
  4529. $output .= '</select>';
  4530. $output .= "\n";
  4531. if ($outputmode == 2) {
  4532. return $cate_arbo;
  4533. } elseif ($outputmode) {
  4534. return $outarray;
  4535. }
  4536. return $output;
  4537. }
  4538. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4539. /**
  4540. * Show a confirmation HTML form or AJAX popup
  4541. *
  4542. * @param string $page Url of page to call if confirmation is OK
  4543. * @param string $title Title
  4544. * @param string $question Question
  4545. * @param string $action Action
  4546. * @param array $formquestion An array with forms complementary inputs
  4547. * @param string $selectedchoice "" or "no" or "yes"
  4548. * @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
  4549. * @param int $height Force height of box
  4550. * @param int $width Force width of box
  4551. * @return void
  4552. * @deprecated
  4553. * @see formconfirm()
  4554. */
  4555. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4556. {
  4557. // phpcs:enable
  4558. dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4559. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4560. }
  4561. /**
  4562. * Show a confirmation HTML form or AJAX popup.
  4563. * Easiest way to use this is with useajax=1.
  4564. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4565. * just after calling this method. For example:
  4566. * print '<script nonce="'.getNonce().'" type="text/javascript">'."\n";
  4567. * print 'jQuery(document).ready(function() {'."\n";
  4568. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4569. * print '});'."\n";
  4570. * print '</script>'."\n";
  4571. *
  4572. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4573. * @param string $title Title
  4574. * @param string $question Question
  4575. * @param string $action Action
  4576. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...'))
  4577. * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss',
  4578. * 'other', 'onecolumn' or 'hidden'...
  4579. * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0
  4580. * @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
  4581. * @param int|string $height Force height of box (0 = auto)
  4582. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4583. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4584. * @param string $labelbuttonyes Label for Yes
  4585. * @param string $labelbuttonno Label for No
  4586. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4587. */
  4588. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4589. {
  4590. global $langs, $conf;
  4591. $more = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
  4592. $formconfirm = '';
  4593. $inputok = array();
  4594. $inputko = array();
  4595. // Clean parameters
  4596. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4597. if ($conf->browser->layout == 'phone') {
  4598. $width = '95%';
  4599. }
  4600. // Set height automatically if not defined
  4601. if (empty($height)) {
  4602. $height = 220;
  4603. if (is_array($formquestion) && count($formquestion) > 2) {
  4604. $height += ((count($formquestion) - 2) * 24);
  4605. }
  4606. }
  4607. if (is_array($formquestion) && !empty($formquestion)) {
  4608. // First add hidden fields and value
  4609. foreach ($formquestion as $key => $input) {
  4610. if (is_array($input) && !empty($input)) {
  4611. if ($input['type'] == 'hidden') {
  4612. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4613. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4614. $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";
  4615. }
  4616. }
  4617. }
  4618. // Now add questions
  4619. $moreonecolumn = '';
  4620. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
  4621. foreach ($formquestion as $key => $input) {
  4622. if (is_array($input) && !empty($input)) {
  4623. $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
  4624. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4625. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4626. if ($input['type'] == 'text') {
  4627. $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";
  4628. } elseif ($input['type'] == 'password') {
  4629. $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";
  4630. } elseif ($input['type'] == 'textarea') {
  4631. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4632. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4633. $more .= $input['value'];
  4634. $more .= '</textarea>';
  4635. $more .= '</div></div>'."\n";*/
  4636. $moreonecolumn .= '<div class="margintoponly">';
  4637. $moreonecolumn .= $input['label'] . '<br>';
  4638. $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
  4639. $moreonecolumn .= $input['value'];
  4640. $moreonecolumn .= '</textarea>';
  4641. $moreonecolumn .= '</div>';
  4642. } elseif (in_array($input['type'], ['select', 'multiselect'])) {
  4643. if (empty($morecss)) {
  4644. $morecss = 'minwidth100';
  4645. }
  4646. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4647. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4648. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4649. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4650. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4651. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4652. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4653. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
  4654. if (!empty($input['label'])) {
  4655. $more .= $input['label'] . '</div><div class="tagtd left">';
  4656. }
  4657. if ($input['type'] == 'select') {
  4658. $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);
  4659. } else {
  4660. $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);
  4661. }
  4662. $more .= '</div></div>' . "\n";
  4663. } elseif ($input['type'] == 'checkbox') {
  4664. $more .= '<div class="tagtr">';
  4665. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '"><label for="' . dol_escape_htmltag($input['name']) . '">' . $input['label'] . '</label></div><div class="tagtd">';
  4666. $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
  4667. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4668. $more .= ' checked';
  4669. }
  4670. if (is_bool($input['value']) && $input['value']) {
  4671. $more .= ' checked';
  4672. }
  4673. if (isset($input['disabled'])) {
  4674. $more .= ' disabled';
  4675. }
  4676. $more .= ' /></div>';
  4677. $more .= '</div>' . "\n";
  4678. } elseif ($input['type'] == 'radio') {
  4679. $i = 0;
  4680. foreach ($input['values'] as $selkey => $selval) {
  4681. $more .= '<div class="tagtr">';
  4682. if (isset($input['label'])) {
  4683. if ($i == 0) {
  4684. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4685. } else {
  4686. $more .= '<div clas="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
  4687. }
  4688. }
  4689. $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;
  4690. if (!empty($input['disabled'])) {
  4691. $more .= ' disabled';
  4692. }
  4693. if (isset($input['default']) && $input['default'] === $selkey) {
  4694. $more .= ' checked="checked"';
  4695. }
  4696. $more .= ' /> ';
  4697. $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
  4698. $more .= '</div></div>' . "\n";
  4699. $i++;
  4700. }
  4701. } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
  4702. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4703. $more .= '<div class="tagtd">';
  4704. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4705. $h = $m = 0;
  4706. if ($input['type'] == 'datetime') {
  4707. $h = isset($input['hours']) ? $input['hours'] : 1;
  4708. $m = isset($input['minutes']) ? $input['minutes'] : 1;
  4709. }
  4710. $more .= $this->selectDate($input['value'], $input['name'], $h, $m, 0, '', 1, $addnowlink);
  4711. $more .= '</div></div>'."\n";
  4712. $formquestion[] = array('name'=>$input['name'].'day');
  4713. $formquestion[] = array('name'=>$input['name'].'month');
  4714. $formquestion[] = array('name'=>$input['name'].'year');
  4715. $formquestion[] = array('name'=>$input['name'].'hour');
  4716. $formquestion[] = array('name'=>$input['name'].'min');
  4717. } elseif ($input['type'] == 'other') { // can be 1 column or 2 depending if label is set or not
  4718. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4719. if (!empty($input['label'])) {
  4720. $more .= $input['label'] . '</div><div class="tagtd">';
  4721. }
  4722. $more .= $input['value'];
  4723. $more .= '</div></div>' . "\n";
  4724. } elseif ($input['type'] == 'onecolumn') {
  4725. $moreonecolumn .= '<div class="margintoponly">';
  4726. $moreonecolumn .= $input['value'];
  4727. $moreonecolumn .= '</div>' . "\n";
  4728. } elseif ($input['type'] == 'hidden') {
  4729. // Do nothing more, already added by a previous loop
  4730. } elseif ($input['type'] == 'separator') {
  4731. $more .= '<br>';
  4732. } else {
  4733. $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
  4734. }
  4735. }
  4736. }
  4737. $more .= '</div>' . "\n";
  4738. $more .= $moreonecolumn;
  4739. }
  4740. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4741. // 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
  4742. // See page product/card.php for example
  4743. if (!empty($conf->dol_use_jmobile)) {
  4744. $useajax = 0;
  4745. }
  4746. if (empty($conf->use_javascript_ajax)) {
  4747. $useajax = 0;
  4748. }
  4749. if ($useajax) {
  4750. $autoOpen = true;
  4751. $dialogconfirm = 'dialog-confirm';
  4752. $button = '';
  4753. if (!is_numeric($useajax)) {
  4754. $button = $useajax;
  4755. $useajax = 1;
  4756. $autoOpen = false;
  4757. $dialogconfirm .= '-' . $button;
  4758. }
  4759. $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
  4760. $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
  4761. // Add input fields into list of fields to read during submit (inputok and inputko)
  4762. if (is_array($formquestion)) {
  4763. foreach ($formquestion as $key => $input) {
  4764. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4765. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4766. if (is_array($input) && isset($input['name'])) {
  4767. if (strpos($input['name'], ',') > 0) {
  4768. $inputok = array_merge($inputok, explode(',', $input['name']));
  4769. } else {
  4770. array_push($inputok, $input['name']);
  4771. }
  4772. }
  4773. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4774. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4775. array_push($inputko, $input['name']);
  4776. }
  4777. }
  4778. }
  4779. // Show JQuery confirm box.
  4780. $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
  4781. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4782. $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
  4783. }
  4784. if (!empty($more)) {
  4785. $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
  4786. }
  4787. $formconfirm .= ($question ? '<div class="confirmmessage">' . img_help('', '') . ' ' . $question . '</div>' : '');
  4788. $formconfirm .= '</div>' . "\n";
  4789. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
  4790. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  4791. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4792. $formconfirm .= 'jQuery(document).ready(function() {
  4793. $(function() {
  4794. $( "#' . $dialogconfirm . '" ).dialog(
  4795. {
  4796. autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
  4797. if ($newselectedchoice == 'no') {
  4798. $formconfirm .= '
  4799. open: function() {
  4800. $(this).parent().find("button.ui-button:eq(2)").focus();
  4801. },';
  4802. }
  4803. $jsforcursor = '';
  4804. if ($useajax == 1) {
  4805. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
  4806. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
  4807. }
  4808. $postconfirmas = 'GET';
  4809. $formconfirm .= '
  4810. resizable: false,
  4811. height: "' . $height . '",
  4812. width: "' . $width . '",
  4813. modal: true,
  4814. closeOnEscape: false,
  4815. buttons: {
  4816. "' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '": function() {
  4817. var options = "token=' . urlencode(newToken()) . '";
  4818. var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
  4819. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4820. var pageyes = "' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '";
  4821. if (inputok.length > 0) {
  4822. $.each(inputok, function(i, inputname) {
  4823. var more = "";
  4824. var inputvalue;
  4825. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4826. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4827. } else {
  4828. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4829. inputvalue = $("#" + inputname + more).val();
  4830. }
  4831. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4832. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4833. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4834. });
  4835. }
  4836. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
  4837. if (pageyes.length > 0) {';
  4838. if ($postconfirmas == 'GET') {
  4839. $formconfirm .= 'location.href = urljump;';
  4840. } else {
  4841. $formconfirm .= $jsforcursor;
  4842. $formconfirm .= 'var post = $.post(
  4843. pageyes,
  4844. options,
  4845. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4846. );';
  4847. }
  4848. $formconfirm .= '
  4849. console.log("after post ok");
  4850. }
  4851. $(this).dialog("close");
  4852. },
  4853. "' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '": function() {
  4854. var options = "token=' . urlencode(newToken()) . '";
  4855. var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
  4856. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4857. var pageno="' . dol_escape_js(!empty($pageno) ? $pageno : '') . '";
  4858. if (inputko.length > 0) {
  4859. $.each(inputko, function(i, inputname) {
  4860. var more = "";
  4861. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4862. var inputvalue = $("#" + inputname + more).val();
  4863. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4864. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4865. });
  4866. }
  4867. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
  4868. //alert(urljump);
  4869. if (pageno.length > 0) {';
  4870. if ($postconfirmas == 'GET') {
  4871. $formconfirm .= 'location.href = urljump;';
  4872. } else {
  4873. $formconfirm .= $jsforcursor;
  4874. $formconfirm .= 'var post = $.post(
  4875. pageno,
  4876. options,
  4877. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4878. );';
  4879. }
  4880. $formconfirm .= '
  4881. console.log("after post ko");
  4882. }
  4883. $(this).dialog("close");
  4884. }
  4885. }
  4886. }
  4887. );
  4888. var button = "' . $button . '";
  4889. if (button.length > 0) {
  4890. $( "#" + button ).click(function() {
  4891. $("#' . $dialogconfirm . '").dialog("open");
  4892. });
  4893. }
  4894. });
  4895. });
  4896. </script>';
  4897. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4898. } else {
  4899. $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
  4900. if (empty($disableformtag)) {
  4901. $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftroright">' . "\n";
  4902. }
  4903. $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
  4904. $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
  4905. $formconfirm .= '<table class="valid centpercent">' . "\n";
  4906. // Line title
  4907. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4908. $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
  4909. $formconfirm .= '</td></tr>' . "\n";
  4910. // Line text
  4911. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4912. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . $formquestion['text'] . '</td></tr>' . "\n";
  4913. }
  4914. // Line form fields
  4915. if ($more) {
  4916. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . "\n";
  4917. $formconfirm .= $more;
  4918. $formconfirm .= '</td></tr>' . "\n";
  4919. }
  4920. // Line with question
  4921. $formconfirm .= '<tr class="valid">';
  4922. $formconfirm .= '<td class="valid">' . $question . '</td>';
  4923. $formconfirm .= '<td class="valid center">';
  4924. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  4925. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
  4926. $formconfirm .= '</td>';
  4927. $formconfirm .= '</tr>' . "\n";
  4928. $formconfirm .= '</table>' . "\n";
  4929. if (empty($disableformtag)) {
  4930. $formconfirm .= "</form>\n";
  4931. }
  4932. $formconfirm .= '<br>';
  4933. if (!empty($conf->use_javascript_ajax)) {
  4934. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4935. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  4936. $formconfirm .= '
  4937. $(document).ready(function () {
  4938. $(".confirmvalidatebutton").on("click", function() {
  4939. console.log("We click on button");
  4940. $(this).attr("disabled", "disabled");
  4941. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4942. //console.log($(this).closest("form"));
  4943. $(this).closest("form").submit();
  4944. });
  4945. });
  4946. ';
  4947. $formconfirm .= '</script>' . "\n";
  4948. }
  4949. $formconfirm .= "<!-- end formconfirm -->\n";
  4950. }
  4951. return $formconfirm;
  4952. }
  4953. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4954. /**
  4955. * Show a form to select a project
  4956. *
  4957. * @param int $page Page
  4958. * @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)
  4959. * @param int $selected Id pre-selected project
  4960. * @param string $htmlname Name of select field
  4961. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4962. * @param int $maxlength Max length
  4963. * @param int $forcefocus Force focus on field (works with javascript only)
  4964. * @param int $nooutput No print is done. String is returned.
  4965. * @param string $textifnoproject Text to show if no project
  4966. * @param string $morecss More CSS
  4967. * @return string Return html content
  4968. */
  4969. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
  4970. {
  4971. // phpcs:enable
  4972. global $langs;
  4973. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  4974. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  4975. $out = '';
  4976. $formproject = new FormProjets($this->db);
  4977. $langs->load("project");
  4978. if ($htmlname != "none") {
  4979. $out .= '<form method="post" action="' . $page . '">';
  4980. $out .= '<input type="hidden" name="action" value="classin">';
  4981. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  4982. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
  4983. $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  4984. $out .= '</form>';
  4985. } else {
  4986. $out .= '<span class="project_head_block">';
  4987. if ($selected) {
  4988. $projet = new Project($this->db);
  4989. $projet->fetch($selected);
  4990. $out .= $projet->getNomUrl(0, '', 1);
  4991. } else {
  4992. $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
  4993. }
  4994. $out .= '</span>';
  4995. }
  4996. if (empty($nooutput)) {
  4997. print $out;
  4998. return '';
  4999. }
  5000. return $out;
  5001. }
  5002. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5003. /**
  5004. * Show a form to select payment conditions
  5005. *
  5006. * @param int $page Page
  5007. * @param string $selected Id condition pre-selectionne
  5008. * @param string $htmlname Name of select html field
  5009. * @param int $addempty Add empty entry
  5010. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5011. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  5012. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  5013. * 0 : use default deposit percentage from entry
  5014. * > 0 : force deposit percentage (for example, from company object)
  5015. * @param int $nooutput No print is done. String is returned.
  5016. * @return string HTML output or ''
  5017. */
  5018. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
  5019. {
  5020. // phpcs:enable
  5021. global $langs;
  5022. $out = '';
  5023. if ($htmlname != "none") {
  5024. $out .= '<form method="POST" action="' . $page . '">';
  5025. $out .= '<input type="hidden" name="action" value="setconditions">';
  5026. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5027. if ($type) {
  5028. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5029. }
  5030. $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  5031. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5032. $out .= '</form>';
  5033. } else {
  5034. if ($selected) {
  5035. $this->load_cache_conditions_paiements();
  5036. if (isset($this->cache_conditions_paiements[$selected])) {
  5037. $label = $this->cache_conditions_paiements[$selected]['label'];
  5038. if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  5039. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  5040. }
  5041. $out .= $label;
  5042. } else {
  5043. $langs->load('errors');
  5044. $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
  5045. }
  5046. } else {
  5047. $out .= '&nbsp;';
  5048. }
  5049. }
  5050. if (empty($nooutput)) {
  5051. print $out;
  5052. return '';
  5053. }
  5054. return $out;
  5055. }
  5056. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5057. /**
  5058. * Show a form to select a delivery delay
  5059. *
  5060. * @param int $page Page
  5061. * @param string $selected Id condition pre-selectionne
  5062. * @param string $htmlname Name of select html field
  5063. * @param int $addempty Add an empty entry
  5064. * @return void
  5065. */
  5066. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  5067. {
  5068. // phpcs:enable
  5069. global $langs;
  5070. if ($htmlname != "none") {
  5071. print '<form method="post" action="' . $page . '">';
  5072. print '<input type="hidden" name="action" value="setavailability">';
  5073. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5074. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  5075. print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5076. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
  5077. print '</form>';
  5078. } else {
  5079. if ($selected) {
  5080. $this->load_cache_availability();
  5081. print $this->cache_availability[$selected]['label'];
  5082. } else {
  5083. print "&nbsp;";
  5084. }
  5085. }
  5086. }
  5087. /**
  5088. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  5089. * List found into table c_input_reason loaded by loadCacheInputReason
  5090. *
  5091. * @param string $page Page
  5092. * @param string $selected Id condition pre-selectionne
  5093. * @param string $htmlname Name of select html field
  5094. * @param int $addempty Add empty entry
  5095. * @return void
  5096. */
  5097. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  5098. {
  5099. global $langs;
  5100. if ($htmlname != "none") {
  5101. print '<form method="post" action="' . $page . '">';
  5102. print '<input type="hidden" name="action" value="setdemandreason">';
  5103. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5104. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  5105. print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5106. print '</form>';
  5107. } else {
  5108. if ($selected) {
  5109. $this->loadCacheInputReason();
  5110. foreach ($this->cache_demand_reason as $key => $val) {
  5111. if ($val['id'] == $selected) {
  5112. print $val['label'];
  5113. break;
  5114. }
  5115. }
  5116. } else {
  5117. print "&nbsp;";
  5118. }
  5119. }
  5120. }
  5121. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5122. /**
  5123. * Show a form + html select a date
  5124. *
  5125. * @param string $page Page
  5126. * @param string $selected Date preselected
  5127. * @param string $htmlname Html name of date input fields or 'none'
  5128. * @param int $displayhour Display hour selector
  5129. * @param int $displaymin Display minutes selector
  5130. * @param int $nooutput 1=No print output, return string
  5131. * @param string $type 'direct-debit' or 'bank-transfer'
  5132. * @return string
  5133. * @see selectDate()
  5134. */
  5135. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  5136. {
  5137. // phpcs:enable
  5138. global $langs;
  5139. $ret = '';
  5140. if ($htmlname != "none") {
  5141. $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5142. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5143. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5144. if ($type) {
  5145. $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5146. }
  5147. $ret .= '<table class="nobordernopadding">';
  5148. $ret .= '<tr><td>';
  5149. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
  5150. $ret .= '</td>';
  5151. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5152. $ret .= '</tr></table></form>';
  5153. } else {
  5154. if ($displayhour) {
  5155. $ret .= dol_print_date($selected, 'dayhour');
  5156. } else {
  5157. $ret .= dol_print_date($selected, 'day');
  5158. }
  5159. }
  5160. if (empty($nooutput)) {
  5161. print $ret;
  5162. }
  5163. return $ret;
  5164. }
  5165. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5166. /**
  5167. * Show a select form to choose a user
  5168. *
  5169. * @param string $page Page
  5170. * @param string $selected Id of user preselected
  5171. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  5172. * @param array $exclude List of users id to exclude
  5173. * @param array $include List of users id to include
  5174. * @return void
  5175. */
  5176. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  5177. {
  5178. // phpcs:enable
  5179. global $langs;
  5180. if ($htmlname != "none") {
  5181. print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5182. print '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5183. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5184. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5185. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5186. print '</form>';
  5187. } else {
  5188. if ($selected) {
  5189. require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
  5190. $theuser = new User($this->db);
  5191. $theuser->fetch($selected);
  5192. print $theuser->getNomUrl(1);
  5193. } else {
  5194. print "&nbsp;";
  5195. }
  5196. }
  5197. }
  5198. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5199. /**
  5200. * Show form with payment mode
  5201. *
  5202. * @param string $page Page
  5203. * @param int $selected Id mode pre-selectionne
  5204. * @param string $htmlname Name of select html field
  5205. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5206. * @param int $active Active or not, -1 = all
  5207. * @param int $addempty 1=Add empty entry
  5208. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5209. * @param int $nooutput 1=Return string, no output
  5210. * @return string HTML output or ''
  5211. */
  5212. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
  5213. {
  5214. // phpcs:enable
  5215. global $langs;
  5216. $out = '';
  5217. if ($htmlname != "none") {
  5218. $out .= '<form method="POST" action="' . $page . '">';
  5219. $out .= '<input type="hidden" name="action" value="setmode">';
  5220. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5221. if ($type) {
  5222. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5223. }
  5224. $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5225. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5226. $out .= '</form>';
  5227. } else {
  5228. if ($selected) {
  5229. $this->load_cache_types_paiements();
  5230. $out .= $this->cache_types_paiements[$selected]['label'];
  5231. } else {
  5232. $out .= "&nbsp;";
  5233. }
  5234. }
  5235. if ($nooutput) {
  5236. return $out;
  5237. } else {
  5238. print $out;
  5239. }
  5240. return '';
  5241. }
  5242. /**
  5243. * Show form with transport mode
  5244. *
  5245. * @param string $page Page
  5246. * @param int $selected Id mode pre-select
  5247. * @param string $htmlname Name of select html field
  5248. * @param int $active Active or not, -1 = all
  5249. * @param int $addempty 1=Add empty entry
  5250. * @return void
  5251. */
  5252. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5253. {
  5254. global $langs;
  5255. if ($htmlname != "none") {
  5256. print '<form method="POST" action="' . $page . '">';
  5257. print '<input type="hidden" name="action" value="settransportmode">';
  5258. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5259. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5260. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5261. print '</form>';
  5262. } else {
  5263. if ($selected) {
  5264. $this->load_cache_transport_mode();
  5265. print $this->cache_transport_mode[$selected]['label'];
  5266. } else {
  5267. print "&nbsp;";
  5268. }
  5269. }
  5270. }
  5271. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5272. /**
  5273. * Show form with multicurrency code
  5274. *
  5275. * @param string $page Page
  5276. * @param string $selected code pre-selectionne
  5277. * @param string $htmlname Name of select html field
  5278. * @return void
  5279. */
  5280. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5281. {
  5282. // phpcs:enable
  5283. global $langs;
  5284. if ($htmlname != "none") {
  5285. print '<form method="POST" action="' . $page . '">';
  5286. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5287. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5288. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5289. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5290. print '</form>';
  5291. } else {
  5292. dol_include_once('/core/lib/company.lib.php');
  5293. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5294. }
  5295. }
  5296. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5297. /**
  5298. * Show form with multicurrency rate
  5299. *
  5300. * @param string $page Page
  5301. * @param double $rate Current rate
  5302. * @param string $htmlname Name of select html field
  5303. * @param string $currency Currency code to explain the rate
  5304. * @return void
  5305. */
  5306. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5307. {
  5308. // phpcs:enable
  5309. global $langs, $mysoc, $conf;
  5310. if ($htmlname != "none") {
  5311. print '<form method="POST" action="' . $page . '">';
  5312. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5313. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5314. print '<input type="text" class="maxwidth100" name="' . $htmlname . '" value="' . (!empty($rate) ? price(price2num($rate, 'CU')) : 1) . '" /> ';
  5315. print '<select name="calculation_mode">';
  5316. print '<option value="1">Change ' . $langs->trans("PriceUHT") . ' of lines</option>';
  5317. print '<option value="2">Change ' . $langs->trans("PriceUHTCurrency") . ' of lines</option>';
  5318. print '</select> ';
  5319. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5320. print '</form>';
  5321. } else {
  5322. if (!empty($rate)) {
  5323. print price($rate, 1, $langs, 1, 0);
  5324. if ($currency && $rate != 1) {
  5325. print ' &nbsp; (' . price($rate, 1, $langs, 1, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')';
  5326. }
  5327. } else {
  5328. print 1;
  5329. }
  5330. }
  5331. }
  5332. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5333. /**
  5334. * Show a select box with available absolute discounts
  5335. *
  5336. * @param string $page Page URL where form is shown
  5337. * @param int $selected Value pre-selected
  5338. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5339. * @param int $socid Third party id
  5340. * @param float $amount Total amount available
  5341. * @param string $filter SQL filter on discounts
  5342. * @param int $maxvalue Max value for lines that can be selected
  5343. * @param string $more More string to add
  5344. * @param int $hidelist 1=Hide list
  5345. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5346. * @return void
  5347. */
  5348. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5349. {
  5350. // phpcs:enable
  5351. global $conf, $langs;
  5352. if ($htmlname != "none") {
  5353. print '<form method="post" action="' . $page . '">';
  5354. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5355. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5356. print '<div class="inline-block">';
  5357. if (!empty($discount_type)) {
  5358. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5359. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5360. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5361. } else {
  5362. $translationKey = 'HasCreditNoteFromSupplier';
  5363. }
  5364. } else {
  5365. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5366. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5367. } else {
  5368. $translationKey = 'HasCreditNoteFromSupplier';
  5369. }
  5370. }
  5371. } else {
  5372. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5373. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5374. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5375. } else {
  5376. $translationKey = 'CompanyHasCreditNote';
  5377. }
  5378. } else {
  5379. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5380. $translationKey = 'CompanyHasAbsoluteDiscount';
  5381. } else {
  5382. $translationKey = 'CompanyHasCreditNote';
  5383. }
  5384. }
  5385. }
  5386. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5387. if (empty($hidelist)) {
  5388. print ' ';
  5389. }
  5390. print '</div>';
  5391. if (empty($hidelist)) {
  5392. print '<div class="inline-block" style="padding-right: 10px">';
  5393. $newfilter = 'discount_type=' . intval($discount_type);
  5394. if (!empty($discount_type)) {
  5395. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5396. } else {
  5397. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5398. }
  5399. if ($filter) {
  5400. $newfilter .= ' AND (' . $filter . ')';
  5401. }
  5402. // output the combo of discounts
  5403. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5404. if ($nbqualifiedlines > 0) {
  5405. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
  5406. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5407. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5408. }
  5409. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5410. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5411. }
  5412. print '>';
  5413. }
  5414. print '</div>';
  5415. }
  5416. if ($more) {
  5417. print '<div class="inline-block">';
  5418. print $more;
  5419. print '</div>';
  5420. }
  5421. print '</form>';
  5422. } else {
  5423. if ($selected) {
  5424. print $selected;
  5425. } else {
  5426. print "0";
  5427. }
  5428. }
  5429. }
  5430. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5431. /**
  5432. * Show forms to select a contact
  5433. *
  5434. * @param string $page Page
  5435. * @param Societe $societe Filter on third party
  5436. * @param int $selected Id contact pre-selectionne
  5437. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5438. * @return void
  5439. */
  5440. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5441. {
  5442. // phpcs:enable
  5443. global $langs, $conf;
  5444. if ($htmlname != "none") {
  5445. print '<form method="post" action="' . $page . '">';
  5446. print '<input type="hidden" name="action" value="set_contact">';
  5447. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5448. print '<table class="nobordernopadding">';
  5449. print '<tr><td>';
  5450. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5451. $num = $this->num;
  5452. if ($num == 0) {
  5453. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5454. print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&amp;action=create&amp;backtoreferer=1">' . $addcontact . '</a>';
  5455. }
  5456. print '</td>';
  5457. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5458. print '</tr></table></form>';
  5459. } else {
  5460. if ($selected) {
  5461. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  5462. $contact = new Contact($this->db);
  5463. $contact->fetch($selected);
  5464. print $contact->getFullName($langs);
  5465. } else {
  5466. print "&nbsp;";
  5467. }
  5468. }
  5469. }
  5470. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5471. /**
  5472. * Output html select to select thirdparty
  5473. *
  5474. * @param string $page Page
  5475. * @param string $selected Id preselected
  5476. * @param string $htmlname Name of HTML select
  5477. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>()] are allowed here (example: 's.rowid <> x', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  5478. * @param int $showempty Add an empty field
  5479. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5480. * @param int $forcecombo Force to use combo box
  5481. * @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')))
  5482. * @param int $nooutput No print output. Return it only.
  5483. * @param array $excludeids Exclude IDs from the select combo
  5484. * @param string $textifnothirdparty Text to show if no thirdparty
  5485. * @return string HTML output or ''
  5486. */
  5487. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
  5488. {
  5489. // phpcs:enable
  5490. global $langs;
  5491. $out = '';
  5492. if ($htmlname != "none") {
  5493. $out .= '<form method="post" action="' . $page . '">';
  5494. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5495. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5496. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5497. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5498. $out .= '</form>';
  5499. } else {
  5500. if ($selected) {
  5501. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  5502. $soc = new Societe($this->db);
  5503. $soc->fetch($selected);
  5504. $out .= $soc->getNomUrl(0, '');
  5505. } else {
  5506. $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
  5507. }
  5508. }
  5509. if ($nooutput) {
  5510. return $out;
  5511. } else {
  5512. print $out;
  5513. }
  5514. return '';
  5515. }
  5516. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5517. /**
  5518. * Retourne la liste des devises, dans la langue de l'utilisateur
  5519. *
  5520. * @param string $selected preselected currency code
  5521. * @param string $htmlname name of HTML select list
  5522. * @deprecated
  5523. * @return void
  5524. */
  5525. public function select_currency($selected = '', $htmlname = 'currency_id')
  5526. {
  5527. // phpcs:enable
  5528. print $this->selectCurrency($selected, $htmlname);
  5529. }
  5530. /**
  5531. * Retourne la liste des devises, dans la langue de l'utilisateur
  5532. *
  5533. * @param string $selected preselected currency code
  5534. * @param string $htmlname name of HTML select list
  5535. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5536. * @param string $useempty '1'=Allow empty value
  5537. * @return string
  5538. */
  5539. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5540. {
  5541. global $conf, $langs, $user;
  5542. $langs->loadCacheCurrencies('');
  5543. $out = '';
  5544. if ($selected == 'euro' || $selected == 'euros') {
  5545. $selected = 'EUR'; // Pour compatibilite
  5546. }
  5547. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
  5548. if ($useempty) {
  5549. $out .= '<option value="-1" selected></option>';
  5550. }
  5551. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5552. $labeltoshow = $currency['label'];
  5553. if ($mode == 1) {
  5554. $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
  5555. } else {
  5556. $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
  5557. }
  5558. if ($selected && $selected == $code_iso) {
  5559. $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5560. } else {
  5561. $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5562. }
  5563. $out .= $labeltoshow;
  5564. $out .= '</option>';
  5565. }
  5566. $out .= '</select>';
  5567. if ($user->admin) {
  5568. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5569. }
  5570. // Make select dynamic
  5571. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5572. $out .= ajax_combobox($htmlname);
  5573. return $out;
  5574. }
  5575. /**
  5576. * Return array of currencies in user language
  5577. *
  5578. * @param string $selected Preselected currency code
  5579. * @param string $htmlname Name of HTML select list
  5580. * @param integer $useempty 1=Add empty line
  5581. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5582. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5583. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5584. * @param string $morecss More css
  5585. * @return string
  5586. */
  5587. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5588. {
  5589. global $conf, $langs;
  5590. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5591. $TCurrency = array();
  5592. $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
  5593. $sql .= " WHERE entity IN ('" . getEntity('mutlicurrency') . "')";
  5594. if ($filter) {
  5595. $sql .= " AND " . $filter;
  5596. }
  5597. $resql = $this->db->query($sql);
  5598. if ($resql) {
  5599. while ($obj = $this->db->fetch_object($resql)) {
  5600. $TCurrency[$obj->code] = $obj->code;
  5601. }
  5602. }
  5603. $out = '';
  5604. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  5605. if ($useempty) {
  5606. $out .= '<option value="">&nbsp;</option>';
  5607. }
  5608. // If company current currency not in table, we add it into list. Should always be available.
  5609. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5610. $TCurrency[$conf->currency] = $conf->currency;
  5611. }
  5612. if (count($TCurrency) > 0) {
  5613. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5614. if (isset($TCurrency[$code_iso])) {
  5615. if (!empty($selected) && $selected == $code_iso) {
  5616. $out .= '<option value="' . $code_iso . '" selected="selected">';
  5617. } else {
  5618. $out .= '<option value="' . $code_iso . '">';
  5619. }
  5620. $out .= $currency['label'];
  5621. $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
  5622. $out .= '</option>';
  5623. }
  5624. }
  5625. }
  5626. $out .= '</select>';
  5627. // Make select dynamic
  5628. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5629. $out .= ajax_combobox($htmlname);
  5630. return $out;
  5631. }
  5632. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5633. /**
  5634. * Load into the cache vat rates of a country
  5635. *
  5636. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5637. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5638. */
  5639. public function load_cache_vatrates($country_code)
  5640. {
  5641. // phpcs:enable
  5642. global $langs, $user;
  5643. $num = count($this->cache_vatrates);
  5644. if ($num > 0) {
  5645. return $num; // Cache already loaded
  5646. }
  5647. dol_syslog(__METHOD__, LOG_DEBUG);
  5648. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5649. $sql .= " FROM " . $this->db->prefix() . "c_tva as t, " . $this->db->prefix() . "c_country as c";
  5650. $sql .= " WHERE t.fk_pays = c.rowid";
  5651. $sql .= " AND t.active > 0";
  5652. $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
  5653. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5654. $resql = $this->db->query($sql);
  5655. if ($resql) {
  5656. $num = $this->db->num_rows($resql);
  5657. if ($num) {
  5658. for ($i = 0; $i < $num; $i++) {
  5659. $obj = $this->db->fetch_object($resql);
  5660. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5661. $this->cache_vatrates[$i]['code'] = $obj->code;
  5662. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5663. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5664. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5665. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5666. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5667. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5668. $this->cache_vatrates[$i]['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
  5669. $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
  5670. $positiverates = '';
  5671. if ($obj->taux) {
  5672. $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
  5673. }
  5674. if ($obj->localtax1) {
  5675. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
  5676. }
  5677. if ($obj->localtax2) {
  5678. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
  5679. }
  5680. if (empty($positiverates)) {
  5681. $positiverates = '0';
  5682. }
  5683. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
  5684. }
  5685. return $num;
  5686. } else {
  5687. $this->error = '<span class="error">';
  5688. $this->error .= $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code);
  5689. $reg = array();
  5690. if (!empty($user) && $user->admin && preg_match('/\'(..)\'/', $country_code, $reg)) {
  5691. $langs->load("errors");
  5692. $new_country_code = $reg[1];
  5693. $country_id = dol_getIdFromCode($this->db, $new_country_code, 'c_pays', 'code', 'rowid');
  5694. $this->error .= '<br>'.$langs->trans("ErrorFixThisHere", DOL_URL_ROOT.'/admin/dict.php?id=10'.($country_id > 0 ? '&countryidforinsert='.$country_id : ''));
  5695. }
  5696. $this->error .= '</span>';
  5697. return -1;
  5698. }
  5699. } else {
  5700. $this->error = '<span class="error">' . $this->db->error() . '</span>';
  5701. return -2;
  5702. }
  5703. }
  5704. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5705. /**
  5706. * Output an HTML select vat rate.
  5707. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5708. *
  5709. * @param string $htmlname Name of HTML select field
  5710. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5711. * @param Societe $societe_vendeuse Thirdparty seller
  5712. * @param Societe $societe_acheteuse Thirdparty buyer
  5713. * @param int $idprod Id product. O if unknown of NA.
  5714. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5715. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5716. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5717. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5718. * 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.
  5719. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5720. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5721. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5722. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5723. * @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
  5724. * @return string
  5725. */
  5726. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5727. {
  5728. // phpcs:enable
  5729. global $langs, $conf, $mysoc;
  5730. $langs->load('errors');
  5731. $return = '';
  5732. // Define defaultnpr, defaultttx and defaultcode
  5733. $defaultnpr = ($info_bits & 0x01);
  5734. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5735. $defaulttx = str_replace('*', '', $selectedrate);
  5736. $defaultcode = '';
  5737. $reg = array();
  5738. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5739. $defaultcode = $reg[1];
  5740. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5741. }
  5742. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5743. // Check parameters
  5744. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5745. if ($societe_vendeuse->id == $mysoc->id) {
  5746. $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
  5747. } else {
  5748. $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
  5749. }
  5750. return $return;
  5751. }
  5752. //var_dump($societe_acheteuse);
  5753. //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";
  5754. //exit;
  5755. // Define list of countries to use to search VAT rates to show
  5756. // First we defined code_country to use to find list
  5757. if (is_object($societe_vendeuse)) {
  5758. $code_country = "'" . $societe_vendeuse->country_code . "'";
  5759. } else {
  5760. $code_country = "'" . $mysoc->country_code . "'"; // Pour compatibilite ascendente
  5761. }
  5762. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5763. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  5764. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5765. // We also add the buyer country code
  5766. if (is_numeric($type)) {
  5767. if ($type == 1) { // We know product is a service
  5768. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5769. }
  5770. } elseif (!$idprod) { // We don't know type of product
  5771. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5772. } else {
  5773. $prodstatic = new Product($this->db);
  5774. $prodstatic->fetch($idprod);
  5775. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5776. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5777. }
  5778. }
  5779. }
  5780. }
  5781. // Now we get list
  5782. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5783. if ($num > 0) {
  5784. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5785. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5786. $tmpthirdparty = new Societe($this->db);
  5787. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5788. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5789. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5790. $defaultcode = $reg[1];
  5791. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5792. }
  5793. if (empty($defaulttx)) {
  5794. $defaultnpr = 0;
  5795. }
  5796. }
  5797. // If we fails to find a default vat rate, we take the last one in list
  5798. // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
  5799. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5800. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5801. // We take the last one found in list
  5802. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5803. } else {
  5804. // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
  5805. $defaulttx = '';
  5806. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5807. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5808. }
  5809. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5810. $defaultcode = $reg[1];
  5811. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5812. }
  5813. }
  5814. }
  5815. // Disabled if seller is not subject to VAT
  5816. $disabled = false;
  5817. $title = '';
  5818. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5819. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5820. // of using supplier invoices (this is a very bad idea !)
  5821. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5822. $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
  5823. $disabled = true;
  5824. }
  5825. }
  5826. if (!$options_only) {
  5827. $return .= '<select class="flat minwidth50imp maxwidth100" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
  5828. }
  5829. $selectedfound = false;
  5830. foreach ($this->cache_vatrates as $rate) {
  5831. // Keep only 0 if seller is not subject to VAT
  5832. if ($disabled && $rate['txtva'] != 0) {
  5833. continue;
  5834. }
  5835. // Define key to use into select list
  5836. $key = $rate['txtva'];
  5837. $key .= $rate['nprtva'] ? '*' : '';
  5838. if ($mode > 0 && $rate['code']) {
  5839. $key .= ' (' . $rate['code'] . ')';
  5840. }
  5841. if ($mode < 0) {
  5842. $key = $rate['rowid'];
  5843. }
  5844. $return .= '<option value="' . $key . '"';
  5845. if (!$selectedfound) {
  5846. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5847. if ($defaultcode == $rate['code']) {
  5848. $return .= ' selected';
  5849. $selectedfound = true;
  5850. }
  5851. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5852. $return .= ' selected';
  5853. $selectedfound = true;
  5854. }
  5855. }
  5856. $return .= '>';
  5857. // Show label of VAT
  5858. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5859. // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
  5860. $return .= $rate['labelpositiverates'];
  5861. } else {
  5862. // Simple label
  5863. $return .= vatrate($rate['label']);
  5864. }
  5865. //$return.=($rate['code']?' '.$rate['code']:'');
  5866. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5867. $return .= '</option>';
  5868. }
  5869. if (!$options_only) {
  5870. $return .= '</select>';
  5871. //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
  5872. }
  5873. } else {
  5874. $return .= $this->error;
  5875. }
  5876. $this->num = $num;
  5877. return $return;
  5878. }
  5879. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5880. /**
  5881. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5882. * Fields are preselected with :
  5883. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5884. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5885. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5886. *
  5887. * @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).
  5888. * @param string $prefix Prefix for fields name
  5889. * @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
  5890. * @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
  5891. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5892. * @param string $form_name Not used
  5893. * @param int $d 1=Show days, month, years
  5894. * @param int $addnowlink Add a link "Now"
  5895. * @param int $nooutput Do not output html string but return it
  5896. * @param int $disabled Disable input fields
  5897. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5898. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5899. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5900. * @return string '' or HTML component string if nooutput is 1
  5901. * @deprecated
  5902. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5903. */
  5904. 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 = '')
  5905. {
  5906. // phpcs:enable
  5907. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5908. if (!empty($nooutput)) {
  5909. return $retstring;
  5910. }
  5911. print $retstring;
  5912. return '';
  5913. }
  5914. /**
  5915. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5916. * Fields are preselected with :
  5917. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5918. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5919. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5920. *
  5921. * @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).
  5922. * @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).
  5923. * @param string $prefix Prefix for fields name
  5924. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5925. * @param string $forcenewline Force new line between the 2 dates.
  5926. * @return string Html for selectDate
  5927. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5928. */
  5929. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5930. {
  5931. global $langs;
  5932. $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5933. if ($forcenewline) {
  5934. $ret .= '<br>';
  5935. }
  5936. $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5937. return $ret;
  5938. }
  5939. /**
  5940. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5941. * Fields are preselected with :
  5942. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5943. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5944. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5945. *
  5946. * @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).
  5947. * @param string $prefix Prefix for fields name
  5948. * @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
  5949. * @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
  5950. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5951. * @param string $form_name Not used
  5952. * @param int $d 1=Show days, month, years
  5953. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5954. * @param int $disabled Disable input fields
  5955. * @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')
  5956. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5957. * @param datetime|string $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5958. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5959. * @param int $stepminutes Specify step for minutes between 1 and 30
  5960. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5961. * @param string $placeholder Placeholder
  5962. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5963. * @return string Html for selectDate
  5964. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5965. */
  5966. 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')
  5967. {
  5968. global $conf, $langs;
  5969. if ($gm === 'auto') {
  5970. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5971. }
  5972. $retstring = '';
  5973. if ($prefix == '') {
  5974. $prefix = 're';
  5975. }
  5976. if ($h == '') {
  5977. $h = 0;
  5978. }
  5979. if ($m == '') {
  5980. $m = 0;
  5981. }
  5982. $emptydate = 0;
  5983. $emptyhours = 0;
  5984. if ($stepminutes <= 0 || $stepminutes > 30) {
  5985. $stepminutes = 1;
  5986. }
  5987. if ($empty == 1) {
  5988. $emptydate = 1;
  5989. $emptyhours = 1;
  5990. }
  5991. if ($empty == 2) {
  5992. $emptydate = 0;
  5993. $emptyhours = 1;
  5994. }
  5995. $orig_set_time = $set_time;
  5996. if ($set_time === '' && $emptydate == 0) {
  5997. include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  5998. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5999. $set_time = dol_now($gm);
  6000. } else {
  6001. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  6002. }
  6003. }
  6004. // Analysis of the pre-selection date
  6005. $reg = array();
  6006. $shour = '';
  6007. $smin = '';
  6008. $ssec = '';
  6009. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  6010. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  6011. $syear = (!empty($reg[1]) ? $reg[1] : '');
  6012. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  6013. $sday = (!empty($reg[3]) ? $reg[3] : '');
  6014. $shour = (!empty($reg[4]) ? $reg[4] : '');
  6015. $smin = (!empty($reg[5]) ? $reg[5] : '');
  6016. } elseif (strval($set_time) != '' && $set_time != -1) {
  6017. // set_time est un timestamps (0 possible)
  6018. $syear = dol_print_date($set_time, "%Y", $gm);
  6019. $smonth = dol_print_date($set_time, "%m", $gm);
  6020. $sday = dol_print_date($set_time, "%d", $gm);
  6021. if ($orig_set_time != '') {
  6022. $shour = dol_print_date($set_time, "%H", $gm);
  6023. $smin = dol_print_date($set_time, "%M", $gm);
  6024. $ssec = dol_print_date($set_time, "%S", $gm);
  6025. }
  6026. } else {
  6027. // Date est '' ou vaut -1
  6028. $syear = '';
  6029. $smonth = '';
  6030. $sday = '';
  6031. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  6032. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  6033. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  6034. }
  6035. if ($h == 3) {
  6036. $shour = '';
  6037. }
  6038. if ($m == 3) {
  6039. $smin = '';
  6040. }
  6041. $nowgmt = dol_now('gmt');
  6042. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  6043. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  6044. $usecalendar = 'combo';
  6045. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  6046. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  6047. }
  6048. if ($d) {
  6049. // Show date with popup
  6050. if ($usecalendar != 'combo') {
  6051. $formated_date = '';
  6052. //print "e".$set_time." t ".$conf->format_date_short;
  6053. if (strval($set_time) != '' && $set_time != -1) {
  6054. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  6055. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6056. }
  6057. // Calendrier popup version eldy
  6058. if ($usecalendar == "eldy") {
  6059. // Input area to enter date manually
  6060. $retstring .= '<input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate" maxlength="11" value="' . $formated_date . '"';
  6061. $retstring .= ($disabled ? ' disabled' : '');
  6062. $retstring .= ' onChange="dpChangeDay(\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6063. $retstring .= '>';
  6064. // Icon calendar
  6065. $retstringbuttom = '';
  6066. if (!$disabled) {
  6067. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
  6068. $base = DOL_URL_ROOT . '/core/';
  6069. $retstringbuttom .= ' onClick="showDP(\'' . $base . '\',\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\',\'' . $langs->defaultlang . '\');"';
  6070. $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"') . '</button>';
  6071. } else {
  6072. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6073. }
  6074. $retstring = $retstringbuttom . $retstring;
  6075. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6076. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6077. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6078. } elseif ($usecalendar == 'jquery') {
  6079. if (!$disabled) {
  6080. // Output javascript for datepicker
  6081. $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (date('Y') - 100));
  6082. $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (date('Y') + 100));
  6083. $retstring .= '<script nonce="' . getNonce() . '" type="text/javascript">';
  6084. $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
  6085. dateFormat: '" . $langs->trans("FormatDateShortJQueryInput") . "',
  6086. autoclose: true,
  6087. todayHighlight: true,
  6088. yearRange: '" . $minYear . ":" . $maxYear . "',";
  6089. if (!empty($conf->dol_use_jmobile)) {
  6090. $retstring .= "
  6091. beforeShow: function (input, datePicker) {
  6092. input.disabled = true;
  6093. },
  6094. onClose: function (dateText, datePicker) {
  6095. this.disabled = false;
  6096. },
  6097. ";
  6098. }
  6099. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  6100. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  6101. $retstring .= "
  6102. showOn: 'button', /* both has problem with autocompletion */
  6103. buttonImage: '" . DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png',
  6104. buttonImageOnly: true";
  6105. }
  6106. $retstring .= "
  6107. }) });";
  6108. $retstring .= "</script>";
  6109. }
  6110. // Zone de saisie manuelle de la date
  6111. $retstring .= '<div class="nowraponall inline-block divfordateinput">';
  6112. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  6113. $retstring .= ($disabled ? ' disabled' : '');
  6114. $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
  6115. $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6116. $retstring .= '>';
  6117. // Icone calendrier
  6118. if (!$disabled) {
  6119. /* Not required. Managed by option buttonImage of jquery
  6120. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  6121. $retstring.='<script nonce="'.getNonce().'" type="text/javascript">';
  6122. $retstring.="jQuery(document).ready(function() {";
  6123. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  6124. $retstring.=" jQuery('#".$prefix."').focus();";
  6125. $retstring.=' });';
  6126. $retstring.='});';
  6127. $retstring.="</script>";*/
  6128. } else {
  6129. $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6130. $retsring = $retstringbutton . $retstring;
  6131. }
  6132. $retstring .= '</div>';
  6133. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6134. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6135. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6136. } else {
  6137. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  6138. }
  6139. } else {
  6140. // Show date with combo selects
  6141. // Day
  6142. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
  6143. if ($emptydate || $set_time == -1) {
  6144. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6145. }
  6146. for ($day = 1; $day <= 31; $day++) {
  6147. $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
  6148. }
  6149. $retstring .= "</select>";
  6150. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
  6151. if ($emptydate || $set_time == -1) {
  6152. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6153. }
  6154. // Month
  6155. for ($month = 1; $month <= 12; $month++) {
  6156. $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
  6157. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  6158. $retstring .= "</option>";
  6159. }
  6160. $retstring .= "</select>";
  6161. // Year
  6162. if ($emptydate || $set_time == -1) {
  6163. $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 . '">';
  6164. } else {
  6165. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
  6166. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  6167. $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
  6168. }
  6169. $retstring .= "</select>\n";
  6170. }
  6171. }
  6172. }
  6173. if ($d && $h) {
  6174. $retstring .= ($h == 2 ? '<br>' : ' ');
  6175. $retstring .= '<span class="nowraponall">';
  6176. }
  6177. if ($h) {
  6178. $hourstart = 0;
  6179. $hourend = 24;
  6180. if ($openinghours != '') {
  6181. $openinghours = explode(',', $openinghours);
  6182. $hourstart = $openinghours[0];
  6183. $hourend = $openinghours[1];
  6184. if ($hourend < $hourstart) {
  6185. $hourend = $hourstart;
  6186. }
  6187. }
  6188. // Show hour
  6189. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
  6190. if ($emptyhours) {
  6191. $retstring .= '<option value="-1">&nbsp;</option>';
  6192. }
  6193. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  6194. if (strlen($hour) < 2) {
  6195. $hour = "0" . $hour;
  6196. }
  6197. $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
  6198. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  6199. $retstring .= '</option>';
  6200. }
  6201. $retstring .= '</select>';
  6202. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  6203. if ($m) {
  6204. $retstring .= ":";
  6205. }
  6206. }
  6207. if ($m) {
  6208. // Show minutes
  6209. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
  6210. if ($emptyhours) {
  6211. $retstring .= '<option value="-1">&nbsp;</option>';
  6212. }
  6213. for ($min = 0; $min < 60; $min += $stepminutes) {
  6214. if (strlen($min) < 2) {
  6215. $min = "0" . $min;
  6216. }
  6217. $retstring .= '<option value="' . $min . '"' . (($min == $smin) ? ' selected' : '') . '>' . $min . (empty($conf->dol_optimize_smallscreen) ? '' : '') . '</option>';
  6218. }
  6219. $retstring .= '</select>';
  6220. $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
  6221. }
  6222. if ($d && $h) {
  6223. $retstring .= '</span>';
  6224. }
  6225. // Add a "Now" link
  6226. if (!empty($conf->use_javascript_ajax) && $addnowlink) {
  6227. // Script which will be inserted in the onClick of the "Now" link
  6228. $reset_scripts = "";
  6229. if ($addnowlink == 2) { // local computer time
  6230. // pad add leading 0 on numbers
  6231. $reset_scripts .= "Number.prototype.pad = function(size) {
  6232. var s = String(this);
  6233. while (s.length < (size || 2)) {s = '0' + s;}
  6234. return s;
  6235. };
  6236. var d = new Date();";
  6237. }
  6238. // Generate the date part, depending on the use or not of the javascript calendar
  6239. if ($addnowlink == 1) { // server time expressed in user time setup
  6240. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6241. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6242. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6243. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6244. } elseif ($addnowlink == 2) {
  6245. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6246. * This break application for foreign languages.
  6247. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6248. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6249. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6250. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6251. */
  6252. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6253. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6254. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6255. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6256. }
  6257. /*if ($usecalendar == "eldy")
  6258. {
  6259. $base=DOL_URL_ROOT.'/core/';
  6260. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6261. }
  6262. else
  6263. {
  6264. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6265. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6266. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6267. }*/
  6268. // Update the hour part
  6269. if ($h) {
  6270. if ($fullday) {
  6271. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6272. }
  6273. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6274. if ($addnowlink == 1) {
  6275. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6276. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6277. } elseif ($addnowlink == 2) {
  6278. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
  6279. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6280. }
  6281. if ($fullday) {
  6282. $reset_scripts .= ' } ';
  6283. }
  6284. }
  6285. // Update the minute part
  6286. if ($m) {
  6287. if ($fullday) {
  6288. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6289. }
  6290. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6291. if ($addnowlink == 1) {
  6292. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6293. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6294. } elseif ($addnowlink == 2) {
  6295. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
  6296. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6297. }
  6298. if ($fullday) {
  6299. $reset_scripts .= ' } ';
  6300. }
  6301. }
  6302. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6303. if ($reset_scripts && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6304. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
  6305. $retstring .= $langs->trans("Now");
  6306. $retstring .= '</button> ';
  6307. }
  6308. }
  6309. // Add a "Plus one hour" link
  6310. if ($conf->use_javascript_ajax && $addplusone) {
  6311. // Script which will be inserted in the onClick of the "Add plusone" link
  6312. $reset_scripts = "";
  6313. // Generate the date part, depending on the use or not of the javascript calendar
  6314. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
  6315. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6316. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6317. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6318. // Update the hour part
  6319. if ($h) {
  6320. if ($fullday) {
  6321. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6322. }
  6323. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6324. if ($fullday) {
  6325. $reset_scripts .= ' } ';
  6326. }
  6327. }
  6328. // Update the minute part
  6329. if ($m) {
  6330. if ($fullday) {
  6331. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6332. }
  6333. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6334. if ($fullday) {
  6335. $reset_scripts .= ' } ';
  6336. }
  6337. }
  6338. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6339. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6340. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
  6341. $retstring .= $langs->trans("DateStartPlusOne");
  6342. $retstring .= '</button> ';
  6343. }
  6344. }
  6345. // Add a link to set data
  6346. if ($conf->use_javascript_ajax && $adddateof) {
  6347. $tmparray = dol_getdate($adddateof);
  6348. if (empty($labeladddateof)) {
  6349. $labeladddateof = $langs->trans("DateInvoice");
  6350. }
  6351. $reset_scripts = 'console.log(\'Click on now link\'); ';
  6352. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');';
  6353. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
  6354. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
  6355. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
  6356. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$labeladddateof.'</a>';
  6357. }
  6358. return $retstring;
  6359. }
  6360. /**
  6361. * selectTypeDuration
  6362. *
  6363. * @param string $prefix Prefix
  6364. * @param string $selected Selected duration type
  6365. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6366. * @return string HTML select string
  6367. */
  6368. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6369. {
  6370. global $langs;
  6371. $TDurationTypes = array(
  6372. 'y' => $langs->trans('Years'),
  6373. 'm' => $langs->trans('Month'),
  6374. 'w' => $langs->trans('Weeks'),
  6375. 'd' => $langs->trans('Days'),
  6376. 'h' => $langs->trans('Hours'),
  6377. 'i' => $langs->trans('Minutes')
  6378. );
  6379. // Removed undesired duration types
  6380. foreach ($excludetypes as $value) {
  6381. unset($TDurationTypes[$value]);
  6382. }
  6383. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
  6384. foreach ($TDurationTypes as $key => $typeduration) {
  6385. $retstring .= '<option value="' . $key . '"';
  6386. if ($key == $selected) {
  6387. $retstring .= " selected";
  6388. }
  6389. $retstring .= ">" . $typeduration . "</option>";
  6390. }
  6391. $retstring .= "</select>";
  6392. $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
  6393. return $retstring;
  6394. }
  6395. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6396. /**
  6397. * Function to show a form to select a duration on a page
  6398. *
  6399. * @param string $prefix Prefix for input fields
  6400. * @param int $iSecond Default preselected duration (number of seconds or '')
  6401. * @param int $disabled Disable the combo box
  6402. * @param string $typehour If 'select' then input hour and input min is a combo,
  6403. * If 'text' input hour is in text and input min is a text,
  6404. * If 'textselect' input hour is in text and input min is a combo
  6405. * @param integer $minunderhours If 1, show minutes selection under the hours
  6406. * @param int $nooutput Do not output html string but return it
  6407. * @return string HTML component
  6408. */
  6409. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6410. {
  6411. // phpcs:enable
  6412. global $langs;
  6413. $retstring = '<span class="nowraponall">';
  6414. $hourSelected = '';
  6415. $minSelected = '';
  6416. // Hours
  6417. if ($iSecond != '') {
  6418. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6419. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6420. $minSelected = convertSecondToTime($iSecond, 'min');
  6421. }
  6422. if ($typehour == 'select') {
  6423. $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
  6424. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6425. $retstring .= '<option value="' . $hour . '"';
  6426. if (is_numeric($hourSelected) && $hourSelected == $hour) {
  6427. $retstring .= " selected";
  6428. }
  6429. $retstring .= ">" . $hour . "</option>";
  6430. }
  6431. $retstring .= "</select>";
  6432. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6433. $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour right" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
  6434. } else {
  6435. return 'BadValueForParameterTypeHour';
  6436. }
  6437. if ($typehour != 'text') {
  6438. $retstring .= ' ' . $langs->trans('HourShort');
  6439. } else {
  6440. $retstring .= '<span class="">:</span>';
  6441. }
  6442. // Minutes
  6443. if ($minunderhours) {
  6444. $retstring .= '<br>';
  6445. } else {
  6446. if ($typehour != 'text') {
  6447. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6448. }
  6449. }
  6450. if ($typehour == 'select' || $typehour == 'textselect') {
  6451. $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
  6452. for ($min = 0; $min <= 55; $min = $min + 5) {
  6453. $retstring .= '<option value="' . $min . '"';
  6454. if (is_numeric($minSelected) && $minSelected == $min) {
  6455. $retstring .= ' selected';
  6456. }
  6457. $retstring .= '>' . $min . '</option>';
  6458. }
  6459. $retstring .= "</select>";
  6460. } elseif ($typehour == 'text') {
  6461. $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute right" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
  6462. }
  6463. if ($typehour != 'text') {
  6464. $retstring .= ' ' . $langs->trans('MinuteShort');
  6465. }
  6466. $retstring .= "</span>";
  6467. if (!empty($nooutput)) {
  6468. return $retstring;
  6469. }
  6470. print $retstring;
  6471. return '';
  6472. }
  6473. /**
  6474. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6475. *
  6476. * @param int $selected Preselected tickets
  6477. * @param string $htmlname Name of HTML select field (must be unique in page).
  6478. * @param string $filtertype To add a filter
  6479. * @param int $limit Limit on number of returned lines
  6480. * @param int $status Ticket status
  6481. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6482. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6483. * @param array $ajaxoptions Options for ajax_autocompleter
  6484. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6485. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6486. * @param int $forcecombo Force to use combo box
  6487. * @param string $morecss Add more css on select
  6488. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6489. * @param string $nooutput No print, return the output into a string
  6490. * @return string
  6491. */
  6492. 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)
  6493. {
  6494. global $langs, $conf;
  6495. $out = '';
  6496. // check parameters
  6497. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6498. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6499. $placeholder = '';
  6500. if ($selected && empty($selected_input_value)) {
  6501. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6502. $tickettmpselect = new Ticket($this->db);
  6503. $tickettmpselect->fetch($selected);
  6504. $selected_input_value = $tickettmpselect->ref;
  6505. unset($tickettmpselect);
  6506. }
  6507. $urloption = '';
  6508. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6509. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6510. elseif ($hidelabel > 1) {
  6511. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6512. if ($hidelabel == 2) {
  6513. $out .= img_picto($langs->trans("Search"), 'search');
  6514. }
  6515. }
  6516. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6517. if ($hidelabel == 3) {
  6518. $out .= img_picto($langs->trans("Search"), 'search');
  6519. }
  6520. } else {
  6521. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6522. }
  6523. if (empty($nooutput)) {
  6524. print $out;
  6525. } else {
  6526. return $out;
  6527. }
  6528. return '';
  6529. }
  6530. /**
  6531. * Return list of tickets.
  6532. * Called by selectTickets.
  6533. *
  6534. * @param int $selected Preselected ticket
  6535. * @param string $htmlname Name of select html
  6536. * @param string $filtertype Filter on ticket type
  6537. * @param int $limit Limit on number of returned lines
  6538. * @param string $filterkey Filter on ticket ref or subject
  6539. * @param int $status Ticket status
  6540. * @param int $outputmode 0=HTML select string, 1=Array
  6541. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6542. * @param int $forcecombo Force to use combo box
  6543. * @param string $morecss Add more css on select
  6544. * @return array|string Array of keys for json or HTML component
  6545. */
  6546. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6547. {
  6548. global $langs, $conf;
  6549. $out = '';
  6550. $outarray = array();
  6551. $selectFields = " p.rowid, p.ref, p.message";
  6552. $sql = "SELECT ";
  6553. $sql .= $selectFields;
  6554. $sql .= " FROM " . $this->db->prefix() . "ticket as p";
  6555. $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
  6556. // Add criteria on ref/label
  6557. if ($filterkey != '') {
  6558. $sql .= ' AND (';
  6559. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6560. // For natural search
  6561. $scrit = explode(' ', $filterkey);
  6562. $i = 0;
  6563. if (count($scrit) > 1) $sql .= "(";
  6564. foreach ($scrit as $crit) {
  6565. if ($i > 0) $sql .= " AND ";
  6566. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6567. $sql .= ")";
  6568. $i++;
  6569. }
  6570. if (count($scrit) > 1) $sql .= ")";
  6571. $sql .= ')';
  6572. }
  6573. $sql .= $this->db->plimit($limit, 0);
  6574. // Build output string
  6575. dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
  6576. $result = $this->db->query($sql);
  6577. if ($result) {
  6578. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6579. require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
  6580. $num = $this->db->num_rows($result);
  6581. $events = null;
  6582. if (!$forcecombo) {
  6583. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6584. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6585. }
  6586. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6587. $textifempty = '';
  6588. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6589. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6590. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6591. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6592. else $textifempty .= $langs->trans("All");
  6593. } else {
  6594. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6595. }
  6596. if ($showempty) $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6597. $i = 0;
  6598. while ($num && $i < $num) {
  6599. $opt = '';
  6600. $optJson = array();
  6601. $objp = $this->db->fetch_object($result);
  6602. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6603. // Add new entry
  6604. // "key" value of json key array is used by jQuery automatically as selected value
  6605. // "label" value of json key array is used by jQuery automatically as text for combo box
  6606. $out .= $opt;
  6607. array_push($outarray, $optJson);
  6608. $i++;
  6609. }
  6610. $out .= '</select>';
  6611. $this->db->free($result);
  6612. if (empty($outputmode)) {
  6613. return $out;
  6614. }
  6615. return $outarray;
  6616. } else {
  6617. dol_print_error($this->db);
  6618. }
  6619. return array();
  6620. }
  6621. /**
  6622. * constructTicketListOption.
  6623. * This define value for &$opt and &$optJson.
  6624. *
  6625. * @param object $objp Result set of fetch
  6626. * @param string $opt Option (var used for returned value in string option format)
  6627. * @param array $optJson Option (var used for returned value in json format)
  6628. * @param string $selected Preselected value
  6629. * @param string $filterkey Filter key to highlight
  6630. * @return void
  6631. */
  6632. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6633. {
  6634. $outkey = '';
  6635. $outref = '';
  6636. $outtype = '';
  6637. $outkey = $objp->rowid;
  6638. $outref = $objp->ref;
  6639. $outtype = $objp->fk_product_type;
  6640. $opt = '<option value="' . $objp->rowid . '"';
  6641. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6642. $opt .= '>';
  6643. $opt .= $objp->ref;
  6644. $objRef = $objp->ref;
  6645. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6646. $opt .= "</option>\n";
  6647. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6648. }
  6649. /**
  6650. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6651. *
  6652. * @param int $selected Preselected tickets
  6653. * @param string $htmlname Name of HTML select field (must be unique in page).
  6654. * @param string $filtertype To add a filter
  6655. * @param int $limit Limit on number of returned lines
  6656. * @param int $status Ticket status
  6657. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6658. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6659. * @param array $ajaxoptions Options for ajax_autocompleter
  6660. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6661. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6662. * @param int $forcecombo Force to use combo box
  6663. * @param string $morecss Add more css on select
  6664. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6665. * @param string $nooutput No print, return the output into a string
  6666. * @return string
  6667. */
  6668. 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)
  6669. {
  6670. global $langs, $conf;
  6671. $out = '';
  6672. // check parameters
  6673. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6674. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6675. $placeholder = '';
  6676. if ($selected && empty($selected_input_value)) {
  6677. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6678. $projecttmpselect = new Project($this->db);
  6679. $projecttmpselect->fetch($selected);
  6680. $selected_input_value = $projecttmpselect->ref;
  6681. unset($projecttmpselect);
  6682. }
  6683. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6684. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6685. elseif ($hidelabel > 1) {
  6686. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6687. if ($hidelabel == 2) {
  6688. $out .= img_picto($langs->trans("Search"), 'search');
  6689. }
  6690. }
  6691. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6692. if ($hidelabel == 3) {
  6693. $out .= img_picto($langs->trans("Search"), 'search');
  6694. }
  6695. } else {
  6696. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6697. }
  6698. if (empty($nooutput)) {
  6699. print $out;
  6700. } else {
  6701. return $out;
  6702. }
  6703. return '';
  6704. }
  6705. /**
  6706. * Return list of projects.
  6707. * Called by selectProjects.
  6708. *
  6709. * @param int $selected Preselected project
  6710. * @param string $htmlname Name of select html
  6711. * @param string $filtertype Filter on project type
  6712. * @param int $limit Limit on number of returned lines
  6713. * @param string $filterkey Filter on project ref or subject
  6714. * @param int $status Ticket status
  6715. * @param int $outputmode 0=HTML select string, 1=Array
  6716. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6717. * @param int $forcecombo Force to use combo box
  6718. * @param string $morecss Add more css on select
  6719. * @return array|string Array of keys for json or HTML component
  6720. */
  6721. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6722. {
  6723. global $langs, $conf;
  6724. $out = '';
  6725. $outarray = array();
  6726. $selectFields = " p.rowid, p.ref";
  6727. $sql = "SELECT ";
  6728. $sql .= $selectFields;
  6729. $sql .= " FROM " . $this->db->prefix() . "projet as p";
  6730. $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
  6731. // Add criteria on ref/label
  6732. if ($filterkey != '') {
  6733. $sql .= ' AND (';
  6734. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6735. // For natural search
  6736. $scrit = explode(' ', $filterkey);
  6737. $i = 0;
  6738. if (count($scrit) > 1) $sql .= "(";
  6739. foreach ($scrit as $crit) {
  6740. if ($i > 0) $sql .= " AND ";
  6741. $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6742. $sql .= "";
  6743. $i++;
  6744. }
  6745. if (count($scrit) > 1) $sql .= ")";
  6746. $sql .= ')';
  6747. }
  6748. $sql .= $this->db->plimit($limit, 0);
  6749. // Build output string
  6750. dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
  6751. $result = $this->db->query($sql);
  6752. if ($result) {
  6753. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6754. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  6755. $num = $this->db->num_rows($result);
  6756. $events = null;
  6757. if (!$forcecombo) {
  6758. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6759. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6760. }
  6761. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6762. $textifempty = '';
  6763. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6764. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6765. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6766. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6767. else $textifempty .= $langs->trans("All");
  6768. } else {
  6769. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6770. }
  6771. if ($showempty) $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6772. $i = 0;
  6773. while ($num && $i < $num) {
  6774. $opt = '';
  6775. $optJson = array();
  6776. $objp = $this->db->fetch_object($result);
  6777. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6778. // Add new entry
  6779. // "key" value of json key array is used by jQuery automatically as selected value
  6780. // "label" value of json key array is used by jQuery automatically as text for combo box
  6781. $out .= $opt;
  6782. array_push($outarray, $optJson);
  6783. $i++;
  6784. }
  6785. $out .= '</select>';
  6786. $this->db->free($result);
  6787. if (empty($outputmode)) {
  6788. return $out;
  6789. }
  6790. return $outarray;
  6791. } else {
  6792. dol_print_error($this->db);
  6793. }
  6794. return array();
  6795. }
  6796. /**
  6797. * constructProjectListOption.
  6798. * This define value for &$opt and &$optJson.
  6799. *
  6800. * @param object $objp Result set of fetch
  6801. * @param string $opt Option (var used for returned value in string option format)
  6802. * @param array $optJson Option (var used for returned value in json format)
  6803. * @param string $selected Preselected value
  6804. * @param string $filterkey Filter key to highlight
  6805. * @return void
  6806. */
  6807. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6808. {
  6809. $outkey = '';
  6810. $outref = '';
  6811. $outtype = '';
  6812. $label = $objp->label;
  6813. $outkey = $objp->rowid;
  6814. $outref = $objp->ref;
  6815. $outlabel = $objp->label;
  6816. $outtype = $objp->fk_product_type;
  6817. $opt = '<option value="' . $objp->rowid . '"';
  6818. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6819. $opt .= '>';
  6820. $opt .= $objp->ref;
  6821. $objRef = $objp->ref;
  6822. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6823. $opt .= "</option>\n";
  6824. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6825. }
  6826. /**
  6827. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6828. *
  6829. * @param int $selected Preselected tickets
  6830. * @param string $htmlname Name of HTML select field (must be unique in page).
  6831. * @param string $filtertype To add a filter
  6832. * @param int $limit Limit on number of returned lines
  6833. * @param int $status Ticket status
  6834. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6835. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6836. * @param array $ajaxoptions Options for ajax_autocompleter
  6837. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6838. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6839. * @param int $forcecombo Force to use combo box
  6840. * @param string $morecss Add more css on select
  6841. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6842. * @param string $nooutput No print, return the output into a string
  6843. * @return string
  6844. */
  6845. 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)
  6846. {
  6847. global $langs, $conf;
  6848. $out = '';
  6849. // check parameters
  6850. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6851. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6852. $placeholder = '';
  6853. $urloption = '';
  6854. if ($selected && empty($selected_input_value)) {
  6855. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  6856. $adherenttmpselect = new Adherent($this->db);
  6857. $adherenttmpselect->fetch($selected);
  6858. $selected_input_value = $adherenttmpselect->ref;
  6859. unset($adherenttmpselect);
  6860. }
  6861. $urloption = '';
  6862. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6863. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6864. elseif ($hidelabel > 1) {
  6865. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6866. if ($hidelabel == 2) {
  6867. $out .= img_picto($langs->trans("Search"), 'search');
  6868. }
  6869. }
  6870. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6871. if ($hidelabel == 3) {
  6872. $out .= img_picto($langs->trans("Search"), 'search');
  6873. }
  6874. } else {
  6875. $filterkey = '';
  6876. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6877. }
  6878. if (empty($nooutput)) {
  6879. print $out;
  6880. } else {
  6881. return $out;
  6882. }
  6883. return '';
  6884. }
  6885. /**
  6886. * Return list of adherents.
  6887. * Called by selectMembers.
  6888. *
  6889. * @param int $selected Preselected adherent
  6890. * @param string $htmlname Name of select html
  6891. * @param string $filtertype Filter on adherent type
  6892. * @param int $limit Limit on number of returned lines
  6893. * @param string $filterkey Filter on member status
  6894. * @param int $status Member status
  6895. * @param int $outputmode 0=HTML select string, 1=Array
  6896. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6897. * @param int $forcecombo Force to use combo box
  6898. * @param string $morecss Add more css on select
  6899. * @return array|string Array of keys for json or HTML string component
  6900. */
  6901. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6902. {
  6903. global $langs, $conf;
  6904. $out = '';
  6905. $outarray = array();
  6906. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6907. $sql = "SELECT ";
  6908. $sql .= $selectFields;
  6909. $sql .= " FROM " . $this->db->prefix() . "adherent as p";
  6910. $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
  6911. // Add criteria on ref/label
  6912. if ($filterkey != '') {
  6913. $sql .= ' AND (';
  6914. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6915. // For natural search
  6916. $scrit = explode(' ', $filterkey);
  6917. $i = 0;
  6918. if (count($scrit) > 1) $sql .= "(";
  6919. foreach ($scrit as $crit) {
  6920. if ($i > 0) $sql .= " AND ";
  6921. $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6922. $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  6923. $i++;
  6924. }
  6925. if (count($scrit) > 1) $sql .= ")";
  6926. $sql .= ')';
  6927. }
  6928. if ($status != -1) {
  6929. $sql .= ' AND statut = ' . ((int) $status);
  6930. }
  6931. $sql .= $this->db->plimit($limit, 0);
  6932. // Build output string
  6933. dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
  6934. $result = $this->db->query($sql);
  6935. if ($result) {
  6936. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  6937. require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
  6938. $num = $this->db->num_rows($result);
  6939. $events = null;
  6940. if (!$forcecombo) {
  6941. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6942. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6943. }
  6944. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6945. $textifempty = '';
  6946. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6947. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6948. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6949. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6950. else $textifempty .= $langs->trans("All");
  6951. } else {
  6952. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6953. }
  6954. if ($showempty) {
  6955. $out .= '<option value="-1" selected>' . $textifempty . '</option>';
  6956. }
  6957. $i = 0;
  6958. while ($num && $i < $num) {
  6959. $opt = '';
  6960. $optJson = array();
  6961. $objp = $this->db->fetch_object($result);
  6962. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6963. // Add new entry
  6964. // "key" value of json key array is used by jQuery automatically as selected value
  6965. // "label" value of json key array is used by jQuery automatically as text for combo box
  6966. $out .= $opt;
  6967. array_push($outarray, $optJson);
  6968. $i++;
  6969. }
  6970. $out .= '</select>';
  6971. $this->db->free($result);
  6972. if (empty($outputmode)) {
  6973. return $out;
  6974. }
  6975. return $outarray;
  6976. } else {
  6977. dol_print_error($this->db);
  6978. }
  6979. return array();
  6980. }
  6981. /**
  6982. * constructMemberListOption.
  6983. * This define value for &$opt and &$optJson.
  6984. *
  6985. * @param object $objp Result set of fetch
  6986. * @param string $opt Option (var used for returned value in string option format)
  6987. * @param array $optJson Option (var used for returned value in json format)
  6988. * @param string $selected Preselected value
  6989. * @param string $filterkey Filter key to highlight
  6990. * @return void
  6991. */
  6992. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6993. {
  6994. $outkey = '';
  6995. $outlabel = '';
  6996. $outtype = '';
  6997. $outkey = $objp->rowid;
  6998. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6999. $outtype = $objp->fk_adherent_type;
  7000. $opt = '<option value="' . $objp->rowid . '"';
  7001. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  7002. $opt .= '>';
  7003. if (!empty($filterkey) && $filterkey != '') {
  7004. $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
  7005. }
  7006. $opt .= $outlabel;
  7007. $opt .= "</option>\n";
  7008. $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
  7009. }
  7010. /**
  7011. * Generic method to select a component from a combo list.
  7012. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  7013. * This is the generic method that will replace all specific existing methods.
  7014. *
  7015. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  7016. * @param string $htmlname Name of HTML select component
  7017. * @param int $preselectedvalue Preselected value (ID of element)
  7018. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7019. * @param string $searchkey Search criteria
  7020. * @param string $placeholder Place holder
  7021. * @param string $morecss More CSS
  7022. * @param string $moreparams More params provided to ajax call
  7023. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7024. * @param int $disabled 1=Html component is disabled
  7025. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  7026. * @return string Return HTML string
  7027. * @see selectForFormsList(), select_thirdparty_list()
  7028. */
  7029. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  7030. {
  7031. global $conf, $user;
  7032. $objecttmp = null;
  7033. // Example of value for $objectdec:
  7034. // Bom:bom/class/bom.class.php:0:t.status=1
  7035. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  7036. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  7037. $InfoFieldList = explode(":", $objectdesc, 4);
  7038. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  7039. $reg = array();
  7040. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  7041. $InfoFieldList[4] = $reg[1]; // take the sort field
  7042. }
  7043. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  7044. $classname = $InfoFieldList[0];
  7045. $classpath = $InfoFieldList[1];
  7046. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  7047. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  7048. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  7049. if (!empty($classpath)) {
  7050. dol_include_once($classpath);
  7051. if ($classname && class_exists($classname)) {
  7052. $objecttmp = new $classname($this->db);
  7053. // Make some replacement
  7054. $sharedentities = getEntity(strtolower($classname));
  7055. $filter = str_replace(
  7056. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  7057. array($conf->entity, $sharedentities, $user->id),
  7058. $filter
  7059. );
  7060. }
  7061. }
  7062. if (!is_object($objecttmp)) {
  7063. dol_syslog('Error bad setup of type for field ' . join(',', $InfoFieldList), LOG_WARNING);
  7064. return 'Error bad setup of type for field ' . join(',', $InfoFieldList);
  7065. }
  7066. //var_dump($filter);
  7067. $prefixforautocompletemode = $objecttmp->element;
  7068. if ($prefixforautocompletemode == 'societe') {
  7069. $prefixforautocompletemode = 'company';
  7070. }
  7071. if ($prefixforautocompletemode == 'product') {
  7072. $prefixforautocompletemode = 'produit';
  7073. }
  7074. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7075. dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
  7076. $out = '';
  7077. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  7078. // No immediate load of all database
  7079. $placeholder = '';
  7080. if ($preselectedvalue && empty($selected_input_value)) {
  7081. $objecttmp->fetch($preselectedvalue);
  7082. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  7083. //unset($objecttmp);
  7084. }
  7085. $objectdesc = $classname . ':' . $classpath . ':' . $addcreatebuttonornot . ':' . $filter;
  7086. $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
  7087. // No immediate load of all database
  7088. $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdesc) . '&filter=' . urlencode($filter) . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
  7089. // Activate the auto complete using ajax call.
  7090. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  7091. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  7092. $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) . '"' : '') . ' />';
  7093. } else {
  7094. // Immediate load of table record.
  7095. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
  7096. }
  7097. return $out;
  7098. }
  7099. /**
  7100. * Output html form to select an object.
  7101. * Note, this function is called by selectForForms or by ajax selectobject.php
  7102. *
  7103. * @param Object $objecttmp Object to knwo the table to scan for combo.
  7104. * @param string $htmlname Name of HTML select component
  7105. * @param int $preselectedvalue Preselected value (ID of element)
  7106. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7107. * @param string $searchkey Search value
  7108. * @param string $placeholder Place holder
  7109. * @param string $morecss More CSS
  7110. * @param string $moreparams More params provided to ajax call
  7111. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7112. * @param int $outputmode 0=HTML select string, 1=Array
  7113. * @param int $disabled 1=Html component is disabled
  7114. * @param string $sortfield Sort field
  7115. * @param string $filter Add more filter
  7116. * @return string|array Return HTML string
  7117. * @see selectForForms()
  7118. */
  7119. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '')
  7120. {
  7121. global $conf, $langs, $user, $hookmanager;
  7122. //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
  7123. $prefixforautocompletemode = $objecttmp->element;
  7124. if ($prefixforautocompletemode == 'societe') {
  7125. $prefixforautocompletemode = 'company';
  7126. }
  7127. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7128. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  7129. $tmpfieldstoshow = '';
  7130. foreach ($objecttmp->fields as $key => $val) {
  7131. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  7132. continue;
  7133. }
  7134. if (!empty($val['showoncombobox'])) {
  7135. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
  7136. }
  7137. }
  7138. if ($tmpfieldstoshow) {
  7139. $fieldstoshow = $tmpfieldstoshow;
  7140. }
  7141. } else {
  7142. // For backward compatibility
  7143. $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'showoncombobox' => 1);
  7144. }
  7145. if (empty($fieldstoshow)) {
  7146. if (isset($objecttmp->fields['ref'])) {
  7147. $fieldstoshow = 't.ref';
  7148. } else {
  7149. $langs->load("errors");
  7150. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  7151. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  7152. }
  7153. }
  7154. $out = '';
  7155. $outarray = array();
  7156. $tmparray = array();
  7157. $num = 0;
  7158. // Search data
  7159. $sql = "SELECT t.rowid, " . $fieldstoshow . " FROM " . $this->db->prefix() . $objecttmp->table_element . " as t";
  7160. if (isset($objecttmp->ismultientitymanaged)) {
  7161. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7162. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  7163. $sql .= " INNER JOIN " . $this->db->prefix() . $tmparray[1] . " as parenttable ON parenttable.rowid = t." . $tmparray[0];
  7164. }
  7165. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7166. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7167. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  7168. }
  7169. }
  7170. }
  7171. // Add where from hooks
  7172. $parameters = array(
  7173. 'object' => $objecttmp,
  7174. 'htmlname' => $htmlname,
  7175. 'filter' => $filter,
  7176. 'searchkey' => $searchkey
  7177. );
  7178. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  7179. if (!empty($hookmanager->resPrint)) {
  7180. $sql .= $hookmanager->resPrint;
  7181. } else {
  7182. $sql .= " WHERE 1=1";
  7183. if (isset($objecttmp->ismultientitymanaged)) {
  7184. if ($objecttmp->ismultientitymanaged == 1) {
  7185. $sql .= " AND t.entity IN (" . getEntity($objecttmp->table_element) . ")";
  7186. }
  7187. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7188. $sql .= " AND parenttable.entity = t." . $tmparray[0];
  7189. }
  7190. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  7191. if ($objecttmp->element == 'societe') {
  7192. $sql .= " AND t.rowid = " . ((int) $user->socid);
  7193. } else {
  7194. $sql .= " AND t.fk_soc = " . ((int) $user->socid);
  7195. }
  7196. }
  7197. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7198. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7199. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  7200. }
  7201. }
  7202. }
  7203. if ($searchkey != '') {
  7204. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  7205. }
  7206. if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  7207. $errormessage = '';
  7208. $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
  7209. if ($errormessage) {
  7210. return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
  7211. }
  7212. }
  7213. }
  7214. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7215. //$sql.=$this->db->plimit($limit, 0);
  7216. //print $sql;
  7217. // Build output string
  7218. $resql = $this->db->query($sql);
  7219. if ($resql) {
  7220. // Construct $out and $outarray
  7221. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
  7222. // 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
  7223. $textifempty = '&nbsp;';
  7224. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7225. if (!empty($conf->global->$confkeyforautocompletemode)) {
  7226. if ($showempty && !is_numeric($showempty)) {
  7227. $textifempty = $langs->trans($showempty);
  7228. } else {
  7229. $textifempty .= $langs->trans("All");
  7230. }
  7231. }
  7232. if ($showempty) {
  7233. $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
  7234. }
  7235. $num = $this->db->num_rows($resql);
  7236. $i = 0;
  7237. if ($num) {
  7238. while ($i < $num) {
  7239. $obj = $this->db->fetch_object($resql);
  7240. $label = '';
  7241. $tmparray = explode(',', $fieldstoshow);
  7242. $oldvalueforshowoncombobox = 0;
  7243. foreach ($tmparray as $key => $val) {
  7244. $val = preg_replace('/t\./', '', $val);
  7245. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7246. $label .= $obj->$val;
  7247. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  7248. }
  7249. if (empty($outputmode)) {
  7250. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7251. $out .= '<option value="' . $obj->rowid . '" selected>' . $label . '</option>';
  7252. } else {
  7253. $out .= '<option value="' . $obj->rowid . '">' . $label . '</option>';
  7254. }
  7255. } else {
  7256. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
  7257. }
  7258. $i++;
  7259. if (($i % 10) == 0) {
  7260. $out .= "\n";
  7261. }
  7262. }
  7263. }
  7264. $out .= '</select>' . "\n";
  7265. if (!$forcecombo) {
  7266. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7267. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  7268. }
  7269. } else {
  7270. dol_print_error($this->db);
  7271. }
  7272. $this->result = array('nbofelement' => $num);
  7273. if ($outputmode) {
  7274. return $outarray;
  7275. }
  7276. return $out;
  7277. }
  7278. /**
  7279. * Return a HTML select string, built from an array of key+value.
  7280. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7281. *
  7282. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7283. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7284. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7285. * @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.
  7286. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7287. * @param int $value_as_key 1 to use value as key
  7288. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7289. * @param int $translate 1=Translate and encode value
  7290. * @param int $maxlen Length maximum for labels
  7291. * @param int $disabled Html select box is disabled
  7292. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7293. * @param string $morecss Add more class to css styles
  7294. * @param int $addjscombo Add js combo
  7295. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7296. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7297. * @param int $nohtmlescape No html escaping.
  7298. * @return string HTML select string.
  7299. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7300. */
  7301. 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)
  7302. {
  7303. global $conf, $langs;
  7304. // Do we want a multiselect ?
  7305. //$jsbeautify = 0;
  7306. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7307. $jsbeautify = 1;
  7308. if ($value_as_key) {
  7309. $array = array_combine($array, $array);
  7310. }
  7311. $out = '';
  7312. if ($addjscombo < 0) {
  7313. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7314. $addjscombo = 1;
  7315. } else {
  7316. $addjscombo = 0;
  7317. }
  7318. }
  7319. $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
  7320. $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . '"';
  7321. $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
  7322. $out .= '>';
  7323. if ($show_empty) {
  7324. $textforempty = ' ';
  7325. if (!empty($conf->use_javascript_ajax)) {
  7326. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7327. }
  7328. if (!is_numeric($show_empty)) {
  7329. $textforempty = $show_empty;
  7330. }
  7331. $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  7332. }
  7333. if (is_array($array)) {
  7334. // Translate
  7335. if ($translate) {
  7336. foreach ($array as $key => $value) {
  7337. if (!is_array($value)) {
  7338. $array[$key] = $langs->trans($value);
  7339. } else {
  7340. $array[$key]['label'] = $langs->trans($value['label']);
  7341. }
  7342. }
  7343. }
  7344. // Sort
  7345. if ($sort == 'ASC') {
  7346. asort($array);
  7347. } elseif ($sort == 'DESC') {
  7348. arsort($array);
  7349. }
  7350. foreach ($array as $key => $tmpvalue) {
  7351. if (is_array($tmpvalue)) {
  7352. $value = $tmpvalue['label'];
  7353. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7354. $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
  7355. } else {
  7356. $value = $tmpvalue;
  7357. $disabled = '';
  7358. $style = '';
  7359. }
  7360. if (!empty($disablebademail)) {
  7361. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7362. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7363. $disabled = ' disabled';
  7364. $style = ' class="warning"';
  7365. }
  7366. }
  7367. if ($key_in_label) {
  7368. if (empty($nohtmlescape)) {
  7369. $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
  7370. } else {
  7371. $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
  7372. }
  7373. } else {
  7374. if (empty($nohtmlescape)) {
  7375. $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
  7376. } else {
  7377. $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
  7378. }
  7379. if ($value == '' || $value == '-') {
  7380. $selectOptionValue = '&nbsp;';
  7381. }
  7382. }
  7383. $out .= '<option value="' . $key . '"';
  7384. $out .= $style . $disabled;
  7385. if (is_array($id)) {
  7386. if (in_array($key, $id) && !$disabled) {
  7387. $out .= ' selected'; // To preselect a value
  7388. }
  7389. } else {
  7390. $id = (string) $id; // if $id = 0, then $id = '0'
  7391. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7392. $out .= ' selected'; // To preselect a value
  7393. }
  7394. }
  7395. if ($nohtmlescape) {
  7396. $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
  7397. }
  7398. if (is_array($tmpvalue)) {
  7399. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7400. if (preg_match('/^data-/', $keyforvalue)) {
  7401. $out .= ' '.$keyforvalue.'="'.dol_escape_htmltag($valueforvalue).'"';
  7402. }
  7403. }
  7404. }
  7405. $out .= '>';
  7406. //var_dump($selectOptionValue);
  7407. $out .= $selectOptionValue;
  7408. $out .= "</option>\n";
  7409. }
  7410. }
  7411. $out .= "</select>";
  7412. // Add code for jquery to use multiselect
  7413. if ($addjscombo && $jsbeautify) {
  7414. // Enhance with select2
  7415. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7416. $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', ($show_empty < 0 ? (string) $show_empty : '-1'), $morecss);
  7417. }
  7418. return $out;
  7419. }
  7420. /**
  7421. * 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.
  7422. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7423. *
  7424. * @param string $htmlname Name of html select area
  7425. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7426. * @param string $id Preselected key
  7427. * @param string $moreparam Add more parameters onto the select tag
  7428. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7429. * @param int $disabled Html select box is disabled
  7430. * @param int $minimumInputLength Minimum Input Length
  7431. * @param string $morecss Add more class to css styles
  7432. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7433. * @param string $placeholder String to use as placeholder
  7434. * @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)
  7435. * @return string HTML select string
  7436. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7437. */
  7438. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7439. {
  7440. global $conf, $langs;
  7441. global $delayedhtmlcontent; // Will be used later outside of this function
  7442. // TODO Use an internal dolibarr component instead of select2
  7443. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7444. return '';
  7445. }
  7446. $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
  7447. $outdelayed = '';
  7448. if (!empty($conf->use_javascript_ajax)) {
  7449. $tmpplugin = 'select2';
  7450. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7451. <script nonce="' . getNonce() . '">
  7452. $(document).ready(function () {
  7453. ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
  7454. $(".' . $htmlname . '").select2({
  7455. ajax: {
  7456. dir: "ltr",
  7457. url: "' . $url . '",
  7458. dataType: \'json\',
  7459. delay: 250,
  7460. data: function (params) {
  7461. return {
  7462. q: params.term, // search term
  7463. page: params.page
  7464. }
  7465. },
  7466. processResults: function (data) {
  7467. // parse the results into the format expected by Select2.
  7468. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7469. //console.log(data);
  7470. saveRemoteData = data;
  7471. /* format json result for select2 */
  7472. result = []
  7473. $.each( data, function( key, value ) {
  7474. result.push({id: key, text: value.text});
  7475. });
  7476. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7477. //console.log(result);
  7478. return {results: result, more: false}
  7479. },
  7480. cache: true
  7481. },
  7482. language: select2arrayoflanguage,
  7483. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7484. placeholder: "' . dol_escape_js($placeholder) . '",
  7485. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7486. minimumInputLength: ' . ((int) $minimumInputLength) . ',
  7487. formatResult: function (result, container, query, escapeMarkup) {
  7488. return escapeMarkup(result.text);
  7489. },
  7490. });
  7491. ' . ($callurlonselect ? '
  7492. /* Code to execute a GET when we select a value */
  7493. $(".' . $htmlname . '").change(function() {
  7494. var selected = $(".' . $htmlname . '").val();
  7495. console.log("We select in selectArrayAjax the entry "+selected)
  7496. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7497. $.each( saveRemoteData, function( key, value ) {
  7498. if (key == selected)
  7499. {
  7500. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7501. location.assign(value.url);
  7502. }
  7503. });
  7504. });' : '') . '
  7505. });
  7506. </script>';
  7507. }
  7508. if ($acceptdelayedhtml) {
  7509. $delayedhtmlcontent .= $outdelayed;
  7510. } else {
  7511. $out .= $outdelayed;
  7512. }
  7513. return $out;
  7514. }
  7515. /**
  7516. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7517. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7518. *
  7519. * @param string $htmlname Name of html select area
  7520. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7521. * @param string $id Preselected key
  7522. * @param string $moreparam Add more parameters onto the select tag
  7523. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7524. * @param int $disabled Html select box is disabled
  7525. * @param int $minimumInputLength Minimum Input Length
  7526. * @param string $morecss Add more class to css styles
  7527. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7528. * @param string $placeholder String to use as placeholder
  7529. * @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)
  7530. * @return string HTML select string
  7531. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7532. */
  7533. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7534. {
  7535. global $conf, $langs;
  7536. global $delayedhtmlcontent; // Will be used later outside of this function
  7537. // TODO Use an internal dolibarr component instead of select2
  7538. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7539. return '';
  7540. }
  7541. $out = '<select type="text" id="'.$htmlname.'" class="'.$htmlname.($morecss ? ' ' . $morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.'"><option></option></select>';
  7542. $formattedarrayresult = array();
  7543. foreach ($array as $key => $value) {
  7544. $o = new stdClass();
  7545. $o->id = $key;
  7546. $o->text = $value['text'];
  7547. $o->url = $value['url'];
  7548. $formattedarrayresult[] = $o;
  7549. }
  7550. $outdelayed = '';
  7551. if (!empty($conf->use_javascript_ajax)) {
  7552. $tmpplugin = 'select2';
  7553. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7554. <script nonce="' . getNonce() . '">
  7555. $(document).ready(function () {
  7556. var data = ' . json_encode($formattedarrayresult) . ';
  7557. ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
  7558. $(".' . $htmlname . '").select2({
  7559. data: data,
  7560. language: select2arrayoflanguage,
  7561. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7562. placeholder: "' . dol_escape_js($placeholder) . '",
  7563. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7564. minimumInputLength: ' . $minimumInputLength . ',
  7565. formatResult: function (result, container, query, escapeMarkup) {
  7566. return escapeMarkup(result.text);
  7567. },
  7568. matcher: function (params, data) {
  7569. if(! data.id) return null;';
  7570. if ($callurlonselect) {
  7571. // We forge the url with 'sall='
  7572. $outdelayed .= '
  7573. var urlBase = data.url;
  7574. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7575. /* console.log("params.term="+params.term); */
  7576. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7577. saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7578. }
  7579. if (!$disableFiltering) {
  7580. $outdelayed .= '
  7581. if(data.text.match(new RegExp(params.term))) {
  7582. return data;
  7583. }
  7584. return null;';
  7585. } else {
  7586. $outdelayed .= '
  7587. return data;';
  7588. }
  7589. $outdelayed .= '
  7590. }
  7591. });
  7592. ' . ($callurlonselect ? '
  7593. /* Code to execute a GET when we select a value */
  7594. $(".' . $htmlname . '").change(function() {
  7595. var selected = $(".' . $htmlname . '").val();
  7596. console.log("We select "+selected)
  7597. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7598. $.each( saveRemoteData, function( key, value ) {
  7599. if (key == selected)
  7600. {
  7601. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7602. location.assign(value.url);
  7603. }
  7604. });
  7605. });' : '') . '
  7606. });
  7607. </script>';
  7608. }
  7609. if ($acceptdelayedhtml) {
  7610. $delayedhtmlcontent .= $outdelayed;
  7611. } else {
  7612. $out .= $outdelayed;
  7613. }
  7614. return $out;
  7615. }
  7616. /**
  7617. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7618. *
  7619. * @param string $htmlname Name of select
  7620. * @param array $array Array(key=>value) or Array(key=>array('id'=> , 'label'=> , 'color'=> , 'picto'=> , 'labelhtml'=> ))
  7621. * @param array $selected Array of keys preselected
  7622. * @param int $key_in_label 1 to show key like in "[key] value"
  7623. * @param int $value_as_key 1 to use value as key
  7624. * @param string $morecss Add more css style
  7625. * @param int $translate Translate and encode value
  7626. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7627. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7628. * @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.
  7629. * @param string $placeholder String to use as placeholder
  7630. * @param int $addjscombo Add js combo
  7631. * @return string HTML multiselect string
  7632. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7633. */
  7634. 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)
  7635. {
  7636. global $conf, $langs;
  7637. $out = '';
  7638. if ($addjscombo < 0) {
  7639. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7640. $addjscombo = 1;
  7641. } else {
  7642. $addjscombo = 0;
  7643. }
  7644. }
  7645. $useenhancedmultiselect = 0;
  7646. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7647. $useenhancedmultiselect = 1;
  7648. }
  7649. // Output select component
  7650. $out .= '<select id="' . $htmlname . '" class="multiselect' . ($useenhancedmultiselect ? ' multiselectononeline' : '') . ($morecss ? ' ' . $morecss : '') . '" multiple name="' . $htmlname . '[]"' . ($moreattrib ? ' ' . $moreattrib : '') . ($width ? ' style="width: ' . (preg_match('/%/', $width) ? $width : $width . 'px') . '"' : '') . '>' . "\n";
  7651. if (is_array($array) && !empty($array)) {
  7652. if ($value_as_key) {
  7653. $array = array_combine($array, $array);
  7654. }
  7655. if (!empty($array)) {
  7656. foreach ($array as $key => $value) {
  7657. $tmpkey = $key;
  7658. $tmpvalue = $value;
  7659. $tmpcolor = '';
  7660. $tmppicto = '';
  7661. $tmplabelhtml = '';
  7662. if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
  7663. $tmpkey = $value['id'];
  7664. $tmpvalue = $value['label'];
  7665. $tmpcolor = $value['color'];
  7666. $tmppicto = $value['picto'];
  7667. $tmplabelhtml = !empty($value['labelhtml']) ? $value['labelhtml'] : '';
  7668. }
  7669. $newval = ($translate ? $langs->trans($tmpvalue) : $tmpvalue);
  7670. $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
  7671. $out .= '<option value="' . $tmpkey . '"';
  7672. if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
  7673. $out .= ' selected';
  7674. }
  7675. if (!empty($tmplabelhtml)) {
  7676. $out .= ' data-html="' . dol_escape_htmltag($tmplabelhtml) . '"';
  7677. } else {
  7678. $out .= ' data-html="' . dol_escape_htmltag(($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval) . '"';
  7679. }
  7680. $out .= '>';
  7681. $out .= dol_htmlentitiesbr($newval);
  7682. $out .= '</option>' . "\n";
  7683. }
  7684. }
  7685. }
  7686. $out .= '</select>' . "\n";
  7687. // Add code for jquery to use multiselect
  7688. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7689. $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
  7690. $out .= "\n" . '<script nonce="' . getNonce() . '">' . "\n";
  7691. if ($addjscombo == 1) {
  7692. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7693. $out .= 'function formatResult(record, container) {' . "\n";
  7694. $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";
  7695. $out .= ' return record.text;';
  7696. $out .= '}' . "\n";
  7697. $out .= 'function formatSelection(record) {' . "\n";
  7698. if ($elemtype == 'category') {
  7699. $out .= 'return \'<span><img src="' . DOL_URL_ROOT . '/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7700. } else {
  7701. $out .= 'return record.text;';
  7702. }
  7703. $out .= '}' . "\n";
  7704. $out .= '$(document).ready(function () {
  7705. $(\'#' . $htmlname . '\').' . $tmpplugin . '({';
  7706. if ($placeholder) {
  7707. $out .= '
  7708. placeholder: {
  7709. id: \'-1\',
  7710. text: \'' . dol_escape_js($placeholder) . '\'
  7711. },';
  7712. }
  7713. $out .= ' dir: \'ltr\',
  7714. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag (ko with multiselect) */
  7715. dropdownCssClass: \'' . $morecss . '\', /* Line to add class on the new <span class="select2-selection...> tag (ok with multiselect) */
  7716. // Specify format function for dropdown item
  7717. formatResult: formatResult,
  7718. templateResult: formatResult, /* For 4.0 */
  7719. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7720. // Specify format function for selected item
  7721. formatSelection: formatSelection,
  7722. templateSelection: formatSelection /* For 4.0 */
  7723. });
  7724. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7725. the size only if component is not hidden by default on load */
  7726. $(\'#' . $htmlname . ' + .select2\').addClass(\'' . $morecss . '\');
  7727. });' . "\n";
  7728. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7729. // Add other js lib
  7730. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7731. // ...
  7732. $out .= 'console.log(\'addjscombo=2 for htmlname=' . $htmlname . '\');';
  7733. $out .= '$(document).ready(function () {
  7734. $(\'#' . $htmlname . '\').multiSelect({
  7735. containerHTML: \'<div class="multi-select-container">\',
  7736. menuHTML: \'<div class="multi-select-menu">\',
  7737. buttonHTML: \'<span class="multi-select-button ' . $morecss . '">\',
  7738. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7739. activeClass: \'multi-select-container--open\',
  7740. noneText: \'' . $placeholder . '\'
  7741. });
  7742. })';
  7743. }
  7744. $out .= '</script>';
  7745. }
  7746. return $out;
  7747. }
  7748. /**
  7749. * 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.
  7750. *
  7751. * @param string $htmlname Name of HTML field
  7752. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7753. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7754. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7755. * @return string HTML multiselect string
  7756. * @see selectarray()
  7757. */
  7758. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7759. {
  7760. global $conf, $langs, $user, $extrafields;
  7761. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7762. return '';
  7763. }
  7764. if (empty($array)) {
  7765. return '';
  7766. }
  7767. $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
  7768. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7769. $tmparray = explode(',', $user->conf->$tmpvar);
  7770. foreach ($array as $key => $val) {
  7771. //var_dump($key);
  7772. //var_dump($tmparray);
  7773. if (in_array($key, $tmparray)) {
  7774. $array[$key]['checked'] = 1;
  7775. } else {
  7776. $array[$key]['checked'] = 0;
  7777. }
  7778. }
  7779. } else { // There is no list of fields already customized for user
  7780. foreach ($array as $key => $val) {
  7781. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7782. $array[$key]['checked'] = 0;
  7783. }
  7784. }
  7785. }
  7786. $listoffieldsforselection = '';
  7787. $listcheckedstring = '';
  7788. foreach ($array as $key => $val) {
  7789. // var_dump($val);
  7790. // var_dump(array_key_exists('enabled', $val));
  7791. // var_dump(!$val['enabled']);
  7792. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7793. unset($array[$key]); // We don't want this field
  7794. continue;
  7795. }
  7796. if (!empty($val['type']) && $val['type'] == 'separate') {
  7797. // Field remains in array but we don't add it into $listoffieldsforselection
  7798. //$listoffieldsforselection .= '<li>-----</li>';
  7799. continue;
  7800. }
  7801. if ($val['label']) {
  7802. if (!empty($val['langfile']) && is_object($langs)) {
  7803. $langs->load($val['langfile']);
  7804. }
  7805. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7806. $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>';
  7807. $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
  7808. }
  7809. }
  7810. $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
  7811. <dl class="dropdown">
  7812. <dt>
  7813. <a href="#' . $htmlname . '">
  7814. ' . img_picto('', 'list') . '
  7815. </a>
  7816. <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
  7817. </dt>
  7818. <dd class="dropdowndd">
  7819. <div class="multiselectcheckbox' . $htmlname . '">
  7820. <ul class="' . $htmlname . ($pos == '1' ? 'left' : '') . '">
  7821. ' . $listoffieldsforselection . '
  7822. </ul>
  7823. </div>
  7824. </dd>
  7825. </dl>
  7826. <script nonce="' . getNonce() . '" type="text/javascript">
  7827. jQuery(document).ready(function () {
  7828. $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on(\'click\', function () {
  7829. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7830. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7831. var title = $(this).val() + ",";
  7832. if ($(this).is(\':checked\')) {
  7833. $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
  7834. }
  7835. else {
  7836. $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
  7837. }
  7838. // Now, we submit page
  7839. //$(this).parents(\'form:first\').submit();
  7840. });
  7841. });
  7842. </script>
  7843. ';
  7844. return $out;
  7845. }
  7846. /**
  7847. * Render list of categories linked to object with id $id and type $type
  7848. *
  7849. * @param int $id Id of object
  7850. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7851. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7852. * @param int $nolink 1=Do not add html links
  7853. * @return string String with categories
  7854. */
  7855. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7856. {
  7857. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  7858. $cat = new Categorie($this->db);
  7859. $categories = $cat->containing($id, $type);
  7860. if ($rendermode == 1) {
  7861. $toprint = array();
  7862. foreach ($categories as $c) {
  7863. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7864. foreach ($ways as $way) {
  7865. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>';
  7866. }
  7867. }
  7868. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  7869. }
  7870. if ($rendermode == 0) {
  7871. $arrayselected = array();
  7872. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7873. foreach ($categories as $c) {
  7874. $arrayselected[] = $c->id;
  7875. }
  7876. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7877. }
  7878. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7879. }
  7880. /**
  7881. * Show linked object block.
  7882. *
  7883. * @param CommonObject $object Object we want to show links to
  7884. * @param string $morehtmlright More html to show on right of title
  7885. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7886. * @param string $title Title
  7887. * @return int <0 if KO, >=0 if OK
  7888. */
  7889. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false, $title = 'RelatedObjects')
  7890. {
  7891. global $conf, $langs, $hookmanager;
  7892. global $bc, $action;
  7893. $object->fetchObjectLinked();
  7894. // Bypass the default method
  7895. $hookmanager->initHooks(array('commonobject'));
  7896. $parameters = array(
  7897. 'morehtmlright' => $morehtmlright,
  7898. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7899. );
  7900. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7901. $nbofdifferenttypes = count($object->linkedObjects);
  7902. if (empty($reshook)) {
  7903. print '<!-- showLinkedObjectBlock -->';
  7904. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7905. print '<div class="div-table-responsive-no-min">';
  7906. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
  7907. print '<tr class="liste_titre">';
  7908. print '<td>' . $langs->trans("Type") . '</td>';
  7909. print '<td>' . $langs->trans("Ref") . '</td>';
  7910. print '<td class="center"></td>';
  7911. print '<td class="center">' . $langs->trans("Date") . '</td>';
  7912. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  7913. print '<td class="right">' . $langs->trans("Status") . '</td>';
  7914. print '<td></td>';
  7915. print '</tr>';
  7916. $nboftypesoutput = 0;
  7917. foreach ($object->linkedObjects as $objecttype => $objects) {
  7918. $tplpath = $element = $subelement = $objecttype;
  7919. // to display inport button on tpl
  7920. $showImportButton = false;
  7921. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7922. $showImportButton = true;
  7923. }
  7924. $regs = array();
  7925. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7926. $element = $regs[1];
  7927. $subelement = $regs[2];
  7928. $tplpath = $element . '/' . $subelement;
  7929. }
  7930. $tplname = 'linkedobjectblock';
  7931. // To work with non standard path
  7932. if ($objecttype == 'facture') {
  7933. $tplpath = 'compta/' . $element;
  7934. if (!isModEnabled('facture')) {
  7935. continue; // Do not show if module disabled
  7936. }
  7937. } elseif ($objecttype == 'facturerec') {
  7938. $tplpath = 'compta/facture';
  7939. $tplname = 'linkedobjectblockForRec';
  7940. if (!isModEnabled('facture')) {
  7941. continue; // Do not show if module disabled
  7942. }
  7943. } elseif ($objecttype == 'propal') {
  7944. $tplpath = 'comm/' . $element;
  7945. if (!isModEnabled('propal')) {
  7946. continue; // Do not show if module disabled
  7947. }
  7948. } elseif ($objecttype == 'supplier_proposal') {
  7949. if (!isModEnabled('supplier_proposal')) {
  7950. continue; // Do not show if module disabled
  7951. }
  7952. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
  7953. $tplpath = 'expedition';
  7954. if (!isModEnabled('expedition')) {
  7955. continue; // Do not show if module disabled
  7956. }
  7957. } elseif ($objecttype == 'reception') {
  7958. $tplpath = 'reception';
  7959. if (!isModEnabled('reception')) {
  7960. continue; // Do not show if module disabled
  7961. }
  7962. } elseif ($objecttype == 'delivery') {
  7963. $tplpath = 'delivery';
  7964. if (!isModEnabled('expedition')) {
  7965. continue; // Do not show if module disabled
  7966. }
  7967. } elseif ($objecttype == 'ficheinter') {
  7968. $tplpath = 'fichinter';
  7969. if (!isModEnabled('ficheinter')) {
  7970. continue; // Do not show if module disabled
  7971. }
  7972. } elseif ($objecttype == 'invoice_supplier') {
  7973. $tplpath = 'fourn/facture';
  7974. } elseif ($objecttype == 'order_supplier') {
  7975. $tplpath = 'fourn/commande';
  7976. } elseif ($objecttype == 'expensereport') {
  7977. $tplpath = 'expensereport';
  7978. } elseif ($objecttype == 'subscription') {
  7979. $tplpath = 'adherents';
  7980. } elseif ($objecttype == 'conferenceorbooth') {
  7981. $tplpath = 'eventorganization';
  7982. } elseif ($objecttype == 'conferenceorboothattendee') {
  7983. $tplpath = 'eventorganization';
  7984. } elseif ($objecttype == 'mo') {
  7985. $tplpath = 'mrp';
  7986. if (!isModEnabled('mrp')) {
  7987. continue; // Do not show if module disabled
  7988. }
  7989. }
  7990. global $linkedObjectBlock;
  7991. $linkedObjectBlock = $objects;
  7992. // Output template part (modules that overwrite templates must declare this into descriptor)
  7993. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
  7994. foreach ($dirtpls as $reldir) {
  7995. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7996. global $noMoreLinkedObjectBlockAfter;
  7997. $noMoreLinkedObjectBlockAfter = 1;
  7998. }
  7999. $res = @include dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
  8000. if ($res) {
  8001. $nboftypesoutput++;
  8002. break;
  8003. }
  8004. }
  8005. }
  8006. if (!$nboftypesoutput) {
  8007. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
  8008. }
  8009. print '</table>';
  8010. if (!empty($compatibleImportElementsList)) {
  8011. $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
  8012. }
  8013. print '</div>';
  8014. }
  8015. return $nbofdifferenttypes;
  8016. }
  8017. /**
  8018. * Show block with links to link to other objects.
  8019. *
  8020. * @param CommonObject $object Object we want to show links to
  8021. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  8022. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  8023. * @return string HTML block
  8024. */
  8025. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  8026. {
  8027. global $conf, $langs, $hookmanager;
  8028. global $action;
  8029. $linktoelem = '';
  8030. $linktoelemlist = '';
  8031. $listofidcompanytoscan = '';
  8032. if (!is_object($object->thirdparty)) {
  8033. $object->fetch_thirdparty();
  8034. }
  8035. $possiblelinks = array();
  8036. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  8037. $listofidcompanytoscan = $object->thirdparty->id;
  8038. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  8039. $listofidcompanytoscan .= ',' . $object->thirdparty->parent;
  8040. }
  8041. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  8042. include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  8043. $tmpproject = new Project($this->db);
  8044. $tmpproject->fetch($object->fk_project);
  8045. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  8046. $listofidcompanytoscan .= ',' . $tmpproject->socid;
  8047. }
  8048. unset($tmpproject);
  8049. }
  8050. $possiblelinks = array(
  8051. 'propal' => array(
  8052. 'enabled' => isModEnabled('propal'),
  8053. 'perms' => 1,
  8054. 'label' => 'LinkToProposal',
  8055. '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') . ')'),
  8056. 'shipping' => array(
  8057. 'enabled' => isModEnabled('expedition'),
  8058. 'perms' => 1,
  8059. 'label' => 'LinkToExpedition',
  8060. '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') . ')'),
  8061. 'order' => array(
  8062. 'enabled' => isModEnabled('commande'),
  8063. 'perms' => 1,
  8064. 'label' => 'LinkToOrder',
  8065. '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') . ')'),
  8066. 'invoice' => array(
  8067. 'enabled' => isModEnabled('facture'),
  8068. 'perms' => 1,
  8069. 'label' => 'LinkToInvoice',
  8070. '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') . ')'),
  8071. 'invoice_template' => array(
  8072. 'enabled' => isModEnabled('facture'),
  8073. 'perms' => 1,
  8074. 'label' => 'LinkToTemplateInvoice',
  8075. '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') . ')'),
  8076. 'contrat' => array(
  8077. 'enabled' => isModEnabled('contrat'),
  8078. 'perms' => 1,
  8079. 'label' => 'LinkToContract',
  8080. '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
  8081. 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'
  8082. ),
  8083. 'fichinter' => array(
  8084. 'enabled' => isModEnabled('ficheinter'),
  8085. 'perms' => 1,
  8086. 'label' => 'LinkToIntervention',
  8087. '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') . ')'),
  8088. 'supplier_proposal' => array(
  8089. 'enabled' => (isModEnabled('supplier_proposal') ? $conf->supplier_proposal->enabled : 0),
  8090. 'perms' => 1,
  8091. 'label' => 'LinkToSupplierProposal',
  8092. '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') . ')'),
  8093. 'order_supplier' => array(
  8094. 'enabled' => (isModEnabled("supplier_order") ? $conf->supplier_order->enabled : 0),
  8095. 'perms' => 1,
  8096. 'label' => 'LinkToSupplierOrder',
  8097. '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') . ')'),
  8098. 'invoice_supplier' => array(
  8099. 'enabled' => (isModEnabled("supplier_invoice") ? $conf->supplier_invoice->enabled : 0),
  8100. 'perms' => 1, 'label' => 'LinkToSupplierInvoice',
  8101. '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') . ')'),
  8102. 'ticket' => array(
  8103. 'enabled' => isModEnabled('ticket'),
  8104. 'perms' => 1,
  8105. 'label' => 'LinkToTicket',
  8106. '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') . ')'),
  8107. 'mo' => array(
  8108. 'enabled' => isModEnabled('mrp'),
  8109. 'perms' => 1,
  8110. 'label' => 'LinkToMo',
  8111. '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') . ')')
  8112. );
  8113. }
  8114. if ($object->table_element == 'commande_fournisseur') {
  8115. $possiblelinks['mo']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM ".$this->db->prefix()."societe as s INNER JOIN ".$this->db->prefix().'mrp_mo as t ON t.fk_soc = s.rowid WHERE t.entity IN ('.getEntity('mo').')';
  8116. } elseif ($object->table_element == 'mrp_mo') {
  8117. $possiblelinks['order_supplier']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix().'commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.entity IN ('.getEntity('commande_fournisseur').')';
  8118. }
  8119. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  8120. // Can complete the possiblelink array
  8121. $hookmanager->initHooks(array('commonobject'));
  8122. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  8123. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8124. }
  8125. if (empty($reshook)) {
  8126. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8127. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  8128. }
  8129. } elseif ($reshook > 0) {
  8130. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8131. $possiblelinks = $hookmanager->resArray;
  8132. }
  8133. }
  8134. foreach ($possiblelinks as $key => $possiblelink) {
  8135. $num = 0;
  8136. if (empty($possiblelink['enabled'])) {
  8137. continue;
  8138. }
  8139. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  8140. print '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
  8141. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8142. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  8143. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8144. print '<input type="hidden" name="action" value="addlinkbyref">';
  8145. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8146. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8147. print '<table class="noborder">';
  8148. print '<tr>';
  8149. print '<td>' . $langs->trans("Ref") . '</td>';
  8150. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;';
  8151. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
  8152. print '<input type="submit" class="button smallpaddingimp" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  8153. print '</tr>';
  8154. print '</table>';
  8155. print '</form>';
  8156. }
  8157. $sql = $possiblelink['sql'];
  8158. $resqllist = $this->db->query($sql);
  8159. if ($resqllist) {
  8160. $num = $this->db->num_rows($resqllist);
  8161. $i = 0;
  8162. print '<br>';
  8163. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
  8164. print '<input type="hidden" name="action" value="addlink">';
  8165. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8166. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8167. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8168. print '<table class="noborder">';
  8169. print '<tr class="liste_titre">';
  8170. print '<td class="nowrap"></td>';
  8171. print '<td class="center">' . $langs->trans("Ref") . '</td>';
  8172. print '<td class="left">' . $langs->trans("RefCustomer") . '</td>';
  8173. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  8174. print '<td class="left">' . $langs->trans("Company") . '</td>';
  8175. print '</tr>';
  8176. while ($i < $num) {
  8177. $objp = $this->db->fetch_object($resqllist);
  8178. print '<tr class="oddeven">';
  8179. print '<td class="left">';
  8180. print '<input type="radio" name="idtolinkto" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
  8181. print '</td>';
  8182. print '<td class="center"><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
  8183. print '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
  8184. print '<td class="right">';
  8185. if ($possiblelink['label'] == 'LinkToContract') {
  8186. $form = new Form($this->db);
  8187. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
  8188. }
  8189. print '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
  8190. print '</td>';
  8191. print '<td>' . $objp->name . '</td>';
  8192. print '</tr>';
  8193. $i++;
  8194. }
  8195. print '</table>';
  8196. print '<div class="center">';
  8197. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="' . $langs->trans('ToLink') . '">';
  8198. if (empty($conf->use_javascript_ajax)) {
  8199. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8200. } else {
  8201. print '<input type="submit" onclick="jQuery(\'#' . $key . 'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8202. }
  8203. print '</form>';
  8204. $this->db->free($resqllist);
  8205. } else {
  8206. dol_print_error($this->db);
  8207. }
  8208. print '</div>';
  8209. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  8210. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8211. $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $num . ')</a></li>';
  8212. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  8213. } else {
  8214. $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  8215. }
  8216. }
  8217. }
  8218. if ($linktoelemlist) {
  8219. $linktoelem = '
  8220. <dl class="dropdown" id="linktoobjectname">
  8221. ';
  8222. if (!empty($conf->use_javascript_ajax)) {
  8223. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
  8224. }
  8225. $linktoelem .= '<dd>
  8226. <div class="multiselectlinkto">
  8227. <ul class="ulselectedfields">' . $linktoelemlist . '
  8228. </ul>
  8229. </div>
  8230. </dd>
  8231. </dl>';
  8232. } else {
  8233. $linktoelem = '';
  8234. }
  8235. if (!empty($conf->use_javascript_ajax)) {
  8236. print '<!-- Add js to show linkto box -->
  8237. <script nonce="' . getNonce() . '">
  8238. jQuery(document).ready(function() {
  8239. jQuery(".linkto").click(function() {
  8240. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  8241. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  8242. });
  8243. });
  8244. </script>
  8245. ';
  8246. }
  8247. return $linktoelem;
  8248. }
  8249. /**
  8250. * Return an html string with a select combo box to choose yes or no
  8251. *
  8252. * @param string $htmlname Name of html select field
  8253. * @param string $value Pre-selected value
  8254. * @param int $option 0 return yes/no, 1 return 1/0
  8255. * @param bool $disabled true or false
  8256. * @param int $useempty 1=Add empty line
  8257. * @param int $addjscombo 1=Add js beautifier on combo box
  8258. * @param string $morecss More CSS
  8259. * @param string $labelyes Label for Yes
  8260. * @param string $labelno Label for No
  8261. * @return string See option
  8262. */
  8263. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8264. {
  8265. global $langs;
  8266. $yes = "yes";
  8267. $no = "no";
  8268. if ($option) {
  8269. $yes = "1";
  8270. $no = "0";
  8271. }
  8272. $disabled = ($disabled ? ' disabled' : '');
  8273. $resultyesno = '<select class="flat width75' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
  8274. if ($useempty) {
  8275. $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8276. }
  8277. if (("$value" == 'yes') || ($value == 1)) {
  8278. $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
  8279. $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
  8280. } else {
  8281. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8282. $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
  8283. $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
  8284. }
  8285. $resultyesno .= '</select>' . "\n";
  8286. if ($addjscombo) {
  8287. $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
  8288. }
  8289. return $resultyesno;
  8290. }
  8291. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8292. /**
  8293. * Return list of export templates
  8294. *
  8295. * @param string $selected Id modele pre-selectionne
  8296. * @param string $htmlname Name of HTML select
  8297. * @param string $type Type of searched templates
  8298. * @param int $useempty Affiche valeur vide dans liste
  8299. * @return void
  8300. */
  8301. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8302. {
  8303. // phpcs:enable
  8304. $sql = "SELECT rowid, label";
  8305. $sql .= " FROM " . $this->db->prefix() . "export_model";
  8306. $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
  8307. $sql .= " ORDER BY rowid";
  8308. $result = $this->db->query($sql);
  8309. if ($result) {
  8310. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  8311. if ($useempty) {
  8312. print '<option value="-1">&nbsp;</option>';
  8313. }
  8314. $num = $this->db->num_rows($result);
  8315. $i = 0;
  8316. while ($i < $num) {
  8317. $obj = $this->db->fetch_object($result);
  8318. if ($selected == $obj->rowid) {
  8319. print '<option value="' . $obj->rowid . '" selected>';
  8320. } else {
  8321. print '<option value="' . $obj->rowid . '">';
  8322. }
  8323. print $obj->label;
  8324. print '</option>';
  8325. $i++;
  8326. }
  8327. print "</select>";
  8328. } else {
  8329. dol_print_error($this->db);
  8330. }
  8331. }
  8332. /**
  8333. * Return a HTML area with the reference of object and a navigation bar for a business object
  8334. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8335. *
  8336. * @param object $object Object to show.
  8337. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8338. * @param string $morehtml More html content to output just before the nav bar.
  8339. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8340. * @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.
  8341. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8342. * @param string $morehtmlref More html to show after ref.
  8343. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8344. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8345. * @param string $morehtmlleft More html code to show before ref.
  8346. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8347. * @param string $morehtmlright More html code to show after ref.
  8348. * @return string Portion HTML with ref + navigation buttons
  8349. */
  8350. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8351. {
  8352. global $conf, $langs, $hookmanager, $extralanguages;
  8353. $ret = '';
  8354. if (empty($fieldid)) {
  8355. $fieldid = 'rowid';
  8356. }
  8357. if (empty($fieldref)) {
  8358. $fieldref = 'ref';
  8359. }
  8360. // Preparing gender's display if there is one
  8361. $addgendertxt = '';
  8362. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8363. $addgendertxt = ' ';
  8364. switch ($object->gender) {
  8365. case 'man':
  8366. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8367. break;
  8368. case 'woman':
  8369. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8370. break;
  8371. case 'other':
  8372. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8373. break;
  8374. }
  8375. }
  8376. /*
  8377. $addadmin = '';
  8378. if (property_exists($object, 'admin')) {
  8379. if (isModEnabled('multicompany') && !empty($object->admin) && empty($object->entity)) {
  8380. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8381. } elseif (!empty($object->admin)) {
  8382. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8383. }
  8384. }*/
  8385. // Add where from hooks
  8386. if (is_object($hookmanager)) {
  8387. $parameters = array('showrefnav' => true);
  8388. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8389. $object->next_prev_filter .= $hookmanager->resPrint;
  8390. }
  8391. $previous_ref = $next_ref = '';
  8392. if ($shownav) {
  8393. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8394. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8395. $navurl = $_SERVER["PHP_SELF"];
  8396. // Special case for project/task page
  8397. if ($paramid == 'project_ref') {
  8398. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8399. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8400. $paramid = 'ref';
  8401. }
  8402. }
  8403. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8404. // accesskey is for Mac: CTRL + key for all browsers
  8405. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8406. if ($conf->browser->name == 'chrome') {
  8407. $stringforfirstkey .= ' ALT +';
  8408. } elseif ($conf->browser->name == 'firefox') {
  8409. $stringforfirstkey .= ' ALT + SHIFT +';
  8410. } else {
  8411. $stringforfirstkey .= ' CTL +';
  8412. }
  8413. $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>';
  8414. $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>';
  8415. }
  8416. //print "xx".$previous_ref."x".$next_ref;
  8417. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8418. // Right part of banner
  8419. if ($morehtmlright) {
  8420. $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
  8421. }
  8422. if ($previous_ref || $next_ref || $morehtml) {
  8423. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8424. }
  8425. if ($morehtml) {
  8426. $ret .= '<li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
  8427. }
  8428. if ($shownav && ($previous_ref || $next_ref)) {
  8429. $ret .= '<li class="pagination">' . $previous_ref . '</li>';
  8430. $ret .= '<li class="pagination">' . $next_ref . '</li>';
  8431. }
  8432. if ($previous_ref || $next_ref || $morehtml) {
  8433. $ret .= '</ul></div>';
  8434. }
  8435. $parameters = array();
  8436. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8437. if (empty($reshook)) {
  8438. $morehtmlstatus .= $hookmanager->resPrint;
  8439. } else {
  8440. $morehtmlstatus = $hookmanager->resPrint;
  8441. }
  8442. if ($morehtmlstatus) {
  8443. $ret .= '<div class="statusref">' . $morehtmlstatus . '</div>';
  8444. }
  8445. $parameters = array();
  8446. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8447. if (empty($reshook)) {
  8448. $morehtmlref .= $hookmanager->resPrint;
  8449. } elseif ($reshook > 0) {
  8450. $morehtmlref = $hookmanager->resPrint;
  8451. }
  8452. // Left part of banner
  8453. if ($morehtmlleft) {
  8454. if ($conf->browser->layout == 'phone') {
  8455. $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>';
  8456. } else {
  8457. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
  8458. }
  8459. }
  8460. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8461. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
  8462. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8463. if ($object->element == 'societe') {
  8464. $ret .= dol_htmlentities($object->name);
  8465. // List of extra languages
  8466. $arrayoflangcode = array();
  8467. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8468. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8469. }
  8470. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8471. if (!is_object($extralanguages)) {
  8472. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  8473. $extralanguages = new ExtraLanguages($this->db);
  8474. }
  8475. $extralanguages->fetch_name_extralanguages('societe');
  8476. if (!empty($extralanguages->attributes['societe']['name'])) {
  8477. $object->fetchValuesForExtraLanguages();
  8478. $htmltext = '';
  8479. // If there is extra languages
  8480. foreach ($arrayoflangcode as $extralangcode) {
  8481. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8482. if ($object->array_languages['name'][$extralangcode]) {
  8483. $htmltext .= $object->array_languages['name'][$extralangcode];
  8484. } else {
  8485. $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
  8486. }
  8487. }
  8488. $ret .= '<!-- Show translations of name -->' . "\n";
  8489. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8490. }
  8491. }
  8492. } elseif ($object->element == 'member') {
  8493. $ret .= $object->ref . '<br>';
  8494. $fullname = $object->getFullName($langs);
  8495. if ($object->morphy == 'mor' && $object->societe) {
  8496. $ret .= dol_htmlentities($object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '');
  8497. } else {
  8498. $ret .= dol_htmlentities($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities($object->societe) . ')' : '');
  8499. }
  8500. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8501. $ret .= dol_htmlentities($object->getFullName($langs)) . $addgendertxt;
  8502. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8503. $ret .= $object->ref . '<br>' . $object->label;
  8504. } elseif (in_array($object->element, array('adherent_type'))) {
  8505. $ret .= $object->label;
  8506. } elseif ($object->element == 'ecm_directories') {
  8507. $ret .= '';
  8508. } elseif ($fieldref != 'none') {
  8509. $ret .= dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "");
  8510. }
  8511. if ($morehtmlref) {
  8512. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8513. if (substr($morehtmlref, 0, 4) != '<div') {
  8514. $ret .= ' ';
  8515. }
  8516. $ret .= $morehtmlref;
  8517. }
  8518. $ret .= '</div>';
  8519. $ret .= '</div><!-- End banner content -->';
  8520. return $ret;
  8521. }
  8522. /**
  8523. * Return HTML code to output a barcode
  8524. *
  8525. * @param Object $object Object containing data to retrieve file name
  8526. * @param int $width Width of photo
  8527. * @param string $morecss More CSS on img of barcode
  8528. * @return string HTML code to output barcode
  8529. */
  8530. public function showbarcode(&$object, $width = 100, $morecss = '')
  8531. {
  8532. global $conf;
  8533. //Check if barcode is filled in the card
  8534. if (empty($object->barcode)) {
  8535. return '';
  8536. }
  8537. // Complete object if not complete
  8538. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8539. $result = $object->fetch_barcode();
  8540. //Check if fetch_barcode() failed
  8541. if ($result < 1) {
  8542. return '<!-- ErrorFetchBarcode -->';
  8543. }
  8544. }
  8545. // Barcode image
  8546. $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
  8547. $out = '<!-- url barcode = ' . $url . ' -->';
  8548. $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
  8549. return $out;
  8550. }
  8551. /**
  8552. * Return HTML code to output a photo
  8553. *
  8554. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8555. * @param object $object Object containing data to retrieve file name
  8556. * @param int $width Width of photo
  8557. * @param int $height Height of photo (auto if 0)
  8558. * @param int $caneditfield Add edit fields
  8559. * @param string $cssclass CSS name to use on img for photo
  8560. * @param string $imagesize 'mini', 'small' or '' (original)
  8561. * @param int $addlinktofullsize Add link to fullsize image
  8562. * @param int $cache 1=Accept to use image in cache
  8563. * @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 ''.
  8564. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8565. * @return string HTML code to output photo
  8566. */
  8567. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8568. {
  8569. global $conf, $langs;
  8570. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8571. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8572. $ret = '';
  8573. $dir = '';
  8574. $file = '';
  8575. $originalfile = '';
  8576. $altfile = '';
  8577. $email = '';
  8578. $capture = '';
  8579. if ($modulepart == 'societe') {
  8580. $dir = $conf->societe->multidir_output[$entity];
  8581. if (!empty($object->logo)) {
  8582. if (dolIsAllowedForPreview($object->logo)) {
  8583. if ((string) $imagesize == 'mini') {
  8584. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8585. } elseif ((string) $imagesize == 'small') {
  8586. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
  8587. } else {
  8588. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8589. }
  8590. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8591. }
  8592. }
  8593. $email = $object->email;
  8594. } elseif ($modulepart == 'contact') {
  8595. $dir = $conf->societe->multidir_output[$entity] . '/contact';
  8596. if (!empty($object->photo)) {
  8597. if (dolIsAllowedForPreview($object->photo)) {
  8598. if ((string) $imagesize == 'mini') {
  8599. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8600. } elseif ((string) $imagesize == 'small') {
  8601. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8602. } else {
  8603. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8604. }
  8605. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8606. }
  8607. }
  8608. $email = $object->email;
  8609. $capture = 'user';
  8610. } elseif ($modulepart == 'userphoto') {
  8611. $dir = $conf->user->dir_output;
  8612. if (!empty($object->photo)) {
  8613. if (dolIsAllowedForPreview($object->photo)) {
  8614. if ((string) $imagesize == 'mini') {
  8615. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8616. } elseif ((string) $imagesize == 'small') {
  8617. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8618. } else {
  8619. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8620. }
  8621. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8622. }
  8623. }
  8624. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8625. $altfile = $object->id . ".jpg"; // For backward compatibility
  8626. }
  8627. $email = $object->email;
  8628. $capture = 'user';
  8629. } elseif ($modulepart == 'memberphoto') {
  8630. $dir = $conf->adherent->dir_output;
  8631. if (!empty($object->photo)) {
  8632. if (dolIsAllowedForPreview($object->photo)) {
  8633. if ((string) $imagesize == 'mini') {
  8634. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8635. } elseif ((string) $imagesize == 'small') {
  8636. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8637. } else {
  8638. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8639. }
  8640. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8641. }
  8642. }
  8643. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8644. $altfile = $object->id . ".jpg"; // For backward compatibility
  8645. }
  8646. $email = $object->email;
  8647. $capture = 'user';
  8648. } else {
  8649. // Generic case to show photos
  8650. $dir = $conf->$modulepart->dir_output;
  8651. if (!empty($object->photo)) {
  8652. if (dolIsAllowedForPreview($object->photo)) {
  8653. if ((string) $imagesize == 'mini') {
  8654. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8655. } elseif ((string) $imagesize == 'small') {
  8656. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8657. } else {
  8658. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8659. }
  8660. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8661. }
  8662. }
  8663. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8664. $altfile = $object->id . ".jpg"; // For backward compatibility
  8665. }
  8666. $email = $object->email;
  8667. }
  8668. if ($forcecapture) {
  8669. $capture = $forcecapture;
  8670. }
  8671. if ($dir) {
  8672. if ($file && file_exists($dir . "/" . $file)) {
  8673. if ($addlinktofullsize) {
  8674. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8675. if ($urladvanced) {
  8676. $ret .= '<a href="' . $urladvanced . '">';
  8677. } else {
  8678. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8679. }
  8680. }
  8681. $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 . '">';
  8682. if ($addlinktofullsize) {
  8683. $ret .= '</a>';
  8684. }
  8685. } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
  8686. if ($addlinktofullsize) {
  8687. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8688. if ($urladvanced) {
  8689. $ret .= '<a href="' . $urladvanced . '">';
  8690. } else {
  8691. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8692. }
  8693. }
  8694. $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 . '">';
  8695. if ($addlinktofullsize) {
  8696. $ret .= '</a>';
  8697. }
  8698. } else {
  8699. $nophoto = '/public/theme/common/nophoto.png';
  8700. $defaultimg = 'identicon'; // For gravatar
  8701. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8702. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8703. $nophoto = 'company';
  8704. } else {
  8705. $nophoto = '/public/theme/common/user_anonymous.png';
  8706. if (!empty($object->gender) && $object->gender == 'man') {
  8707. $nophoto = '/public/theme/common/user_man.png';
  8708. }
  8709. if (!empty($object->gender) && $object->gender == 'woman') {
  8710. $nophoto = '/public/theme/common/user_woman.png';
  8711. }
  8712. }
  8713. }
  8714. if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
  8715. // see https://gravatar.com/site/implement/images/php/
  8716. $ret .= '<!-- Put link to gravatar -->';
  8717. $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
  8718. } else {
  8719. if ($nophoto == 'company') {
  8720. $ret .= '<div class="divforspanimg photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
  8721. $ret .= '<div class="difforspanimgright"></div>';
  8722. } else {
  8723. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
  8724. }
  8725. }
  8726. }
  8727. if ($caneditfield) {
  8728. if ($object->photo) {
  8729. $ret .= "<br>\n";
  8730. }
  8731. $ret .= '<table class="nobordernopadding centpercent">';
  8732. if ($object->photo) {
  8733. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
  8734. }
  8735. $ret .= '<tr><td class="tdoverflow">';
  8736. $maxfilesizearray = getMaxFileSizeArray();
  8737. $maxmin = $maxfilesizearray['maxmin'];
  8738. if ($maxmin > 0) {
  8739. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
  8740. }
  8741. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . $capture . '"' : '') . '>';
  8742. $ret .= '</td></tr>';
  8743. $ret .= '</table>';
  8744. }
  8745. } else {
  8746. dol_print_error('', 'Call of showphoto with wrong parameters modulepart=' . $modulepart);
  8747. }
  8748. return $ret;
  8749. }
  8750. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8751. /**
  8752. * Return select list of groups
  8753. *
  8754. * @param string|object $selected Id group or group preselected
  8755. * @param string $htmlname Field name in form
  8756. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8757. * @param string|array $exclude Array list of groups id to exclude
  8758. * @param int $disabled If select list must be disabled
  8759. * @param string|array $include Array list of groups id to include
  8760. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8761. * @param string $force_entity '0' or Ids of environment to force
  8762. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8763. * @param string $morecss More css to add to html component
  8764. * @return string
  8765. * @see select_dolusers()
  8766. */
  8767. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8768. {
  8769. // phpcs:enable
  8770. global $conf, $user, $langs;
  8771. // Permettre l'exclusion de groupes
  8772. $excludeGroups = null;
  8773. if (is_array($exclude)) {
  8774. $excludeGroups = implode(",", $exclude);
  8775. }
  8776. // Permettre l'inclusion de groupes
  8777. $includeGroups = null;
  8778. if (is_array($include)) {
  8779. $includeGroups = implode(",", $include);
  8780. }
  8781. if (!is_array($selected)) {
  8782. $selected = array($selected);
  8783. }
  8784. $out = '';
  8785. // On recherche les groupes
  8786. $sql = "SELECT ug.rowid, ug.nom as name";
  8787. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8788. $sql .= ", e.label";
  8789. }
  8790. $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
  8791. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8792. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
  8793. if ($force_entity) {
  8794. $sql .= " WHERE ug.entity IN (0, " . $force_entity . ")";
  8795. } else {
  8796. $sql .= " WHERE ug.entity IS NOT NULL";
  8797. }
  8798. } else {
  8799. $sql .= " WHERE ug.entity IN (0, " . $conf->entity . ")";
  8800. }
  8801. if (is_array($exclude) && $excludeGroups) {
  8802. $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
  8803. }
  8804. if (is_array($include) && $includeGroups) {
  8805. $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
  8806. }
  8807. $sql .= " ORDER BY ug.nom ASC";
  8808. dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
  8809. $resql = $this->db->query($sql);
  8810. if ($resql) {
  8811. // Enhance with select2
  8812. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  8813. $out .= '<select class="flat minwidth200' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  8814. $num = $this->db->num_rows($resql);
  8815. $i = 0;
  8816. if ($num) {
  8817. if ($show_empty && !$multiple) {
  8818. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8819. }
  8820. while ($i < $num) {
  8821. $obj = $this->db->fetch_object($resql);
  8822. $disableline = 0;
  8823. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8824. $disableline = 1;
  8825. }
  8826. $out .= '<option value="' . $obj->rowid . '"';
  8827. if ($disableline) {
  8828. $out .= ' disabled';
  8829. }
  8830. 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))) {
  8831. $out .= ' selected';
  8832. }
  8833. $out .= '>';
  8834. $out .= $obj->name;
  8835. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8836. $out .= " (" . $obj->label . ")";
  8837. }
  8838. $out .= '</option>';
  8839. $i++;
  8840. }
  8841. } else {
  8842. if ($show_empty) {
  8843. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
  8844. }
  8845. $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
  8846. }
  8847. $out .= '</select>';
  8848. $out .= ajax_combobox($htmlname);
  8849. } else {
  8850. dol_print_error($this->db);
  8851. }
  8852. return $out;
  8853. }
  8854. /**
  8855. * Return HTML to show the search and clear seach button
  8856. *
  8857. * @param string $pos Position of colon on the list. Value 'left' or 'right'
  8858. * @return string
  8859. */
  8860. public function showFilterButtons($pos = '')
  8861. {
  8862. $out = '<div class="nowraponall">';
  8863. if ($pos == 'left') {
  8864. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8865. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8866. } else {
  8867. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8868. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8869. }
  8870. $out .= '</div>';
  8871. return $out;
  8872. }
  8873. /**
  8874. * Return HTML to show the search and clear search button
  8875. *
  8876. * @param string $cssclass CSS class
  8877. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8878. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8879. * @return string
  8880. */
  8881. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8882. {
  8883. global $conf, $langs;
  8884. $out = '';
  8885. if (!empty($conf->use_javascript_ajax)) {
  8886. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
  8887. }
  8888. $out .= '<script nonce="' . getNonce() . '">
  8889. $(document).ready(function() {
  8890. $("#' . $cssclass . 's").click(function() {
  8891. if($(this).is(\':checked\')){
  8892. console.log("We check all ' . $cssclass . ' and trigger the change method");
  8893. $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
  8894. }
  8895. else
  8896. {
  8897. console.log("We uncheck all");
  8898. $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
  8899. }' . "\n";
  8900. if ($calljsfunction) {
  8901. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8902. }
  8903. $out .= ' });
  8904. $(".' . $cssclass . '").change(function() {
  8905. $(this).closest("tr").toggleClass("highlight", this.checked);
  8906. });
  8907. });
  8908. </script>';
  8909. return $out;
  8910. }
  8911. /**
  8912. * Return HTML to show the search and clear seach button
  8913. *
  8914. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8915. * @param string $cssclass CSS class
  8916. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8917. * @param string $massactionname Mass action name
  8918. * @return string
  8919. */
  8920. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8921. {
  8922. $out = $this->showFilterButtons();
  8923. if ($addcheckuncheckall) {
  8924. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8925. }
  8926. return $out;
  8927. }
  8928. /**
  8929. * Return HTML to show the select of expense categories
  8930. *
  8931. * @param string $selected preselected category
  8932. * @param string $htmlname name of HTML select list
  8933. * @param integer $useempty 1=Add empty line
  8934. * @param array $excludeid id to exclude
  8935. * @param string $target htmlname of target select to bind event
  8936. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8937. * @param array $params param to give
  8938. * @param int $info_admin Show the tooltip help picto to setup list
  8939. * @return string
  8940. */
  8941. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8942. {
  8943. global $langs, $user;
  8944. $out = '';
  8945. $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
  8946. $sql .= " AND entity IN (0," . getEntity('exp_tax_cat') . ")";
  8947. if (!empty($excludeid)) {
  8948. $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
  8949. }
  8950. $sql .= " ORDER BY label";
  8951. $resql = $this->db->query($sql);
  8952. if ($resql) {
  8953. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
  8954. if ($useempty) {
  8955. $out .= '<option value="0">&nbsp;</option>';
  8956. }
  8957. while ($obj = $this->db->fetch_object($resql)) {
  8958. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
  8959. }
  8960. $out .= '</select>';
  8961. $out .= ajax_combobox('select_' . $htmlname);
  8962. if (!empty($htmlname) && $user->admin && $info_admin) {
  8963. $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8964. }
  8965. if (!empty($target)) {
  8966. $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8967. $resql = $this->db->query($sql);
  8968. if ($resql) {
  8969. if ($this->db->num_rows($resql) > 0) {
  8970. $obj = $this->db->fetch_object($resql);
  8971. $out .= '<script nonce="' . getNonce() . '">
  8972. $(function() {
  8973. $("select[name=' . $target . ']").on("change", function() {
  8974. var current_val = $(this).val();
  8975. if (current_val == ' . $obj->id . ') {';
  8976. if (!empty($default_selected) || !empty($selected)) {
  8977. $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
  8978. }
  8979. $out .= '
  8980. $("select[name=' . $htmlname . ']").change();
  8981. }
  8982. });
  8983. $("select[name=' . $htmlname . ']").change(function() {
  8984. if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
  8985. // get price of kilometer to fill the unit price
  8986. $.ajax({
  8987. method: "POST",
  8988. dataType: "json",
  8989. data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
  8990. url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . join('&', $params)) . '",
  8991. }).done(function( data, textStatus, jqXHR ) {
  8992. console.log(data);
  8993. if (typeof data.up != "undefined") {
  8994. $("input[name=value_unit]").val(data.up);
  8995. $("select[name=' . $htmlname . ']").attr("title", data.title);
  8996. } else {
  8997. $("input[name=value_unit]").val("");
  8998. $("select[name=' . $htmlname . ']").attr("title", "");
  8999. }
  9000. });
  9001. }
  9002. });
  9003. });
  9004. </script>';
  9005. }
  9006. }
  9007. }
  9008. } else {
  9009. dol_print_error($this->db);
  9010. }
  9011. return $out;
  9012. }
  9013. /**
  9014. * Return HTML to show the select ranges of expense range
  9015. *
  9016. * @param string $selected preselected category
  9017. * @param string $htmlname name of HTML select list
  9018. * @param integer $useempty 1=Add empty line
  9019. * @return string
  9020. */
  9021. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  9022. {
  9023. global $conf, $langs;
  9024. $out = '';
  9025. $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
  9026. $sql .= " WHERE entity = " . $conf->entity . " AND active = 1";
  9027. $resql = $this->db->query($sql);
  9028. if ($resql) {
  9029. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9030. if ($useempty) {
  9031. $out .= '<option value="0"></option>';
  9032. }
  9033. while ($obj = $this->db->fetch_object($resql)) {
  9034. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
  9035. }
  9036. $out .= '</select>';
  9037. } else {
  9038. dol_print_error($this->db);
  9039. }
  9040. return $out;
  9041. }
  9042. /**
  9043. * Return HTML to show a select of expense
  9044. *
  9045. * @param string $selected preselected category
  9046. * @param string $htmlname name of HTML select list
  9047. * @param integer $useempty 1=Add empty choice
  9048. * @param integer $allchoice 1=Add all choice
  9049. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  9050. * @return string
  9051. */
  9052. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  9053. {
  9054. global $langs;
  9055. $out = '';
  9056. $sql = "SELECT id, code, label FROM " . $this->db->prefix() . "c_type_fees";
  9057. $sql .= " WHERE active = 1";
  9058. $resql = $this->db->query($sql);
  9059. if ($resql) {
  9060. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9061. if ($useempty) {
  9062. $out .= '<option value="0"></option>';
  9063. }
  9064. if ($allchoice) {
  9065. $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
  9066. }
  9067. $field = 'code';
  9068. if ($useid) {
  9069. $field = 'id';
  9070. }
  9071. while ($obj = $this->db->fetch_object($resql)) {
  9072. $key = $langs->trans($obj->code);
  9073. $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
  9074. }
  9075. $out .= '</select>';
  9076. } else {
  9077. dol_print_error($this->db);
  9078. }
  9079. return $out;
  9080. }
  9081. /**
  9082. * Output a combo list with invoices qualified for a third party
  9083. *
  9084. * @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)
  9085. * @param int $selected Id invoice preselected
  9086. * @param string $htmlname Name of HTML select
  9087. * @param int $maxlength Maximum length of label
  9088. * @param int $option_only Return only html options lines without the select tag
  9089. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9090. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  9091. * @param int $forcefocus Force focus on field (works with javascript only)
  9092. * @param int $disabled Disabled
  9093. * @param string $morecss More css added to the select component
  9094. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  9095. * @param string $showproject 'all' = Show project info, ''=Hide project info
  9096. * @param User $usertofilter User object to use for filtering
  9097. * @return string HTML Select Invoice
  9098. */
  9099. 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)
  9100. {
  9101. global $user, $conf, $langs;
  9102. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  9103. if (is_null($usertofilter)) {
  9104. $usertofilter = $user;
  9105. }
  9106. $out = '';
  9107. $hideunselectables = false;
  9108. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  9109. $hideunselectables = true;
  9110. }
  9111. if (empty($projectsListId)) {
  9112. if (empty($usertofilter->rights->projet->all->lire)) {
  9113. $projectstatic = new Project($this->db);
  9114. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  9115. }
  9116. }
  9117. // Search all projects
  9118. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  9119. p.title, p.fk_soc, p.fk_statut, p.public,";
  9120. $sql .= ' s.nom as name';
  9121. $sql .= ' FROM ' . $this->db->prefix() . 'projet as p';
  9122. $sql .= ' LEFT JOIN ' . $this->db->prefix() . 'societe as s ON s.rowid = p.fk_soc,';
  9123. $sql .= ' ' . $this->db->prefix() . 'facture as f';
  9124. $sql .= " WHERE p.entity IN (" . getEntity('project') . ")";
  9125. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  9126. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  9127. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  9128. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  9129. $sql .= " ORDER BY p.ref, f.ref ASC";
  9130. $resql = $this->db->query($sql);
  9131. if ($resql) {
  9132. // Use select2 selector
  9133. if (!empty($conf->use_javascript_ajax)) {
  9134. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9135. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9136. $out .= $comboenhancement;
  9137. $morecss = 'minwidth200imp maxwidth500';
  9138. }
  9139. if (empty($option_only)) {
  9140. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9141. }
  9142. if (!empty($show_empty)) {
  9143. $out .= '<option value="0" class="optiongrey">';
  9144. if (!is_numeric($show_empty)) {
  9145. $out .= $show_empty;
  9146. } else {
  9147. $out .= '&nbsp;';
  9148. }
  9149. $out .= '</option>';
  9150. }
  9151. $num = $this->db->num_rows($resql);
  9152. $i = 0;
  9153. if ($num) {
  9154. while ($i < $num) {
  9155. $obj = $this->db->fetch_object($resql);
  9156. // 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.
  9157. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  9158. // Do nothing
  9159. } else {
  9160. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  9161. $i++;
  9162. continue;
  9163. }
  9164. $labeltoshow = '';
  9165. if ($showproject == 'all') {
  9166. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  9167. if ($obj->name) {
  9168. $labeltoshow .= ' - ' . $obj->name; // Soc name
  9169. }
  9170. $disabled = 0;
  9171. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  9172. $disabled = 1;
  9173. $labeltoshow .= ' - ' . $langs->trans("Draft");
  9174. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  9175. if ($discard_closed == 2) {
  9176. $disabled = 1;
  9177. }
  9178. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9179. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  9180. $disabled = 1;
  9181. $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
  9182. }
  9183. }
  9184. if (!empty($selected) && $selected == $obj->rowid) {
  9185. $out .= '<option value="' . $obj->rowid . '" selected';
  9186. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9187. $out .= '>' . $labeltoshow . '</option>';
  9188. } else {
  9189. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  9190. $resultat = '';
  9191. } else {
  9192. $resultat = '<option value="' . $obj->rowid . '"';
  9193. if ($disabled) {
  9194. $resultat .= ' disabled';
  9195. }
  9196. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  9197. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  9198. $resultat .= '>';
  9199. $resultat .= $labeltoshow;
  9200. $resultat .= '</option>';
  9201. }
  9202. $out .= $resultat;
  9203. }
  9204. }
  9205. $i++;
  9206. }
  9207. }
  9208. if (empty($option_only)) {
  9209. $out .= '</select>';
  9210. }
  9211. $this->db->free($resql);
  9212. return $out;
  9213. } else {
  9214. dol_print_error($this->db);
  9215. return '';
  9216. }
  9217. }
  9218. /**
  9219. * Output a combo list with invoices qualified for a third party
  9220. *
  9221. * @param int $selected Id invoice preselected
  9222. * @param string $htmlname Name of HTML select
  9223. * @param int $maxlength Maximum length of label
  9224. * @param int $option_only Return only html options lines without the select tag
  9225. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9226. * @param int $forcefocus Force focus on field (works with javascript only)
  9227. * @param int $disabled Disabled
  9228. * @param string $morecss More css added to the select component
  9229. * @return int Nbr of project if OK, <0 if KO
  9230. */
  9231. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  9232. {
  9233. global $user, $conf, $langs;
  9234. $out = '';
  9235. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  9236. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  9237. //$sql.= ', el.fk_source';
  9238. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  9239. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  9240. $sql .= " ORDER BY f.titre ASC";
  9241. $resql = $this->db->query($sql);
  9242. if ($resql) {
  9243. // Use select2 selector
  9244. if (!empty($conf->use_javascript_ajax)) {
  9245. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9246. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9247. $out .= $comboenhancement;
  9248. $morecss = 'minwidth200imp maxwidth500';
  9249. }
  9250. if (empty($option_only)) {
  9251. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9252. }
  9253. if (!empty($show_empty)) {
  9254. $out .= '<option value="0" class="optiongrey">';
  9255. if (!is_numeric($show_empty)) {
  9256. $out .= $show_empty;
  9257. } else {
  9258. $out .= '&nbsp;';
  9259. }
  9260. $out .= '</option>';
  9261. }
  9262. $num = $this->db->num_rows($resql);
  9263. if ($num) {
  9264. while ($obj = $this->db->fetch_object($resql)) {
  9265. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9266. $disabled = 0;
  9267. if (!empty($obj->suspended)) {
  9268. $disabled = 1;
  9269. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9270. }
  9271. if (!empty($selected) && $selected == $obj->rowid) {
  9272. $out .= '<option value="' . $obj->rowid . '" selected';
  9273. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9274. $out .= '>' . $labeltoshow . '</option>';
  9275. } else {
  9276. if ($disabled && ($selected != $obj->rowid)) {
  9277. $resultat = '';
  9278. } else {
  9279. $resultat = '<option value="' . $obj->rowid . '"';
  9280. if ($disabled) {
  9281. $resultat .= ' disabled';
  9282. }
  9283. $resultat .= '>';
  9284. $resultat .= $labeltoshow;
  9285. $resultat .= '</option>';
  9286. }
  9287. $out .= $resultat;
  9288. }
  9289. }
  9290. }
  9291. if (empty($option_only)) {
  9292. $out .= '</select>';
  9293. }
  9294. print $out;
  9295. $this->db->free($resql);
  9296. return $num;
  9297. } else {
  9298. $this->errors[] = $this->db->lasterror;
  9299. return -1;
  9300. }
  9301. }
  9302. /**
  9303. * Output the component to make advanced search criteries
  9304. *
  9305. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9306. * @param array $search_component_params Array of selected search criterias
  9307. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9308. * @param string $search_component_params_hidden String with $search_component_params criterias
  9309. * @return string HTML component for advanced search
  9310. */
  9311. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9312. {
  9313. global $langs;
  9314. $ret = '';
  9315. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9316. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  9317. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9318. $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
  9319. //$ret .= $langs->trans("Filters");
  9320. $ret .= '</a>';
  9321. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9322. // Show select fields as tags.
  9323. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9324. if ($search_component_params_hidden) {
  9325. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9326. $search_component_params_hidden .= '(' . $search_component_params_hidden . ')';
  9327. }
  9328. $errormessage = '';
  9329. $searchtags = forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage);
  9330. if ($errormessage) {
  9331. print 'ERROR in parsing search string: ' . dol_escape_htmltag($errormessage);
  9332. }
  9333. //var_dump($searchtags);
  9334. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> ' . dol_escape_htmltag($searchtags) . '</span>';
  9335. }
  9336. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9337. //$ret .= search_component_params
  9338. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9339. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9340. $show_search_component_params_hidden = 1;
  9341. if ($show_search_component_params_hidden) {
  9342. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9343. }
  9344. $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%')) -->";
  9345. $ret .= '<input type="hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
  9346. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  9347. foreach ($arrayofcriterias as $criterias) {
  9348. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9349. if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9350. continue;
  9351. }
  9352. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9353. continue;
  9354. }
  9355. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9356. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
  9357. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
  9358. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
  9359. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
  9360. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
  9361. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
  9362. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
  9363. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
  9364. } else {
  9365. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
  9366. }
  9367. }
  9368. }
  9369. $ret .= '</div>';
  9370. $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";
  9371. $ret .= '<input type="text" placeholder="' . $langs->trans("Search") . '" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9372. $ret .= '</div>';
  9373. $ret .= '</div>';
  9374. return $ret;
  9375. }
  9376. /**
  9377. * selectModelMail
  9378. *
  9379. * @param string $prefix Prefix
  9380. * @param string $modelType Model type
  9381. * @param int $default 1=Show also Default mail template
  9382. * @param int $addjscombo Add js combobox
  9383. * @return string HTML select string
  9384. */
  9385. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9386. {
  9387. global $langs, $user;
  9388. $retstring = '';
  9389. $TModels = array();
  9390. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  9391. $formmail = new FormMail($this->db);
  9392. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9393. if ($default) {
  9394. $TModels[0] = $langs->trans('DefaultMailModel');
  9395. }
  9396. if ($result > 0) {
  9397. foreach ($formmail->lines_model as $model) {
  9398. $TModels[$model->id] = $model->label;
  9399. }
  9400. }
  9401. $retstring .= '<select class="flat" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
  9402. foreach ($TModels as $id_model => $label_model) {
  9403. $retstring .= '<option value="' . $id_model . '"';
  9404. $retstring .= ">" . $label_model . "</option>";
  9405. }
  9406. $retstring .= "</select>";
  9407. if ($addjscombo) {
  9408. $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
  9409. }
  9410. return $retstring;
  9411. }
  9412. /**
  9413. * Output the buttons to submit a creation/edit form
  9414. *
  9415. * @param string $save_label Alternative label for save button
  9416. * @param string $cancel_label Alternative label for cancel button
  9417. * @param array $morebuttons Add additional buttons between save and cancel
  9418. * @param bool $withoutdiv Option to remove enclosing centered div
  9419. * @param string $morecss More CSS
  9420. * @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.
  9421. * @return string Html code with the buttons
  9422. */
  9423. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9424. {
  9425. global $langs;
  9426. $buttons = array();
  9427. $save = array(
  9428. 'name' => 'save',
  9429. 'label_key' => $save_label,
  9430. );
  9431. if ($save_label == 'Create' || $save_label == 'Add') {
  9432. $save['name'] = 'add';
  9433. } elseif ($save_label == 'Modify') {
  9434. $save['name'] = 'edit';
  9435. }
  9436. $cancel = array(
  9437. 'name' => 'cancel',
  9438. 'label_key' => 'Cancel',
  9439. );
  9440. !empty($save_label) ? $buttons[] = $save : '';
  9441. if (!empty($morebuttons)) {
  9442. $buttons[] = $morebuttons;
  9443. }
  9444. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9445. $retstring = $withoutdiv ? '' : '<div class="center">';
  9446. foreach ($buttons as $button) {
  9447. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9448. $retstring .= '<input type="submit" class="button button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->trans($button['label_key'])) . '">';
  9449. }
  9450. $retstring .= $withoutdiv ? '' : '</div>';
  9451. if ($dol_openinpopup) {
  9452. $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . $dol_openinpopup . ' context, so we enable the close of dialog on cancel -->' . "\n";
  9453. $retstring .= '<script nonce="' . getNonce() . '">';
  9454. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9455. e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . $dol_openinpopup . '\');
  9456. window.parent.jQuery(\'#idfordialog' . $dol_openinpopup . '\').dialog(\'close\');
  9457. });';
  9458. $retstring .= '</script>';
  9459. }
  9460. return $retstring;
  9461. }
  9462. }