html.form.class.php 422 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
  10. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  11. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  12. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  13. * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  16. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  17. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  18. * Copyright (C) 2014-2020 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  21. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  22. * Copyright (C) 2018 Christophe Battarel <christophe@altairis.fr>
  23. * Copyright (C) 2018 Josep Lluis Amador <joseplluis@lliuretic.cat>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. */
  38. /**
  39. * \file htdocs/core/class/html.form.class.php
  40. * \ingroup core
  41. * \brief File of class with all html predefined components
  42. */
  43. /**
  44. * Class to manage generation of HTML components
  45. * Only common components must be here.
  46. *
  47. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  48. */
  49. class Form
  50. {
  51. /**
  52. * @var DoliDB Database handler.
  53. */
  54. public $db;
  55. /**
  56. * @var string Error code (or message)
  57. */
  58. public $error = '';
  59. /**
  60. * @var string[] Array of error strings
  61. */
  62. public $errors = array();
  63. public $num;
  64. // Cache arrays
  65. public $cache_types_paiements = array();
  66. public $cache_conditions_paiements = array();
  67. public $cache_transport_mode = array();
  68. public $cache_availability = array();
  69. public $cache_demand_reason = array();
  70. public $cache_types_fees = array();
  71. public $cache_vatrates = array();
  72. /**
  73. * Constructor
  74. *
  75. * @param DoliDB $db Database handler
  76. */
  77. public function __construct($db)
  78. {
  79. $this->db = $db;
  80. }
  81. /**
  82. * Output key field for an editable field
  83. *
  84. * @param string $text Text of label or key to translate
  85. * @param string $htmlname Name of select field ('edit' prefix will be added)
  86. * @param string $preselected Value to show/edit (not used in this function)
  87. * @param object $object Object
  88. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  89. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  90. * @param string $moreparam More param to add on a href URL.
  91. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  92. * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
  93. * @param string $paramid Key of parameter for id ('id', 'socid')
  94. * @param string $help Tooltip help
  95. * @return string HTML edit field
  96. */
  97. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  98. {
  99. global $conf, $langs;
  100. $ret = '';
  101. // TODO change for compatibility
  102. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  103. if (!empty($perm)) {
  104. $tmp = explode(':', $typeofdata);
  105. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  106. if ($fieldrequired) {
  107. $ret .= '<span class="fieldrequired">';
  108. }
  109. if ($help) {
  110. $ret .= $this->textwithpicto($langs->trans($text), $help);
  111. } else {
  112. $ret .= $langs->trans($text);
  113. }
  114. if ($fieldrequired) {
  115. $ret .= '</span>';
  116. }
  117. $ret .= '</div>'."\n";
  118. } else {
  119. if ($fieldrequired) {
  120. $ret .= '<span class="fieldrequired">';
  121. }
  122. if ($help) {
  123. $ret .= $this->textwithpicto($langs->trans($text), $help);
  124. } else {
  125. $ret .= $langs->trans($text);
  126. }
  127. if ($fieldrequired) {
  128. $ret .= '</span>';
  129. }
  130. }
  131. } else {
  132. if (empty($notabletag) && $perm) {
  133. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  134. }
  135. if ($fieldrequired) {
  136. $ret .= '<span class="fieldrequired">';
  137. }
  138. if ($help) {
  139. $ret .= $this->textwithpicto($langs->trans($text), $help);
  140. } else {
  141. $ret .= $langs->trans($text);
  142. }
  143. if ($fieldrequired) {
  144. $ret .= '</span>';
  145. }
  146. if (!empty($notabletag)) {
  147. $ret .= ' ';
  148. }
  149. if (empty($notabletag) && $perm) {
  150. $ret .= '</td>';
  151. }
  152. if (empty($notabletag) && $perm) {
  153. $ret .= '<td class="right">';
  154. }
  155. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  156. $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&token='.newToken().'&'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  157. }
  158. if (!empty($notabletag) && $notabletag == 1) {
  159. $ret .= ' : ';
  160. }
  161. if (!empty($notabletag) && $notabletag == 3) {
  162. $ret .= ' ';
  163. }
  164. if (empty($notabletag) && $perm) {
  165. $ret .= '</td>';
  166. }
  167. if (empty($notabletag) && $perm) {
  168. $ret .= '</tr></table>';
  169. }
  170. }
  171. return $ret;
  172. }
  173. /**
  174. * Output value of a field for an editable field
  175. *
  176. * @param string $text Text of label (not used in this function)
  177. * @param string $htmlname Name of select field
  178. * @param string $value Value to show/edit
  179. * @param object $object Object
  180. * @param boolean $perm Permission to allow button to edit parameter
  181. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  182. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of numeric value). Use '' to use same than $value
  183. * @param object $extObject External object
  184. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  185. * @param string $moreparam More param to add on the form action href URL
  186. * @param int $notabletag Do no output table tags
  187. * @param string $formatfunc Call a specific function to output field in view mode (For example: 'dol_print_email')
  188. * @param string $paramid Key of parameter for id ('id', 'socid')
  189. * @param string $gm 'auto' or 'tzuser' or 'tzserver' (when $typeofdata is a date)
  190. * @return string HTML edit field
  191. */
  192. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id', $gm = 'auto')
  193. {
  194. global $conf, $langs;
  195. $ret = '';
  196. // Check parameters
  197. if (empty($typeofdata)) {
  198. return 'ErrorBadParameter';
  199. }
  200. // When option to edit inline is activated
  201. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  202. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  203. } else {
  204. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  205. if ($editmode) {
  206. $ret .= "\n";
  207. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  208. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  209. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  210. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  211. if (empty($notabletag)) {
  212. $ret .= '<table class="nobordernopadding centpercent">';
  213. }
  214. if (empty($notabletag)) {
  215. $ret .= '<tr><td>';
  216. }
  217. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  218. $tmp = explode(':', $typeofdata);
  219. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  220. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  221. $tmp = explode(':', $typeofdata);
  222. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  223. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.$valuetoshow.'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  224. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  225. $tmp = explode(':', $typeofdata);
  226. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  227. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  228. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  229. $tmp = explode(':', $typeofdata);
  230. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  231. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  232. $tmp = explode(':', $typeofdata);
  233. $cols = $tmp[2];
  234. $morealt = '';
  235. if (preg_match('/%/', $cols)) {
  236. $morealt = ' style="width: '.$cols.'"';
  237. $cols = '';
  238. }
  239. $valuetoshow = ($editvalue ? $editvalue : $value);
  240. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  241. // textarea convert automatically entities chars into simple chars.
  242. // 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.
  243. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  244. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  245. $ret .= '</textarea>';
  246. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  247. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  248. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  249. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  250. } elseif (preg_match('/^select;/', $typeofdata)) {
  251. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  252. $arraylist = array();
  253. foreach ($arraydata as $val) {
  254. $tmp = explode(':', $val);
  255. $tmpkey = str_replace('|', ':', $tmp[0]);
  256. $arraylist[$tmpkey] = $tmp[1];
  257. }
  258. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  259. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  260. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  261. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  262. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), ($tmp[2] ? $tmp[2] : ''), ($tmp[3] ? $tmp[3] : '100'), ($tmp[1] ? $tmp[1] : 'dolibarr_notes'), 'In', ($tmp[5] ? $tmp[5] : 0), (isset($tmp[8]) ? ($tmp[8] ?true:false) : true), true, ($tmp[6] ? $tmp[6] : '20'), ($tmp[7] ? $tmp[7] : '100'));
  263. $ret .= $doleditor->Create(1);
  264. }
  265. if (empty($notabletag)) {
  266. $ret .= '</td>';
  267. }
  268. // Button save-cancel
  269. if (empty($notabletag)) {
  270. $ret .= '<td class="left">';
  271. }
  272. //else $ret.='<div class="clearboth"></div>';
  273. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  274. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  275. $ret .= '<br>'."\n";
  276. }
  277. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  278. if (empty($notabletag)) {
  279. $ret .= '</td>';
  280. }
  281. if (empty($notabletag)) {
  282. $ret .= '</tr></table>'."\n";
  283. }
  284. $ret .= '</form>'."\n";
  285. } else {
  286. if (preg_match('/^(email)/', $typeofdata)) {
  287. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  288. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  289. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  290. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  291. $tmp = explode(':', $typeofdata);
  292. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  293. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  294. $ret .= dol_htmlentitiesbr($value);
  295. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  296. $ret .= dol_string_onlythesehtmltags($value);
  297. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  298. $ret .= dol_string_onlythesehtmltags($value);
  299. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  300. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day', $gm).'</span>';
  301. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  302. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour', $gm).'</span>';
  303. } elseif (preg_match('/^select;/', $typeofdata)) {
  304. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  305. $arraylist = array();
  306. foreach ($arraydata as $val) {
  307. $tmp = explode(':', $val);
  308. $arraylist[$tmp[0]] = $tmp[1];
  309. }
  310. $ret .= $arraylist[$value];
  311. if ($htmlname == 'fk_product_type') {
  312. if ($value == 0) {
  313. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  314. } else {
  315. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  316. }
  317. }
  318. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  319. $tmpcontent = dol_htmlentitiesbr($value);
  320. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  321. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  322. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  323. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  324. }
  325. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  326. // clean data from some dangerous html
  327. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  328. } else {
  329. $ret .= dol_escape_htmltag($value);
  330. }
  331. if ($formatfunc && method_exists($object, $formatfunc)) {
  332. $ret = $object->$formatfunc($ret);
  333. }
  334. }
  335. }
  336. return $ret;
  337. }
  338. /**
  339. * Output edit in place form
  340. *
  341. * @param string $fieldname Name of the field
  342. * @param object $object Object
  343. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  344. * @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]'...)
  345. * @param string $check Same coe than $check parameter of GETPOST()
  346. * @param string $morecss More CSS
  347. * @return string HTML code for the edit of alternative language
  348. */
  349. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  350. {
  351. global $conf, $langs, $extralanguages;
  352. $result = '';
  353. // List of extra languages
  354. $arrayoflangcode = array();
  355. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  356. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  357. }
  358. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  359. if (!is_object($extralanguages)) {
  360. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  361. $extralanguages = new ExtraLanguages($this->db);
  362. }
  363. $extralanguages->fetch_name_extralanguages('societe');
  364. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  365. return ''; // No extralang field to show
  366. }
  367. $result .= '<!-- Widget for translation -->'."\n";
  368. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  369. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  370. $result .= $s;
  371. $result .= '</div>';
  372. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  373. $resultforextrlang = '';
  374. foreach ($arrayoflangcode as $langcode) {
  375. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  376. if (empty($valuetoshow)) {
  377. $object->fetchValuesForExtraLanguages();
  378. //var_dump($object->array_languages);
  379. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  380. }
  381. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  382. $resultforextrlang .= $s;
  383. // TODO Use the showInputField() method of ExtraLanguages object
  384. if ($typeofdata == 'textarea') {
  385. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  386. $resultforextrlang .= $valuetoshow;
  387. $resultforextrlang .= '</textarea>';
  388. } else {
  389. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  390. }
  391. }
  392. $result .= $resultforextrlang;
  393. $result .= '</div>';
  394. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  395. }
  396. return $result;
  397. }
  398. /**
  399. * Output edit in place form
  400. *
  401. * @param object $object Object
  402. * @param string $value Value to show/edit
  403. * @param string $htmlname DIV ID (field name)
  404. * @param int $condition Condition to edit
  405. * @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')
  406. * @param string $editvalue When in edit mode, use this value as $value instead of value
  407. * @param object $extObject External object
  408. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  409. * @return string HTML edit in place
  410. */
  411. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  412. {
  413. global $conf;
  414. $out = '';
  415. // Check parameters
  416. if (preg_match('/^text/', $inputType)) {
  417. $value = dol_nl2br($value);
  418. } elseif (preg_match('/^numeric/', $inputType)) {
  419. $value = price($value);
  420. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  421. $value = dol_print_date($value, 'day');
  422. }
  423. if ($condition) {
  424. $element = false;
  425. $table_element = false;
  426. $fk_element = false;
  427. $loadmethod = false;
  428. $savemethod = false;
  429. $ext_element = false;
  430. $button_only = false;
  431. $inputOption = '';
  432. $rows = '';
  433. $cols = '';
  434. if (is_object($object)) {
  435. $element = $object->element;
  436. $table_element = $object->table_element;
  437. $fk_element = $object->id;
  438. }
  439. if (is_object($extObject)) {
  440. $ext_element = $extObject->element;
  441. }
  442. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  443. $tmp = explode(':', $inputType);
  444. $inputType = $tmp[0];
  445. if (!empty($tmp[1])) {
  446. $inputOption = $tmp[1];
  447. }
  448. if (!empty($tmp[2])) {
  449. $savemethod = $tmp[2];
  450. }
  451. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  452. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  453. $tmp = explode(':', $inputType);
  454. $inputType = $tmp[0];
  455. if (!empty($tmp[1])) {
  456. $inputOption = $tmp[1];
  457. }
  458. if (!empty($tmp[2])) {
  459. $savemethod = $tmp[2];
  460. }
  461. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  462. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  463. $tmp = explode(':', $inputType);
  464. $inputType = $tmp[0];
  465. $loadmethod = $tmp[1];
  466. if (!empty($tmp[2])) {
  467. $savemethod = $tmp[2];
  468. }
  469. if (!empty($tmp[3])) {
  470. $button_only = true;
  471. }
  472. } elseif (preg_match('/^textarea/', $inputType)) {
  473. $tmp = explode(':', $inputType);
  474. $inputType = $tmp[0];
  475. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  476. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  477. } elseif (preg_match('/^ckeditor/', $inputType)) {
  478. $tmp = explode(':', $inputType);
  479. $inputType = $tmp[0];
  480. $toolbar = $tmp[1];
  481. if (!empty($tmp[2])) {
  482. $width = $tmp[2];
  483. }
  484. if (!empty($tmp[3])) {
  485. $heigth = $tmp[3];
  486. }
  487. if (!empty($tmp[4])) {
  488. $savemethod = $tmp[4];
  489. }
  490. if (!empty($conf->fckeditor->enabled)) {
  491. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  492. } else {
  493. $inputType = 'textarea';
  494. }
  495. }
  496. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  497. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  498. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  499. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  500. if (!empty($savemethod)) {
  501. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  502. }
  503. if (!empty($ext_element)) {
  504. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  505. }
  506. if (!empty($custommsg)) {
  507. if (is_array($custommsg)) {
  508. if (!empty($custommsg['success'])) {
  509. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  510. }
  511. if (!empty($custommsg['error'])) {
  512. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  513. }
  514. } else {
  515. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  516. }
  517. }
  518. if ($inputType == 'textarea') {
  519. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  520. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  521. }
  522. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  523. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  524. } else {
  525. $out = $value;
  526. }
  527. return $out;
  528. }
  529. /**
  530. * Show a text and picto with tooltip on text or picto.
  531. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  532. *
  533. * @param string $text Text to show
  534. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  535. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  536. * @param int $direction -1=image is before, 0=no image, 1=image is after
  537. * @param string $img Html code for image (use img_xxx() function to get it)
  538. * @param string $extracss Add a CSS style to td tags
  539. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  540. * @param string $incbefore Include code before the text
  541. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  542. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  543. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  544. * @return string Code html du tooltip (texte+picto)
  545. * @see textwithpicto() Use thisfunction if you can.
  546. */
  547. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  548. {
  549. if ($incbefore) {
  550. $text = $incbefore.$text;
  551. }
  552. if (!$htmltext) {
  553. return $text;
  554. }
  555. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  556. $tag = 'td';
  557. if ($notabs == 2) {
  558. $tag = 'div';
  559. }
  560. if ($notabs == 3) {
  561. $tag = 'span';
  562. }
  563. // Sanitize tooltip
  564. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  565. $extrastyle = '';
  566. if ($direction < 0) {
  567. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  568. $extrastyle = 'padding: 0px; padding-left: 3px !important;';
  569. }
  570. if ($direction > 0) {
  571. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  572. $extrastyle = 'padding: 0px; padding-right: 3px !important;';
  573. }
  574. $classfortooltip = 'classfortooltip';
  575. $s = '';
  576. $textfordialog = '';
  577. if ($tooltiptrigger == '') {
  578. $htmltext = str_replace('"', '&quot;', $htmltext);
  579. } else {
  580. $classfortooltip = 'classfortooltiponclick';
  581. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  582. }
  583. if ($tooltipon == 2 || $tooltipon == 3) {
  584. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  585. if ($tooltiptrigger == '') {
  586. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  587. } else {
  588. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  589. }
  590. } else {
  591. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  592. }
  593. if ($tooltipon == 1 || $tooltipon == 3) {
  594. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  595. if ($tooltiptrigger == '') {
  596. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  597. } else {
  598. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  599. }
  600. } else {
  601. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  602. }
  603. if (empty($notabs)) {
  604. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  605. } elseif ($notabs == 2) {
  606. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  607. }
  608. // Define value if value is before
  609. if ($direction < 0) {
  610. $s .= '<'.$tag.$paramfortooltipimg;
  611. if ($tag == 'td') {
  612. $s .= ' class=valigntop" width="14"';
  613. }
  614. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  615. }
  616. // Use another method to help avoid having a space in value in order to use this value with jquery
  617. // Define label
  618. if ((string) $text != '') {
  619. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  620. }
  621. // Define value if value is after
  622. if ($direction > 0) {
  623. $s .= '<'.$tag.$paramfortooltipimg;
  624. if ($tag == 'td') {
  625. $s .= ' class="valignmiddle" width="14"';
  626. }
  627. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  628. }
  629. if (empty($notabs)) {
  630. $s .= '</tr></table>';
  631. } elseif ($notabs == 2) {
  632. $s .= '</div>';
  633. }
  634. return $s;
  635. }
  636. /**
  637. * Show a text with a picto and a tooltip on picto
  638. *
  639. * @param string $text Text to show
  640. * @param string $htmltext Content of tooltip
  641. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  642. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  643. * @param string $extracss Add a CSS style to td, div or span tag
  644. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  645. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  646. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key, clickable link is on image or on link if param $type='none' or on both if $type='xxxclickable')
  647. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  648. * @return string HTML code of text, picto, tooltip
  649. */
  650. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  651. {
  652. global $conf, $langs;
  653. $alt = '';
  654. if ($tooltiptrigger) {
  655. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  656. }
  657. //For backwards compatibility
  658. if ($type == '0') {
  659. $type = 'info';
  660. } elseif ($type == '1') {
  661. $type = 'help';
  662. }
  663. // If info or help with no javascript, show only text
  664. if (empty($conf->use_javascript_ajax)) {
  665. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  666. return $text;
  667. } else {
  668. $alt = $htmltext;
  669. $htmltext = '';
  670. }
  671. }
  672. // If info or help with smartphone, show only text (tooltip hover can't works)
  673. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  674. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  675. return $text;
  676. }
  677. }
  678. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  679. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  680. //{
  681. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  682. //}
  683. $img = '';
  684. if ($type == 'info') {
  685. $img = img_help(0, $alt);
  686. } elseif ($type == 'help') {
  687. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  688. } elseif ($type == 'helpclickable') {
  689. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  690. } elseif ($type == 'superadmin') {
  691. $img = img_picto($alt, 'redstar');
  692. } elseif ($type == 'admin') {
  693. $img = img_picto($alt, 'star');
  694. } elseif ($type == 'warning') {
  695. $img = img_warning($alt);
  696. } elseif ($type != 'none') {
  697. $img = img_picto($alt, $type); // $type can be an image path
  698. }
  699. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  700. }
  701. /**
  702. * Generate select HTML to choose massaction
  703. *
  704. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  705. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  706. * @param int $alwaysvisible 1=select button always visible
  707. * @param string $name Name for massaction
  708. * @param string $cssclass CSS class used to check for select
  709. * @return string|void Select list
  710. */
  711. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  712. {
  713. global $conf, $langs, $hookmanager;
  714. $disabled = 0;
  715. $ret = '<div class="centpercent center">';
  716. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  717. // 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.
  718. $parameters = array();
  719. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  720. // check if there is a mass action
  721. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  722. return;
  723. }
  724. if (empty($reshook)) {
  725. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  726. foreach ($arrayofaction as $code => $label) {
  727. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  728. }
  729. }
  730. $ret .= $hookmanager->resPrint;
  731. $ret .= '</select>';
  732. if (empty($conf->dol_optimize_smallscreen)) {
  733. $ret .= ajax_combobox('.'.$name.'select');
  734. }
  735. // 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
  736. $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.
  737. $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")).'">';
  738. $ret .= '</div>';
  739. if (!empty($conf->use_javascript_ajax)) {
  740. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  741. <script>
  742. 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 */
  743. {
  744. atleastoneselected=0;
  745. jQuery("."+cssclass).each(function( index ) {
  746. /* console.log( index + ": " + $( this ).text() ); */
  747. if ($(this).is(\':checked\')) atleastoneselected++;
  748. });
  749. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  750. if (atleastoneselected || '.$alwaysvisible.')
  751. {
  752. jQuery("."+name).show();
  753. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  754. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  755. }
  756. else
  757. {
  758. jQuery("."+name).hide();
  759. jQuery("."+name+"other").hide();
  760. }
  761. }
  762. jQuery(document).ready(function () {
  763. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  764. jQuery(".' . $cssclass.'").click(function() {
  765. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  766. });
  767. jQuery(".' . $name.'select").change(function() {
  768. var massaction = $( this ).val();
  769. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  770. if (massaction == "builddoc")
  771. {
  772. urlform = urlform + "#show_files";
  773. }
  774. $( this ).closest("form").attr("action", urlform);
  775. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  776. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  777. if ($(this).val() != \'0\')
  778. {
  779. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  780. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  781. jQuery(".' . $name.'"+massaction).show();
  782. }
  783. else
  784. {
  785. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  786. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  787. }
  788. });
  789. });
  790. </script>
  791. ';
  792. }
  793. return $ret;
  794. }
  795. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  796. /**
  797. * Return combo list of activated countries, into language of user
  798. *
  799. * @param string $selected Id or Code or Label of preselected country
  800. * @param string $htmlname Name of html select object
  801. * @param string $htmloption More html options on select object
  802. * @param integer $maxlength Max length for labels (0=no limit)
  803. * @param string $morecss More css class
  804. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  805. * @param int $showempty Show empty choice
  806. * @param int $disablefavorites 1=Disable favorites,
  807. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  808. * @param array $exclude_country_code Array of country code (iso2) to exclude
  809. * @param int $hideflags Hide flags
  810. * @return string HTML string with select
  811. */
  812. 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)
  813. {
  814. // phpcs:enable
  815. global $conf, $langs, $mysoc;
  816. $langs->load("dict");
  817. $out = '';
  818. $countryArray = array();
  819. $favorite = array();
  820. $label = array();
  821. $atleastonefavorite = 0;
  822. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  823. $sql .= " FROM ".$this->db->prefix()."c_country";
  824. $sql .= " WHERE active > 0";
  825. //$sql.= " ORDER BY code ASC";
  826. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  827. $resql = $this->db->query($sql);
  828. if ($resql) {
  829. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  830. $num = $this->db->num_rows($resql);
  831. $i = 0;
  832. if ($num) {
  833. while ($i < $num) {
  834. $obj = $this->db->fetch_object($resql);
  835. $countryArray[$i]['rowid'] = $obj->rowid;
  836. $countryArray[$i]['code_iso'] = $obj->code_iso;
  837. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  838. $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 : ''));
  839. $countryArray[$i]['favorite'] = $obj->favorite;
  840. $countryArray[$i]['eec'] = $obj->eec;
  841. $favorite[$i] = $obj->favorite;
  842. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  843. $i++;
  844. }
  845. if (empty($disablefavorites)) {
  846. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  847. } else {
  848. $countryArray = dol_sort_array($countryArray, 'label');
  849. }
  850. if ($showempty) {
  851. $out .= '<option value="">&nbsp;</option>'."\n";
  852. }
  853. if ($addspecialentries) { // Add dedicated entries for groups of countries
  854. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  855. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  856. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  857. if ($mysoc->isInEEC()) {
  858. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  859. }
  860. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  861. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  862. }
  863. foreach ($countryArray as $row) {
  864. //if (empty($showempty) && empty($row['rowid'])) continue;
  865. if (empty($row['rowid'])) {
  866. continue;
  867. }
  868. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  869. continue; // exclude some countries
  870. }
  871. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  872. $atleastonefavorite++;
  873. }
  874. if (empty($row['favorite']) && $atleastonefavorite) {
  875. $atleastonefavorite = 0;
  876. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  877. }
  878. $labeltoshow = '';
  879. if ($row['label']) {
  880. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  881. } else {
  882. $labeltoshow .= '&nbsp;';
  883. }
  884. if ($row['code_iso']) {
  885. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  886. if (empty($hideflags)) {
  887. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  888. $labeltoshow = $tmpflag.' '.$labeltoshow;
  889. }
  890. }
  891. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  892. $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']).'">';
  893. } else {
  894. $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']).'">';
  895. }
  896. $out .= $labeltoshow;
  897. $out .= '</option>'."\n";
  898. }
  899. }
  900. $out .= '</select>';
  901. } else {
  902. dol_print_error($this->db);
  903. }
  904. // Make select dynamic
  905. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  906. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  907. return $out;
  908. }
  909. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  910. /**
  911. * Return select list of incoterms
  912. *
  913. * @param string $selected Id or Code of preselected incoterm
  914. * @param string $location_incoterms Value of input location
  915. * @param string $page Defined the form action
  916. * @param string $htmlname Name of html select object
  917. * @param string $htmloption Options html on select object
  918. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  919. * @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')))
  920. * @param array $disableautocomplete Disable autocomplete
  921. * @return string HTML string with select and input
  922. */
  923. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  924. {
  925. // phpcs:enable
  926. global $conf, $langs;
  927. $langs->load("dict");
  928. $out = '';
  929. $moreattrib = '';
  930. $incotermArray = array();
  931. $sql = "SELECT rowid, code";
  932. $sql .= " FROM ".$this->db->prefix()."c_incoterms";
  933. $sql .= " WHERE active > 0";
  934. $sql .= " ORDER BY code ASC";
  935. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  936. $resql = $this->db->query($sql);
  937. if ($resql) {
  938. if ($conf->use_javascript_ajax && !$forcecombo) {
  939. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  940. $out .= ajax_combobox($htmlname, $events);
  941. }
  942. if (!empty($page)) {
  943. $out .= '<form method="post" action="'.$page.'">';
  944. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  945. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  946. }
  947. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  948. $out .= '<option value="0">&nbsp;</option>';
  949. $num = $this->db->num_rows($resql);
  950. $i = 0;
  951. if ($num) {
  952. while ($i < $num) {
  953. $obj = $this->db->fetch_object($resql);
  954. $incotermArray[$i]['rowid'] = $obj->rowid;
  955. $incotermArray[$i]['code'] = $obj->code;
  956. $i++;
  957. }
  958. foreach ($incotermArray as $row) {
  959. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  960. $out .= '<option value="'.$row['rowid'].'" selected>';
  961. } else {
  962. $out .= '<option value="'.$row['rowid'].'">';
  963. }
  964. if ($row['code']) {
  965. $out .= $row['code'];
  966. }
  967. $out .= '</option>';
  968. }
  969. }
  970. $out .= '</select>';
  971. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  972. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  973. $moreattrib .= ' autocomplete="off"';
  974. }
  975. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  976. if (!empty($page)) {
  977. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  978. }
  979. } else {
  980. dol_print_error($this->db);
  981. }
  982. return $out;
  983. }
  984. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  985. /**
  986. * Return list of types of lines (product or service)
  987. * Example: 0=product, 1=service, 9=other (for external module)
  988. *
  989. * @param string $selected Preselected type
  990. * @param string $htmlname Name of field in html form
  991. * @param int $showempty Add an empty field
  992. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  993. * @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')
  994. * @return void
  995. */
  996. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  997. {
  998. // phpcs:enable
  999. global $langs, $conf;
  1000. // If product & services are enabled or both disabled.
  1001. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  1002. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
  1003. if (empty($hidetext)) {
  1004. print $langs->trans("Type").': ';
  1005. }
  1006. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  1007. if ($showempty) {
  1008. print '<option value="-1"';
  1009. if ($selected == -1) {
  1010. print ' selected';
  1011. }
  1012. print '>&nbsp;</option>';
  1013. }
  1014. print '<option value="0"';
  1015. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1016. print ' selected';
  1017. }
  1018. print '>'.$langs->trans("Product");
  1019. print '<option value="1"';
  1020. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1021. print ' selected';
  1022. }
  1023. print '>'.$langs->trans("Service");
  1024. print '</select>';
  1025. print ajax_combobox('select_'.$htmlname);
  1026. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1027. }
  1028. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
  1029. print $langs->trans("Service");
  1030. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1031. }
  1032. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
  1033. print $langs->trans("Product");
  1034. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1035. }
  1036. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1037. 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
  1038. }
  1039. }
  1040. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1041. /**
  1042. * Load into cache cache_types_fees, array of types of fees
  1043. *
  1044. * @return int Nb of lines loaded, <0 if KO
  1045. */
  1046. public function load_cache_types_fees()
  1047. {
  1048. // phpcs:enable
  1049. global $langs;
  1050. $num = count($this->cache_types_fees);
  1051. if ($num > 0) {
  1052. return 0; // Cache already loaded
  1053. }
  1054. dol_syslog(__METHOD__, LOG_DEBUG);
  1055. $langs->load("trips");
  1056. $sql = "SELECT c.code, c.label";
  1057. $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
  1058. $sql .= " WHERE active > 0";
  1059. $resql = $this->db->query($sql);
  1060. if ($resql) {
  1061. $num = $this->db->num_rows($resql);
  1062. $i = 0;
  1063. while ($i < $num) {
  1064. $obj = $this->db->fetch_object($resql);
  1065. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1066. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1067. $this->cache_types_fees[$obj->code] = $label;
  1068. $i++;
  1069. }
  1070. asort($this->cache_types_fees);
  1071. return $num;
  1072. } else {
  1073. dol_print_error($this->db);
  1074. return -1;
  1075. }
  1076. }
  1077. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1078. /**
  1079. * Return list of types of notes
  1080. *
  1081. * @param string $selected Preselected type
  1082. * @param string $htmlname Name of field in form
  1083. * @param int $showempty Add an empty field
  1084. * @return void
  1085. */
  1086. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1087. {
  1088. // phpcs:enable
  1089. global $user, $langs;
  1090. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1091. $this->load_cache_types_fees();
  1092. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1093. if ($showempty) {
  1094. print '<option value="-1"';
  1095. if ($selected == -1) {
  1096. print ' selected';
  1097. }
  1098. print '>&nbsp;</option>';
  1099. }
  1100. foreach ($this->cache_types_fees as $key => $value) {
  1101. print '<option value="'.$key.'"';
  1102. if ($key == $selected) {
  1103. print ' selected';
  1104. }
  1105. print '>';
  1106. print $value;
  1107. print '</option>';
  1108. }
  1109. print '</select>';
  1110. if ($user->admin) {
  1111. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1112. }
  1113. }
  1114. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1115. /**
  1116. * Output html form to select a third party
  1117. *
  1118. * @param string $selected Preselected type
  1119. * @param string $htmlname Name of field in form
  1120. * @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)')
  1121. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1122. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1123. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1124. * @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')))
  1125. * @param int $limit Maximum number of elements
  1126. * @param string $morecss Add more css styles to the SELECT component
  1127. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1128. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1129. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1130. * @param array $ajaxoptions Options for ajax_autocompleter
  1131. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1132. * @param array $excludeids Exclude IDs from the select combo
  1133. * @return string HTML string with select box for thirdparty.
  1134. */
  1135. 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())
  1136. {
  1137. // phpcs:enable
  1138. global $conf, $user, $langs;
  1139. $out = '';
  1140. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1141. if (is_null($ajaxoptions)) {
  1142. $ajaxoptions = array();
  1143. }
  1144. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1145. // No immediate load of all database
  1146. $placeholder = '';
  1147. if ($selected && empty($selected_input_value)) {
  1148. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1149. $societetmp = new Societe($this->db);
  1150. $societetmp->fetch($selected);
  1151. $selected_input_value = $societetmp->name;
  1152. unset($societetmp);
  1153. }
  1154. // mode 1
  1155. $urloption = 'htmlname='.urlencode(str_replace('.', '_', $htmlname)).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '');
  1156. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1157. if (empty($hidelabel)) {
  1158. print $langs->trans("RefOrLabel").' : ';
  1159. } elseif ($hidelabel > 1) {
  1160. $placeholder = $langs->trans("RefOrLabel");
  1161. if ($hidelabel == 2) {
  1162. $out .= img_picto($langs->trans("Search"), 'search');
  1163. }
  1164. }
  1165. $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' : '').' />';
  1166. if ($hidelabel == 3) {
  1167. $out .= img_picto($langs->trans("Search"), 'search');
  1168. }
  1169. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1170. } else {
  1171. // Immediate load of all database
  1172. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids);
  1173. }
  1174. return $out;
  1175. }
  1176. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1177. /**
  1178. * Output html form to select a third party.
  1179. * 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.
  1180. *
  1181. * @param string $selected Preselected type
  1182. * @param string $htmlname Name of field in form
  1183. * @param string $filter Optional filters criteras (example: 's.rowid NOT IN (x)', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1184. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1185. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1186. * @param int $forcecombo Force to use standard HTML select component without beautification
  1187. * @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')))
  1188. * @param string $filterkey Filter on key value
  1189. * @param int $outputmode 0=HTML select string, 1=Array
  1190. * @param int $limit Limit number of answers
  1191. * @param string $morecss Add more css styles to the SELECT component
  1192. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1193. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1194. * @param array $excludeids Exclude IDs from the select combo
  1195. * @return string HTML string with
  1196. */
  1197. 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())
  1198. {
  1199. // phpcs:enable
  1200. global $conf, $user, $langs;
  1201. global $hookmanager;
  1202. $out = '';
  1203. $num = 0;
  1204. $outarray = array();
  1205. if ($selected === '') {
  1206. $selected = array();
  1207. } elseif (!is_array($selected)) {
  1208. $selected = array($selected);
  1209. }
  1210. // Clean $filter that may contains sql conditions so sql code
  1211. if (function_exists('testSqlAndScriptInject')) {
  1212. if (testSqlAndScriptInject($filter, 3) > 0) {
  1213. $filter = '';
  1214. }
  1215. }
  1216. // We search companies
  1217. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1218. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1219. $sql .= ", s.address, s.zip, s.town";
  1220. $sql .= ", dictp.code as country_code";
  1221. }
  1222. $sql .= " FROM ".$this->db->prefix()."societe as s";
  1223. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1224. $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
  1225. }
  1226. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1227. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  1228. }
  1229. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1230. if (!empty($user->socid)) {
  1231. $sql .= " AND s.rowid = ".((int) $user->socid);
  1232. }
  1233. if ($filter) {
  1234. $sql .= " AND (".$filter.")";
  1235. }
  1236. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1237. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1238. }
  1239. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1240. $sql .= " AND s.status <> 0";
  1241. }
  1242. if (!empty($excludeids)) {
  1243. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1244. }
  1245. // Add where from hooks
  1246. $parameters = array();
  1247. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1248. $sql .= $hookmanager->resPrint;
  1249. // Add criteria
  1250. if ($filterkey && $filterkey != '') {
  1251. $sql .= " AND (";
  1252. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1253. // For natural search
  1254. $scrit = explode(' ', $filterkey);
  1255. $i = 0;
  1256. if (count($scrit) > 1) {
  1257. $sql .= "(";
  1258. }
  1259. foreach ($scrit as $crit) {
  1260. if ($i > 0) {
  1261. $sql .= " AND ";
  1262. }
  1263. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1264. $i++;
  1265. }
  1266. if (count($scrit) > 1) {
  1267. $sql .= ")";
  1268. }
  1269. if (!empty($conf->barcode->enabled)) {
  1270. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1271. }
  1272. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1273. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1274. $sql .= ")";
  1275. }
  1276. $sql .= $this->db->order("nom", "ASC");
  1277. $sql .= $this->db->plimit($limit, 0);
  1278. // Build output string
  1279. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1280. $resql = $this->db->query($sql);
  1281. if ($resql) {
  1282. if (!$forcecombo) {
  1283. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1284. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1285. }
  1286. // Construct $out and $outarray
  1287. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1288. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1289. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1290. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1291. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1292. if ($showempty && !is_numeric($showempty)) {
  1293. $textifempty = $langs->trans($showempty);
  1294. } else {
  1295. $textifempty .= $langs->trans("All");
  1296. }
  1297. }
  1298. if ($showempty) {
  1299. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1300. }
  1301. $num = $this->db->num_rows($resql);
  1302. $i = 0;
  1303. if ($num) {
  1304. while ($i < $num) {
  1305. $obj = $this->db->fetch_object($resql);
  1306. $label = '';
  1307. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1308. if (($obj->client) && (!empty($obj->code_client))) {
  1309. $label = $obj->code_client.' - ';
  1310. }
  1311. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1312. $label .= $obj->code_fournisseur.' - ';
  1313. }
  1314. $label .= ' '.$obj->name;
  1315. } else {
  1316. $label = $obj->name;
  1317. }
  1318. if (!empty($obj->name_alias)) {
  1319. $label .= ' ('.$obj->name_alias.')';
  1320. }
  1321. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1322. $label .= ' - '.$obj->tva_intra.'';
  1323. }
  1324. if ($showtype) {
  1325. if ($obj->client || $obj->fournisseur) {
  1326. $label .= ' (';
  1327. }
  1328. if ($obj->client == 1 || $obj->client == 3) {
  1329. $label .= $langs->trans("Customer");
  1330. }
  1331. if ($obj->client == 2 || $obj->client == 3) {
  1332. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1333. }
  1334. if ($obj->fournisseur) {
  1335. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1336. }
  1337. if ($obj->client || $obj->fournisseur) {
  1338. $label .= ')';
  1339. }
  1340. }
  1341. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1342. $label .= ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1343. if (!empty($obj->country_code)) {
  1344. $label .= ', '.$langs->trans('Country'.$obj->country_code);
  1345. }
  1346. }
  1347. if (empty($outputmode)) {
  1348. if (in_array($obj->rowid, $selected)) {
  1349. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1350. } else {
  1351. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1352. }
  1353. } else {
  1354. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1355. }
  1356. $i++;
  1357. if (($i % 10) == 0) {
  1358. $out .= "\n";
  1359. }
  1360. }
  1361. }
  1362. $out .= '</select>'."\n";
  1363. } else {
  1364. dol_print_error($this->db);
  1365. }
  1366. $this->result = array('nbofthirdparties'=>$num);
  1367. if ($outputmode) {
  1368. return $outarray;
  1369. }
  1370. return $out;
  1371. }
  1372. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1373. /**
  1374. * Return HTML combo list of absolute discounts
  1375. *
  1376. * @param string $selected Id remise fixe pre-selectionnee
  1377. * @param string $htmlname Nom champ formulaire
  1378. * @param string $filter Criteres optionnels de filtre
  1379. * @param int $socid Id of thirdparty
  1380. * @param int $maxvalue Max value for lines that can be selected
  1381. * @return int Return number of qualifed lines in list
  1382. */
  1383. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1384. {
  1385. // phpcs:enable
  1386. global $langs, $conf;
  1387. // On recherche les remises
  1388. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1389. $sql .= " re.description, re.fk_facture_source";
  1390. $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
  1391. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1392. $sql .= " AND re.entity = ".$conf->entity;
  1393. if ($filter) {
  1394. $sql .= " AND ".$filter;
  1395. }
  1396. $sql .= " ORDER BY re.description ASC";
  1397. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1398. $resql = $this->db->query($sql);
  1399. if ($resql) {
  1400. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1401. $num = $this->db->num_rows($resql);
  1402. $qualifiedlines = $num;
  1403. $i = 0;
  1404. if ($num) {
  1405. print '<option value="0">&nbsp;</option>';
  1406. while ($i < $num) {
  1407. $obj = $this->db->fetch_object($resql);
  1408. $desc = dol_trunc($obj->description, 40);
  1409. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1410. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1411. }
  1412. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1413. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1414. }
  1415. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1416. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1417. }
  1418. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1419. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1420. }
  1421. $selectstring = '';
  1422. if ($selected > 0 && $selected == $obj->rowid) {
  1423. $selectstring = ' selected';
  1424. }
  1425. $disabled = '';
  1426. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1427. $qualifiedlines--;
  1428. $disabled = ' disabled';
  1429. }
  1430. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1431. $tmpfac = new Facture($this->db);
  1432. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1433. $desc = $desc.' - '.$tmpfac->ref;
  1434. }
  1435. }
  1436. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1437. $i++;
  1438. }
  1439. }
  1440. print '</select>';
  1441. print ajax_combobox('select_'.$htmlname);
  1442. return $qualifiedlines;
  1443. } else {
  1444. dol_print_error($this->db);
  1445. return -1;
  1446. }
  1447. }
  1448. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1449. /**
  1450. * Return list of all contacts (for a third party or all)
  1451. *
  1452. * @param int $socid Id ot third party or 0 for all
  1453. * @param string $selected Id contact pre-selectionne
  1454. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1455. * @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
  1456. * @param string $exclude List of contacts id to exclude
  1457. * @param string $limitto Disable answers that are not id in this array list
  1458. * @param integer $showfunction Add function into label
  1459. * @param string $morecss Add more class to class style
  1460. * @param integer $showsoc Add company into label
  1461. * @param int $forcecombo Force to use combo box
  1462. * @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')))
  1463. * @param bool $options_only Return options only (for ajax treatment)
  1464. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1465. * @param string $htmlid Html id to use instead of htmlname
  1466. * @return int <0 if KO, Nb of contact in list if OK
  1467. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1468. */
  1469. 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 = '')
  1470. {
  1471. // phpcs:enable
  1472. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1473. return $this->num;
  1474. }
  1475. /**
  1476. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1477. * This also set the number of contacts found into $this->num
  1478. *
  1479. * @since 9.0 Add afterSelectContactOptions hook
  1480. *
  1481. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1482. * @param array|int $selected Array of ID of pre-selected contact id
  1483. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1484. * @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
  1485. * @param string $exclude List of contacts id to exclude
  1486. * @param string $limitto Disable answers that are not id in this array list
  1487. * @param integer $showfunction Add function into label
  1488. * @param string $morecss Add more class to class style
  1489. * @param bool $options_only Return options only (for ajax treatment)
  1490. * @param integer $showsoc Add company into label
  1491. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1492. * @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')))
  1493. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1494. * @param string $htmlid Html id to use instead of htmlname
  1495. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1496. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1497. * @return int|string <0 if KO, HTML with select string if OK.
  1498. */
  1499. 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)
  1500. {
  1501. global $conf, $langs, $hookmanager, $action;
  1502. $langs->load('companies');
  1503. if (empty($htmlid)) {
  1504. $htmlid = $htmlname;
  1505. }
  1506. $num = 0;
  1507. if ($selected === '') {
  1508. $selected = array();
  1509. } elseif (!is_array($selected)) {
  1510. $selected = array($selected);
  1511. }
  1512. $out = '';
  1513. if (!is_object($hookmanager)) {
  1514. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1515. $hookmanager = new HookManager($this->db);
  1516. }
  1517. // We search third parties
  1518. $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";
  1519. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1520. $sql .= ", s.nom as company, s.town AS company_town";
  1521. }
  1522. $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
  1523. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1524. $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
  1525. }
  1526. $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
  1527. if ($socid > 0 || $socid == -1) {
  1528. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1529. }
  1530. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1531. $sql .= " AND sp.statut <> 0";
  1532. }
  1533. // Add where from hooks
  1534. $parameters = array();
  1535. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1536. $sql .= $hookmanager->resPrint;
  1537. $sql .= " ORDER BY sp.lastname ASC";
  1538. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1539. $resql = $this->db->query($sql);
  1540. if ($resql) {
  1541. $num = $this->db->num_rows($resql);
  1542. if ($htmlname != 'none' && !$options_only) {
  1543. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1544. }
  1545. if ($showempty && ! is_numeric($showempty)) {
  1546. $textforempty = $showempty;
  1547. $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
  1548. } else {
  1549. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1550. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1551. }
  1552. if ($showempty == 2) {
  1553. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1554. }
  1555. }
  1556. $i = 0;
  1557. if ($num) {
  1558. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1559. $contactstatic = new Contact($this->db);
  1560. while ($i < $num) {
  1561. $obj = $this->db->fetch_object($resql);
  1562. // Set email (or phones) and town extended infos
  1563. $extendedInfos = '';
  1564. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1565. $extendedInfos = array();
  1566. $email = trim($obj->email);
  1567. if (!empty($email)) {
  1568. $extendedInfos[] = $email;
  1569. } else {
  1570. $phone = trim($obj->phone);
  1571. $phone_perso = trim($obj->phone_perso);
  1572. $phone_mobile = trim($obj->phone_mobile);
  1573. if (!empty($phone)) {
  1574. $extendedInfos[] = $phone;
  1575. }
  1576. if (!empty($phone_perso)) {
  1577. $extendedInfos[] = $phone_perso;
  1578. }
  1579. if (!empty($phone_mobile)) {
  1580. $extendedInfos[] = $phone_mobile;
  1581. }
  1582. }
  1583. $contact_town = trim($obj->contact_town);
  1584. $company_town = trim($obj->company_town);
  1585. if (!empty($contact_town)) {
  1586. $extendedInfos[] = $contact_town;
  1587. } elseif (!empty($company_town)) {
  1588. $extendedInfos[] = $company_town;
  1589. }
  1590. $extendedInfos = implode(' - ', $extendedInfos);
  1591. if (!empty($extendedInfos)) {
  1592. $extendedInfos = ' - '.$extendedInfos;
  1593. }
  1594. }
  1595. $contactstatic->id = $obj->rowid;
  1596. $contactstatic->lastname = $obj->lastname;
  1597. $contactstatic->firstname = $obj->firstname;
  1598. if ($obj->statut == 1) {
  1599. if ($htmlname != 'none') {
  1600. $disabled = 0;
  1601. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1602. $disabled = 1;
  1603. }
  1604. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1605. $disabled = 1;
  1606. }
  1607. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1608. $out .= '<option value="'.$obj->rowid.'"';
  1609. if ($disabled) {
  1610. $out .= ' disabled';
  1611. }
  1612. $out .= ' selected>';
  1613. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1614. if ($showfunction && $obj->poste) {
  1615. $out .= ' ('.$obj->poste.')';
  1616. }
  1617. if (($showsoc > 0) && $obj->company) {
  1618. $out .= ' - ('.$obj->company.')';
  1619. }
  1620. $out .= '</option>';
  1621. } else {
  1622. $out .= '<option value="'.$obj->rowid.'"';
  1623. if ($disabled) {
  1624. $out .= ' disabled';
  1625. }
  1626. $out .= '>';
  1627. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1628. if ($showfunction && $obj->poste) {
  1629. $out .= ' ('.$obj->poste.')';
  1630. }
  1631. if (($showsoc > 0) && $obj->company) {
  1632. $out .= ' - ('.$obj->company.')';
  1633. }
  1634. $out .= '</option>';
  1635. }
  1636. } else {
  1637. if (in_array($obj->rowid, $selected)) {
  1638. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1639. if ($showfunction && $obj->poste) {
  1640. $out .= ' ('.$obj->poste.')';
  1641. }
  1642. if (($showsoc > 0) && $obj->company) {
  1643. $out .= ' - ('.$obj->company.')';
  1644. }
  1645. }
  1646. }
  1647. }
  1648. $i++;
  1649. }
  1650. } else {
  1651. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1652. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1653. $out .= $labeltoshow;
  1654. $out .= '</option>';
  1655. }
  1656. $parameters = array(
  1657. 'socid'=>$socid,
  1658. 'htmlname'=>$htmlname,
  1659. 'resql'=>$resql,
  1660. 'out'=>&$out,
  1661. 'showfunction'=>$showfunction,
  1662. 'showsoc'=>$showsoc,
  1663. );
  1664. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1665. if ($htmlname != 'none' && !$options_only) {
  1666. $out .= '</select>';
  1667. }
  1668. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1669. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1670. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1671. }
  1672. $this->num = $num;
  1673. return $out;
  1674. } else {
  1675. dol_print_error($this->db);
  1676. return -1;
  1677. }
  1678. }
  1679. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1680. /**
  1681. * Return the HTML select list of users
  1682. *
  1683. * @param string $selected Id user preselected
  1684. * @param string $htmlname Field name in form
  1685. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1686. * @param array $exclude Array list of users id to exclude
  1687. * @param int $disabled If select list must be disabled
  1688. * @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
  1689. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1690. * @param string $force_entity '0' or Ids of environment to force
  1691. * @return void
  1692. * @deprecated Use select_dolusers instead
  1693. * @see select_dolusers()
  1694. */
  1695. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1696. {
  1697. // phpcs:enable
  1698. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1699. }
  1700. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1701. /**
  1702. * Return select list of users
  1703. *
  1704. * @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)
  1705. * @param string $htmlname Field name in form
  1706. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1707. * @param array $exclude Array list of users id to exclude
  1708. * @param int $disabled If select list must be disabled
  1709. * @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
  1710. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1711. * @param string $force_entity '0' or Ids of environment to force
  1712. * @param int $maxlength Maximum length of string into list (0=no limit)
  1713. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1714. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1715. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1716. * @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.
  1717. * @param string $morecss More css
  1718. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1719. * @param int $outputmode 0=HTML select string, 1=Array
  1720. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1721. * @return string HTML select string
  1722. * @see select_dolgroups()
  1723. */
  1724. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $noactive = 0, $outputmode = 0, $multiple = false)
  1725. {
  1726. // phpcs:enable
  1727. global $conf, $user, $langs, $hookmanager;
  1728. global $action;
  1729. // If no preselected user defined, we take current user
  1730. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1731. $selected = $user->id;
  1732. }
  1733. if ($selected === '') {
  1734. $selected = array();
  1735. } elseif (!is_array($selected)) {
  1736. $selected = array($selected);
  1737. }
  1738. $excludeUsers = null;
  1739. $includeUsers = null;
  1740. // Permettre l'exclusion d'utilisateurs
  1741. if (is_array($exclude)) {
  1742. $excludeUsers = implode(",", $exclude);
  1743. }
  1744. // Permettre l'inclusion d'utilisateurs
  1745. if (is_array($include)) {
  1746. $includeUsers = implode(",", $include);
  1747. } elseif ($include == 'hierarchy') {
  1748. // Build list includeUsers to have only hierarchy
  1749. $includeUsers = implode(",", $user->getAllChildIds(0));
  1750. } elseif ($include == 'hierarchyme') {
  1751. // Build list includeUsers to have only hierarchy and current user
  1752. $includeUsers = implode(",", $user->getAllChildIds(1));
  1753. }
  1754. $out = '';
  1755. $outarray = array();
  1756. // Forge request to select users
  1757. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1758. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1759. $sql .= ", e.label";
  1760. }
  1761. $sql .= " FROM ".$this->db->prefix()."user as u";
  1762. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1763. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
  1764. if ($force_entity) {
  1765. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1766. } else {
  1767. $sql .= " WHERE u.entity IS NOT NULL";
  1768. }
  1769. } else {
  1770. if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1771. $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
  1772. $sql .= " ON ug.fk_user = u.rowid";
  1773. $sql .= " WHERE ug.entity = ".$conf->entity;
  1774. } else {
  1775. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1776. }
  1777. }
  1778. if (!empty($user->socid)) {
  1779. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1780. }
  1781. if (is_array($exclude) && $excludeUsers) {
  1782. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1783. }
  1784. if ($includeUsers) {
  1785. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1786. }
  1787. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
  1788. $sql .= " AND u.statut <> 0";
  1789. }
  1790. if (!empty($morefilter)) {
  1791. $sql .= " ".$morefilter;
  1792. }
  1793. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1794. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1795. if (!empty($reshook)) {
  1796. $sql .= $hookmanager->resPrint;
  1797. }
  1798. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1799. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1800. } else {
  1801. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1802. }
  1803. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1804. $resql = $this->db->query($sql);
  1805. if ($resql) {
  1806. $num = $this->db->num_rows($resql);
  1807. $i = 0;
  1808. if ($num) {
  1809. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1810. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1811. if ($show_empty && !$multiple) {
  1812. $textforempty = ' ';
  1813. if (!empty($conf->use_javascript_ajax)) {
  1814. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1815. }
  1816. if (!is_numeric($show_empty)) {
  1817. $textforempty = $show_empty;
  1818. }
  1819. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1820. }
  1821. if ($show_every) {
  1822. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1823. }
  1824. $userstatic = new User($this->db);
  1825. while ($i < $num) {
  1826. $obj = $this->db->fetch_object($resql);
  1827. $userstatic->id = $obj->rowid;
  1828. $userstatic->lastname = $obj->lastname;
  1829. $userstatic->firstname = $obj->firstname;
  1830. $userstatic->photo = $obj->photo;
  1831. $userstatic->statut = $obj->status;
  1832. $userstatic->entity = $obj->entity;
  1833. $userstatic->admin = $obj->admin;
  1834. $disableline = '';
  1835. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1836. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1837. }
  1838. $labeltoshow = '';
  1839. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1840. $fullNameMode = 0;
  1841. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1842. $fullNameMode = 1; //Firstname+lastname
  1843. }
  1844. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1845. if (empty($obj->firstname) && empty($obj->lastname)) {
  1846. $labeltoshow .= $obj->login;
  1847. }
  1848. // Complete name with more info
  1849. $moreinfo = '';
  1850. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1851. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1852. }
  1853. if ($showstatus >= 0) {
  1854. if ($obj->status == 1 && $showstatus == 1) {
  1855. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1856. }
  1857. if ($obj->status == 0 && $showstatus == 1) {
  1858. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1859. }
  1860. }
  1861. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1862. if (!$obj->entity) {
  1863. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1864. } else {
  1865. if ($obj->entity != $conf->entity) {
  1866. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1867. }
  1868. }
  1869. }
  1870. $moreinfo .= ($moreinfo ? ')' : '');
  1871. if ($disableline && $disableline != '1') {
  1872. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1873. }
  1874. $labeltoshow .= $moreinfo;
  1875. $out .= '<option value="'.$obj->rowid.'"';
  1876. if ($disableline) {
  1877. $out .= ' disabled';
  1878. }
  1879. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1880. $out .= ' selected';
  1881. }
  1882. $out .= ' data-html="';
  1883. $outhtml = '';
  1884. // if (!empty($obj->photo)) {
  1885. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1886. // }
  1887. if ($showstatus >= 0 && $obj->status == 0) {
  1888. $outhtml .= '<strike class="opacitymediumxxx">';
  1889. }
  1890. $outhtml .= $labeltoshow;
  1891. if ($showstatus >= 0 && $obj->status == 0) {
  1892. $outhtml .= '</strike>';
  1893. }
  1894. $out .= dol_escape_htmltag($outhtml);
  1895. $out .= '">';
  1896. $out .= $labeltoshow;
  1897. $out .= '</option>';
  1898. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1899. $i++;
  1900. }
  1901. } else {
  1902. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1903. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1904. }
  1905. $out .= '</select>';
  1906. if ($num) {
  1907. // Enhance with select2
  1908. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1909. $out .= ajax_combobox($htmlname);
  1910. }
  1911. } else {
  1912. dol_print_error($this->db);
  1913. }
  1914. if ($outputmode) {
  1915. return $outarray;
  1916. }
  1917. return $out;
  1918. }
  1919. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1920. /**
  1921. * Return select list of users. Selected users are stored into session.
  1922. * List of users are provided into $_SESSION['assignedtouser'].
  1923. *
  1924. * @param string $action Value for $action
  1925. * @param string $htmlname Field name in form
  1926. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1927. * @param array $exclude Array list of users id to exclude
  1928. * @param int $disabled If select list must be disabled
  1929. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1930. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1931. * @param int $force_entity '0' or Ids of environment to force
  1932. * @param int $maxlength Maximum length of string into list (0=no limit)
  1933. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1934. * @param string $morefilter Add more filters into sql request
  1935. * @param int $showproperties Show properties of each attendees
  1936. * @param array $listofuserid Array with properties of each user
  1937. * @param array $listofcontactid Array with properties of each contact
  1938. * @param array $listofotherid Array with properties of each other contact
  1939. * @return string HTML select string
  1940. * @see select_dolgroups()
  1941. */
  1942. 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())
  1943. {
  1944. // phpcs:enable
  1945. global $conf, $user, $langs;
  1946. $userstatic = new User($this->db);
  1947. $out = '';
  1948. $assignedtouser = array();
  1949. if (!empty($_SESSION['assignedtouser'])) {
  1950. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1951. }
  1952. $nbassignetouser = count($assignedtouser);
  1953. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1954. if ($nbassignetouser) {
  1955. $out .= '<ul class="attendees">';
  1956. }
  1957. $i = 0;
  1958. $ownerid = 0;
  1959. foreach ($assignedtouser as $key => $value) {
  1960. if ($value['id'] == $ownerid) {
  1961. continue;
  1962. }
  1963. $out .= '<li>';
  1964. $userstatic->fetch($value['id']);
  1965. $out .= $userstatic->getNomUrl(-1);
  1966. if ($i == 0) {
  1967. $ownerid = $value['id'];
  1968. $out .= ' ('.$langs->trans("Owner").')';
  1969. }
  1970. if ($nbassignetouser > 1 && $action != 'view') {
  1971. $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.'">';
  1972. }
  1973. // Show my availability
  1974. if ($showproperties) {
  1975. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  1976. $out .= '<div class="myavailability inline-block">';
  1977. $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>';
  1978. $out .= '</div>';
  1979. }
  1980. }
  1981. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1982. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1983. $out .= '</li>';
  1984. $i++;
  1985. }
  1986. if ($nbassignetouser) {
  1987. $out .= '</ul>';
  1988. }
  1989. // Method with no ajax
  1990. if ($action != 'view') {
  1991. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1992. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  1993. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  1994. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  1995. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  1996. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  1997. $out .= '});';
  1998. $out .= '})</script>';
  1999. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2000. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  2001. $out .= '<br>';
  2002. }
  2003. return $out;
  2004. }
  2005. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2006. /**
  2007. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2008. *
  2009. * @param int $selected Preselected products
  2010. * @param string $htmlname Name of HTML select field (must be unique in page).
  2011. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2012. * @param int $limit Limit on number of returned lines
  2013. * @param int $price_level Level of price to show
  2014. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2015. * @param int $finished 2=all, 1=finished, 0=raw material
  2016. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2017. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2018. * @param array $ajaxoptions Options for ajax_autocompleter
  2019. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2020. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2021. * @param int $forcecombo Force to use combo box
  2022. * @param string $morecss Add more css on select
  2023. * @param int $hidepriceinlabel 1=Hide prices in label
  2024. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2025. * 'warehouseopen' = count products from open warehouses,
  2026. * 'warehouseclosed' = count products from closed warehouses,
  2027. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2028. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2029. * @param string $nooutput No print, return the output into a string
  2030. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2031. * @return void|string
  2032. */
  2033. 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)
  2034. {
  2035. // phpcs:enable
  2036. global $langs, $conf;
  2037. $out = '';
  2038. // check parameters
  2039. $price_level = (!empty($price_level) ? $price_level : 0);
  2040. if (is_null($ajaxoptions)) {
  2041. $ajaxoptions = array();
  2042. }
  2043. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  2044. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  2045. $filtertype = '0';
  2046. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  2047. $filtertype = '1';
  2048. }
  2049. }
  2050. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2051. $placeholder = '';
  2052. if ($selected && empty($selected_input_value)) {
  2053. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2054. $producttmpselect = new Product($this->db);
  2055. $producttmpselect->fetch($selected);
  2056. $selected_input_value = $producttmpselect->ref;
  2057. unset($producttmpselect);
  2058. }
  2059. // handle case where product or service module is disabled + no filter specified
  2060. if ($filtertype == '') {
  2061. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2062. $filtertype = 1;
  2063. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2064. $filtertype = 0;
  2065. }
  2066. }
  2067. // mode=1 means customers products
  2068. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&status_purchase='.$status_purchase.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  2069. //Price by customer
  2070. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2071. $urloption .= '&socid='.$socid;
  2072. }
  2073. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2074. if (!empty($conf->variants->enabled) && is_array($selected_combinations)) {
  2075. // Code to automatically insert with javascript the select of attributes under the select of product
  2076. // when a parent of variant has been selected.
  2077. $out .= '
  2078. <!-- script to auto show attributes select tags if a variant was selected -->
  2079. <script>
  2080. // auto show attributes fields
  2081. selected = '.json_encode($selected_combinations).';
  2082. combvalues = {};
  2083. jQuery(document).ready(function () {
  2084. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2085. if (jQuery(this).val() == \'free\') {
  2086. jQuery(\'div#attributes_box\').empty();
  2087. }
  2088. });
  2089. jQuery("input#'.$htmlname.'").change(function () {
  2090. if (!jQuery(this).val()) {
  2091. jQuery(\'div#attributes_box\').empty();
  2092. return;
  2093. }
  2094. console.log("A change has started. We get variants fields to inject html select");
  2095. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2096. id: jQuery(this).val()
  2097. }, function (data) {
  2098. jQuery(\'div#attributes_box\').empty();
  2099. jQuery.each(data, function (key, val) {
  2100. combvalues[val.id] = val.values;
  2101. var span = jQuery(document.createElement(\'div\')).css({
  2102. \'display\': \'table-row\'
  2103. });
  2104. span.append(
  2105. jQuery(document.createElement(\'div\')).text(val.label).css({
  2106. \'font-weight\': \'bold\',
  2107. \'display\': \'table-cell\'
  2108. })
  2109. );
  2110. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2111. \'margin-left\': \'15px\',
  2112. \'white-space\': \'pre\'
  2113. }).append(
  2114. jQuery(document.createElement(\'option\')).val(\'\')
  2115. );
  2116. jQuery.each(combvalues[val.id], function (key, val) {
  2117. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2118. if (selected[val.fk_product_attribute] == val.id) {
  2119. tag.attr(\'selected\', \'selected\');
  2120. }
  2121. html.append(tag);
  2122. });
  2123. span.append(html);
  2124. jQuery(\'div#attributes_box\').append(span);
  2125. });
  2126. })
  2127. });
  2128. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2129. });
  2130. </script>
  2131. ';
  2132. }
  2133. if (empty($hidelabel)) {
  2134. $out .= $langs->trans("RefOrLabel").' : ';
  2135. } elseif ($hidelabel > 1) {
  2136. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2137. if ($hidelabel == 2) {
  2138. $out .= img_picto($langs->trans("Search"), 'search');
  2139. }
  2140. }
  2141. $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' : '').' />';
  2142. if ($hidelabel == 3) {
  2143. $out .= img_picto($langs->trans("Search"), 'search');
  2144. }
  2145. } else {
  2146. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2147. }
  2148. if (empty($nooutput)) {
  2149. print $out;
  2150. } else {
  2151. return $out;
  2152. }
  2153. }
  2154. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2155. /**
  2156. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2157. *
  2158. * @param int $selected Preselected BOM id
  2159. * @param string $htmlname Name of HTML select field (must be unique in page).
  2160. * @param int $limit Limit on number of returned lines
  2161. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2162. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2163. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2164. * @param string $morecss Add more css on select
  2165. * @param string $nooutput No print, return the output into a string
  2166. * @param int $forcecombo Force to use combo box
  2167. * @return void|string
  2168. */
  2169. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 1, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0)
  2170. {
  2171. // phpcs:enable
  2172. global $conf, $user, $langs, $db;
  2173. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2174. $error = 0;
  2175. $out = '';
  2176. if (!$forcecombo) {
  2177. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2178. $events = array();
  2179. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2180. }
  2181. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2182. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2183. $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
  2184. $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
  2185. if (!empty($status)) $sql.= ' AND status = '. (int) $status;
  2186. if (!empty($type)) $sql.= ' AND status = '. (int) $type;
  2187. if (!empty($limit)) $sql.= 'LIMIT '. (int) $limit;
  2188. $resql = $db->query($sql);
  2189. if ($resql) {
  2190. if ($showempty) {
  2191. $out .= '<option value="-1"';
  2192. if (empty($selected)) $out .= ' selected';
  2193. $out .= '>&nbsp;</option>';
  2194. }
  2195. while ($obj = $db->fetch_object($resql)) {
  2196. $product = new Product($db);
  2197. $res = $product->fetch($obj->fk_product);
  2198. if ($obj->rowid == $selected) $out .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.' - '. $product->label .' - '.$obj->label.'</option>';
  2199. $out .= '<option value="'.$obj->rowid.'">'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
  2200. }
  2201. } else {
  2202. $error++;
  2203. dol_print_error($db);
  2204. }
  2205. if (empty($nooutput)) {
  2206. print $out;
  2207. } else {
  2208. return $out;
  2209. }
  2210. }
  2211. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2212. /**
  2213. * Return list of products for a customer.
  2214. * Called by select_produits.
  2215. *
  2216. * @param int $selected Preselected product
  2217. * @param string $htmlname Name of select html
  2218. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2219. * @param int $limit Limit on number of returned lines
  2220. * @param int $price_level Level of price to show
  2221. * @param string $filterkey Filter on product
  2222. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2223. * @param int $finished Filter on finished field: 2=No filter
  2224. * @param int $outputmode 0=HTML select string, 1=Array
  2225. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2226. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2227. * @param int $forcecombo Force to use combo box
  2228. * @param string $morecss Add more css on select
  2229. * @param int $hidepriceinlabel 1=Hide prices in label
  2230. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2231. * 'warehouseopen' = count products from open warehouses,
  2232. * 'warehouseclosed' = count products from closed warehouses,
  2233. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2234. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2235. * @return array Array of keys for json
  2236. */
  2237. 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)
  2238. {
  2239. // phpcs:enable
  2240. global $langs, $conf;
  2241. global $hookmanager;
  2242. $out = '';
  2243. $outarray = array();
  2244. // Units
  2245. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2246. $langs->load('other');
  2247. }
  2248. $warehouseStatusArray = array();
  2249. if (!empty($warehouseStatus)) {
  2250. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2251. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2252. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2253. }
  2254. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2255. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2256. }
  2257. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2258. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2259. }
  2260. }
  2261. $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";
  2262. if (count($warehouseStatusArray)) {
  2263. $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
  2264. } else {
  2265. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2266. }
  2267. $sql = "SELECT ";
  2268. $sql .= $selectFields.$selectFieldsGrouped;
  2269. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2270. //Product category
  2271. $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
  2272. FROM ".$this->db->prefix()."categorie_product
  2273. WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
  2274. LIMIT 1
  2275. ) AS categorie_product_id ";
  2276. }
  2277. //Price by customer
  2278. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2279. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2280. $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';
  2281. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2282. }
  2283. // Units
  2284. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2285. $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";
  2286. $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';
  2287. }
  2288. // Multilang : we add translation
  2289. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2290. $sql .= ", pl.label as label_translated";
  2291. $sql .= ", pl.description as description_translated";
  2292. $selectFields .= ", label_translated";
  2293. $selectFields .= ", description_translated";
  2294. }
  2295. // Price by quantity
  2296. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2297. $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
  2298. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2299. $sql .= " AND price_level = ".((int) $price_level);
  2300. }
  2301. $sql .= " ORDER BY date_price";
  2302. $sql .= " DESC LIMIT 1) as price_rowid";
  2303. $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
  2304. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2305. $sql .= " AND price_level = ".((int) $price_level);
  2306. }
  2307. $sql .= " ORDER BY date_price";
  2308. $sql .= " DESC LIMIT 1) as price_by_qty";
  2309. $selectFields .= ", price_rowid, price_by_qty";
  2310. }
  2311. $sql .= " FROM ".$this->db->prefix()."product as p";
  2312. if (count($warehouseStatusArray)) {
  2313. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
  2314. $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2315. $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.
  2316. }
  2317. // include search in supplier ref
  2318. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2319. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2320. }
  2321. //Price by customer
  2322. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2323. $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2324. }
  2325. // Units
  2326. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2327. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2328. }
  2329. // Multilang : we add translation
  2330. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2331. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
  2332. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2333. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2334. $soc = new Societe($this->db);
  2335. $result = $soc->fetch($socid);
  2336. if ($result > 0 && !empty($soc->default_lang)) {
  2337. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2338. } else {
  2339. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2340. }
  2341. } else {
  2342. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2343. }
  2344. }
  2345. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2346. $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2347. }
  2348. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2349. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2350. $sql .= " AND pac.rowid IS NULL";
  2351. }
  2352. if ($finished == 0) {
  2353. $sql .= " AND p.finished = ".((int) $finished);
  2354. } elseif ($finished == 1) {
  2355. $sql .= " AND p.finished = ".((int) $finished);
  2356. if ($status >= 0) {
  2357. $sql .= " AND p.tosell = ".((int) $status);
  2358. }
  2359. } elseif ($status >= 0) {
  2360. $sql .= " AND p.tosell = ".((int) $status);
  2361. }
  2362. if ($status_purchase >= 0) {
  2363. $sql .= " AND p.tobuy = ".((int) $status_purchase);
  2364. }
  2365. // Filter by product type
  2366. if (strval($filtertype) != '') {
  2367. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2368. } elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2369. $sql .= " AND p.fk_product_type = 1";
  2370. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2371. $sql .= " AND p.fk_product_type = 0";
  2372. }
  2373. // Add where from hooks
  2374. $parameters = array();
  2375. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2376. $sql .= $hookmanager->resPrint;
  2377. // Add criteria on ref/label
  2378. if ($filterkey != '') {
  2379. $sql .= ' AND (';
  2380. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2381. // For natural search
  2382. $scrit = explode(' ', $filterkey);
  2383. $i = 0;
  2384. if (count($scrit) > 1) {
  2385. $sql .= "(";
  2386. }
  2387. foreach ($scrit as $crit) {
  2388. if ($i > 0) {
  2389. $sql .= " AND ";
  2390. }
  2391. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2392. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2393. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2394. }
  2395. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) {
  2396. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2397. }
  2398. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2399. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2400. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2401. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2402. }
  2403. }
  2404. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2405. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2406. }
  2407. $sql .= ")";
  2408. $i++;
  2409. }
  2410. if (count($scrit) > 1) {
  2411. $sql .= ")";
  2412. }
  2413. if (!empty($conf->barcode->enabled)) {
  2414. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2415. }
  2416. $sql .= ')';
  2417. }
  2418. if (count($warehouseStatusArray)) {
  2419. $sql .= " GROUP BY ".$selectFields;
  2420. }
  2421. //Sort by category
  2422. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2423. $sql .= " ORDER BY categorie_product_id ";
  2424. //ASC OR DESC order
  2425. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2426. } else {
  2427. $sql .= $this->db->order("p.ref");
  2428. }
  2429. $sql .= $this->db->plimit($limit, 0);
  2430. // Build output string
  2431. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2432. $result = $this->db->query($sql);
  2433. if ($result) {
  2434. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2435. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2436. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2437. $num = $this->db->num_rows($result);
  2438. $events = null;
  2439. if (!$forcecombo) {
  2440. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2441. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2442. }
  2443. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2444. $textifempty = '';
  2445. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2446. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2447. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2448. if ($showempty && !is_numeric($showempty)) {
  2449. $textifempty = $langs->trans($showempty);
  2450. } else {
  2451. $textifempty .= $langs->trans("All");
  2452. }
  2453. } else {
  2454. if ($showempty && !is_numeric($showempty)) {
  2455. $textifempty = $langs->trans($showempty);
  2456. }
  2457. }
  2458. if ($showempty) {
  2459. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2460. }
  2461. $i = 0;
  2462. while ($num && $i < $num) {
  2463. $opt = '';
  2464. $optJson = array();
  2465. $objp = $this->db->fetch_object($result);
  2466. 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
  2467. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2468. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2469. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2470. $sql .= " ORDER BY quantity ASC";
  2471. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2472. $result2 = $this->db->query($sql);
  2473. if ($result2) {
  2474. $nb_prices = $this->db->num_rows($result2);
  2475. $j = 0;
  2476. while ($nb_prices && $j < $nb_prices) {
  2477. $objp2 = $this->db->fetch_object($result2);
  2478. $objp->price_by_qty_rowid = $objp2->rowid;
  2479. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2480. $objp->price_by_qty_quantity = $objp2->quantity;
  2481. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2482. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2483. // For backward compatibility
  2484. $objp->quantity = $objp2->quantity;
  2485. $objp->price = $objp2->price;
  2486. $objp->unitprice = $objp2->unitprice;
  2487. $objp->remise_percent = $objp2->remise_percent;
  2488. //$objp->tva_tx is not overwritten by $objp2 value
  2489. //$objp->default_vat_code is not overwritten by $objp2 value
  2490. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2491. $j++;
  2492. // Add new entry
  2493. // "key" value of json key array is used by jQuery automatically as selected value
  2494. // "label" value of json key array is used by jQuery automatically as text for combo box
  2495. $out .= $opt;
  2496. array_push($outarray, $optJson);
  2497. }
  2498. }
  2499. } else {
  2500. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2501. $price_product = new Product($this->db);
  2502. $price_product->fetch($objp->rowid, '', '', 1);
  2503. $priceparser = new PriceParser($this->db);
  2504. $price_result = $priceparser->parseProduct($price_product);
  2505. if ($price_result >= 0) {
  2506. $objp->price = $price_result;
  2507. $objp->unitprice = $price_result;
  2508. //Calculate the VAT
  2509. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2510. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2511. }
  2512. }
  2513. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2514. // Add new entry
  2515. // "key" value of json key array is used by jQuery automatically as selected value
  2516. // "label" value of json key array is used by jQuery automatically as text for combo box
  2517. $out .= $opt;
  2518. array_push($outarray, $optJson);
  2519. }
  2520. $i++;
  2521. }
  2522. $out .= '</select>';
  2523. $this->db->free($result);
  2524. if (empty($outputmode)) {
  2525. return $out;
  2526. }
  2527. return $outarray;
  2528. } else {
  2529. dol_print_error($this->db);
  2530. }
  2531. }
  2532. /**
  2533. * Function to forge the string with OPTIONs of SELECT.
  2534. * This define value for &$opt and &$optJson.
  2535. * This function is called by select_produits_list().
  2536. *
  2537. * @param resource $objp Resultset of fetch
  2538. * @param string $opt Option (var used for returned value in string option format)
  2539. * @param string $optJson Option (var used for returned value in json format)
  2540. * @param int $price_level Price level
  2541. * @param string $selected Preselected value
  2542. * @param int $hidepriceinlabel Hide price in label
  2543. * @param string $filterkey Filter key to highlight
  2544. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2545. * @return void
  2546. */
  2547. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2548. {
  2549. global $langs, $conf, $user;
  2550. $outkey = '';
  2551. $outval = '';
  2552. $outref = '';
  2553. $outlabel = '';
  2554. $outlabel_translated = '';
  2555. $outdesc = '';
  2556. $outdesc_translated = '';
  2557. $outbarcode = '';
  2558. $outorigin = '';
  2559. $outtype = '';
  2560. $outprice_ht = '';
  2561. $outprice_ttc = '';
  2562. $outpricebasetype = '';
  2563. $outtva_tx = '';
  2564. $outdefault_vat_code = '';
  2565. $outqty = 1;
  2566. $outdiscount = 0;
  2567. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2568. $label = $objp->label;
  2569. if (!empty($objp->label_translated)) {
  2570. $label = $objp->label_translated;
  2571. }
  2572. if (!empty($filterkey) && $filterkey != '') {
  2573. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2574. }
  2575. $outkey = $objp->rowid;
  2576. $outref = $objp->ref;
  2577. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2578. $outlabel = $objp->label;
  2579. $outdesc = $objp->description;
  2580. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2581. $outlabel_translated = $objp->label_translated;
  2582. $outdesc_translated = $objp->description_translated;
  2583. }
  2584. $outbarcode = $objp->barcode;
  2585. $outorigin = $objp->fk_country;
  2586. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2587. $outtype = $objp->fk_product_type;
  2588. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2589. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2590. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2591. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2592. }
  2593. // Units
  2594. $outvalUnits = '';
  2595. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2596. if (!empty($objp->unit_short)) {
  2597. $outvalUnits .= ' - '.$objp->unit_short;
  2598. }
  2599. }
  2600. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2601. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2602. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2603. $outvalUnits .= ' - '.$unitToShow;
  2604. }
  2605. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2606. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2607. $outvalUnits .= ' - '.$unitToShow;
  2608. }
  2609. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2610. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2611. $outvalUnits .= ' - '.$unitToShow;
  2612. }
  2613. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2614. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2615. $outvalUnits .= ' - '.$unitToShow;
  2616. }
  2617. }
  2618. if ($outdurationvalue && $outdurationunit) {
  2619. $da = array(
  2620. 'h' => $langs->trans('Hour'),
  2621. 'd' => $langs->trans('Day'),
  2622. 'w' => $langs->trans('Week'),
  2623. 'm' => $langs->trans('Month'),
  2624. 'y' => $langs->trans('Year')
  2625. );
  2626. if (isset($da[$outdurationunit])) {
  2627. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2628. }
  2629. }
  2630. $opt = '<option value="'.$objp->rowid.'"';
  2631. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2632. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2633. $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.'"';
  2634. }
  2635. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2636. if (!empty($user->rights->stock->lire)) {
  2637. if ($objp->stock > 0) {
  2638. $opt .= ' class="product_line_stock_ok"';
  2639. } elseif ($objp->stock <= 0) {
  2640. $opt .= ' class="product_line_stock_too_low"';
  2641. }
  2642. }
  2643. }
  2644. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2645. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2646. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2647. }
  2648. $opt .= '>';
  2649. $opt .= $objp->ref;
  2650. if (! empty($objp->custref)) {
  2651. $opt.= ' (' . $objp->custref . ')';
  2652. }
  2653. if ($outbarcode) {
  2654. $opt .= ' ('.$outbarcode.')';
  2655. }
  2656. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2657. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2658. $opt .= ' ('.getCountry($outorigin, 1).')';
  2659. }
  2660. $objRef = $objp->ref;
  2661. if (! empty($objp->custref)) {
  2662. $objRef .= ' (' . $objp->custref . ')';
  2663. }
  2664. if (!empty($filterkey) && $filterkey != '') {
  2665. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2666. }
  2667. $outval .= $objRef;
  2668. if ($outbarcode) {
  2669. $outval .= ' ('.$outbarcode.')';
  2670. }
  2671. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2672. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2673. $outval .= ' ('.getCountry($outorigin, 1).')';
  2674. }
  2675. // Units
  2676. $opt .= $outvalUnits;
  2677. $outval .= $outvalUnits;
  2678. $found = 0;
  2679. // Multiprice
  2680. // If we need a particular price level (from 1 to n)
  2681. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2682. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2683. $sql .= " FROM ".$this->db->prefix()."product_price";
  2684. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2685. $sql .= " AND entity IN (".getEntity('productprice').")";
  2686. $sql .= " AND price_level = ".((int) $price_level);
  2687. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2688. $sql .= " LIMIT 1";
  2689. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2690. $result2 = $this->db->query($sql);
  2691. if ($result2) {
  2692. $objp2 = $this->db->fetch_object($result2);
  2693. if ($objp2) {
  2694. $found = 1;
  2695. if ($objp2->price_base_type == 'HT') {
  2696. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2697. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2698. } else {
  2699. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2700. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2701. }
  2702. $outprice_ht = price($objp2->price);
  2703. $outprice_ttc = price($objp2->price_ttc);
  2704. $outpricebasetype = $objp2->price_base_type;
  2705. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2706. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2707. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2708. } else {
  2709. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2710. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2711. }
  2712. }
  2713. } else {
  2714. dol_print_error($this->db);
  2715. }
  2716. }
  2717. // Price by quantity
  2718. 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))) {
  2719. $found = 1;
  2720. $outqty = $objp->quantity;
  2721. $outdiscount = $objp->remise_percent;
  2722. if ($objp->quantity == 1) {
  2723. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2724. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2725. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2726. $outval .= $langs->transnoentities("Unit");
  2727. } else {
  2728. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2729. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2730. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2731. $outval .= $langs->transnoentities("Units");
  2732. }
  2733. $outprice_ht = price($objp->unitprice);
  2734. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2735. $outpricebasetype = $objp->price_base_type;
  2736. $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
  2737. $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
  2738. }
  2739. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2740. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2741. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2742. }
  2743. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2744. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2745. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2746. }
  2747. // Price by customer
  2748. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2749. if (!empty($objp->idprodcustprice)) {
  2750. $found = 1;
  2751. if ($objp->custprice_base_type == 'HT') {
  2752. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2753. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2754. } else {
  2755. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2756. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2757. }
  2758. $outprice_ht = price($objp->custprice);
  2759. $outprice_ttc = price($objp->custprice_ttc);
  2760. $outpricebasetype = $objp->custprice_base_type;
  2761. $outtva_tx = $objp->custtva_tx;
  2762. $outdefault_vat_code = $objp->custdefault_vat_code;
  2763. }
  2764. }
  2765. // If level no defined or multiprice not found, we used the default price
  2766. if (empty($hidepriceinlabel) && !$found) {
  2767. if ($objp->price_base_type == 'HT') {
  2768. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2769. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2770. } else {
  2771. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2772. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2773. }
  2774. $outprice_ht = price($objp->price);
  2775. $outprice_ttc = price($objp->price_ttc);
  2776. $outpricebasetype = $objp->price_base_type;
  2777. $outtva_tx = $objp->tva_tx;
  2778. $outdefault_vat_code = $objp->default_vat_code;
  2779. }
  2780. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2781. if (!empty($user->rights->stock->lire)) {
  2782. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2783. if ($objp->stock > 0) {
  2784. $outval .= ' - <span class="product_line_stock_ok">';
  2785. } elseif ($objp->stock <= 0) {
  2786. $outval .= ' - <span class="product_line_stock_too_low">';
  2787. }
  2788. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2789. $outval .= '</span>';
  2790. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2791. $langs->load("stocks");
  2792. $tmpproduct = new Product($this->db);
  2793. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2794. $tmpproduct->load_virtual_stock();
  2795. $virtualstock = $tmpproduct->stock_theorique;
  2796. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2797. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2798. if ($virtualstock > 0) {
  2799. $outval .= '<span class="product_line_stock_ok">';
  2800. } elseif ($virtualstock <= 0) {
  2801. $outval .= '<span class="product_line_stock_too_low">';
  2802. }
  2803. $outval .= $virtualstock;
  2804. $outval .= '</span>';
  2805. unset($tmpproduct);
  2806. }
  2807. }
  2808. }
  2809. $opt .= "</option>\n";
  2810. $optJson = array(
  2811. 'key'=>$outkey,
  2812. 'value'=>$outref,
  2813. 'label'=>$outval,
  2814. 'label2'=>$outlabel,
  2815. 'desc'=>$outdesc,
  2816. 'type'=>$outtype,
  2817. 'price_ht'=>price2num($outprice_ht),
  2818. 'price_ttc'=>price2num($outprice_ttc),
  2819. 'pricebasetype'=>$outpricebasetype,
  2820. 'tva_tx'=>$outtva_tx,
  2821. 'default_vat_code'=>$outdefault_vat_code,
  2822. 'qty'=>$outqty,
  2823. 'discount'=>$outdiscount,
  2824. 'duration_value'=>$outdurationvalue,
  2825. 'duration_unit'=>$outdurationunit,
  2826. 'pbq'=>$outpbq,
  2827. 'labeltrans'=>$outlabel_translated,
  2828. 'desctrans'=>$outdesc_translated,
  2829. 'ref_customer'=>$outrefcust
  2830. );
  2831. }
  2832. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2833. /**
  2834. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2835. *
  2836. * @param int $socid Id third party
  2837. * @param string $selected Preselected product
  2838. * @param string $htmlname Name of HTML Select
  2839. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2840. * @param string $filtre For a SQL filter
  2841. * @param array $ajaxoptions Options for ajax_autocompleter
  2842. * @param int $hidelabel Hide label (0=no, 1=yes)
  2843. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2844. * @param string $morecss More CSS
  2845. * @param string $placeholder Placeholder
  2846. * @return void
  2847. */
  2848. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2849. {
  2850. // phpcs:enable
  2851. global $langs, $conf;
  2852. global $price_level, $status, $finished;
  2853. if (!isset($status)) {
  2854. $status = 1;
  2855. }
  2856. $selected_input_value = '';
  2857. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2858. if ($selected > 0) {
  2859. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2860. $producttmpselect = new Product($this->db);
  2861. $producttmpselect->fetch($selected);
  2862. $selected_input_value = $producttmpselect->ref;
  2863. unset($producttmpselect);
  2864. }
  2865. // mode=2 means suppliers products
  2866. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2867. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2868. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2869. } else {
  2870. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2871. }
  2872. }
  2873. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2874. /**
  2875. * Return list of suppliers products
  2876. *
  2877. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2878. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2879. * @param string $htmlname Name of HTML select
  2880. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2881. * @param string $filtre Generic filter. Data must not come from user input.
  2882. * @param string $filterkey Filter of produdts
  2883. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2884. * @param int $outputmode 0=HTML select string, 1=Array
  2885. * @param int $limit Limit of line number
  2886. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2887. * @param string $morecss Add more CSS
  2888. * @param int $showstockinlist Show stock information (slower).
  2889. * @param string $placeholder Placeholder
  2890. * @return array Array of keys for json
  2891. */
  2892. 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 = '')
  2893. {
  2894. // phpcs:enable
  2895. global $langs, $conf, $user;
  2896. global $hookmanager;
  2897. $out = '';
  2898. $outarray = array();
  2899. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2900. $langs->load('stocks');
  2901. // Units
  2902. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2903. $langs->load('other');
  2904. }
  2905. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2906. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2907. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2908. $sql .= " pfp.supplier_reputation";
  2909. // if we use supplier description of the products
  2910. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2911. $sql .= " ,pfp.desc_fourn as description";
  2912. } else {
  2913. $sql .= " ,p.description";
  2914. }
  2915. // Units
  2916. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2917. $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";
  2918. }
  2919. if (!empty($conf->barcode->enabled)) {
  2920. $sql .= ", pfp.barcode";
  2921. }
  2922. $sql .= " FROM ".$this->db->prefix()."product as p";
  2923. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2924. if ($socid > 0) {
  2925. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2926. }
  2927. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  2928. // Units
  2929. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2930. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2931. }
  2932. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2933. if ($statut != -1) {
  2934. $sql .= " AND p.tobuy = ".((int) $statut);
  2935. }
  2936. if (strval($filtertype) != '') {
  2937. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2938. }
  2939. if (!empty($filtre)) {
  2940. $sql .= " ".$filtre;
  2941. }
  2942. // Add where from hooks
  2943. $parameters = array();
  2944. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2945. $sql .= $hookmanager->resPrint;
  2946. // Add criteria on ref/label
  2947. if ($filterkey != '') {
  2948. $sql .= ' AND (';
  2949. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2950. // For natural search
  2951. $scrit = explode(' ', $filterkey);
  2952. $i = 0;
  2953. if (count($scrit) > 1) {
  2954. $sql .= "(";
  2955. }
  2956. foreach ($scrit as $crit) {
  2957. if ($i > 0) {
  2958. $sql .= " AND ";
  2959. }
  2960. $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)."%'";
  2961. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2962. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2963. }
  2964. $sql .= ")";
  2965. $i++;
  2966. }
  2967. if (count($scrit) > 1) {
  2968. $sql .= ")";
  2969. }
  2970. if (!empty($conf->barcode->enabled)) {
  2971. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2972. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2973. }
  2974. $sql .= ')';
  2975. }
  2976. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2977. $sql .= $this->db->plimit($limit, 0);
  2978. // Build output string
  2979. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2980. $result = $this->db->query($sql);
  2981. if ($result) {
  2982. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2983. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2984. $num = $this->db->num_rows($result);
  2985. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2986. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2987. if (!$selected) {
  2988. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2989. } else {
  2990. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2991. }
  2992. $i = 0;
  2993. while ($i < $num) {
  2994. $objp = $this->db->fetch_object($result);
  2995. $outkey = $objp->idprodfournprice; // id in table of price
  2996. if (!$outkey && $alsoproductwithnosupplierprice) {
  2997. $outkey = 'idprod_'.$objp->rowid; // id of product
  2998. }
  2999. $outref = $objp->ref;
  3000. $outval = '';
  3001. $outbarcode = $objp->barcode;
  3002. $outqty = 1;
  3003. $outdiscount = 0;
  3004. $outtype = $objp->fk_product_type;
  3005. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3006. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  3007. // Units
  3008. $outvalUnits = '';
  3009. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3010. if (!empty($objp->unit_short)) {
  3011. $outvalUnits .= ' - '.$objp->unit_short;
  3012. }
  3013. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3014. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3015. $outvalUnits .= ' - '.$unitToShow;
  3016. }
  3017. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3018. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  3019. $outvalUnits .= ' - '.$unitToShow;
  3020. }
  3021. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3022. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3023. $outvalUnits .= ' - '.$unitToShow;
  3024. }
  3025. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3026. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3027. $outvalUnits .= ' - '.$unitToShow;
  3028. }
  3029. if ($outdurationvalue && $outdurationunit) {
  3030. $da = array(
  3031. 'h' => $langs->trans('Hour'),
  3032. 'd' => $langs->trans('Day'),
  3033. 'w' => $langs->trans('Week'),
  3034. 'm' => $langs->trans('Month'),
  3035. 'y' => $langs->trans('Year')
  3036. );
  3037. if (isset($da[$outdurationunit])) {
  3038. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  3039. }
  3040. }
  3041. }
  3042. $objRef = $objp->ref;
  3043. if ($filterkey && $filterkey != '') {
  3044. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  3045. }
  3046. $objRefFourn = $objp->ref_fourn;
  3047. if ($filterkey && $filterkey != '') {
  3048. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3049. }
  3050. $label = $objp->label;
  3051. if ($filterkey && $filterkey != '') {
  3052. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  3053. }
  3054. $optlabel = $objp->ref;
  3055. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3056. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  3057. }
  3058. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3059. $optlabel .= ' ('.$outbarcode.')';
  3060. }
  3061. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3062. $outvallabel = $objRef;
  3063. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3064. $outvallabel .= ' ('.$objRefFourn.')';
  3065. }
  3066. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3067. $outvallabel .= ' ('.$outbarcode.')';
  3068. }
  3069. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3070. // Units
  3071. $optlabel .= $outvalUnits;
  3072. $outvallabel .= $outvalUnits;
  3073. if (!empty($objp->idprodfournprice)) {
  3074. $outqty = $objp->quantity;
  3075. $outdiscount = $objp->remise_percent;
  3076. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3077. $prod_supplier = new ProductFournisseur($this->db);
  3078. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3079. $prod_supplier->id = $objp->fk_product;
  3080. $prod_supplier->fourn_qty = $objp->quantity;
  3081. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3082. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3083. $priceparser = new PriceParser($this->db);
  3084. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3085. if ($price_result >= 0) {
  3086. $objp->fprice = $price_result;
  3087. if ($objp->quantity >= 1) {
  3088. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3089. }
  3090. }
  3091. }
  3092. if ($objp->quantity == 1) {
  3093. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3094. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3095. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3096. $outvallabel .= $langs->transnoentities("Unit");
  3097. } else {
  3098. $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;
  3099. $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;
  3100. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3101. $outvallabel .= ' '.$langs->transnoentities("Units");
  3102. }
  3103. if ($objp->quantity > 1) {
  3104. $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
  3105. $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
  3106. }
  3107. if ($objp->remise_percent >= 1) {
  3108. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3109. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3110. }
  3111. if ($objp->duration) {
  3112. $optlabel .= " - ".$objp->duration;
  3113. $outvallabel .= " - ".$objp->duration;
  3114. }
  3115. if (!$socid) {
  3116. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3117. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3118. }
  3119. if ($objp->supplier_reputation) {
  3120. //TODO dictionary
  3121. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3122. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3123. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3124. }
  3125. } else {
  3126. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3127. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3128. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3129. } else // No supplier price defined for product, even on other suppliers
  3130. {
  3131. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3132. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3133. }
  3134. }
  3135. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3136. $novirtualstock = ($showstockinlist == 2);
  3137. if (!empty($user->rights->stock->lire)) {
  3138. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3139. if ($objp->stock > 0) {
  3140. $optlabel .= ' - <span class="product_line_stock_ok">';
  3141. } elseif ($objp->stock <= 0) {
  3142. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3143. }
  3144. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3145. $optlabel .= '</span>';
  3146. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3147. $langs->load("stocks");
  3148. $tmpproduct = new Product($this->db);
  3149. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3150. $tmpproduct->load_virtual_stock();
  3151. $virtualstock = $tmpproduct->stock_theorique;
  3152. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3153. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3154. if ($virtualstock > 0) {
  3155. $optlabel .= '<span class="product_line_stock_ok">';
  3156. } elseif ($virtualstock <= 0) {
  3157. $optlabel .= '<span class="product_line_stock_too_low">';
  3158. }
  3159. $optlabel .= $virtualstock;
  3160. $optlabel .= '</span>';
  3161. unset($tmpproduct);
  3162. }
  3163. }
  3164. }
  3165. $opt = '<option value="'.$outkey.'"';
  3166. if ($selected && $selected == $objp->idprodfournprice) {
  3167. $opt .= ' selected';
  3168. }
  3169. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3170. $opt .= ' disabled';
  3171. }
  3172. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3173. $opt .= ' data-product-id="'.$objp->rowid.'" data-price-id="'.$objp->idprodfournprice.'" data-qty="'.$objp->quantity.'" data-up="'.$objp->unitprice.'" data-discount="'.$outdiscount.'" data-tvatx="'.$objp->tva_tx.'"';
  3174. }
  3175. $opt .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3176. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  3177. $opt .= '>';
  3178. $opt .= $optlabel;
  3179. $outval .= $outvallabel;
  3180. $opt .= "</option>\n";
  3181. // Add new entry
  3182. // "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
  3183. // "label" value of json key array is used by jQuery automatically as text for combo box
  3184. $out .= $opt;
  3185. array_push(
  3186. $outarray,
  3187. array('key'=>$outkey,
  3188. 'value'=>$outref,
  3189. 'label'=>$outval,
  3190. 'qty'=>$outqty,
  3191. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3192. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3193. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3194. 'tva_tx'=>$objp->tva_tx,
  3195. 'default_vat_code'=>$objp->default_vat_code,
  3196. 'discount'=>$outdiscount,
  3197. 'type'=>$outtype,
  3198. 'duration_value'=>$outdurationvalue,
  3199. 'duration_unit'=>$outdurationunit,
  3200. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3201. 'description'=>$objp->description
  3202. )
  3203. );
  3204. // Exemple of var_dump $outarray
  3205. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3206. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3207. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3208. //}
  3209. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3210. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3211. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3212. $i++;
  3213. }
  3214. $out .= '</select>';
  3215. $this->db->free($result);
  3216. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3217. $out .= ajax_combobox($htmlname);
  3218. if (empty($outputmode)) {
  3219. return $out;
  3220. }
  3221. return $outarray;
  3222. } else {
  3223. dol_print_error($this->db);
  3224. }
  3225. }
  3226. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3227. /**
  3228. * Return list of suppliers prices for a product
  3229. *
  3230. * @param int $productid Id of product
  3231. * @param string $htmlname Name of HTML field
  3232. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3233. * @return string
  3234. */
  3235. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3236. {
  3237. // phpcs:enable
  3238. global $langs, $conf;
  3239. $langs->load('stocks');
  3240. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3241. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3242. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3243. $sql .= " FROM ".$this->db->prefix()."product as p";
  3244. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3245. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  3246. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3247. $sql .= " AND p.tobuy = 1";
  3248. $sql .= " AND s.fournisseur = 1";
  3249. $sql .= " AND p.rowid = ".((int) $productid);
  3250. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3251. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3252. $result = $this->db->query($sql);
  3253. if ($result) {
  3254. $num = $this->db->num_rows($result);
  3255. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3256. if (!$num) {
  3257. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3258. } else {
  3259. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3260. $form .= '<option value="0">&nbsp;</option>';
  3261. $i = 0;
  3262. while ($i < $num) {
  3263. $objp = $this->db->fetch_object($result);
  3264. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3265. //if there is only one supplier, preselect it
  3266. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  3267. $opt .= ' selected';
  3268. }
  3269. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3270. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3271. $prod_supplier = new ProductFournisseur($this->db);
  3272. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3273. $prod_supplier->id = $productid;
  3274. $prod_supplier->fourn_qty = $objp->quantity;
  3275. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3276. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3277. $priceparser = new PriceParser($this->db);
  3278. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3279. if ($price_result >= 0) {
  3280. $objp->fprice = $price_result;
  3281. if ($objp->quantity >= 1) {
  3282. $objp->unitprice = $objp->fprice / $objp->quantity;
  3283. }
  3284. }
  3285. }
  3286. if ($objp->quantity == 1) {
  3287. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3288. }
  3289. $opt .= $objp->quantity.' ';
  3290. if ($objp->quantity == 1) {
  3291. $opt .= $langs->trans("Unit");
  3292. } else {
  3293. $opt .= $langs->trans("Units");
  3294. }
  3295. if ($objp->quantity > 1) {
  3296. $opt .= " - ";
  3297. $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");
  3298. }
  3299. if ($objp->duration) {
  3300. $opt .= " - ".$objp->duration;
  3301. }
  3302. $opt .= "</option>\n";
  3303. $form .= $opt;
  3304. $i++;
  3305. }
  3306. }
  3307. $form .= '</select>';
  3308. $this->db->free($result);
  3309. return $form;
  3310. } else {
  3311. dol_print_error($this->db);
  3312. }
  3313. }
  3314. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3315. /**
  3316. * Return list of delivery address
  3317. *
  3318. * @param string $selected Id contact pre-selectionn
  3319. * @param int $socid Id of company
  3320. * @param string $htmlname Name of HTML field
  3321. * @param int $showempty Add an empty field
  3322. * @return integer|null
  3323. */
  3324. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3325. {
  3326. // phpcs:enable
  3327. // looking for users
  3328. $sql = "SELECT a.rowid, a.label";
  3329. $sql .= " FROM ".$this->db->prefix()."societe_address as a";
  3330. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3331. $sql .= " ORDER BY a.label ASC";
  3332. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3333. $resql = $this->db->query($sql);
  3334. if ($resql) {
  3335. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3336. if ($showempty) {
  3337. print '<option value="0">&nbsp;</option>';
  3338. }
  3339. $num = $this->db->num_rows($resql);
  3340. $i = 0;
  3341. if ($num) {
  3342. while ($i < $num) {
  3343. $obj = $this->db->fetch_object($resql);
  3344. if ($selected && $selected == $obj->rowid) {
  3345. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3346. } else {
  3347. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3348. }
  3349. $i++;
  3350. }
  3351. }
  3352. print '</select>';
  3353. return $num;
  3354. } else {
  3355. dol_print_error($this->db);
  3356. }
  3357. }
  3358. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3359. /**
  3360. * Load into cache list of payment terms
  3361. *
  3362. * @return int Nb of lines loaded, <0 if KO
  3363. */
  3364. public function load_cache_conditions_paiements()
  3365. {
  3366. // phpcs:enable
  3367. global $langs;
  3368. $num = count($this->cache_conditions_paiements);
  3369. if ($num > 0) {
  3370. return 0; // Cache already loaded
  3371. }
  3372. dol_syslog(__METHOD__, LOG_DEBUG);
  3373. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3374. $sql .= " FROM ".$this->db->prefix().'c_payment_term';
  3375. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3376. $sql .= " AND active > 0";
  3377. $sql .= " ORDER BY sortorder";
  3378. $resql = $this->db->query($sql);
  3379. if ($resql) {
  3380. $num = $this->db->num_rows($resql);
  3381. $i = 0;
  3382. while ($i < $num) {
  3383. $obj = $this->db->fetch_object($resql);
  3384. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3385. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3386. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3387. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3388. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3389. $i++;
  3390. }
  3391. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3392. return $num;
  3393. } else {
  3394. dol_print_error($this->db);
  3395. return -1;
  3396. }
  3397. }
  3398. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3399. /**
  3400. * Load int a cache property th elist of possible delivery delays.
  3401. *
  3402. * @return int Nb of lines loaded, <0 if KO
  3403. */
  3404. public function load_cache_availability()
  3405. {
  3406. // phpcs:enable
  3407. global $langs;
  3408. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3409. if ($num > 0) {
  3410. return 0; // Cache already loaded
  3411. }
  3412. dol_syslog(__METHOD__, LOG_DEBUG);
  3413. $langs->load('propal');
  3414. $sql = "SELECT rowid, code, label, position";
  3415. $sql .= " FROM ".$this->db->prefix().'c_availability';
  3416. $sql .= " WHERE active > 0";
  3417. $resql = $this->db->query($sql);
  3418. if ($resql) {
  3419. $num = $this->db->num_rows($resql);
  3420. $i = 0;
  3421. while ($i < $num) {
  3422. $obj = $this->db->fetch_object($resql);
  3423. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3424. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3425. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3426. $this->cache_availability[$obj->rowid]['label'] = $label;
  3427. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3428. $i++;
  3429. }
  3430. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3431. return $num;
  3432. } else {
  3433. dol_print_error($this->db);
  3434. return -1;
  3435. }
  3436. }
  3437. /**
  3438. * Retourne la liste des types de delais de livraison possibles
  3439. *
  3440. * @param int $selected Id du type de delais pre-selectionne
  3441. * @param string $htmlname Nom de la zone select
  3442. * @param string $filtertype To add a filter
  3443. * @param int $addempty Add empty entry
  3444. * @param string $morecss More CSS
  3445. * @return void
  3446. */
  3447. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3448. {
  3449. global $langs, $user;
  3450. $this->load_cache_availability();
  3451. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3452. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3453. if ($addempty) {
  3454. print '<option value="0">&nbsp;</option>';
  3455. }
  3456. foreach ($this->cache_availability as $id => $arrayavailability) {
  3457. if ($selected == $id) {
  3458. print '<option value="'.$id.'" selected>';
  3459. } else {
  3460. print '<option value="'.$id.'">';
  3461. }
  3462. print dol_escape_htmltag($arrayavailability['label']);
  3463. print '</option>';
  3464. }
  3465. print '</select>';
  3466. if ($user->admin) {
  3467. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3468. }
  3469. print ajax_combobox($htmlname);
  3470. }
  3471. /**
  3472. * Load into cache cache_demand_reason, array of input reasons
  3473. *
  3474. * @return int Nb of lines loaded, <0 if KO
  3475. */
  3476. public function loadCacheInputReason()
  3477. {
  3478. global $langs;
  3479. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3480. if ($num > 0) {
  3481. return 0; // Cache already loaded
  3482. }
  3483. $sql = "SELECT rowid, code, label";
  3484. $sql .= " FROM ".$this->db->prefix().'c_input_reason';
  3485. $sql .= " WHERE active > 0";
  3486. $resql = $this->db->query($sql);
  3487. if ($resql) {
  3488. $num = $this->db->num_rows($resql);
  3489. $i = 0;
  3490. $tmparray = array();
  3491. while ($i < $num) {
  3492. $obj = $this->db->fetch_object($resql);
  3493. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3494. $label = ($obj->label != '-' ? $obj->label : '');
  3495. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3496. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3497. }
  3498. if ($langs->trans($obj->code) != $obj->code) {
  3499. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3500. }
  3501. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3502. $tmparray[$obj->rowid]['code'] = $obj->code;
  3503. $tmparray[$obj->rowid]['label'] = $label;
  3504. $i++;
  3505. }
  3506. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3507. unset($tmparray);
  3508. return $num;
  3509. } else {
  3510. dol_print_error($this->db);
  3511. return -1;
  3512. }
  3513. }
  3514. /**
  3515. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3516. * List found into table c_input_reason loaded by loadCacheInputReason
  3517. *
  3518. * @param int $selected Id or code of type origin to select by default
  3519. * @param string $htmlname Nom de la zone select
  3520. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3521. * @param int $addempty Add an empty entry
  3522. * @param string $morecss Add more css to the HTML select component
  3523. * @param int $notooltip Do not show the tooltip for admin
  3524. * @return void
  3525. */
  3526. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3527. {
  3528. global $langs, $user;
  3529. $this->loadCacheInputReason();
  3530. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3531. if ($addempty) {
  3532. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3533. }
  3534. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3535. if ($arraydemandreason['code'] == $exclude) {
  3536. continue;
  3537. }
  3538. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3539. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3540. } else {
  3541. print '<option value="'.$arraydemandreason['id'].'">';
  3542. }
  3543. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3544. print $langs->trans($label);
  3545. print '</option>';
  3546. }
  3547. print '</select>';
  3548. if ($user->admin && empty($notooltip)) {
  3549. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3550. }
  3551. print ajax_combobox('select_'.$htmlname);
  3552. }
  3553. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3554. /**
  3555. * Charge dans cache la liste des types de paiements possibles
  3556. *
  3557. * @return int Nb of lines loaded, <0 if KO
  3558. */
  3559. public function load_cache_types_paiements()
  3560. {
  3561. // phpcs:enable
  3562. global $langs;
  3563. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3564. if ($num > 0) {
  3565. return $num; // Cache already loaded
  3566. }
  3567. dol_syslog(__METHOD__, LOG_DEBUG);
  3568. $this->cache_types_paiements = array();
  3569. $sql = "SELECT id, code, libelle as label, type, active";
  3570. $sql .= " FROM ".$this->db->prefix()."c_paiement";
  3571. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3572. $resql = $this->db->query($sql);
  3573. if ($resql) {
  3574. $num = $this->db->num_rows($resql);
  3575. $i = 0;
  3576. while ($i < $num) {
  3577. $obj = $this->db->fetch_object($resql);
  3578. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3579. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3580. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3581. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3582. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3583. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3584. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3585. $i++;
  3586. }
  3587. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3588. return $num;
  3589. } else {
  3590. dol_print_error($this->db);
  3591. return -1;
  3592. }
  3593. }
  3594. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3595. /**
  3596. * print list of payment modes.
  3597. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3598. * See instead to force the default value by the caller.
  3599. *
  3600. * @param int $selected Id of payment term to preselect by default
  3601. * @param string $htmlname Nom de la zone select
  3602. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3603. * @param int $addempty Add an empty entry
  3604. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3605. * @param string $morecss Add more CSS on select tag
  3606. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3607. * 0 : use default deposit percentage from entry
  3608. * > 0 : force deposit percentage (for example, from company object)
  3609. * @return void
  3610. */
  3611. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3612. {
  3613. // phpcs:enable
  3614. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent = -1);
  3615. }
  3616. /**
  3617. * Return list of payment modes.
  3618. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3619. * See instead to force the default value by the caller.
  3620. *
  3621. * @param int $selected Id of payment term to preselect by default
  3622. * @param string $htmlname Nom de la zone select
  3623. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3624. * @param int $addempty Add an empty entry
  3625. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3626. * @param string $morecss Add more CSS on select tag
  3627. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3628. * 0 : use default deposit percentage from entry
  3629. * > 0 : force deposit percentage (for example, from company object)
  3630. * @return string String for the HTML select component
  3631. */
  3632. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3633. {
  3634. global $langs, $user, $conf;
  3635. $out = '';
  3636. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3637. $this->load_cache_conditions_paiements();
  3638. // Set default value if not already set by caller
  3639. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3640. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3641. }
  3642. $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3643. if ($addempty) {
  3644. $out.= '<option value="0">&nbsp;</option>';
  3645. }
  3646. $selectedDepositPercent = null;
  3647. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3648. if ($filtertype <= 0 && ! empty($arrayconditions['deposit_percent'])) {
  3649. continue;
  3650. }
  3651. if ($selected == $id) {
  3652. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3653. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3654. } else {
  3655. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3656. }
  3657. $label = $arrayconditions['label'];
  3658. if (! empty($arrayconditions['deposit_percent'])) {
  3659. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3660. }
  3661. $out.= $label;
  3662. $out.= '</option>';
  3663. }
  3664. $out.= '</select>';
  3665. if ($user->admin && empty($noinfoadmin)) {
  3666. $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3667. }
  3668. $out.= ajax_combobox($htmlname);
  3669. if ($deposit_percent >= 0) {
  3670. $out .= ' <span id="'.$htmlname.'_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3671. $out .= $langs->trans('DepositPercent') . ' : ';
  3672. $out .= '<input id="'.$htmlname.'_deposit_percent" name="'.$htmlname.'_deposit_percent" class="maxwidth50" value="' . strval($deposit_percent) . '" />';
  3673. $out .= '</span>';
  3674. $out .= '
  3675. <script>
  3676. $(document).ready(function () {
  3677. $("#' . $htmlname . '").change(function () {
  3678. let $selected = $(this).find("option:selected");
  3679. let depositPercent = $selected.attr("data-deposit_percent");
  3680. if (depositPercent.length > 0) {
  3681. $("#'.$htmlname.'_deposit_percent_container").show().find("#'.$htmlname.'_deposit_percent").val(depositPercent);
  3682. } else {
  3683. $("#'.$htmlname.'_deposit_percent_container").hide();
  3684. }
  3685. return true;
  3686. });
  3687. });
  3688. </script>';
  3689. }
  3690. return $out;
  3691. }
  3692. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3693. /**
  3694. * Return list of payment methods
  3695. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3696. *
  3697. * @param string $selected Id or code or preselected payment mode
  3698. * @param string $htmlname Name of select field
  3699. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3700. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3701. * @param int $empty 1=can be empty, 0 otherwise
  3702. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3703. * @param int $maxlength Max length of label
  3704. * @param int $active Active or not, -1 = all
  3705. * @param string $morecss Add more CSS on select tag
  3706. * @param int $nooutput 1=Return string, do not send to output
  3707. * @return string|void String for the HTML select component
  3708. */
  3709. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3710. {
  3711. // phpcs:enable
  3712. global $langs, $user, $conf;
  3713. $out = '';
  3714. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3715. $filterarray = array();
  3716. if ($filtertype == 'CRDT') {
  3717. $filterarray = array(0, 2, 3);
  3718. } elseif ($filtertype == 'DBIT') {
  3719. $filterarray = array(1, 2, 3);
  3720. } elseif ($filtertype != '' && $filtertype != '-1') {
  3721. $filterarray = explode(',', $filtertype);
  3722. }
  3723. $this->load_cache_types_paiements();
  3724. // Set default value if not already set by caller
  3725. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3726. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3727. }
  3728. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3729. if ($empty) {
  3730. $out .= '<option value="">&nbsp;</option>';
  3731. }
  3732. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3733. // If not good status
  3734. if ($active >= 0 && $arraytypes['active'] != $active) {
  3735. continue;
  3736. }
  3737. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3738. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3739. continue;
  3740. }
  3741. // We discard empty line if showempty is on because an empty line has already been output.
  3742. if ($empty && empty($arraytypes['code'])) {
  3743. continue;
  3744. }
  3745. if ($format == 0) {
  3746. $out .= '<option value="'.$id.'"';
  3747. } elseif ($format == 1) {
  3748. $out .= '<option value="'.$arraytypes['code'].'"';
  3749. } elseif ($format == 2) {
  3750. $out .= '<option value="'.$arraytypes['code'].'"';
  3751. } elseif ($format == 3) {
  3752. $out .= '<option value="'.$id.'"';
  3753. }
  3754. // Print attribute selected or not
  3755. if ($format == 1 || $format == 2) {
  3756. if ($selected == $arraytypes['code']) {
  3757. $out .= ' selected';
  3758. }
  3759. } else {
  3760. if ($selected == $id) {
  3761. $out .= ' selected';
  3762. }
  3763. }
  3764. $out .= '>';
  3765. $value = '';
  3766. if ($format == 0) {
  3767. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3768. } elseif ($format == 1) {
  3769. $value = $arraytypes['code'];
  3770. } elseif ($format == 2) {
  3771. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3772. } elseif ($format == 3) {
  3773. $value = $arraytypes['code'];
  3774. }
  3775. $out .= $value ? $value : '&nbsp;';
  3776. $out .= '</option>';
  3777. }
  3778. $out .= '</select>';
  3779. if ($user->admin && !$noadmininfo) {
  3780. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3781. }
  3782. $out .= ajax_combobox('select'.$htmlname);
  3783. if (empty($nooutput)) {
  3784. print $out;
  3785. } else {
  3786. return $out;
  3787. }
  3788. }
  3789. /**
  3790. * Selection HT or TTC
  3791. *
  3792. * @param string $selected Id pre-selectionne
  3793. * @param string $htmlname Nom de la zone select
  3794. * @param string $addjscombo Add js combo
  3795. * @return string Code of HTML select to chose tax or not
  3796. */
  3797. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3798. {
  3799. global $langs;
  3800. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3801. $options = array(
  3802. 'HT'=>$langs->trans("HT"),
  3803. 'TTC'=>$langs->trans("TTC")
  3804. );
  3805. foreach ($options as $id => $value) {
  3806. if ($selected == $id) {
  3807. $return .= '<option value="'.$id.'" selected>'.$value;
  3808. } else {
  3809. $return .= '<option value="'.$id.'">'.$value;
  3810. }
  3811. $return .= '</option>';
  3812. }
  3813. $return .= '</select>';
  3814. if ($addjscombo) {
  3815. $return .= ajax_combobox('select_'.$htmlname);
  3816. }
  3817. return $return;
  3818. }
  3819. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3820. /**
  3821. * Load in cache list of transport mode
  3822. *
  3823. * @return int Nb of lines loaded, <0 if KO
  3824. */
  3825. public function load_cache_transport_mode()
  3826. {
  3827. // phpcs:enable
  3828. global $langs;
  3829. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3830. if ($num > 0) {
  3831. return $num; // Cache already loaded
  3832. }
  3833. dol_syslog(__METHOD__, LOG_DEBUG);
  3834. $this->cache_transport_mode = array();
  3835. $sql = "SELECT rowid, code, label, active";
  3836. $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
  3837. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3838. $resql = $this->db->query($sql);
  3839. if ($resql) {
  3840. $num = $this->db->num_rows($resql);
  3841. $i = 0;
  3842. while ($i < $num) {
  3843. $obj = $this->db->fetch_object($resql);
  3844. // If traduction exist, we use it else we take the default label
  3845. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3846. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3847. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3848. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3849. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3850. $i++;
  3851. }
  3852. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3853. return $num;
  3854. } else {
  3855. dol_print_error($this->db);
  3856. return -1;
  3857. }
  3858. }
  3859. /**
  3860. * Return list of transport mode for intracomm report
  3861. *
  3862. * @param string $selected Id of the transport mode pre-selected
  3863. * @param string $htmlname Name of the select field
  3864. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3865. * @param int $empty 1=can be empty, 0 else
  3866. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3867. * @param int $maxlength Max length of label
  3868. * @param int $active Active or not, -1 = all
  3869. * @param string $morecss Add more CSS on select tag
  3870. * @return void
  3871. */
  3872. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3873. {
  3874. global $langs, $user;
  3875. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3876. $this->load_cache_transport_mode();
  3877. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3878. if ($empty) {
  3879. print '<option value="">&nbsp;</option>';
  3880. }
  3881. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3882. // If not good status
  3883. if ($active >= 0 && $arraytypes['active'] != $active) {
  3884. continue;
  3885. }
  3886. // We discard empty line if showempty is on because an empty line has already been output.
  3887. if ($empty && empty($arraytypes['code'])) {
  3888. continue;
  3889. }
  3890. if ($format == 0) {
  3891. print '<option value="'.$id.'"';
  3892. } elseif ($format == 1) {
  3893. print '<option value="'.$arraytypes['code'].'"';
  3894. } elseif ($format == 2) {
  3895. print '<option value="'.$arraytypes['code'].'"';
  3896. } elseif ($format == 3) {
  3897. print '<option value="'.$id.'"';
  3898. }
  3899. // If text is selected, we compare with code, else with id
  3900. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  3901. print ' selected';
  3902. } elseif ($selected == $id) {
  3903. print ' selected';
  3904. }
  3905. print '>';
  3906. if ($format == 0) {
  3907. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3908. } elseif ($format == 1) {
  3909. $value = $arraytypes['code'];
  3910. } elseif ($format == 2) {
  3911. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3912. } elseif ($format == 3) {
  3913. $value = $arraytypes['code'];
  3914. }
  3915. print $value ? $value : '&nbsp;';
  3916. print '</option>';
  3917. }
  3918. print '</select>';
  3919. if ($user->admin && !$noadmininfo) {
  3920. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3921. }
  3922. }
  3923. /**
  3924. * Return a HTML select list of shipping mode
  3925. *
  3926. * @param string $selected Id shipping mode pre-selected
  3927. * @param string $htmlname Name of select zone
  3928. * @param string $filtre To filter list. This parameter must not come from input of users
  3929. * @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.
  3930. * @param string $moreattrib To add more attribute on select
  3931. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3932. * @param string $morecss More CSS
  3933. * @return void
  3934. */
  3935. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  3936. {
  3937. global $langs, $conf, $user;
  3938. $langs->load("admin");
  3939. $langs->load("deliveries");
  3940. $sql = "SELECT rowid, code, libelle as label";
  3941. $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
  3942. $sql .= " WHERE active > 0";
  3943. if ($filtre) {
  3944. $sql .= " AND ".$filtre;
  3945. }
  3946. $sql .= " ORDER BY libelle ASC";
  3947. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3948. $result = $this->db->query($sql);
  3949. if ($result) {
  3950. $num = $this->db->num_rows($result);
  3951. $i = 0;
  3952. if ($num) {
  3953. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3954. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3955. print '<option value="-1">&nbsp;</option>';
  3956. }
  3957. while ($i < $num) {
  3958. $obj = $this->db->fetch_object($result);
  3959. if ($selected == $obj->rowid) {
  3960. print '<option value="'.$obj->rowid.'" selected>';
  3961. } else {
  3962. print '<option value="'.$obj->rowid.'">';
  3963. }
  3964. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3965. print '</option>';
  3966. $i++;
  3967. }
  3968. print "</select>";
  3969. if ($user->admin && empty($noinfoadmin)) {
  3970. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3971. }
  3972. print ajax_combobox('select'.$htmlname);
  3973. } else {
  3974. print $langs->trans("NoShippingMethodDefined");
  3975. }
  3976. } else {
  3977. dol_print_error($this->db);
  3978. }
  3979. }
  3980. /**
  3981. * Display form to select shipping mode
  3982. *
  3983. * @param string $page Page
  3984. * @param int $selected Id of shipping mode
  3985. * @param string $htmlname Name of select html field
  3986. * @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.
  3987. * @return void
  3988. */
  3989. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3990. {
  3991. global $langs;
  3992. $langs->load("deliveries");
  3993. if ($htmlname != "none") {
  3994. print '<form method="POST" action="'.$page.'">';
  3995. print '<input type="hidden" name="action" value="setshippingmethod">';
  3996. print '<input type="hidden" name="token" value="'.newToken().'">';
  3997. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3998. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3999. print '</form>';
  4000. } else {
  4001. if ($selected) {
  4002. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4003. print $langs->trans("SendingMethod".strtoupper($code));
  4004. } else {
  4005. print "&nbsp;";
  4006. }
  4007. }
  4008. }
  4009. /**
  4010. * Creates HTML last in cycle situation invoices selector
  4011. *
  4012. * @param string $selected Preselected ID
  4013. * @param int $socid Company ID
  4014. *
  4015. * @return string HTML select
  4016. */
  4017. public function selectSituationInvoices($selected = '', $socid = 0)
  4018. {
  4019. global $langs;
  4020. $langs->load('bills');
  4021. $opt = '<option value="" selected></option>';
  4022. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4023. $sql .= ' FROM '.$this->db->prefix().'facture';
  4024. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  4025. $sql .= ' AND situation_counter >= 1';
  4026. $sql .= ' AND fk_soc = '.(int) $socid;
  4027. $sql .= ' AND type <> 2';
  4028. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4029. $resql = $this->db->query($sql);
  4030. if ($resql && $this->db->num_rows($resql) > 0) {
  4031. // Last seen cycle
  4032. $ref = 0;
  4033. while ($obj = $this->db->fetch_object($resql)) {
  4034. //Same cycle ?
  4035. if ($obj->situation_cycle_ref != $ref) {
  4036. // Just seen this cycle
  4037. $ref = $obj->situation_cycle_ref;
  4038. //not final ?
  4039. if ($obj->situation_final != 1) {
  4040. //Not prov?
  4041. if (substr($obj->ref, 1, 4) != 'PROV') {
  4042. if ($selected == $obj->rowid) {
  4043. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  4044. } else {
  4045. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  4046. }
  4047. }
  4048. }
  4049. }
  4050. }
  4051. } else {
  4052. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4053. }
  4054. if ($opt == '<option value ="" selected></option>') {
  4055. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  4056. }
  4057. return $opt;
  4058. }
  4059. /**
  4060. * Creates HTML units selector (code => label)
  4061. *
  4062. * @param string $selected Preselected Unit ID
  4063. * @param string $htmlname Select name
  4064. * @param int $showempty Add a nempty line
  4065. * @param string $unit_type Restrict to one given unit type
  4066. * @return string HTML select
  4067. */
  4068. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4069. {
  4070. global $langs;
  4071. $langs->load('products');
  4072. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  4073. $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
  4074. $sql .= ' WHERE active > 0';
  4075. if (!empty($unit_type)) {
  4076. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  4077. }
  4078. $sql .= " ORDER BY sortorder";
  4079. $resql = $this->db->query($sql);
  4080. if ($resql && $this->db->num_rows($resql) > 0) {
  4081. if ($showempty) {
  4082. $return .= '<option value="none"></option>';
  4083. }
  4084. while ($res = $this->db->fetch_object($resql)) {
  4085. $unitLabel = $res->label;
  4086. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  4087. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  4088. }
  4089. if ($selected == $res->rowid) {
  4090. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  4091. } else {
  4092. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  4093. }
  4094. }
  4095. $return .= '</select>';
  4096. }
  4097. return $return;
  4098. }
  4099. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4100. /**
  4101. * Return a HTML select list of bank accounts
  4102. *
  4103. * @param string $selected Id account pre-selected
  4104. * @param string $htmlname Name of select zone
  4105. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4106. * @param string $filtre To filter list. This parameter must not come from input of users
  4107. * @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.
  4108. * @param string $moreattrib To add more attribute on select
  4109. * @param int $showcurrency Show currency in label
  4110. * @param string $morecss More CSS
  4111. * @param int $nooutput 1=Return string, do not send to output
  4112. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4113. */
  4114. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4115. {
  4116. // phpcs:enable
  4117. global $langs, $conf;
  4118. $out = '';
  4119. $langs->load("admin");
  4120. $num = 0;
  4121. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4122. $sql .= " FROM ".$this->db->prefix()."bank_account";
  4123. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  4124. if ($status != 2) {
  4125. $sql .= " AND clos = ".(int) $status;
  4126. }
  4127. if ($filtre) {
  4128. $sql .= " AND ".$filtre;
  4129. }
  4130. $sql .= " ORDER BY label";
  4131. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  4132. $result = $this->db->query($sql);
  4133. if ($result) {
  4134. $num = $this->db->num_rows($result);
  4135. $i = 0;
  4136. if ($num) {
  4137. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4138. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4139. $out .= '<option value="-1">&nbsp;</option>';
  4140. }
  4141. while ($i < $num) {
  4142. $obj = $this->db->fetch_object($result);
  4143. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4144. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  4145. } else {
  4146. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  4147. }
  4148. $out .= trim($obj->label);
  4149. if ($showcurrency) {
  4150. $out .= ' ('.$obj->currency_code.')';
  4151. }
  4152. if ($status == 2 && $obj->status == 1) {
  4153. $out .= ' ('.$langs->trans("Closed").')';
  4154. }
  4155. $out .= '</option>';
  4156. $i++;
  4157. }
  4158. $out .= "</select>";
  4159. $out .= ajax_combobox('select'.$htmlname);
  4160. } else {
  4161. if ($status == 0) {
  4162. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4163. } else {
  4164. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4165. }
  4166. }
  4167. } else {
  4168. dol_print_error($this->db);
  4169. }
  4170. // Output or return
  4171. if (empty($nooutput)) {
  4172. print $out;
  4173. } else {
  4174. return $out;
  4175. }
  4176. return $num;
  4177. }
  4178. /**
  4179. * Return a HTML select list of establishment
  4180. *
  4181. * @param string $selected Id establishment pre-selected
  4182. * @param string $htmlname Name of select zone
  4183. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4184. * @param string $filtre To filter list. This parameter must not come from input of users
  4185. * @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.
  4186. * @param string $moreattrib To add more attribute on select
  4187. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4188. */
  4189. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4190. {
  4191. global $langs, $conf;
  4192. $langs->load("admin");
  4193. $num = 0;
  4194. $sql = "SELECT rowid, name, fk_country, status, entity";
  4195. $sql .= " FROM ".$this->db->prefix()."establishment";
  4196. $sql .= " WHERE 1=1";
  4197. if ($status != 2) {
  4198. $sql .= " AND status = ".(int) $status;
  4199. }
  4200. if ($filtre) {
  4201. $sql .= " AND ".$filtre;
  4202. }
  4203. $sql .= " ORDER BY name";
  4204. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4205. $result = $this->db->query($sql);
  4206. if ($result) {
  4207. $num = $this->db->num_rows($result);
  4208. $i = 0;
  4209. if ($num) {
  4210. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4211. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4212. print '<option value="-1">&nbsp;</option>';
  4213. }
  4214. while ($i < $num) {
  4215. $obj = $this->db->fetch_object($result);
  4216. if ($selected == $obj->rowid) {
  4217. print '<option value="'.$obj->rowid.'" selected>';
  4218. } else {
  4219. print '<option value="'.$obj->rowid.'">';
  4220. }
  4221. print trim($obj->name);
  4222. if ($status == 2 && $obj->status == 1) {
  4223. print ' ('.$langs->trans("Closed").')';
  4224. }
  4225. print '</option>';
  4226. $i++;
  4227. }
  4228. print "</select>";
  4229. } else {
  4230. if ($status == 0) {
  4231. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4232. } else {
  4233. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4234. }
  4235. }
  4236. } else {
  4237. dol_print_error($this->db);
  4238. }
  4239. }
  4240. /**
  4241. * Display form to select bank account
  4242. *
  4243. * @param string $page Page
  4244. * @param int $selected Id of bank account
  4245. * @param string $htmlname Name of select html field
  4246. * @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.
  4247. * @return void
  4248. */
  4249. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4250. {
  4251. global $langs;
  4252. if ($htmlname != "none") {
  4253. print '<form method="POST" action="'.$page.'">';
  4254. print '<input type="hidden" name="action" value="setbankaccount">';
  4255. print '<input type="hidden" name="token" value="'.newToken().'">';
  4256. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4257. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4258. if ($nbaccountfound > 0) {
  4259. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4260. }
  4261. print '</form>';
  4262. } else {
  4263. $langs->load('banks');
  4264. if ($selected) {
  4265. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4266. $bankstatic = new Account($this->db);
  4267. $result = $bankstatic->fetch($selected);
  4268. if ($result) {
  4269. print $bankstatic->getNomUrl(1);
  4270. }
  4271. } else {
  4272. print "&nbsp;";
  4273. }
  4274. }
  4275. }
  4276. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4277. /**
  4278. * Return list of categories having choosed type
  4279. *
  4280. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4281. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4282. * @param string $htmlname HTML field name
  4283. * @param int $maxlength Maximum length for labels
  4284. * @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.
  4285. * $markafterid can be an :
  4286. * - int (id of category)
  4287. * - string (categories ids seprated by comma)
  4288. * - array (list of categories ids)
  4289. * @param int $outputmode 0=HTML select string, 1=Array
  4290. * @param int $include [=0] Removed or 1=Keep only
  4291. * @param string $morecss More CSS
  4292. * @return string
  4293. * @see select_categories()
  4294. */
  4295. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4296. {
  4297. // phpcs:enable
  4298. global $conf, $langs;
  4299. $langs->load("categories");
  4300. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4301. // For backward compatibility
  4302. if (is_numeric($type)) {
  4303. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4304. }
  4305. if ($type === Categorie::TYPE_BANK_LINE) {
  4306. // TODO Move this into common category feature
  4307. $cate_arbo = array();
  4308. $sql = "SELECT c.label, c.rowid";
  4309. $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
  4310. $sql .= " WHERE entity = ".$conf->entity;
  4311. $sql .= " ORDER BY c.label";
  4312. $result = $this->db->query($sql);
  4313. if ($result) {
  4314. $num = $this->db->num_rows($result);
  4315. $i = 0;
  4316. while ($i < $num) {
  4317. $objp = $this->db->fetch_object($result);
  4318. if ($objp) {
  4319. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  4320. }
  4321. $i++;
  4322. }
  4323. $this->db->free($result);
  4324. } else {
  4325. dol_print_error($this->db);
  4326. }
  4327. } else {
  4328. $cat = new Categorie($this->db);
  4329. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4330. }
  4331. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4332. $outarray = array();
  4333. if (is_array($cate_arbo)) {
  4334. if (!count($cate_arbo)) {
  4335. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4336. } else {
  4337. $output .= '<option value="-1">&nbsp;</option>';
  4338. foreach ($cate_arbo as $key => $value) {
  4339. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4340. $add = 'selected ';
  4341. } else {
  4342. $add = '';
  4343. }
  4344. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  4345. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4346. }
  4347. }
  4348. }
  4349. $output .= '</select>';
  4350. $output .= "\n";
  4351. if ($outputmode) {
  4352. return $outarray;
  4353. }
  4354. return $output;
  4355. }
  4356. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4357. /**
  4358. * Show a confirmation HTML form or AJAX popup
  4359. *
  4360. * @param string $page Url of page to call if confirmation is OK
  4361. * @param string $title Title
  4362. * @param string $question Question
  4363. * @param string $action Action
  4364. * @param array $formquestion An array with forms complementary inputs
  4365. * @param string $selectedchoice "" or "no" or "yes"
  4366. * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
  4367. * @param int $height Force height of box
  4368. * @param int $width Force width of box
  4369. * @return void
  4370. * @deprecated
  4371. * @see formconfirm()
  4372. */
  4373. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4374. {
  4375. // phpcs:enable
  4376. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4377. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4378. }
  4379. /**
  4380. * Show a confirmation HTML form or AJAX popup.
  4381. * Easiest way to use this is with useajax=1.
  4382. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4383. * just after calling this method. For example:
  4384. * print '<script type="text/javascript">'."\n";
  4385. * print 'jQuery(document).ready(function() {'."\n";
  4386. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4387. * print '});'."\n";
  4388. * print '</script>'."\n";
  4389. *
  4390. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4391. * @param string $title Title
  4392. * @param string $question Question
  4393. * @param string $action Action
  4394. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>))
  4395. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', 'other' or 'onecolumn'...
  4396. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  4397. * @param int|string $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4398. * @param int|string $height Force height of box (0 = auto)
  4399. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4400. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4401. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4402. */
  4403. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  4404. {
  4405. global $langs, $conf;
  4406. $more = '<!-- formconfirm before calling page='.dol_escape_htmltag($page).' -->';
  4407. $formconfirm = '';
  4408. $inputok = array();
  4409. $inputko = array();
  4410. // Clean parameters
  4411. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4412. if ($conf->browser->layout == 'phone') {
  4413. $width = '95%';
  4414. }
  4415. // Set height automatically if not defined
  4416. if (empty($height)) {
  4417. $height = 220;
  4418. if (is_array($formquestion) && count($formquestion) > 2) {
  4419. $height += ((count($formquestion) - 2) * 24);
  4420. }
  4421. }
  4422. if (is_array($formquestion) && !empty($formquestion)) {
  4423. // First add hidden fields and value
  4424. foreach ($formquestion as $key => $input) {
  4425. if (is_array($input) && !empty($input)) {
  4426. if ($input['type'] == 'hidden') {
  4427. $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  4428. }
  4429. }
  4430. }
  4431. // Now add questions
  4432. $moreonecolumn = '';
  4433. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4434. foreach ($formquestion as $key => $input) {
  4435. if (is_array($input) && !empty($input)) {
  4436. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4437. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4438. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4439. if ($input['type'] == 'text') {
  4440. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="text" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4441. } elseif ($input['type'] == 'password') {
  4442. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="password" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4443. } elseif ($input['type'] == 'textarea') {
  4444. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4445. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4446. $more .= $input['value'];
  4447. $more .= '</textarea>';
  4448. $more .= '</div></div>'."\n";*/
  4449. $moreonecolumn .= '<div class="margintoponly">';
  4450. $moreonecolumn .= $input['label'].'<br>';
  4451. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4452. $moreonecolumn .= $input['value'];
  4453. $moreonecolumn .= '</textarea>';
  4454. $moreonecolumn .= '</div>';
  4455. } elseif ($input['type'] == 'select') {
  4456. if (empty($morecss)) {
  4457. $morecss = 'minwidth100';
  4458. }
  4459. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4460. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4461. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4462. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4463. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4464. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4465. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4466. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4467. if (!empty($input['label'])) {
  4468. $more .= $input['label'].'</div><div class="tagtd left">';
  4469. }
  4470. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4471. $more .= '</div></div>'."\n";
  4472. } elseif ($input['type'] == 'checkbox') {
  4473. $more .= '<div class="tagtr">';
  4474. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4475. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4476. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4477. $more .= ' checked';
  4478. }
  4479. if (is_bool($input['value']) && $input['value']) {
  4480. $more .= ' checked';
  4481. }
  4482. if (isset($input['disabled'])) {
  4483. $more .= ' disabled';
  4484. }
  4485. $more .= ' /></div>';
  4486. $more .= '</div>'."\n";
  4487. } elseif ($input['type'] == 'radio') {
  4488. $i = 0;
  4489. foreach ($input['values'] as $selkey => $selval) {
  4490. $more .= '<div class="tagtr">';
  4491. if ($i == 0) {
  4492. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4493. } else {
  4494. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4495. }
  4496. $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;
  4497. if ($input['disabled']) {
  4498. $more .= ' disabled';
  4499. }
  4500. if (isset($input['default']) && $input['default'] === $selkey) {
  4501. $more .= ' checked="checked"';
  4502. }
  4503. $more .= ' /> ';
  4504. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'">'.$selval.'</label>';
  4505. $more .= '</div></div>'."\n";
  4506. $i++;
  4507. }
  4508. } elseif ($input['type'] == 'date') {
  4509. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4510. $more .= '<div class="tagtd">';
  4511. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4512. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4513. $more .= '</div></div>'."\n";
  4514. $formquestion[] = array('name'=>$input['name'].'day');
  4515. $formquestion[] = array('name'=>$input['name'].'month');
  4516. $formquestion[] = array('name'=>$input['name'].'year');
  4517. $formquestion[] = array('name'=>$input['name'].'hour');
  4518. $formquestion[] = array('name'=>$input['name'].'min');
  4519. } elseif ($input['type'] == 'other') {
  4520. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4521. if (!empty($input['label'])) {
  4522. $more .= $input['label'].'</div><div class="tagtd">';
  4523. }
  4524. $more .= $input['value'];
  4525. $more .= '</div></div>'."\n";
  4526. } elseif ($input['type'] == 'onecolumn') {
  4527. $moreonecolumn .= '<div class="margintoponly">';
  4528. $moreonecolumn .= $input['value'];
  4529. $moreonecolumn .= '</div>'."\n";
  4530. } elseif ($input['type'] == 'hidden') {
  4531. // Do nothing more, already added by a previous loop
  4532. } elseif ($input['type'] == 'separator') {
  4533. $more .= '<br>';
  4534. } else {
  4535. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4536. }
  4537. }
  4538. }
  4539. $more .= '</div>'."\n";
  4540. $more .= $moreonecolumn;
  4541. }
  4542. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4543. // 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
  4544. // See page product/card.php for example
  4545. if (!empty($conf->dol_use_jmobile)) {
  4546. $useajax = 0;
  4547. }
  4548. if (empty($conf->use_javascript_ajax)) {
  4549. $useajax = 0;
  4550. }
  4551. if ($useajax) {
  4552. $autoOpen = true;
  4553. $dialogconfirm = 'dialog-confirm';
  4554. $button = '';
  4555. if (!is_numeric($useajax)) {
  4556. $button = $useajax;
  4557. $useajax = 1;
  4558. $autoOpen = false;
  4559. $dialogconfirm .= '-'.$button;
  4560. }
  4561. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=yes';
  4562. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=no' : '');
  4563. // Add input fields into list of fields to read during submit (inputok and inputko)
  4564. if (is_array($formquestion)) {
  4565. foreach ($formquestion as $key => $input) {
  4566. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4567. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4568. if (is_array($input) && isset($input['name'])) {
  4569. if (strpos($input['name'], ',') > 0) {
  4570. $inputok = array_merge($inputok, explode(',', $input['name']));
  4571. } else {
  4572. array_push($inputok, $input['name']);
  4573. }
  4574. }
  4575. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4576. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4577. array_push($inputko, $input['name']);
  4578. }
  4579. }
  4580. }
  4581. // Show JQuery confirm box.
  4582. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4583. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4584. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4585. }
  4586. if (!empty($more)) {
  4587. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4588. }
  4589. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4590. $formconfirm .= '</div>'."\n";
  4591. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4592. $formconfirm .= '<script type="text/javascript">'."\n";
  4593. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4594. $formconfirm .= 'jQuery(document).ready(function() {
  4595. $(function() {
  4596. $( "#'.$dialogconfirm.'" ).dialog(
  4597. {
  4598. autoOpen: '.($autoOpen ? "true" : "false").',';
  4599. if ($newselectedchoice == 'no') {
  4600. $formconfirm .= '
  4601. open: function() {
  4602. $(this).parent().find("button.ui-button:eq(2)").focus();
  4603. },';
  4604. }
  4605. $formconfirm .= '
  4606. resizable: false,
  4607. height: "'.$height.'",
  4608. width: "'.$width.'",
  4609. modal: true,
  4610. closeOnEscape: false,
  4611. buttons: {
  4612. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  4613. var options = "&token='.urlencode(newToken()).'";
  4614. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4615. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4616. if (inputok.length>0) {
  4617. $.each(inputok, function(i, inputname) {
  4618. var more = "";
  4619. var inputvalue;
  4620. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4621. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4622. } else {
  4623. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4624. inputvalue = $("#" + inputname + more).val();
  4625. }
  4626. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4627. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4628. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4629. });
  4630. }
  4631. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  4632. if (pageyes.length > 0) { location.href = urljump; }
  4633. $(this).dialog("close");
  4634. },
  4635. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  4636. var options = "&token='.urlencode(newToken()).'";
  4637. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4638. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4639. if (inputko.length>0) {
  4640. $.each(inputko, function(i, inputname) {
  4641. var more = "";
  4642. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4643. var inputvalue = $("#" + inputname + more).val();
  4644. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4645. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4646. });
  4647. }
  4648. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  4649. //alert(urljump);
  4650. if (pageno.length > 0) { location.href = urljump; }
  4651. $(this).dialog("close");
  4652. }
  4653. }
  4654. }
  4655. );
  4656. var button = "'.$button.'";
  4657. if (button.length > 0) {
  4658. $( "#" + button ).click(function() {
  4659. $("#'.$dialogconfirm.'").dialog("open");
  4660. });
  4661. }
  4662. });
  4663. });
  4664. </script>';
  4665. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4666. } else {
  4667. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4668. if (empty($disableformtag)) {
  4669. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4670. }
  4671. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4672. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4673. $formconfirm .= '<table class="valid centpercent">'."\n";
  4674. // Line title
  4675. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4676. $formconfirm .= img_picto('', 'recent').' '.$title;
  4677. $formconfirm .= '</td></tr>'."\n";
  4678. // Line text
  4679. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4680. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4681. }
  4682. // Line form fields
  4683. if ($more) {
  4684. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4685. $formconfirm .= $more;
  4686. $formconfirm .= '</td></tr>'."\n";
  4687. }
  4688. // Line with question
  4689. $formconfirm .= '<tr class="valid">';
  4690. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4691. $formconfirm .= '<td class="valid center">';
  4692. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly');
  4693. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
  4694. $formconfirm .= '</td>';
  4695. $formconfirm .= '</tr>'."\n";
  4696. $formconfirm .= '</table>'."\n";
  4697. if (empty($disableformtag)) {
  4698. $formconfirm .= "</form>\n";
  4699. }
  4700. $formconfirm .= '<br>';
  4701. if (!empty($conf->use_javascript_ajax)) {
  4702. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4703. $formconfirm .= '<script type="text/javascript">'."\n";
  4704. $formconfirm .= '
  4705. $(document).ready(function () {
  4706. $(".confirmvalidatebutton").on("click", function() {
  4707. console.log("We click on button");
  4708. $(this).attr("disabled", "disabled");
  4709. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4710. //console.log($(this).closest("form"));
  4711. $(this).closest("form").submit();
  4712. });
  4713. });
  4714. ';
  4715. $formconfirm .= '</script>'."\n";
  4716. }
  4717. $formconfirm .= "<!-- end formconfirm -->\n";
  4718. }
  4719. return $formconfirm;
  4720. }
  4721. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4722. /**
  4723. * Show a form to select a project
  4724. *
  4725. * @param int $page Page
  4726. * @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)
  4727. * @param int $selected Id pre-selected project
  4728. * @param string $htmlname Name of select field
  4729. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4730. * @param int $maxlength Max length
  4731. * @param int $forcefocus Force focus on field (works with javascript only)
  4732. * @param int $nooutput No print is done. String is returned.
  4733. * @return string Return html content
  4734. */
  4735. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4736. {
  4737. // phpcs:enable
  4738. global $langs;
  4739. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4740. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4741. $out = '';
  4742. $formproject = new FormProjets($this->db);
  4743. $langs->load("project");
  4744. if ($htmlname != "none") {
  4745. $out .= "\n";
  4746. $out .= '<form method="post" action="'.$page.'">';
  4747. $out .= '<input type="hidden" name="action" value="classin">';
  4748. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4749. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4750. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4751. $out .= '</form>';
  4752. } else {
  4753. $out .= '<span class="project_head_block">';
  4754. if ($selected) {
  4755. $projet = new Project($this->db);
  4756. $projet->fetch($selected);
  4757. $out .= $projet->getNomUrl(1, '', 1);
  4758. } else {
  4759. $out .= "&nbsp;";
  4760. }
  4761. $out .= '</span>';
  4762. }
  4763. if (empty($nooutput)) {
  4764. print $out;
  4765. return '';
  4766. }
  4767. return $out;
  4768. }
  4769. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4770. /**
  4771. * Show a form to select payment conditions
  4772. *
  4773. * @param int $page Page
  4774. * @param string $selected Id condition pre-selectionne
  4775. * @param string $htmlname Name of select html field
  4776. * @param int $addempty Add empty entry
  4777. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4778. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  4779. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  4780. * 0 : use default deposit percentage from entry
  4781. * > 0 : force deposit percentage (for example, from company object)
  4782. * @return void
  4783. */
  4784. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1)
  4785. {
  4786. // phpcs:enable
  4787. global $langs;
  4788. if ($htmlname != "none") {
  4789. print '<form method="POST" action="'.$page.'">';
  4790. print '<input type="hidden" name="action" value="setconditions">';
  4791. print '<input type="hidden" name="token" value="'.newToken().'">';
  4792. if ($type) {
  4793. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4794. }
  4795. $this->select_conditions_paiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  4796. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4797. print '</form>';
  4798. } else {
  4799. if ($selected) {
  4800. $this->load_cache_conditions_paiements();
  4801. if (isset($this->cache_conditions_paiements[$selected])) {
  4802. $label = $this->cache_conditions_paiements[$selected]['label'];
  4803. if (! empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  4804. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  4805. }
  4806. print $label;
  4807. } else {
  4808. $langs->load('errors');
  4809. print $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4810. }
  4811. } else {
  4812. print "&nbsp;";
  4813. }
  4814. }
  4815. }
  4816. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4817. /**
  4818. * Show a form to select a delivery delay
  4819. *
  4820. * @param int $page Page
  4821. * @param string $selected Id condition pre-selectionne
  4822. * @param string $htmlname Name of select html field
  4823. * @param int $addempty Ajoute entree vide
  4824. * @return void
  4825. */
  4826. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4827. {
  4828. // phpcs:enable
  4829. global $langs;
  4830. if ($htmlname != "none") {
  4831. print '<form method="post" action="'.$page.'">';
  4832. print '<input type="hidden" name="action" value="setavailability">';
  4833. print '<input type="hidden" name="token" value="'.newToken().'">';
  4834. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4835. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4836. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4837. print '</form>';
  4838. } else {
  4839. if ($selected) {
  4840. $this->load_cache_availability();
  4841. print $this->cache_availability[$selected]['label'];
  4842. } else {
  4843. print "&nbsp;";
  4844. }
  4845. }
  4846. }
  4847. /**
  4848. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4849. * List found into table c_input_reason loaded by loadCacheInputReason
  4850. *
  4851. * @param string $page Page
  4852. * @param string $selected Id condition pre-selectionne
  4853. * @param string $htmlname Name of select html field
  4854. * @param int $addempty Add empty entry
  4855. * @return void
  4856. */
  4857. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4858. {
  4859. global $langs;
  4860. if ($htmlname != "none") {
  4861. print '<form method="post" action="'.$page.'">';
  4862. print '<input type="hidden" name="action" value="setdemandreason">';
  4863. print '<input type="hidden" name="token" value="'.newToken().'">';
  4864. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4865. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4866. print '</form>';
  4867. } else {
  4868. if ($selected) {
  4869. $this->loadCacheInputReason();
  4870. foreach ($this->cache_demand_reason as $key => $val) {
  4871. if ($val['id'] == $selected) {
  4872. print $val['label'];
  4873. break;
  4874. }
  4875. }
  4876. } else {
  4877. print "&nbsp;";
  4878. }
  4879. }
  4880. }
  4881. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4882. /**
  4883. * Show a form + html select a date
  4884. *
  4885. * @param string $page Page
  4886. * @param string $selected Date preselected
  4887. * @param string $htmlname Html name of date input fields or 'none'
  4888. * @param int $displayhour Display hour selector
  4889. * @param int $displaymin Display minutes selector
  4890. * @param int $nooutput 1=No print output, return string
  4891. * @param string $type 'direct-debit' or 'bank-transfer'
  4892. * @return string
  4893. * @see selectDate()
  4894. */
  4895. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  4896. {
  4897. // phpcs:enable
  4898. global $langs;
  4899. $ret = '';
  4900. if ($htmlname != "none") {
  4901. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4902. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4903. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4904. if ($type) {
  4905. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4906. }
  4907. $ret .= '<table class="nobordernopadding">';
  4908. $ret .= '<tr><td>';
  4909. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4910. $ret .= '</td>';
  4911. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4912. $ret .= '</tr></table></form>';
  4913. } else {
  4914. if ($displayhour) {
  4915. $ret .= dol_print_date($selected, 'dayhour');
  4916. } else {
  4917. $ret .= dol_print_date($selected, 'day');
  4918. }
  4919. }
  4920. if (empty($nooutput)) {
  4921. print $ret;
  4922. }
  4923. return $ret;
  4924. }
  4925. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4926. /**
  4927. * Show a select form to choose a user
  4928. *
  4929. * @param string $page Page
  4930. * @param string $selected Id of user preselected
  4931. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4932. * @param array $exclude List of users id to exclude
  4933. * @param array $include List of users id to include
  4934. * @return void
  4935. */
  4936. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4937. {
  4938. // phpcs:enable
  4939. global $langs;
  4940. if ($htmlname != "none") {
  4941. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4942. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4943. print '<input type="hidden" name="token" value="'.newToken().'">';
  4944. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4945. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4946. print '</form>';
  4947. } else {
  4948. if ($selected) {
  4949. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4950. $theuser = new User($this->db);
  4951. $theuser->fetch($selected);
  4952. print $theuser->getNomUrl(1);
  4953. } else {
  4954. print "&nbsp;";
  4955. }
  4956. }
  4957. }
  4958. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4959. /**
  4960. * Show form with payment mode
  4961. *
  4962. * @param string $page Page
  4963. * @param int $selected Id mode pre-selectionne
  4964. * @param string $htmlname Name of select html field
  4965. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  4966. * @param int $active Active or not, -1 = all
  4967. * @param int $addempty 1=Add empty entry
  4968. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4969. * @return void
  4970. */
  4971. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '')
  4972. {
  4973. // phpcs:enable
  4974. global $langs;
  4975. if ($htmlname != "none") {
  4976. print '<form method="POST" action="'.$page.'">';
  4977. print '<input type="hidden" name="action" value="setmode">';
  4978. print '<input type="hidden" name="token" value="'.newToken().'">';
  4979. if ($type) {
  4980. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4981. }
  4982. print $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  4983. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4984. print '</form>';
  4985. } else {
  4986. if ($selected) {
  4987. $this->load_cache_types_paiements();
  4988. print $this->cache_types_paiements[$selected]['label'];
  4989. } else {
  4990. print "&nbsp;";
  4991. }
  4992. }
  4993. }
  4994. /**
  4995. * Show form with transport mode
  4996. *
  4997. * @param string $page Page
  4998. * @param int $selected Id mode pre-select
  4999. * @param string $htmlname Name of select html field
  5000. * @param int $active Active or not, -1 = all
  5001. * @param int $addempty 1=Add empty entry
  5002. * @return void
  5003. */
  5004. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5005. {
  5006. global $langs;
  5007. if ($htmlname != "none") {
  5008. print '<form method="POST" action="'.$page.'">';
  5009. print '<input type="hidden" name="action" value="settransportmode">';
  5010. print '<input type="hidden" name="token" value="'.newToken().'">';
  5011. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5012. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5013. print '</form>';
  5014. } else {
  5015. if ($selected) {
  5016. $this->load_cache_transport_mode();
  5017. print $this->cache_transport_mode[$selected]['label'];
  5018. } else {
  5019. print "&nbsp;";
  5020. }
  5021. }
  5022. }
  5023. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5024. /**
  5025. * Show form with multicurrency code
  5026. *
  5027. * @param string $page Page
  5028. * @param string $selected code pre-selectionne
  5029. * @param string $htmlname Name of select html field
  5030. * @return void
  5031. */
  5032. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5033. {
  5034. // phpcs:enable
  5035. global $langs;
  5036. if ($htmlname != "none") {
  5037. print '<form method="POST" action="'.$page.'">';
  5038. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5039. print '<input type="hidden" name="token" value="'.newToken().'">';
  5040. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5041. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5042. print '</form>';
  5043. } else {
  5044. dol_include_once('/core/lib/company.lib.php');
  5045. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5046. }
  5047. }
  5048. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5049. /**
  5050. * Show form with multicurrency rate
  5051. *
  5052. * @param string $page Page
  5053. * @param double $rate Current rate
  5054. * @param string $htmlname Name of select html field
  5055. * @param string $currency Currency code to explain the rate
  5056. * @return void
  5057. */
  5058. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5059. {
  5060. // phpcs:enable
  5061. global $langs, $mysoc, $conf;
  5062. if ($htmlname != "none") {
  5063. print '<form method="POST" action="'.$page.'">';
  5064. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5065. print '<input type="hidden" name="token" value="'.newToken().'">';
  5066. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  5067. print '<select name="calculation_mode">';
  5068. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  5069. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  5070. print '</select> ';
  5071. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5072. print '</form>';
  5073. } else {
  5074. if (!empty($rate)) {
  5075. print price($rate, 1, $langs, 1, 0);
  5076. if ($currency && $rate != 1) {
  5077. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  5078. }
  5079. } else {
  5080. print 1;
  5081. }
  5082. }
  5083. }
  5084. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5085. /**
  5086. * Show a select box with available absolute discounts
  5087. *
  5088. * @param string $page Page URL where form is shown
  5089. * @param int $selected Value pre-selected
  5090. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5091. * @param int $socid Third party id
  5092. * @param float $amount Total amount available
  5093. * @param string $filter SQL filter on discounts
  5094. * @param int $maxvalue Max value for lines that can be selected
  5095. * @param string $more More string to add
  5096. * @param int $hidelist 1=Hide list
  5097. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5098. * @return void
  5099. */
  5100. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5101. {
  5102. // phpcs:enable
  5103. global $conf, $langs;
  5104. if ($htmlname != "none") {
  5105. print '<form method="post" action="'.$page.'">';
  5106. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5107. print '<input type="hidden" name="token" value="'.newToken().'">';
  5108. print '<div class="inline-block">';
  5109. if (!empty($discount_type)) {
  5110. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5111. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5112. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5113. } else {
  5114. $translationKey = 'HasCreditNoteFromSupplier';
  5115. }
  5116. } else {
  5117. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5118. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5119. } else {
  5120. $translationKey = 'HasCreditNoteFromSupplier';
  5121. }
  5122. }
  5123. } else {
  5124. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5125. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5126. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5127. } else {
  5128. $translationKey = 'CompanyHasCreditNote';
  5129. }
  5130. } else {
  5131. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5132. $translationKey = 'CompanyHasAbsoluteDiscount';
  5133. } else {
  5134. $translationKey = 'CompanyHasCreditNote';
  5135. }
  5136. }
  5137. }
  5138. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5139. if (empty($hidelist)) {
  5140. print ' ';
  5141. }
  5142. print '</div>';
  5143. if (empty($hidelist)) {
  5144. print '<div class="inline-block" style="padding-right: 10px">';
  5145. $newfilter = 'discount_type='.intval($discount_type);
  5146. if (!empty($discount_type)) {
  5147. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5148. } else {
  5149. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5150. }
  5151. if ($filter) {
  5152. $newfilter .= ' AND ('.$filter.')';
  5153. }
  5154. // output the combo of discounts
  5155. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5156. if ($nbqualifiedlines > 0) {
  5157. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  5158. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5159. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5160. }
  5161. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5162. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5163. }
  5164. print '>';
  5165. }
  5166. print '</div>';
  5167. }
  5168. if ($more) {
  5169. print '<div class="inline-block">';
  5170. print $more;
  5171. print '</div>';
  5172. }
  5173. print '</form>';
  5174. } else {
  5175. if ($selected) {
  5176. print $selected;
  5177. } else {
  5178. print "0";
  5179. }
  5180. }
  5181. }
  5182. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5183. /**
  5184. * Show forms to select a contact
  5185. *
  5186. * @param string $page Page
  5187. * @param Societe $societe Filter on third party
  5188. * @param int $selected Id contact pre-selectionne
  5189. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5190. * @return void
  5191. */
  5192. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5193. {
  5194. // phpcs:enable
  5195. global $langs, $conf;
  5196. if ($htmlname != "none") {
  5197. print '<form method="post" action="'.$page.'">';
  5198. print '<input type="hidden" name="action" value="set_contact">';
  5199. print '<input type="hidden" name="token" value="'.newToken().'">';
  5200. print '<table class="nobordernopadding">';
  5201. print '<tr><td>';
  5202. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5203. $num = $this->num;
  5204. if ($num == 0) {
  5205. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5206. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5207. }
  5208. print '</td>';
  5209. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5210. print '</tr></table></form>';
  5211. } else {
  5212. if ($selected) {
  5213. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5214. $contact = new Contact($this->db);
  5215. $contact->fetch($selected);
  5216. print $contact->getFullName($langs);
  5217. } else {
  5218. print "&nbsp;";
  5219. }
  5220. }
  5221. }
  5222. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5223. /**
  5224. * Output html select to select thirdparty
  5225. *
  5226. * @param string $page Page
  5227. * @param string $selected Id preselected
  5228. * @param string $htmlname Name of HTML select
  5229. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5230. * @param int $showempty Add an empty field
  5231. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5232. * @param int $forcecombo Force to use combo box
  5233. * @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')))
  5234. * @param int $nooutput No print output. Return it only.
  5235. * @param array $excludeids Exclude IDs from the select combo
  5236. * @return void|string
  5237. */
  5238. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array())
  5239. {
  5240. // phpcs:enable
  5241. global $langs;
  5242. $out = '';
  5243. if ($htmlname != "none") {
  5244. $out .= '<form method="post" action="'.$page.'">';
  5245. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5246. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5247. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5248. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5249. $out .= '</form>';
  5250. } else {
  5251. if ($selected) {
  5252. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5253. $soc = new Societe($this->db);
  5254. $soc->fetch($selected);
  5255. $out .= $soc->getNomUrl($langs);
  5256. } else {
  5257. $out .= "&nbsp;";
  5258. }
  5259. }
  5260. if ($nooutput) {
  5261. return $out;
  5262. } else {
  5263. print $out;
  5264. }
  5265. }
  5266. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5267. /**
  5268. * Retourne la liste des devises, dans la langue de l'utilisateur
  5269. *
  5270. * @param string $selected preselected currency code
  5271. * @param string $htmlname name of HTML select list
  5272. * @deprecated
  5273. * @return void
  5274. */
  5275. public function select_currency($selected = '', $htmlname = 'currency_id')
  5276. {
  5277. // phpcs:enable
  5278. print $this->selectCurrency($selected, $htmlname);
  5279. }
  5280. /**
  5281. * Retourne la liste des devises, dans la langue de l'utilisateur
  5282. *
  5283. * @param string $selected preselected currency code
  5284. * @param string $htmlname name of HTML select list
  5285. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5286. * @return string
  5287. */
  5288. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  5289. {
  5290. global $conf, $langs, $user;
  5291. $langs->loadCacheCurrencies('');
  5292. $out = '';
  5293. if ($selected == 'euro' || $selected == 'euros') {
  5294. $selected = 'EUR'; // Pour compatibilite
  5295. }
  5296. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5297. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5298. $labeltoshow = $currency['label'];
  5299. if ($mode == 1) {
  5300. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5301. } else {
  5302. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5303. }
  5304. if ($selected && $selected == $code_iso) {
  5305. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5306. } else {
  5307. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5308. }
  5309. $out .= $labeltoshow;
  5310. $out .= '</option>';
  5311. }
  5312. $out .= '</select>';
  5313. if ($user->admin) {
  5314. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5315. }
  5316. // Make select dynamic
  5317. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5318. $out .= ajax_combobox($htmlname);
  5319. return $out;
  5320. }
  5321. /**
  5322. * Return array of currencies in user language
  5323. *
  5324. * @param string $selected Preselected currency code
  5325. * @param string $htmlname Name of HTML select list
  5326. * @param integer $useempty 1=Add empty line
  5327. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5328. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5329. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5330. * @param string $morecss More css
  5331. * @return string
  5332. */
  5333. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5334. {
  5335. global $conf, $langs;
  5336. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5337. $TCurrency = array();
  5338. $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
  5339. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5340. if ($filter) {
  5341. $sql .= " AND ".$filter;
  5342. }
  5343. $resql = $this->db->query($sql);
  5344. if ($resql) {
  5345. while ($obj = $this->db->fetch_object($resql)) {
  5346. $TCurrency[$obj->code] = $obj->code;
  5347. }
  5348. }
  5349. $out = '';
  5350. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  5351. if ($useempty) {
  5352. $out .= '<option value="">&nbsp;</option>';
  5353. }
  5354. // If company current currency not in table, we add it into list. Should always be available.
  5355. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5356. $TCurrency[$conf->currency] = $conf->currency;
  5357. }
  5358. if (count($TCurrency) > 0) {
  5359. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5360. if (isset($TCurrency[$code_iso])) {
  5361. if (!empty($selected) && $selected == $code_iso) {
  5362. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5363. } else {
  5364. $out .= '<option value="'.$code_iso.'">';
  5365. }
  5366. $out .= $currency['label'];
  5367. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5368. $out .= '</option>';
  5369. }
  5370. }
  5371. }
  5372. $out .= '</select>';
  5373. // Make select dynamic
  5374. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5375. $out .= ajax_combobox($htmlname);
  5376. return $out;
  5377. }
  5378. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5379. /**
  5380. * Load into the cache vat rates of a country
  5381. *
  5382. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5383. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5384. */
  5385. public function load_cache_vatrates($country_code)
  5386. {
  5387. // phpcs:enable
  5388. global $langs;
  5389. $num = count($this->cache_vatrates);
  5390. if ($num > 0) {
  5391. return $num; // Cache already loaded
  5392. }
  5393. dol_syslog(__METHOD__, LOG_DEBUG);
  5394. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5395. $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
  5396. $sql .= " WHERE t.fk_pays = c.rowid";
  5397. $sql .= " AND t.active > 0";
  5398. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5399. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5400. $resql = $this->db->query($sql);
  5401. if ($resql) {
  5402. $num = $this->db->num_rows($resql);
  5403. if ($num) {
  5404. for ($i = 0; $i < $num; $i++) {
  5405. $obj = $this->db->fetch_object($resql);
  5406. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5407. $this->cache_vatrates[$i]['code'] = $obj->code;
  5408. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5409. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5410. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5411. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5412. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5413. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5414. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5415. $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
  5416. $positiverates = '';
  5417. if ($obj->taux) {
  5418. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5419. }
  5420. if ($obj->localtax1) {
  5421. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5422. }
  5423. if ($obj->localtax2) {
  5424. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5425. }
  5426. if (empty($positiverates)) {
  5427. $positiverates = '0';
  5428. }
  5429. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5430. }
  5431. return $num;
  5432. } else {
  5433. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5434. return -1;
  5435. }
  5436. } else {
  5437. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5438. return -2;
  5439. }
  5440. }
  5441. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5442. /**
  5443. * Output an HTML select vat rate.
  5444. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5445. *
  5446. * @param string $htmlname Name of HTML select field
  5447. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5448. * @param Societe $societe_vendeuse Thirdparty seller
  5449. * @param Societe $societe_acheteuse Thirdparty buyer
  5450. * @param int $idprod Id product. O if unknown of NA.
  5451. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5452. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5453. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5454. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5455. * 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.
  5456. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5457. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5458. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5459. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5460. * @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
  5461. * @return string
  5462. */
  5463. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5464. {
  5465. // phpcs:enable
  5466. global $langs, $conf, $mysoc;
  5467. $langs->load('errors');
  5468. $return = '';
  5469. // Define defaultnpr, defaultttx and defaultcode
  5470. $defaultnpr = ($info_bits & 0x01);
  5471. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5472. $defaulttx = str_replace('*', '', $selectedrate);
  5473. $defaultcode = '';
  5474. $reg = array();
  5475. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5476. $defaultcode = $reg[1];
  5477. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5478. }
  5479. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5480. // Check parameters
  5481. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5482. if ($societe_vendeuse->id == $mysoc->id) {
  5483. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5484. } else {
  5485. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5486. }
  5487. return $return;
  5488. }
  5489. //var_dump($societe_acheteuse);
  5490. //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";
  5491. //exit;
  5492. // Define list of countries to use to search VAT rates to show
  5493. // First we defined code_country to use to find list
  5494. if (is_object($societe_vendeuse)) {
  5495. $code_country = "'".$societe_vendeuse->country_code."'";
  5496. } else {
  5497. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5498. }
  5499. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5500. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5501. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5502. // We also add the buyer
  5503. if (is_numeric($type)) {
  5504. if ($type == 1) { // We know product is a service
  5505. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5506. }
  5507. } elseif (!$idprod) { // We don't know type of product
  5508. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5509. } else {
  5510. $prodstatic = new Product($this->db);
  5511. $prodstatic->fetch($idprod);
  5512. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5513. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5514. }
  5515. }
  5516. }
  5517. }
  5518. // Now we get list
  5519. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5520. if ($num > 0) {
  5521. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5522. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5523. $tmpthirdparty = new Societe($this->db);
  5524. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5525. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5526. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5527. $defaultcode = $reg[1];
  5528. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5529. }
  5530. if (empty($defaulttx)) {
  5531. $defaultnpr = 0;
  5532. }
  5533. }
  5534. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  5535. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  5536. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5537. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5538. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5539. } else {
  5540. $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  5541. }
  5542. }
  5543. // Disabled if seller is not subject to VAT
  5544. $disabled = false;
  5545. $title = '';
  5546. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5547. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5548. // of using supplier invoices (this is a very bad idea !)
  5549. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5550. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  5551. $disabled = true;
  5552. }
  5553. }
  5554. if (!$options_only) {
  5555. $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5556. }
  5557. $selectedfound = false;
  5558. foreach ($this->cache_vatrates as $rate) {
  5559. // Keep only 0 if seller is not subject to VAT
  5560. if ($disabled && $rate['txtva'] != 0) {
  5561. continue;
  5562. }
  5563. // Define key to use into select list
  5564. $key = $rate['txtva'];
  5565. $key .= $rate['nprtva'] ? '*' : '';
  5566. if ($mode > 0 && $rate['code']) {
  5567. $key .= ' ('.$rate['code'].')';
  5568. }
  5569. if ($mode < 0) {
  5570. $key = $rate['rowid'];
  5571. }
  5572. $return .= '<option value="'.$key.'"';
  5573. if (!$selectedfound) {
  5574. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5575. if ($defaultcode == $rate['code']) {
  5576. $return .= ' selected';
  5577. $selectedfound = true;
  5578. }
  5579. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5580. $return .= ' selected';
  5581. $selectedfound = true;
  5582. }
  5583. }
  5584. $return .= '>';
  5585. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  5586. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5587. $return .= $rate['labelpositiverates'];
  5588. } else {
  5589. $return .= vatrate($rate['label']);
  5590. }
  5591. //$return.=($rate['code']?' '.$rate['code']:'');
  5592. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5593. $return .= '</option>';
  5594. }
  5595. if (!$options_only) {
  5596. $return .= '</select>';
  5597. }
  5598. } else {
  5599. $return .= $this->error;
  5600. }
  5601. $this->num = $num;
  5602. return $return;
  5603. }
  5604. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5605. /**
  5606. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5607. * Fields are preselected with :
  5608. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5609. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5610. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5611. *
  5612. * @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).
  5613. * @param string $prefix Prefix for fields name
  5614. * @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
  5615. * @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
  5616. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5617. * @param string $form_name Not used
  5618. * @param int $d 1=Show days, month, years
  5619. * @param int $addnowlink Add a link "Now"
  5620. * @param int $nooutput Do not output html string but return it
  5621. * @param int $disabled Disable input fields
  5622. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5623. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5624. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5625. * @return string|void Nothing or string if nooutput is 1
  5626. * @deprecated
  5627. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5628. */
  5629. 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 = '')
  5630. {
  5631. // phpcs:enable
  5632. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5633. if (!empty($nooutput)) {
  5634. return $retstring;
  5635. }
  5636. print $retstring;
  5637. return;
  5638. }
  5639. /**
  5640. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5641. * Fields are preselected with :
  5642. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5643. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5644. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5645. *
  5646. * @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).
  5647. * @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).
  5648. * @param string $prefix Prefix for fields name
  5649. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5650. * @param string $forcenewline Force new line between the 2 dates.
  5651. * @return string Html for selectDate
  5652. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5653. */
  5654. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5655. {
  5656. global $langs;
  5657. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5658. if ($forcenewline) {
  5659. $ret .= '<br>';
  5660. }
  5661. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5662. return $ret;
  5663. }
  5664. /**
  5665. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5666. * Fields are preselected with :
  5667. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5668. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5669. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5670. *
  5671. * @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).
  5672. * @param string $prefix Prefix for fields name
  5673. * @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
  5674. * @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
  5675. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5676. * @param string $form_name Not used
  5677. * @param int $d 1=Show days, month, years
  5678. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5679. * @param int $disabled Disable input fields
  5680. * @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')
  5681. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5682. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5683. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5684. * @param int $stepminutes Specify step for minutes between 1 and 30
  5685. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5686. * @param string $placeholder Placeholder
  5687. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5688. * @return string Html for selectDate
  5689. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5690. */
  5691. 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')
  5692. {
  5693. global $conf, $langs;
  5694. if ($gm === 'auto') {
  5695. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5696. }
  5697. $retstring = '';
  5698. if ($prefix == '') {
  5699. $prefix = 're';
  5700. }
  5701. if ($h == '') {
  5702. $h = 0;
  5703. }
  5704. if ($m == '') {
  5705. $m = 0;
  5706. }
  5707. $emptydate = 0;
  5708. $emptyhours = 0;
  5709. if ($stepminutes <= 0 || $stepminutes > 30) {
  5710. $stepminutes = 1;
  5711. }
  5712. if ($empty == 1) {
  5713. $emptydate = 1;
  5714. $emptyhours = 1;
  5715. }
  5716. if ($empty == 2) {
  5717. $emptydate = 0;
  5718. $emptyhours = 1;
  5719. }
  5720. $orig_set_time = $set_time;
  5721. if ($set_time === '' && $emptydate == 0) {
  5722. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5723. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5724. $set_time = dol_now($gm);
  5725. } else {
  5726. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5727. }
  5728. }
  5729. // Analysis of the pre-selection date
  5730. $reg = array();
  5731. $shour = '';
  5732. $smin = '';
  5733. $ssec = '';
  5734. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5735. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5736. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5737. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5738. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5739. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5740. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5741. } elseif (strval($set_time) != '' && $set_time != -1) {
  5742. // set_time est un timestamps (0 possible)
  5743. $syear = dol_print_date($set_time, "%Y", $gm);
  5744. $smonth = dol_print_date($set_time, "%m", $gm);
  5745. $sday = dol_print_date($set_time, "%d", $gm);
  5746. if ($orig_set_time != '') {
  5747. $shour = dol_print_date($set_time, "%H", $gm);
  5748. $smin = dol_print_date($set_time, "%M", $gm);
  5749. $ssec = dol_print_date($set_time, "%S", $gm);
  5750. }
  5751. } else {
  5752. // Date est '' ou vaut -1
  5753. $syear = '';
  5754. $smonth = '';
  5755. $sday = '';
  5756. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5757. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5758. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5759. }
  5760. if ($h == 3) {
  5761. $shour = '';
  5762. }
  5763. if ($m == 3) {
  5764. $smin = '';
  5765. }
  5766. $nowgmt = dol_now('gmt');
  5767. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5768. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5769. $usecalendar = 'combo';
  5770. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5771. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5772. }
  5773. if ($d) {
  5774. // Show date with popup
  5775. if ($usecalendar != 'combo') {
  5776. $formated_date = '';
  5777. //print "e".$set_time." t ".$conf->format_date_short;
  5778. if (strval($set_time) != '' && $set_time != -1) {
  5779. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5780. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5781. }
  5782. // Calendrier popup version eldy
  5783. if ($usecalendar == "eldy") {
  5784. // Input area to enter date manually
  5785. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5786. $retstring .= ($disabled ? ' disabled' : '');
  5787. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5788. $retstring .= '>';
  5789. // Icon calendar
  5790. $retstringbuttom = '';
  5791. if (!$disabled) {
  5792. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5793. $base = DOL_URL_ROOT.'/core/';
  5794. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5795. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5796. } else {
  5797. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5798. }
  5799. $retstring = $retstringbuttom.$retstring;
  5800. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5801. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5802. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5803. } elseif ($usecalendar == 'jquery') {
  5804. if (!$disabled) {
  5805. // Output javascript for datepicker
  5806. $retstring .= "<script type='text/javascript'>";
  5807. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5808. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5809. autoclose: true,
  5810. todayHighlight: true,";
  5811. if (!empty($conf->dol_use_jmobile)) {
  5812. $retstring .= "
  5813. beforeShow: function (input, datePicker) {
  5814. input.disabled = true;
  5815. },
  5816. onClose: function (dateText, datePicker) {
  5817. this.disabled = false;
  5818. },
  5819. ";
  5820. }
  5821. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5822. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  5823. $retstring .= "
  5824. showOn: 'button', /* both has problem with autocompletion */
  5825. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  5826. buttonImageOnly: true";
  5827. }
  5828. $retstring .= "
  5829. }) });";
  5830. $retstring .= "</script>";
  5831. }
  5832. // Zone de saisie manuelle de la date
  5833. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  5834. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5835. $retstring .= ($disabled ? ' disabled' : '');
  5836. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  5837. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5838. $retstring .= '>';
  5839. // Icone calendrier
  5840. if (!$disabled) {
  5841. /* Not required. Managed by option buttonImage of jquery
  5842. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5843. $retstring.="<script type='text/javascript'>";
  5844. $retstring.="jQuery(document).ready(function() {";
  5845. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5846. $retstring.=" jQuery('#".$prefix."').focus();";
  5847. $retstring.=' });';
  5848. $retstring.='});';
  5849. $retstring.="</script>";*/
  5850. } else {
  5851. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5852. $retsring = $retstringbutton.$retstring;
  5853. }
  5854. $retstring .= '</div>';
  5855. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5856. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5857. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5858. } else {
  5859. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5860. }
  5861. } else {
  5862. // Show date with combo selects
  5863. // Day
  5864. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5865. if ($emptydate || $set_time == -1) {
  5866. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5867. }
  5868. for ($day = 1; $day <= 31; $day++) {
  5869. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5870. }
  5871. $retstring .= "</select>";
  5872. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5873. if ($emptydate || $set_time == -1) {
  5874. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5875. }
  5876. // Month
  5877. for ($month = 1; $month <= 12; $month++) {
  5878. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5879. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5880. $retstring .= "</option>";
  5881. }
  5882. $retstring .= "</select>";
  5883. // Year
  5884. if ($emptydate || $set_time == -1) {
  5885. $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.'">';
  5886. } else {
  5887. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5888. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  5889. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5890. }
  5891. $retstring .= "</select>\n";
  5892. }
  5893. }
  5894. }
  5895. if ($d && $h) {
  5896. $retstring .= ($h == 2 ? '<br>' : ' ');
  5897. $retstring .= '<span class="nowraponall">';
  5898. }
  5899. if ($h) {
  5900. $hourstart = 0;
  5901. $hourend = 24;
  5902. if ($openinghours != '') {
  5903. $openinghours = explode(',', $openinghours);
  5904. $hourstart = $openinghours[0];
  5905. $hourend = $openinghours[1];
  5906. if ($hourend < $hourstart) {
  5907. $hourend = $hourstart;
  5908. }
  5909. }
  5910. // Show hour
  5911. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5912. if ($emptyhours) {
  5913. $retstring .= '<option value="-1">&nbsp;</option>';
  5914. }
  5915. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  5916. if (strlen($hour) < 2) {
  5917. $hour = "0".$hour;
  5918. }
  5919. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5920. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5921. $retstring .= '</option>';
  5922. }
  5923. $retstring .= '</select>';
  5924. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5925. if ($m) {
  5926. $retstring .= ":";
  5927. }
  5928. }
  5929. if ($m) {
  5930. // Show minutes
  5931. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  5932. if ($emptyhours) {
  5933. $retstring .= '<option value="-1">&nbsp;</option>';
  5934. }
  5935. for ($min = 0; $min < 60; $min += $stepminutes) {
  5936. if (strlen($min) < 2) {
  5937. $min = "0".$min;
  5938. }
  5939. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  5940. }
  5941. $retstring .= '</select>';
  5942. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  5943. }
  5944. if ($d && $h) {
  5945. $retstring .= '</span>';
  5946. }
  5947. // Add a "Now" link
  5948. if ($conf->use_javascript_ajax && $addnowlink) {
  5949. // Script which will be inserted in the onClick of the "Now" link
  5950. $reset_scripts = "";
  5951. if ($addnowlink == 2) { // local computer time
  5952. // pad add leading 0 on numbers
  5953. $reset_scripts .= "Number.prototype.pad = function(size) {
  5954. var s = String(this);
  5955. while (s.length < (size || 2)) {s = '0' + s;}
  5956. return s;
  5957. };
  5958. var d = new Date();";
  5959. }
  5960. // Generate the date part, depending on the use or not of the javascript calendar
  5961. if ($addnowlink == 1) { // server time expressed in user time setup
  5962. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5963. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5964. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5965. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5966. } elseif ($addnowlink == 2) {
  5967. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5968. * This break application for foreign languages.
  5969. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5970. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5971. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5972. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5973. */
  5974. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5975. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5976. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5977. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5978. }
  5979. /*if ($usecalendar == "eldy")
  5980. {
  5981. $base=DOL_URL_ROOT.'/core/';
  5982. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5983. }
  5984. else
  5985. {
  5986. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5987. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5988. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5989. }*/
  5990. // Update the hour part
  5991. if ($h) {
  5992. if ($fullday) {
  5993. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5994. }
  5995. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5996. if ($addnowlink == 1) {
  5997. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5998. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5999. } elseif ($addnowlink == 2) {
  6000. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  6001. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  6002. }
  6003. if ($fullday) {
  6004. $reset_scripts .= ' } ';
  6005. }
  6006. }
  6007. // Update the minute part
  6008. if ($m) {
  6009. if ($fullday) {
  6010. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6011. }
  6012. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6013. if ($addnowlink == 1) {
  6014. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6015. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6016. } elseif ($addnowlink == 2) {
  6017. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  6018. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6019. }
  6020. if ($fullday) {
  6021. $reset_scripts .= ' } ';
  6022. }
  6023. }
  6024. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6025. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6026. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  6027. $retstring .= $langs->trans("Now");
  6028. $retstring .= '</button> ';
  6029. }
  6030. }
  6031. // Add a "Plus one hour" link
  6032. if ($conf->use_javascript_ajax && $addplusone) {
  6033. // Script which will be inserted in the onClick of the "Add plusone" link
  6034. $reset_scripts = "";
  6035. // Generate the date part, depending on the use or not of the javascript calendar
  6036. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  6037. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6038. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6039. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6040. // Update the hour part
  6041. if ($h) {
  6042. if ($fullday) {
  6043. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6044. }
  6045. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6046. if ($fullday) {
  6047. $reset_scripts .= ' } ';
  6048. }
  6049. }
  6050. // Update the minute part
  6051. if ($m) {
  6052. if ($fullday) {
  6053. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6054. }
  6055. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6056. if ($fullday) {
  6057. $reset_scripts .= ' } ';
  6058. }
  6059. }
  6060. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6061. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6062. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  6063. $retstring .= $langs->trans("DateStartPlusOne");
  6064. $retstring .= '</button> ';
  6065. }
  6066. }
  6067. // Add a link to set data
  6068. if ($conf->use_javascript_ajax && $adddateof) {
  6069. $tmparray = dol_getdate($adddateof);
  6070. if (empty($labeladddateof)) {
  6071. $labeladddateof = $langs->trans("DateInvoice");
  6072. }
  6073. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="console.log(\'Click on now link\'); jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  6074. }
  6075. return $retstring;
  6076. }
  6077. /**
  6078. * selectTypeDuration
  6079. *
  6080. * @param string $prefix Prefix
  6081. * @param string $selected Selected duration type
  6082. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6083. * @return string HTML select string
  6084. */
  6085. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6086. {
  6087. global $langs;
  6088. $TDurationTypes = array(
  6089. 'y'=>$langs->trans('Years'),
  6090. 'm'=>$langs->trans('Month'),
  6091. 'w'=>$langs->trans('Weeks'),
  6092. 'd'=>$langs->trans('Days'),
  6093. 'h'=>$langs->trans('Hours'),
  6094. 'i'=>$langs->trans('Minutes')
  6095. );
  6096. // Removed undesired duration types
  6097. foreach ($excludetypes as $value) {
  6098. unset($TDurationTypes[$value]);
  6099. }
  6100. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  6101. foreach ($TDurationTypes as $key => $typeduration) {
  6102. $retstring .= '<option value="'.$key.'"';
  6103. if ($key == $selected) {
  6104. $retstring .= " selected";
  6105. }
  6106. $retstring .= ">".$typeduration."</option>";
  6107. }
  6108. $retstring .= "</select>";
  6109. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  6110. return $retstring;
  6111. }
  6112. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6113. /**
  6114. * Function to show a form to select a duration on a page
  6115. *
  6116. * @param string $prefix Prefix for input fields
  6117. * @param int $iSecond Default preselected duration (number of seconds or '')
  6118. * @param int $disabled Disable the combo box
  6119. * @param string $typehour If 'select' then input hour and input min is a combo,
  6120. * If 'text' input hour is in text and input min is a text,
  6121. * If 'textselect' input hour is in text and input min is a combo
  6122. * @param integer $minunderhours If 1, show minutes selection under the hours
  6123. * @param int $nooutput Do not output html string but return it
  6124. * @return string|void
  6125. */
  6126. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6127. {
  6128. // phpcs:enable
  6129. global $langs;
  6130. $retstring = '<span class="nowraponall">';
  6131. $hourSelected = 0;
  6132. $minSelected = 0;
  6133. // Hours
  6134. if ($iSecond != '') {
  6135. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6136. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6137. $minSelected = convertSecondToTime($iSecond, 'min');
  6138. }
  6139. if ($typehour == 'select') {
  6140. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  6141. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6142. $retstring .= '<option value="'.$hour.'"';
  6143. if ($hourSelected == $hour) {
  6144. $retstring .= " selected";
  6145. }
  6146. $retstring .= ">".$hour."</option>";
  6147. }
  6148. $retstring .= "</select>";
  6149. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6150. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  6151. } else {
  6152. return 'BadValueForParameterTypeHour';
  6153. }
  6154. if ($typehour != 'text') {
  6155. $retstring .= ' '.$langs->trans('HourShort');
  6156. } else {
  6157. $retstring .= '<span class="">:</span>';
  6158. }
  6159. // Minutes
  6160. if ($minunderhours) {
  6161. $retstring .= '<br>';
  6162. } else {
  6163. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6164. }
  6165. if ($typehour == 'select' || $typehour == 'textselect') {
  6166. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  6167. for ($min = 0; $min <= 55; $min = $min + 5) {
  6168. $retstring .= '<option value="'.$min.'"';
  6169. if ($minSelected == $min) {
  6170. $retstring .= ' selected';
  6171. }
  6172. $retstring .= '>'.$min.'</option>';
  6173. }
  6174. $retstring .= "</select>";
  6175. } elseif ($typehour == 'text') {
  6176. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6177. }
  6178. if ($typehour != 'text') {
  6179. $retstring .= ' '.$langs->trans('MinuteShort');
  6180. }
  6181. $retstring.="</span>";
  6182. if (!empty($nooutput)) {
  6183. return $retstring;
  6184. }
  6185. print $retstring;
  6186. return;
  6187. }
  6188. /**
  6189. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6190. *
  6191. * @param int $selected Preselected tickets
  6192. * @param string $htmlname Name of HTML select field (must be unique in page).
  6193. * @param string $filtertype To add a filter
  6194. * @param int $limit Limit on number of returned lines
  6195. * @param int $status Ticket status
  6196. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6197. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6198. * @param array $ajaxoptions Options for ajax_autocompleter
  6199. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6200. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6201. * @param int $forcecombo Force to use combo box
  6202. * @param string $morecss Add more css on select
  6203. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6204. * @param string $nooutput No print, return the output into a string
  6205. * @return void|string
  6206. */
  6207. 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)
  6208. {
  6209. global $langs, $conf;
  6210. $out = '';
  6211. // check parameters
  6212. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6213. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6214. $placeholder = '';
  6215. if ($selected && empty($selected_input_value)) {
  6216. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6217. $tickettmpselect = new Ticket($this->db);
  6218. $tickettmpselect->fetch($selected);
  6219. $selected_input_value = $tickettmpselect->ref;
  6220. unset($tickettmpselect);
  6221. }
  6222. $urloption = '';
  6223. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6224. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6225. elseif ($hidelabel > 1) {
  6226. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6227. if ($hidelabel == 2) {
  6228. $out .= img_picto($langs->trans("Search"), 'search');
  6229. }
  6230. }
  6231. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6232. if ($hidelabel == 3) {
  6233. $out .= img_picto($langs->trans("Search"), 'search');
  6234. }
  6235. } else {
  6236. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6237. }
  6238. if (empty($nooutput)) print $out;
  6239. else return $out;
  6240. }
  6241. /**
  6242. * Return list of tickets.
  6243. * Called by selectTickets.
  6244. *
  6245. * @param int $selected Preselected ticket
  6246. * @param string $htmlname Name of select html
  6247. * @param string $filtertype Filter on ticket type
  6248. * @param int $limit Limit on number of returned lines
  6249. * @param string $filterkey Filter on ticket ref or subject
  6250. * @param int $status Ticket status
  6251. * @param int $outputmode 0=HTML select string, 1=Array
  6252. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6253. * @param int $forcecombo Force to use combo box
  6254. * @param string $morecss Add more css on select
  6255. * @return array Array of keys for json
  6256. */
  6257. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6258. {
  6259. global $langs, $conf;
  6260. $out = '';
  6261. $outarray = array();
  6262. $selectFields = " p.rowid, p.ref, p.message";
  6263. $sql = "SELECT ";
  6264. $sql .= $selectFields;
  6265. $sql .= " FROM ".$this->db->prefix()."ticket as p";
  6266. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6267. // Add criteria on ref/label
  6268. if ($filterkey != '') {
  6269. $sql .= ' AND (';
  6270. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6271. // For natural search
  6272. $scrit = explode(' ', $filterkey);
  6273. $i = 0;
  6274. if (count($scrit) > 1) $sql .= "(";
  6275. foreach ($scrit as $crit) {
  6276. if ($i > 0) $sql .= " AND ";
  6277. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6278. $sql .= ")";
  6279. $i++;
  6280. }
  6281. if (count($scrit) > 1) $sql .= ")";
  6282. $sql .= ')';
  6283. }
  6284. $sql .= $this->db->plimit($limit, 0);
  6285. // Build output string
  6286. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6287. $result = $this->db->query($sql);
  6288. if ($result) {
  6289. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6290. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6291. $num = $this->db->num_rows($result);
  6292. $events = null;
  6293. if (!$forcecombo) {
  6294. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6295. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6296. }
  6297. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6298. $textifempty = '';
  6299. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6300. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6301. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6302. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6303. else $textifempty .= $langs->trans("All");
  6304. } else {
  6305. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6306. }
  6307. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6308. $i = 0;
  6309. while ($num && $i < $num) {
  6310. $opt = '';
  6311. $optJson = array();
  6312. $objp = $this->db->fetch_object($result);
  6313. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6314. // Add new entry
  6315. // "key" value of json key array is used by jQuery automatically as selected value
  6316. // "label" value of json key array is used by jQuery automatically as text for combo box
  6317. $out .= $opt;
  6318. array_push($outarray, $optJson);
  6319. $i++;
  6320. }
  6321. $out .= '</select>';
  6322. $this->db->free($result);
  6323. if (empty($outputmode)) return $out;
  6324. return $outarray;
  6325. } else {
  6326. dol_print_error($this->db);
  6327. }
  6328. }
  6329. /**
  6330. * constructTicketListOption.
  6331. * This define value for &$opt and &$optJson.
  6332. *
  6333. * @param resource $objp Result set of fetch
  6334. * @param string $opt Option (var used for returned value in string option format)
  6335. * @param string $optJson Option (var used for returned value in json format)
  6336. * @param string $selected Preselected value
  6337. * @param string $filterkey Filter key to highlight
  6338. * @return void
  6339. */
  6340. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6341. {
  6342. $outkey = '';
  6343. $outref = '';
  6344. $outtype = '';
  6345. $outkey = $objp->rowid;
  6346. $outref = $objp->ref;
  6347. $outtype = $objp->fk_product_type;
  6348. $opt = '<option value="'.$objp->rowid.'"';
  6349. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6350. $opt .= '>';
  6351. $opt .= $objp->ref;
  6352. $objRef = $objp->ref;
  6353. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6354. $opt .= "</option>\n";
  6355. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6356. }
  6357. /**
  6358. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6359. *
  6360. * @param int $selected Preselected tickets
  6361. * @param string $htmlname Name of HTML select field (must be unique in page).
  6362. * @param string $filtertype To add a filter
  6363. * @param int $limit Limit on number of returned lines
  6364. * @param int $status Ticket status
  6365. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6366. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6367. * @param array $ajaxoptions Options for ajax_autocompleter
  6368. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6369. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6370. * @param int $forcecombo Force to use combo box
  6371. * @param string $morecss Add more css on select
  6372. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6373. * @param string $nooutput No print, return the output into a string
  6374. * @return void|string
  6375. */
  6376. 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)
  6377. {
  6378. global $langs, $conf;
  6379. $out = '';
  6380. // check parameters
  6381. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6382. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6383. $placeholder = '';
  6384. if ($selected && empty($selected_input_value)) {
  6385. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6386. $projecttmpselect = new Project($this->db);
  6387. $projecttmpselect->fetch($selected);
  6388. $selected_input_value = $projecttmpselect->ref;
  6389. unset($projecttmpselect);
  6390. }
  6391. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6392. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6393. elseif ($hidelabel > 1) {
  6394. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6395. if ($hidelabel == 2) {
  6396. $out .= img_picto($langs->trans("Search"), 'search');
  6397. }
  6398. }
  6399. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6400. if ($hidelabel == 3) {
  6401. $out .= img_picto($langs->trans("Search"), 'search');
  6402. }
  6403. } else {
  6404. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6405. }
  6406. if (empty($nooutput)) print $out;
  6407. else return $out;
  6408. }
  6409. /**
  6410. * Return list of projects.
  6411. * Called by selectProjects.
  6412. *
  6413. * @param int $selected Preselected project
  6414. * @param string $htmlname Name of select html
  6415. * @param string $filtertype Filter on project type
  6416. * @param int $limit Limit on number of returned lines
  6417. * @param string $filterkey Filter on project ref or subject
  6418. * @param int $status Ticket status
  6419. * @param int $outputmode 0=HTML select string, 1=Array
  6420. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6421. * @param int $forcecombo Force to use combo box
  6422. * @param string $morecss Add more css on select
  6423. * @return array Array of keys for json
  6424. */
  6425. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6426. {
  6427. global $langs, $conf;
  6428. $out = '';
  6429. $outarray = array();
  6430. $selectFields = " p.rowid, p.ref";
  6431. $sql = "SELECT ";
  6432. $sql .= $selectFields;
  6433. $sql .= " FROM ".$this->db->prefix()."projet as p";
  6434. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6435. // Add criteria on ref/label
  6436. if ($filterkey != '') {
  6437. $sql .= ' AND (';
  6438. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6439. // For natural search
  6440. $scrit = explode(' ', $filterkey);
  6441. $i = 0;
  6442. if (count($scrit) > 1) $sql .= "(";
  6443. foreach ($scrit as $crit) {
  6444. if ($i > 0) $sql .= " AND ";
  6445. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6446. $sql .= "";
  6447. $i++;
  6448. }
  6449. if (count($scrit) > 1) $sql .= ")";
  6450. $sql .= ')';
  6451. }
  6452. $sql .= $this->db->plimit($limit, 0);
  6453. // Build output string
  6454. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6455. $result = $this->db->query($sql);
  6456. if ($result) {
  6457. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6458. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6459. $num = $this->db->num_rows($result);
  6460. $events = null;
  6461. if (!$forcecombo) {
  6462. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6463. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6464. }
  6465. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6466. $textifempty = '';
  6467. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6468. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6469. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6470. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6471. else $textifempty .= $langs->trans("All");
  6472. } else {
  6473. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6474. }
  6475. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6476. $i = 0;
  6477. while ($num && $i < $num) {
  6478. $opt = '';
  6479. $optJson = array();
  6480. $objp = $this->db->fetch_object($result);
  6481. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6482. // Add new entry
  6483. // "key" value of json key array is used by jQuery automatically as selected value
  6484. // "label" value of json key array is used by jQuery automatically as text for combo box
  6485. $out .= $opt;
  6486. array_push($outarray, $optJson);
  6487. $i++;
  6488. }
  6489. $out .= '</select>';
  6490. $this->db->free($result);
  6491. if (empty($outputmode)) return $out;
  6492. return $outarray;
  6493. } else {
  6494. dol_print_error($this->db);
  6495. }
  6496. }
  6497. /**
  6498. * constructProjectListOption.
  6499. * This define value for &$opt and &$optJson.
  6500. *
  6501. * @param resource $objp Result set of fetch
  6502. * @param string $opt Option (var used for returned value in string option format)
  6503. * @param string $optJson Option (var used for returned value in json format)
  6504. * @param string $selected Preselected value
  6505. * @param string $filterkey Filter key to highlight
  6506. * @return void
  6507. */
  6508. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6509. {
  6510. $outkey = '';
  6511. $outval = '';
  6512. $outref = '';
  6513. $outlabel = '';
  6514. $outtype = '';
  6515. $label = $objp->label;
  6516. $outkey = $objp->rowid;
  6517. $outref = $objp->ref;
  6518. $outlabel = $objp->label;
  6519. $outtype = $objp->fk_product_type;
  6520. $opt = '<option value="'.$objp->rowid.'"';
  6521. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6522. $opt .= '>';
  6523. $opt .= $objp->ref;
  6524. $objRef = $objp->ref;
  6525. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6526. $outval .= $objRef;
  6527. $opt .= "</option>\n";
  6528. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6529. }
  6530. /**
  6531. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6532. *
  6533. * @param int $selected Preselected tickets
  6534. * @param string $htmlname Name of HTML select field (must be unique in page).
  6535. * @param string $filtertype To add a filter
  6536. * @param int $limit Limit on number of returned lines
  6537. * @param int $status Ticket status
  6538. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6539. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6540. * @param array $ajaxoptions Options for ajax_autocompleter
  6541. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6542. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6543. * @param int $forcecombo Force to use combo box
  6544. * @param string $morecss Add more css on select
  6545. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6546. * @param string $nooutput No print, return the output into a string
  6547. * @return void|string
  6548. */
  6549. 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)
  6550. {
  6551. global $langs, $conf;
  6552. $out = '';
  6553. // check parameters
  6554. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6555. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6556. $placeholder = '';
  6557. $urloption = '';
  6558. if ($selected && empty($selected_input_value)) {
  6559. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6560. $adherenttmpselect = new Adherent($this->db);
  6561. $adherenttmpselect->fetch($selected);
  6562. $selected_input_value = $adherenttmpselect->ref;
  6563. unset($adherenttmpselect);
  6564. }
  6565. $urloption = '';
  6566. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6567. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6568. elseif ($hidelabel > 1) {
  6569. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6570. if ($hidelabel == 2) {
  6571. $out .= img_picto($langs->trans("Search"), 'search');
  6572. }
  6573. }
  6574. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6575. if ($hidelabel == 3) {
  6576. $out .= img_picto($langs->trans("Search"), 'search');
  6577. }
  6578. } else {
  6579. $filterkey = '';
  6580. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6581. }
  6582. if (empty($nooutput)) print $out;
  6583. else return $out;
  6584. }
  6585. /**
  6586. * Return list of adherents.
  6587. * Called by selectMembers.
  6588. *
  6589. * @param int $selected Preselected adherent
  6590. * @param string $htmlname Name of select html
  6591. * @param string $filtertype Filter on adherent type
  6592. * @param int $limit Limit on number of returned lines
  6593. * @param string $filterkey Filter on member status
  6594. * @param int $status Member status
  6595. * @param int $outputmode 0=HTML select string, 1=Array
  6596. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6597. * @param int $forcecombo Force to use combo box
  6598. * @param string $morecss Add more css on select
  6599. * @return array Array of keys for json
  6600. */
  6601. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6602. {
  6603. global $langs, $conf;
  6604. $out = '';
  6605. $outarray = array();
  6606. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6607. $sql = "SELECT ";
  6608. $sql .= $selectFields;
  6609. $sql .= " FROM ".$this->db->prefix()."adherent as p";
  6610. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6611. // Add criteria on ref/label
  6612. if ($filterkey != '') {
  6613. $sql .= ' AND (';
  6614. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6615. // For natural search
  6616. $scrit = explode(' ', $filterkey);
  6617. $i = 0;
  6618. if (count($scrit) > 1) $sql .= "(";
  6619. foreach ($scrit as $crit) {
  6620. if ($i > 0) $sql .= " AND ";
  6621. $sql .= "(p.firstname LIKE '".$this->db->escape($prefix.$crit)."%'";
  6622. $sql .= " OR p.lastname LIKE '".$this->db->escape($prefix.$crit)."%')";
  6623. $i++;
  6624. }
  6625. if (count($scrit) > 1) $sql .= ")";
  6626. $sql .= ')';
  6627. }
  6628. if ($status != -1) {
  6629. $sql .= ' AND statut = '.((int) $status);
  6630. }
  6631. $sql .= $this->db->plimit($limit, 0);
  6632. // Build output string
  6633. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6634. $result = $this->db->query($sql);
  6635. if ($result) {
  6636. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6637. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6638. $num = $this->db->num_rows($result);
  6639. $events = null;
  6640. if (!$forcecombo) {
  6641. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6642. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6643. }
  6644. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6645. $textifempty = '';
  6646. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6647. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6648. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6649. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6650. else $textifempty .= $langs->trans("All");
  6651. } else {
  6652. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6653. }
  6654. if ($showempty) {
  6655. $out .= '<option value="-1" selected>'.$textifempty.'</option>';
  6656. }
  6657. $i = 0;
  6658. while ($num && $i < $num) {
  6659. $opt = '';
  6660. $optJson = array();
  6661. $objp = $this->db->fetch_object($result);
  6662. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6663. // Add new entry
  6664. // "key" value of json key array is used by jQuery automatically as selected value
  6665. // "label" value of json key array is used by jQuery automatically as text for combo box
  6666. $out .= $opt;
  6667. array_push($outarray, $optJson);
  6668. $i++;
  6669. }
  6670. $out .= '</select>';
  6671. $this->db->free($result);
  6672. if (empty($outputmode)) return $out;
  6673. return $outarray;
  6674. } else {
  6675. dol_print_error($this->db);
  6676. }
  6677. }
  6678. /**
  6679. * constructMemberListOption.
  6680. * This define value for &$opt and &$optJson.
  6681. *
  6682. * @param resource $objp Result set of fetch
  6683. * @param string $opt Option (var used for returned value in string option format)
  6684. * @param string $optJson Option (var used for returned value in json format)
  6685. * @param string $selected Preselected value
  6686. * @param string $filterkey Filter key to highlight
  6687. * @return void
  6688. */
  6689. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6690. {
  6691. $outkey = '';
  6692. $outlabel = '';
  6693. $outtype = '';
  6694. $outkey = $objp->rowid;
  6695. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6696. $outtype = $objp->fk_adherent_type;
  6697. $opt = '<option value="'.$objp->rowid.'"';
  6698. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6699. $opt .= '>';
  6700. if (!empty($filterkey) && $filterkey != '') {
  6701. $outlabel = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $outlabel, 1);
  6702. }
  6703. $opt .= $outlabel;
  6704. $opt .= "</option>\n";
  6705. $optJson = array('key'=>$outkey, 'value'=>$outlabel, 'type'=>$outtype);
  6706. }
  6707. /**
  6708. * Generic method to select a component from a combo list.
  6709. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6710. * This is the generic method that will replace all specific existing methods.
  6711. *
  6712. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6713. * @param string $htmlname Name of HTML select component
  6714. * @param int $preselectedvalue Preselected value (ID of element)
  6715. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6716. * @param string $searchkey Search criteria
  6717. * @param string $placeholder Place holder
  6718. * @param string $morecss More CSS
  6719. * @param string $moreparams More params provided to ajax call
  6720. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6721. * @param int $disabled 1=Html component is disabled
  6722. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6723. * @return string Return HTML string
  6724. * @see selectForFormsList() select_thirdparty_list()
  6725. */
  6726. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6727. {
  6728. global $conf, $user;
  6729. $objecttmp = null;
  6730. // Example of value for $objectdec:
  6731. // Bom:bom/class/bom.class.php:0:t.status=1
  6732. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6733. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6734. $InfoFieldList = explode(":", $objectdesc, 4);
  6735. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  6736. $reg = array();
  6737. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6738. $InfoFieldList[4] = $reg[1]; // take the sort field
  6739. }
  6740. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6741. $classname = $InfoFieldList[0];
  6742. $classpath = $InfoFieldList[1];
  6743. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6744. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6745. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6746. if (!empty($classpath)) {
  6747. dol_include_once($classpath);
  6748. if ($classname && class_exists($classname)) {
  6749. $objecttmp = new $classname($this->db);
  6750. // Make some replacement
  6751. $sharedentities = getEntity(strtolower($classname));
  6752. $objecttmp->filter = str_replace(
  6753. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6754. array($conf->entity, $sharedentities, $user->id),
  6755. $filter
  6756. );
  6757. }
  6758. }
  6759. if (!is_object($objecttmp)) {
  6760. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  6761. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6762. }
  6763. //var_dump($objecttmp->filter);
  6764. $prefixforautocompletemode = $objecttmp->element;
  6765. if ($prefixforautocompletemode == 'societe') {
  6766. $prefixforautocompletemode = 'company';
  6767. }
  6768. if ($prefixforautocompletemode == 'product') {
  6769. $prefixforautocompletemode = 'produit';
  6770. }
  6771. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6772. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  6773. $out = '';
  6774. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6775. // No immediate load of all database
  6776. $placeholder = '';
  6777. if ($preselectedvalue && empty($selected_input_value)) {
  6778. $objecttmp->fetch($preselectedvalue);
  6779. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6780. //unset($objecttmp);
  6781. }
  6782. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6783. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6784. // No immediate load of all database
  6785. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($objecttmp->filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6786. // Activate the auto complete using ajax call.
  6787. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6788. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6789. $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).'"' : '') .' />';
  6790. } else {
  6791. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  6792. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield);
  6793. }
  6794. return $out;
  6795. }
  6796. /**
  6797. * Function to forge a SQL criteria
  6798. *
  6799. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  6800. * @return string Forged criteria. Example: "t.field like 'abc%'"
  6801. */
  6802. protected static function forgeCriteriaCallback($matches)
  6803. {
  6804. global $db;
  6805. //dol_syslog("Convert matches ".$matches[1]);
  6806. if (empty($matches[1])) {
  6807. return '';
  6808. }
  6809. $tmp = explode(':', $matches[1]);
  6810. if (count($tmp) < 3) {
  6811. return '';
  6812. }
  6813. $tmpescaped = $tmp[2];
  6814. $regbis = array();
  6815. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  6816. $tmpescaped = "'".$db->escape($regbis[1])."'";
  6817. } else {
  6818. $tmpescaped = $db->escape($tmpescaped);
  6819. }
  6820. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  6821. }
  6822. /**
  6823. * Output html form to select an object.
  6824. * Note, this function is called by selectForForms or by ajax selectobject.php
  6825. *
  6826. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6827. * @param string $htmlname Name of HTML select component
  6828. * @param int $preselectedvalue Preselected value (ID of element)
  6829. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6830. * @param string $searchkey Search value
  6831. * @param string $placeholder Place holder
  6832. * @param string $morecss More CSS
  6833. * @param string $moreparams More params provided to ajax call
  6834. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6835. * @param int $outputmode 0=HTML select string, 1=Array
  6836. * @param int $disabled 1=Html component is disabled
  6837. * @param string $sortfield Sort field
  6838. * @return string|array Return HTML string
  6839. * @see selectForForms()
  6840. */
  6841. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '')
  6842. {
  6843. global $conf, $langs, $user, $hookmanager;
  6844. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  6845. $prefixforautocompletemode = $objecttmp->element;
  6846. if ($prefixforautocompletemode == 'societe') {
  6847. $prefixforautocompletemode = 'company';
  6848. }
  6849. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6850. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  6851. $tmpfieldstoshow = '';
  6852. foreach ($objecttmp->fields as $key => $val) {
  6853. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  6854. continue;
  6855. }
  6856. if (!empty($val['showoncombobox'])) {
  6857. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  6858. }
  6859. }
  6860. if ($tmpfieldstoshow) {
  6861. $fieldstoshow = $tmpfieldstoshow;
  6862. }
  6863. } else {
  6864. // For backward compatibility
  6865. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  6866. }
  6867. if (empty($fieldstoshow)) {
  6868. if (isset($objecttmp->fields['ref'])) {
  6869. $fieldstoshow = 't.ref';
  6870. } else {
  6871. $langs->load("errors");
  6872. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  6873. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  6874. }
  6875. }
  6876. $out = '';
  6877. $outarray = array();
  6878. $tmparray = array();
  6879. $num = 0;
  6880. // Search data
  6881. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".$this->db->prefix().$objecttmp->table_element." as t";
  6882. if (isset($objecttmp->ismultientitymanaged)) {
  6883. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6884. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  6885. $sql .= " INNER JOIN ".$this->db->prefix().$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  6886. }
  6887. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6888. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6889. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  6890. }
  6891. }
  6892. }
  6893. // Add where from hooks
  6894. $parameters = array();
  6895. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  6896. if (!empty($hookmanager->resPrint)) {
  6897. $sql .= $hookmanager->resPrint;
  6898. } else {
  6899. $sql .= " WHERE 1=1";
  6900. if (isset($objecttmp->ismultientitymanaged)) {
  6901. if ($objecttmp->ismultientitymanaged == 1) {
  6902. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  6903. }
  6904. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6905. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  6906. }
  6907. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  6908. if ($objecttmp->element == 'societe') {
  6909. $sql .= " AND t.rowid = ".((int) $user->socid);
  6910. } else {
  6911. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  6912. }
  6913. }
  6914. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6915. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6916. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  6917. }
  6918. }
  6919. }
  6920. if ($searchkey != '') {
  6921. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  6922. }
  6923. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  6924. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  6925. {
  6926. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  6927. }*/
  6928. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  6929. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  6930. }
  6931. }
  6932. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  6933. //$sql.=$this->db->plimit($limit, 0);
  6934. //print $sql;
  6935. // Build output string
  6936. $resql = $this->db->query($sql);
  6937. if ($resql) {
  6938. // Construct $out and $outarray
  6939. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  6940. // 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
  6941. $textifempty = '&nbsp;';
  6942. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6943. if (!empty($conf->global->$confkeyforautocompletemode)) {
  6944. if ($showempty && !is_numeric($showempty)) {
  6945. $textifempty = $langs->trans($showempty);
  6946. } else {
  6947. $textifempty .= $langs->trans("All");
  6948. }
  6949. }
  6950. if ($showempty) {
  6951. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  6952. }
  6953. $num = $this->db->num_rows($resql);
  6954. $i = 0;
  6955. if ($num) {
  6956. while ($i < $num) {
  6957. $obj = $this->db->fetch_object($resql);
  6958. $label = '';
  6959. $tmparray = explode(',', $fieldstoshow);
  6960. $oldvalueforshowoncombobox = 0;
  6961. foreach ($tmparray as $key => $val) {
  6962. $val = preg_replace('/t\./', '', $val);
  6963. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  6964. $label .= $obj->$val;
  6965. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  6966. }
  6967. if (empty($outputmode)) {
  6968. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  6969. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  6970. } else {
  6971. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  6972. }
  6973. } else {
  6974. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  6975. }
  6976. $i++;
  6977. if (($i % 10) == 0) {
  6978. $out .= "\n";
  6979. }
  6980. }
  6981. }
  6982. $out .= '</select>'."\n";
  6983. if (!$forcecombo) {
  6984. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6985. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  6986. }
  6987. } else {
  6988. dol_print_error($this->db);
  6989. }
  6990. $this->result = array('nbofelement'=>$num);
  6991. if ($outputmode) {
  6992. return $outarray;
  6993. }
  6994. return $out;
  6995. }
  6996. /**
  6997. * Return a HTML select string, built from an array of key+value.
  6998. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  6999. *
  7000. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7001. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7002. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7003. * @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.
  7004. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7005. * @param int $value_as_key 1 to use value as key
  7006. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7007. * @param int $translate 1=Translate and encode value
  7008. * @param int $maxlen Length maximum for labels
  7009. * @param int $disabled Html select box is disabled
  7010. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7011. * @param string $morecss Add more class to css styles
  7012. * @param int $addjscombo Add js combo
  7013. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7014. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7015. * @param int $nohtmlescape No html escaping.
  7016. * @return string HTML select string.
  7017. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7018. */
  7019. public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  7020. {
  7021. global $conf, $langs;
  7022. // Do we want a multiselect ?
  7023. //$jsbeautify = 0;
  7024. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7025. $jsbeautify = 1;
  7026. if ($value_as_key) {
  7027. $array = array_combine($array, $array);
  7028. }
  7029. $out = '';
  7030. if ($addjscombo < 0) {
  7031. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7032. $addjscombo = 1;
  7033. } else {
  7034. $addjscombo = 0;
  7035. }
  7036. }
  7037. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  7038. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  7039. $out .= '>';
  7040. if ($show_empty) {
  7041. $textforempty = ' ';
  7042. if (!empty($conf->use_javascript_ajax)) {
  7043. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7044. }
  7045. if (!is_numeric($show_empty)) {
  7046. $textforempty = $show_empty;
  7047. }
  7048. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  7049. }
  7050. if (is_array($array)) {
  7051. // Translate
  7052. if ($translate) {
  7053. foreach ($array as $key => $value) {
  7054. if (!is_array($value)) {
  7055. $array[$key] = $langs->trans($value);
  7056. } else {
  7057. $array[$key]['label'] = $langs->trans($value['label']);
  7058. }
  7059. }
  7060. }
  7061. // Sort
  7062. if ($sort == 'ASC') {
  7063. asort($array);
  7064. } elseif ($sort == 'DESC') {
  7065. arsort($array);
  7066. }
  7067. foreach ($array as $key => $tmpvalue) {
  7068. if (is_array($tmpvalue)) {
  7069. $value = $tmpvalue['label'];
  7070. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7071. $style = empty($tmpvalue['css']) ? '' : ' class="'.$tmpvalue['css'].'"';
  7072. } else {
  7073. $value = $tmpvalue;
  7074. $disabled = '';
  7075. $style = '';
  7076. }
  7077. if (!empty($disablebademail)) {
  7078. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7079. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7080. $disabled = ' disabled';
  7081. $style = ' class="warning"';
  7082. }
  7083. }
  7084. if ($key_in_label) {
  7085. if (empty($nohtmlescape)) {
  7086. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  7087. } else {
  7088. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  7089. }
  7090. } else {
  7091. if (empty($nohtmlescape)) {
  7092. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  7093. } else {
  7094. $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  7095. }
  7096. if ($value == '' || $value == '-') {
  7097. $selectOptionValue = '&nbsp;';
  7098. }
  7099. }
  7100. $out .= '<option value="'.$key.'"';
  7101. $out .= $style.$disabled;
  7102. if (is_array($id)) {
  7103. if (in_array($key, $id) && !$disabled) {
  7104. $out .= ' selected'; // To preselect a value
  7105. }
  7106. } else {
  7107. $id = (string) $id; // if $id = 0, then $id = '0'
  7108. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7109. $out .= ' selected'; // To preselect a value
  7110. }
  7111. }
  7112. if ($nohtmlescape) {
  7113. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  7114. }
  7115. if (is_array($tmpvalue)) {
  7116. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7117. if (preg_match('/^data-/', $keyforvalue)) {
  7118. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  7119. }
  7120. }
  7121. }
  7122. $out .= '>';
  7123. //var_dump($selectOptionValue);
  7124. $out .= $selectOptionValue;
  7125. $out .= "</option>\n";
  7126. }
  7127. }
  7128. $out .= "</select>";
  7129. // Add code for jquery to use multiselect
  7130. if ($addjscombo && $jsbeautify) {
  7131. // Enhance with select2
  7132. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7133. $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', $show_empty < 0 ? (string) $show_empty : '-1');
  7134. }
  7135. return $out;
  7136. }
  7137. /**
  7138. * 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.
  7139. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7140. *
  7141. * @param string $htmlname Name of html select area
  7142. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7143. * @param string $id Preselected key
  7144. * @param string $moreparam Add more parameters onto the select tag
  7145. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7146. * @param int $disabled Html select box is disabled
  7147. * @param int $minimumInputLength Minimum Input Length
  7148. * @param string $morecss Add more class to css styles
  7149. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7150. * @param string $placeholder String to use as placeholder
  7151. * @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)
  7152. * @return string HTML select string
  7153. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7154. */
  7155. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7156. {
  7157. global $conf, $langs;
  7158. global $delayedhtmlcontent; // Will be used later outside of this function
  7159. // TODO Use an internal dolibarr component instead of select2
  7160. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7161. return '';
  7162. }
  7163. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  7164. $outdelayed = '';
  7165. if (!empty($conf->use_javascript_ajax)) {
  7166. $tmpplugin = 'select2';
  7167. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7168. <script>
  7169. $(document).ready(function () {
  7170. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  7171. $(".'.$htmlname.'").select2({
  7172. ajax: {
  7173. dir: "ltr",
  7174. url: "'.$url.'",
  7175. dataType: \'json\',
  7176. delay: 250,
  7177. data: function (params) {
  7178. return {
  7179. q: params.term, // search term
  7180. page: params.page
  7181. };
  7182. },
  7183. processResults: function (data) {
  7184. // parse the results into the format expected by Select2.
  7185. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7186. //console.log(data);
  7187. saveRemoteData = data;
  7188. /* format json result for select2 */
  7189. result = []
  7190. $.each( data, function( key, value ) {
  7191. result.push({id: key, text: value.text});
  7192. });
  7193. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7194. //console.log(result);
  7195. return {results: result, more: false}
  7196. },
  7197. cache: true
  7198. },
  7199. language: select2arrayoflanguage,
  7200. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7201. placeholder: "'.dol_escape_js($placeholder).'",
  7202. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7203. minimumInputLength: '.$minimumInputLength.',
  7204. formatResult: function(result, container, query, escapeMarkup) {
  7205. return escapeMarkup(result.text);
  7206. },
  7207. });
  7208. '.($callurlonselect ? '
  7209. /* Code to execute a GET when we select a value */
  7210. $(".'.$htmlname.'").change(function() {
  7211. var selected = $(".'.$htmlname.'").val();
  7212. console.log("We select in selectArrayAjax the entry "+selected)
  7213. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7214. $.each( saveRemoteData, function( key, value ) {
  7215. if (key == selected)
  7216. {
  7217. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7218. location.assign(value.url);
  7219. }
  7220. });
  7221. });' : '').'
  7222. });
  7223. </script>';
  7224. }
  7225. if ($acceptdelayedhtml) {
  7226. $delayedhtmlcontent .= $outdelayed;
  7227. } else {
  7228. $out .= $outdelayed;
  7229. }
  7230. return $out;
  7231. }
  7232. /**
  7233. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7234. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7235. *
  7236. * @param string $htmlname Name of html select area
  7237. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7238. * @param string $id Preselected key
  7239. * @param string $moreparam Add more parameters onto the select tag
  7240. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7241. * @param int $disabled Html select box is disabled
  7242. * @param int $minimumInputLength Minimum Input Length
  7243. * @param string $morecss Add more class to css styles
  7244. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7245. * @param string $placeholder String to use as placeholder
  7246. * @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)
  7247. * @return string HTML select string
  7248. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7249. */
  7250. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7251. {
  7252. global $conf, $langs;
  7253. global $delayedhtmlcontent; // Will be used later outside of this function
  7254. // TODO Use an internal dolibarr component instead of select2
  7255. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7256. return '';
  7257. }
  7258. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7259. $formattedarrayresult = array();
  7260. foreach ($array as $key => $value) {
  7261. $o = new stdClass();
  7262. $o->id = $key;
  7263. $o->text = $value['text'];
  7264. $o->url = $value['url'];
  7265. $formattedarrayresult[] = $o;
  7266. }
  7267. $outdelayed = '';
  7268. if (!empty($conf->use_javascript_ajax)) {
  7269. $tmpplugin = 'select2';
  7270. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7271. <script>
  7272. $(document).ready(function () {
  7273. var data = '.json_encode($formattedarrayresult).';
  7274. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7275. $(".'.$htmlname.'").select2({
  7276. data: data,
  7277. language: select2arrayoflanguage,
  7278. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7279. placeholder: "'.dol_escape_js($placeholder).'",
  7280. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7281. minimumInputLength: '.$minimumInputLength.',
  7282. formatResult: function(result, container, query, escapeMarkup) {
  7283. return escapeMarkup(result.text);
  7284. },
  7285. matcher: function (params, data) {
  7286. if(! data.id) return null;';
  7287. if ($callurlonselect) {
  7288. $outdelayed .= '
  7289. var urlBase = data.url;
  7290. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7291. /* console.log("params.term="+params.term); */
  7292. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7293. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7294. }
  7295. if (!$disableFiltering) {
  7296. $outdelayed .= '
  7297. if(data.text.match(new RegExp(params.term))) {
  7298. return data;
  7299. }
  7300. return null;';
  7301. } else {
  7302. $outdelayed .= '
  7303. return data;';
  7304. }
  7305. $outdelayed .= '
  7306. }
  7307. });
  7308. '.($callurlonselect ? '
  7309. /* Code to execute a GET when we select a value */
  7310. $(".'.$htmlname.'").change(function() {
  7311. var selected = $(".'.$htmlname.'").val();
  7312. console.log("We select "+selected)
  7313. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7314. $.each( saveRemoteData, function( key, value ) {
  7315. if (key == selected)
  7316. {
  7317. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7318. location.assign(value.url);
  7319. }
  7320. });
  7321. });' : '').'
  7322. });
  7323. </script>';
  7324. }
  7325. if ($acceptdelayedhtml) {
  7326. $delayedhtmlcontent .= $outdelayed;
  7327. } else {
  7328. $out .= $outdelayed;
  7329. }
  7330. return $out;
  7331. }
  7332. /**
  7333. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7334. *
  7335. * @param string $htmlname Name of select
  7336. * @param array $array Array with key+value
  7337. * @param array $selected Array with key+value preselected
  7338. * @param int $key_in_label 1 to show key like in "[key] value"
  7339. * @param int $value_as_key 1 to use value as key
  7340. * @param string $morecss Add more css style
  7341. * @param int $translate Translate and encode value
  7342. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7343. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7344. * @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.
  7345. * @param string $placeholder String to use as placeholder
  7346. * @param int $addjscombo Add js combo
  7347. * @return string HTML multiselect string
  7348. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7349. */
  7350. 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)
  7351. {
  7352. global $conf, $langs;
  7353. $out = '';
  7354. if ($addjscombo < 0) {
  7355. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7356. $addjscombo = 1;
  7357. } else {
  7358. $addjscombo = 0;
  7359. }
  7360. }
  7361. // Try also magic suggest
  7362. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  7363. if (is_array($array) && !empty($array)) {
  7364. if ($value_as_key) {
  7365. $array = array_combine($array, $array);
  7366. }
  7367. if (!empty($array)) {
  7368. foreach ($array as $key => $value) {
  7369. $newval = ($translate ? $langs->trans($value) : $value);
  7370. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  7371. $out .= '<option value="'.$key.'"';
  7372. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != '')) {
  7373. $out .= ' selected';
  7374. }
  7375. $out .= ' data-html="'.dol_escape_htmltag($newval).'"';
  7376. $out .= '>';
  7377. $out .= dol_htmlentitiesbr($newval);
  7378. $out .= '</option>'."\n";
  7379. }
  7380. }
  7381. }
  7382. $out .= '</select>'."\n";
  7383. // Add code for jquery to use multiselect
  7384. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7385. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7386. $out .= "\n".'<script>'."\n";
  7387. if ($addjscombo == 1) {
  7388. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7389. $out .= 'function formatResult(record, container) {'."\n";
  7390. $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";
  7391. $out .= ' return record.text;';
  7392. $out .= '};'."\n";
  7393. $out .= 'function formatSelection(record) {'."\n";
  7394. if ($elemtype == 'category') {
  7395. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7396. } else {
  7397. $out .= 'return record.text;';
  7398. }
  7399. $out .= '};'."\n";
  7400. $out .= '$(document).ready(function () {
  7401. $(\'#'.$htmlname.'\').'.$tmpplugin.'({';
  7402. if ($placeholder) {
  7403. $out .= '
  7404. placeholder: {
  7405. id: \'-1\',
  7406. text: \''.dol_escape_js($placeholder).'\'
  7407. },';
  7408. }
  7409. $out .= ' dir: \'ltr\',
  7410. // Specify format function for dropdown item
  7411. formatResult: formatResult,
  7412. templateResult: formatResult, /* For 4.0 */
  7413. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7414. // Specify format function for selected item
  7415. formatSelection: formatSelection,
  7416. templateSelection: formatSelection /* For 4.0 */
  7417. });
  7418. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7419. the size only if component is not hidden by default on load */
  7420. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7421. });'."\n";
  7422. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7423. // Add other js lib
  7424. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7425. // ...
  7426. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7427. $out .= '$(document).ready(function () {
  7428. $(\'#'.$htmlname.'\').multiSelect({
  7429. containerHTML: \'<div class="multi-select-container">\',
  7430. menuHTML: \'<div class="multi-select-menu">\',
  7431. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7432. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7433. activeClass: \'multi-select-container--open\',
  7434. noneText: \''.$placeholder.'\'
  7435. });
  7436. })';
  7437. }
  7438. $out .= '</script>';
  7439. }
  7440. return $out;
  7441. }
  7442. /**
  7443. * 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.
  7444. *
  7445. * @param string $htmlname Name of HTML field
  7446. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7447. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7448. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7449. * @return string HTML multiselect string
  7450. * @see selectarray()
  7451. */
  7452. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7453. {
  7454. global $conf, $langs, $user, $extrafields;
  7455. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7456. return '';
  7457. }
  7458. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7459. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7460. $tmparray = explode(',', $user->conf->$tmpvar);
  7461. foreach ($array as $key => $val) {
  7462. //var_dump($key);
  7463. //var_dump($tmparray);
  7464. if (in_array($key, $tmparray)) {
  7465. $array[$key]['checked'] = 1;
  7466. } else {
  7467. $array[$key]['checked'] = 0;
  7468. }
  7469. }
  7470. } else { // There is no list of fields already customized for user
  7471. foreach ($array as $key => $val) {
  7472. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7473. $array[$key]['checked'] = 0;
  7474. }
  7475. }
  7476. }
  7477. $listoffieldsforselection = '';
  7478. $listcheckedstring = '';
  7479. foreach ($array as $key => $val) {
  7480. // var_dump($val);
  7481. // var_dump(array_key_exists('enabled', $val));
  7482. // var_dump(!$val['enabled']);
  7483. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7484. unset($array[$key]); // We don't want this field
  7485. continue;
  7486. }
  7487. if (!empty($val['type']) && $val['type'] == 'separate') {
  7488. // Field remains in array but we don't add it into $listoffieldsforselection
  7489. //$listoffieldsforselection .= '<li>-----</li>';
  7490. continue;
  7491. }
  7492. if ($val['label']) {
  7493. if (!empty($val['langfile']) && is_object($langs)) {
  7494. $langs->load($val['langfile']);
  7495. }
  7496. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7497. $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>';
  7498. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7499. }
  7500. }
  7501. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7502. <dl class="dropdown">
  7503. <dt>
  7504. <a href="#'.$htmlname.'">
  7505. '.img_picto('', 'list').'
  7506. </a>
  7507. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7508. </dt>
  7509. <dd class="dropdowndd">
  7510. <div class="multiselectcheckbox'.$htmlname.'">
  7511. <ul class="ul'.$htmlname.' '.$htmlname.$pos.'">
  7512. '.$listoffieldsforselection.'
  7513. </ul>
  7514. </div>
  7515. </dd>
  7516. </dl>
  7517. <script type="text/javascript">
  7518. jQuery(document).ready(function () {
  7519. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7520. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7521. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7522. var title = $(this).val() + ",";
  7523. if ($(this).is(\':checked\')) {
  7524. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7525. }
  7526. else {
  7527. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7528. }
  7529. // Now, we submit page
  7530. //$(this).parents(\'form:first\').submit();
  7531. });
  7532. });
  7533. </script>
  7534. ';
  7535. return $out;
  7536. }
  7537. /**
  7538. * Render list of categories linked to object with id $id and type $type
  7539. *
  7540. * @param int $id Id of object
  7541. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7542. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7543. * @param int $nolink 1=Do not add html links
  7544. * @return string String with categories
  7545. */
  7546. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7547. {
  7548. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7549. $cat = new Categorie($this->db);
  7550. $categories = $cat->containing($id, $type);
  7551. if ($rendermode == 1) {
  7552. $toprint = array();
  7553. foreach ($categories as $c) {
  7554. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7555. foreach ($ways as $way) {
  7556. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7557. }
  7558. }
  7559. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7560. }
  7561. if ($rendermode == 0) {
  7562. $arrayselected = array();
  7563. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7564. foreach ($categories as $c) {
  7565. $arrayselected[] = $c->id;
  7566. }
  7567. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7568. }
  7569. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7570. }
  7571. /**
  7572. * Show linked object block.
  7573. *
  7574. * @param CommonObject $object Object we want to show links to
  7575. * @param string $morehtmlright More html to show on right of title
  7576. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7577. * @return int <0 if KO, >=0 if OK
  7578. */
  7579. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  7580. {
  7581. global $conf, $langs, $hookmanager;
  7582. global $bc, $action;
  7583. $object->fetchObjectLinked();
  7584. // Bypass the default method
  7585. $hookmanager->initHooks(array('commonobject'));
  7586. $parameters = array(
  7587. 'morehtmlright' => $morehtmlright,
  7588. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7589. );
  7590. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7591. if (empty($reshook)) {
  7592. $nbofdifferenttypes = count($object->linkedObjects);
  7593. print '<!-- showLinkedObjectBlock -->';
  7594. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7595. print '<div class="div-table-responsive-no-min">';
  7596. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7597. print '<tr class="liste_titre">';
  7598. print '<td>'.$langs->trans("Type").'</td>';
  7599. print '<td>'.$langs->trans("Ref").'</td>';
  7600. print '<td class="center"></td>';
  7601. print '<td class="center">'.$langs->trans("Date").'</td>';
  7602. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7603. print '<td class="right">'.$langs->trans("Status").'</td>';
  7604. print '<td></td>';
  7605. print '</tr>';
  7606. $nboftypesoutput = 0;
  7607. foreach ($object->linkedObjects as $objecttype => $objects) {
  7608. $tplpath = $element = $subelement = $objecttype;
  7609. // to display inport button on tpl
  7610. $showImportButton = false;
  7611. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7612. $showImportButton = true;
  7613. }
  7614. $regs = array();
  7615. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7616. $element = $regs[1];
  7617. $subelement = $regs[2];
  7618. $tplpath = $element.'/'.$subelement;
  7619. }
  7620. $tplname = 'linkedobjectblock';
  7621. // To work with non standard path
  7622. if ($objecttype == 'facture') {
  7623. $tplpath = 'compta/'.$element;
  7624. if (empty($conf->facture->enabled)) {
  7625. continue; // Do not show if module disabled
  7626. }
  7627. } elseif ($objecttype == 'facturerec') {
  7628. $tplpath = 'compta/facture';
  7629. $tplname = 'linkedobjectblockForRec';
  7630. if (empty($conf->facture->enabled)) {
  7631. continue; // Do not show if module disabled
  7632. }
  7633. } elseif ($objecttype == 'propal') {
  7634. $tplpath = 'comm/'.$element;
  7635. if (empty($conf->propal->enabled)) {
  7636. continue; // Do not show if module disabled
  7637. }
  7638. } elseif ($objecttype == 'supplier_proposal') {
  7639. if (empty($conf->supplier_proposal->enabled)) {
  7640. continue; // Do not show if module disabled
  7641. }
  7642. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  7643. $tplpath = 'expedition';
  7644. if (empty($conf->expedition->enabled)) {
  7645. continue; // Do not show if module disabled
  7646. }
  7647. } elseif ($objecttype == 'reception') {
  7648. $tplpath = 'reception';
  7649. if (empty($conf->reception->enabled)) {
  7650. continue; // Do not show if module disabled
  7651. }
  7652. } elseif ($objecttype == 'delivery') {
  7653. $tplpath = 'delivery';
  7654. if (empty($conf->expedition->enabled)) {
  7655. continue; // Do not show if module disabled
  7656. }
  7657. } elseif ($objecttype == 'mo') {
  7658. $tplpath = 'mrp/mo';
  7659. if (empty($conf->mrp->enabled)) {
  7660. continue; // Do not show if module disabled
  7661. }
  7662. } elseif ($objecttype == 'ficheinter') {
  7663. $tplpath = 'fichinter';
  7664. if (empty($conf->ficheinter->enabled)) {
  7665. continue; // Do not show if module disabled
  7666. }
  7667. } elseif ($objecttype == 'invoice_supplier') {
  7668. $tplpath = 'fourn/facture';
  7669. } elseif ($objecttype == 'order_supplier') {
  7670. $tplpath = 'fourn/commande';
  7671. } elseif ($objecttype == 'expensereport') {
  7672. $tplpath = 'expensereport';
  7673. } elseif ($objecttype == 'subscription') {
  7674. $tplpath = 'adherents';
  7675. } elseif ($objecttype == 'conferenceorbooth') {
  7676. $tplpath = 'eventorganization';
  7677. } elseif ($objecttype == 'conferenceorboothattendee') {
  7678. $tplpath = 'eventorganization';
  7679. } elseif ($objecttype == 'mo') {
  7680. $tplpath = 'mrp';
  7681. if (empty($conf->mrp->enabled)) {
  7682. continue; // Do not show if module disabled
  7683. }
  7684. }
  7685. global $linkedObjectBlock;
  7686. $linkedObjectBlock = $objects;
  7687. // Output template part (modules that overwrite templates must declare this into descriptor)
  7688. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7689. foreach ($dirtpls as $reldir) {
  7690. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7691. global $noMoreLinkedObjectBlockAfter;
  7692. $noMoreLinkedObjectBlockAfter = 1;
  7693. }
  7694. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7695. if ($res) {
  7696. $nboftypesoutput++;
  7697. break;
  7698. }
  7699. }
  7700. }
  7701. if (!$nboftypesoutput) {
  7702. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7703. }
  7704. print '</table>';
  7705. if (!empty($compatibleImportElementsList)) {
  7706. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  7707. }
  7708. print '</div>';
  7709. return $nbofdifferenttypes;
  7710. }
  7711. }
  7712. /**
  7713. * Show block with links to link to other objects.
  7714. *
  7715. * @param CommonObject $object Object we want to show links to
  7716. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7717. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7718. * @return string <0 if KO, >0 if OK
  7719. */
  7720. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7721. {
  7722. global $conf, $langs, $hookmanager;
  7723. global $action;
  7724. $linktoelem = '';
  7725. $linktoelemlist = '';
  7726. $listofidcompanytoscan = '';
  7727. if (!is_object($object->thirdparty)) {
  7728. $object->fetch_thirdparty();
  7729. }
  7730. $possiblelinks = array();
  7731. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7732. $listofidcompanytoscan = $object->thirdparty->id;
  7733. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7734. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7735. }
  7736. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7737. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7738. $tmpproject = new Project($this->db);
  7739. $tmpproject->fetch($object->fk_project);
  7740. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7741. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7742. }
  7743. unset($tmpproject);
  7744. }
  7745. $possiblelinks = array(
  7746. 'propal'=>array(
  7747. 'enabled'=>$conf->propal->enabled,
  7748. 'perms'=>1,
  7749. 'label'=>'LinkToProposal',
  7750. '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').')'),
  7751. 'order'=>array(
  7752. 'enabled'=>$conf->commande->enabled,
  7753. 'perms'=>1,
  7754. 'label'=>'LinkToOrder',
  7755. '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').')'),
  7756. 'invoice'=>array(
  7757. 'enabled'=>$conf->facture->enabled,
  7758. 'perms'=>1,
  7759. 'label'=>'LinkToInvoice',
  7760. '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').')'),
  7761. 'invoice_template'=>array(
  7762. 'enabled'=>$conf->facture->enabled,
  7763. 'perms'=>1,
  7764. 'label'=>'LinkToTemplateInvoice',
  7765. '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').')'),
  7766. 'contrat'=>array(
  7767. 'enabled'=>$conf->contrat->enabled,
  7768. 'perms'=>1,
  7769. 'label'=>'LinkToContract',
  7770. '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
  7771. 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'
  7772. ),
  7773. 'fichinter'=>array(
  7774. 'enabled'=>(!empty($conf->ficheinter->enabled) ? $conf->ficheinter->enabled : 0),
  7775. 'perms'=>1,
  7776. 'label'=>'LinkToIntervention',
  7777. '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').')'),
  7778. 'supplier_proposal'=>array(
  7779. 'enabled'=>(!empty($conf->supplier_proposal->enabled) ? $conf->supplier_proposal->enabled : 0),
  7780. 'perms'=>1,
  7781. 'label'=>'LinkToSupplierProposal',
  7782. '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').')'),
  7783. 'order_supplier'=>array(
  7784. 'enabled'=>(!empty($conf->supplier_order->enabled) ? $conf->supplier_order->enabled : 0),
  7785. 'perms'=>1,
  7786. 'label'=>'LinkToSupplierOrder',
  7787. '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').')'),
  7788. 'invoice_supplier'=>array(
  7789. 'enabled'=>(!empty($conf->supplier_invoice->enabled) ? $conf->supplier_invoice->enabled : 0),
  7790. 'perms'=>1, 'label'=>'LinkToSupplierInvoice',
  7791. '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').')'),
  7792. 'ticket'=>array(
  7793. 'enabled'=>(!empty($conf->ticket->enabled) ? $conf->ticket->enabled : 0),
  7794. 'perms'=>1,
  7795. 'label'=>'LinkToTicket',
  7796. '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').')'),
  7797. 'mo'=>array(
  7798. 'enabled'=>(!empty($conf->mrp->enabled) ? $conf->mrp->enabled : 0),
  7799. 'perms'=>1,
  7800. 'label'=>'LinkToMo',
  7801. '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').')')
  7802. );
  7803. }
  7804. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7805. // Can complete the possiblelink array
  7806. $hookmanager->initHooks(array('commonobject'));
  7807. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  7808. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7809. }
  7810. if (empty($reshook)) {
  7811. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7812. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  7813. }
  7814. } elseif ($reshook > 0) {
  7815. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7816. $possiblelinks = $hookmanager->resArray;
  7817. }
  7818. }
  7819. foreach ($possiblelinks as $key => $possiblelink) {
  7820. $num = 0;
  7821. if (empty($possiblelink['enabled'])) {
  7822. continue;
  7823. }
  7824. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  7825. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  7826. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7827. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  7828. print '<input type="hidden" name="id" value="' . $object->id . '">';
  7829. print '<input type="hidden" name="action" value="addlinkbyref">';
  7830. print '<input type="hidden" name="token" value="'.newToken().'">';
  7831. print '<input type="hidden" name="addlink" value="' . $key . '">';
  7832. print '<table class="noborder">';
  7833. print '<tr>';
  7834. print '<td>' . $langs->trans("Ref") . '</td>';
  7835. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;<input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  7836. print '</tr>';
  7837. print '</table>';
  7838. print '</form>';
  7839. }
  7840. $sql = $possiblelink['sql'];
  7841. $resqllist = $this->db->query($sql);
  7842. if ($resqllist) {
  7843. $num = $this->db->num_rows($resqllist);
  7844. $i = 0;
  7845. print '<br>';
  7846. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  7847. print '<input type="hidden" name="action" value="addlink">';
  7848. print '<input type="hidden" name="token" value="'.newToken().'">';
  7849. print '<input type="hidden" name="id" value="'.$object->id.'">';
  7850. print '<input type="hidden" name="addlink" value="'.$key.'">';
  7851. print '<table class="noborder">';
  7852. print '<tr class="liste_titre">';
  7853. print '<td class="nowrap"></td>';
  7854. print '<td class="center">'.$langs->trans("Ref").'</td>';
  7855. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  7856. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7857. print '<td class="left">'.$langs->trans("Company").'</td>';
  7858. print '</tr>';
  7859. while ($i < $num) {
  7860. $objp = $this->db->fetch_object($resqllist);
  7861. print '<tr class="oddeven">';
  7862. print '<td class="left">';
  7863. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  7864. print '</td>';
  7865. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  7866. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  7867. print '<td class="right">';
  7868. if ($possiblelink['label'] == 'LinkToContract') {
  7869. $form = new Form($this->db);
  7870. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  7871. }
  7872. print '<span class="amount">'.price($objp->total_ht).'</span>';
  7873. print '</td>';
  7874. print '<td>'.$objp->name.'</td>';
  7875. print '</tr>';
  7876. $i++;
  7877. }
  7878. print '</table>';
  7879. print '<div class="center">';
  7880. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  7881. if (empty($conf->use_javascript_ajax)) {
  7882. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7883. } else {
  7884. print '<input type="submit"; onclick="javascript:jQuery(\'#'.$key.'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7885. }
  7886. print '</form>';
  7887. $this->db->free($resqllist);
  7888. } else {
  7889. dol_print_error($this->db);
  7890. }
  7891. print '</div>';
  7892. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  7893. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7894. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  7895. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  7896. } else {
  7897. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  7898. }
  7899. }
  7900. }
  7901. if ($linktoelemlist) {
  7902. $linktoelem = '
  7903. <dl class="dropdown" id="linktoobjectname">
  7904. ';
  7905. if (!empty($conf->use_javascript_ajax)) {
  7906. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  7907. }
  7908. $linktoelem .= '<dd>
  7909. <div class="multiselectlinkto">
  7910. <ul class="ulselectedfields">'.$linktoelemlist.'
  7911. </ul>
  7912. </div>
  7913. </dd>
  7914. </dl>';
  7915. } else {
  7916. $linktoelem = '';
  7917. }
  7918. if (!empty($conf->use_javascript_ajax)) {
  7919. print '<!-- Add js to show linkto box -->
  7920. <script>
  7921. jQuery(document).ready(function() {
  7922. jQuery(".linkto").click(function() {
  7923. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  7924. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  7925. });
  7926. });
  7927. </script>
  7928. ';
  7929. }
  7930. return $linktoelem;
  7931. }
  7932. /**
  7933. * Return an html string with a select combo box to choose yes or no
  7934. *
  7935. * @param string $htmlname Name of html select field
  7936. * @param string $value Pre-selected value
  7937. * @param int $option 0 return yes/no, 1 return 1/0
  7938. * @param bool $disabled true or false
  7939. * @param int $useempty 1=Add empty line
  7940. * @param int $addjscombo 1=Add js beautifier on combo box
  7941. * @param string $morecss More CSS
  7942. * @return string See option
  7943. */
  7944. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '')
  7945. {
  7946. global $langs;
  7947. $yes = "yes";
  7948. $no = "no";
  7949. if ($option) {
  7950. $yes = "1";
  7951. $no = "0";
  7952. }
  7953. $disabled = ($disabled ? ' disabled' : '');
  7954. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  7955. if ($useempty) {
  7956. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  7957. }
  7958. if (("$value" == 'yes') || ($value == 1)) {
  7959. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  7960. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  7961. } else {
  7962. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  7963. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  7964. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  7965. }
  7966. $resultyesno .= '</select>'."\n";
  7967. if ($addjscombo) {
  7968. $resultyesno .= ajax_combobox($htmlname);
  7969. }
  7970. return $resultyesno;
  7971. }
  7972. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7973. /**
  7974. * Return list of export templates
  7975. *
  7976. * @param string $selected Id modele pre-selectionne
  7977. * @param string $htmlname Name of HTML select
  7978. * @param string $type Type of searched templates
  7979. * @param int $useempty Affiche valeur vide dans liste
  7980. * @return void
  7981. */
  7982. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  7983. {
  7984. // phpcs:enable
  7985. $sql = "SELECT rowid, label";
  7986. $sql .= " FROM ".$this->db->prefix()."export_model";
  7987. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  7988. $sql .= " ORDER BY rowid";
  7989. $result = $this->db->query($sql);
  7990. if ($result) {
  7991. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  7992. if ($useempty) {
  7993. print '<option value="-1">&nbsp;</option>';
  7994. }
  7995. $num = $this->db->num_rows($result);
  7996. $i = 0;
  7997. while ($i < $num) {
  7998. $obj = $this->db->fetch_object($result);
  7999. if ($selected == $obj->rowid) {
  8000. print '<option value="'.$obj->rowid.'" selected>';
  8001. } else {
  8002. print '<option value="'.$obj->rowid.'">';
  8003. }
  8004. print $obj->label;
  8005. print '</option>';
  8006. $i++;
  8007. }
  8008. print "</select>";
  8009. } else {
  8010. dol_print_error($this->db);
  8011. }
  8012. }
  8013. /**
  8014. * Return a HTML area with the reference of object and a navigation bar for a business object
  8015. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8016. *
  8017. * @param object $object Object to show.
  8018. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8019. * @param string $morehtml More html content to output just before the nav bar.
  8020. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8021. * @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.
  8022. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8023. * @param string $morehtmlref More html to show after ref.
  8024. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8025. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8026. * @param string $morehtmlleft More html code to show before ref.
  8027. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8028. * @param string $morehtmlright More html code to show after ref.
  8029. * @return string Portion HTML with ref + navigation buttons
  8030. */
  8031. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8032. {
  8033. global $conf, $langs, $hookmanager, $extralanguages;
  8034. $ret = '';
  8035. if (empty($fieldid)) {
  8036. $fieldid = 'rowid';
  8037. }
  8038. if (empty($fieldref)) {
  8039. $fieldref = 'ref';
  8040. }
  8041. // Preparing gender's display if there is one
  8042. $addgendertxt = '';
  8043. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8044. $addgendertxt = ' ';
  8045. switch ($object->gender) {
  8046. case 'man':
  8047. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8048. break;
  8049. case 'woman':
  8050. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8051. break;
  8052. case 'other':
  8053. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8054. break;
  8055. }
  8056. }
  8057. /*
  8058. $addadmin = '';
  8059. if (property_exists($object, 'admin')) {
  8060. if (!empty($conf->multicompany->enabled) && !empty($object->admin) && empty($object->entity)) {
  8061. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8062. } elseif (!empty($object->admin)) {
  8063. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8064. }
  8065. }*/
  8066. // Add where from hooks
  8067. if (is_object($hookmanager)) {
  8068. $parameters = array('showrefnav' => true);
  8069. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8070. $object->next_prev_filter .= $hookmanager->resPrint;
  8071. }
  8072. $previous_ref = $next_ref = '';
  8073. if ($shownav) {
  8074. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8075. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8076. $navurl = $_SERVER["PHP_SELF"];
  8077. // Special case for project/task page
  8078. if ($paramid == 'project_ref') {
  8079. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8080. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8081. $paramid = 'ref';
  8082. }
  8083. }
  8084. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8085. // accesskey is for Mac: CTRL + key for all browsers
  8086. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8087. if ($conf->browser->name == 'chrome') {
  8088. $stringforfirstkey .= ' ALT +';
  8089. } elseif ($conf->browser->name == 'firefox') {
  8090. $stringforfirstkey .= ' ALT + SHIFT +';
  8091. } else {
  8092. $stringforfirstkey .= ' CTL +';
  8093. }
  8094. $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>';
  8095. $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>';
  8096. }
  8097. //print "xx".$previous_ref."x".$next_ref;
  8098. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8099. // Right part of banner
  8100. if ($morehtmlright) {
  8101. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  8102. }
  8103. if ($previous_ref || $next_ref || $morehtml) {
  8104. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8105. }
  8106. if ($morehtml) {
  8107. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  8108. }
  8109. if ($shownav && ($previous_ref || $next_ref)) {
  8110. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  8111. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  8112. }
  8113. if ($previous_ref || $next_ref || $morehtml) {
  8114. $ret .= '</ul></div>';
  8115. }
  8116. $parameters = array();
  8117. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8118. if (empty($reshook)) {
  8119. $morehtmlstatus .= $hookmanager->resPrint;
  8120. } else {
  8121. $morehtmlstatus = $hookmanager->resPrint;
  8122. }
  8123. if ($morehtmlstatus) {
  8124. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  8125. }
  8126. $parameters = array();
  8127. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8128. if (empty($reshook)) {
  8129. $morehtmlref .= $hookmanager->resPrint;
  8130. } elseif ($reshook > 0) {
  8131. $morehtmlref = $hookmanager->resPrint;
  8132. }
  8133. // Left part of banner
  8134. if ($morehtmlleft) {
  8135. if ($conf->browser->layout == 'phone') {
  8136. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  8137. } else {
  8138. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  8139. }
  8140. }
  8141. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8142. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  8143. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8144. if ($object->element == 'societe') {
  8145. $ret .= dol_htmlentities($object->name);
  8146. // List of extra languages
  8147. $arrayoflangcode = array();
  8148. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8149. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8150. }
  8151. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8152. if (!is_object($extralanguages)) {
  8153. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  8154. $extralanguages = new ExtraLanguages($this->db);
  8155. }
  8156. $extralanguages->fetch_name_extralanguages('societe');
  8157. if (!empty($extralanguages->attributes['societe']['name'])) {
  8158. $object->fetchValuesForExtraLanguages();
  8159. $htmltext = '';
  8160. // If there is extra languages
  8161. foreach ($arrayoflangcode as $extralangcode) {
  8162. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8163. if ($object->array_languages['name'][$extralangcode]) {
  8164. $htmltext .= $object->array_languages['name'][$extralangcode];
  8165. } else {
  8166. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  8167. }
  8168. }
  8169. $ret .= '<!-- Show translations of name -->'."\n";
  8170. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8171. }
  8172. }
  8173. } elseif ($object->element == 'member') {
  8174. $ret .= $object->ref.'<br>';
  8175. $fullname = $object->getFullName($langs);
  8176. if ($object->morphy == 'mor' && $object->societe) {
  8177. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  8178. } else {
  8179. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  8180. }
  8181. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8182. $ret .= dol_htmlentities($object->getFullName($langs)).$addgendertxt;
  8183. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8184. $ret .= $object->ref.'<br>'.$object->label;
  8185. } elseif (in_array($object->element, array('adherent_type'))) {
  8186. $ret .= $object->label;
  8187. } elseif ($object->element == 'ecm_directories') {
  8188. $ret .= '';
  8189. } elseif ($fieldref != 'none') {
  8190. $ret .= dol_htmlentities($object->$fieldref);
  8191. }
  8192. if ($morehtmlref) {
  8193. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8194. if (substr($morehtmlref, 0, 4) != '<div') {
  8195. $ret .= ' ';
  8196. }
  8197. $ret .= $morehtmlref;
  8198. }
  8199. $ret .= '</div>';
  8200. $ret .= '</div><!-- End banner content -->';
  8201. return $ret;
  8202. }
  8203. /**
  8204. * Return HTML code to output a barcode
  8205. *
  8206. * @param Object $object Object containing data to retrieve file name
  8207. * @param int $width Width of photo
  8208. * @param string $morecss More CSS on img of barcode
  8209. * @return string HTML code to output barcode
  8210. */
  8211. public function showbarcode(&$object, $width = 100, $morecss = '')
  8212. {
  8213. global $conf;
  8214. //Check if barcode is filled in the card
  8215. if (empty($object->barcode)) {
  8216. return '';
  8217. }
  8218. // Complete object if not complete
  8219. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8220. $result = $object->fetch_barcode();
  8221. //Check if fetch_barcode() failed
  8222. if ($result < 1) {
  8223. return '<!-- ErrorFetchBarcode -->';
  8224. }
  8225. }
  8226. // Barcode image
  8227. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8228. $out = '<!-- url barcode = '.$url.' -->';
  8229. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8230. return $out;
  8231. }
  8232. /**
  8233. * Return HTML code to output a photo
  8234. *
  8235. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8236. * @param object $object Object containing data to retrieve file name
  8237. * @param int $width Width of photo
  8238. * @param int $height Height of photo (auto if 0)
  8239. * @param int $caneditfield Add edit fields
  8240. * @param string $cssclass CSS name to use on img for photo
  8241. * @param string $imagesize 'mini', 'small' or '' (original)
  8242. * @param int $addlinktofullsize Add link to fullsize image
  8243. * @param int $cache 1=Accept to use image in cache
  8244. * @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 ''.
  8245. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8246. * @return string HTML code to output photo
  8247. */
  8248. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8249. {
  8250. global $conf, $langs;
  8251. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8252. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8253. $ret = '';
  8254. $dir = '';
  8255. $file = '';
  8256. $originalfile = '';
  8257. $altfile = '';
  8258. $email = '';
  8259. $capture = '';
  8260. if ($modulepart == 'societe') {
  8261. $dir = $conf->societe->multidir_output[$entity];
  8262. if (!empty($object->logo)) {
  8263. if (dolIsAllowedForPreview($object->logo)) {
  8264. if ((string) $imagesize == 'mini') {
  8265. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8266. } elseif ((string) $imagesize == 'small') {
  8267. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8268. } else {
  8269. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8270. }
  8271. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8272. }
  8273. }
  8274. $email = $object->email;
  8275. } elseif ($modulepart == 'contact') {
  8276. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8277. if (!empty($object->photo)) {
  8278. if (dolIsAllowedForPreview($object->photo)) {
  8279. if ((string) $imagesize == 'mini') {
  8280. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8281. } elseif ((string) $imagesize == 'small') {
  8282. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8283. } else {
  8284. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8285. }
  8286. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8287. }
  8288. }
  8289. $email = $object->email;
  8290. $capture = 'user';
  8291. } elseif ($modulepart == 'userphoto') {
  8292. $dir = $conf->user->dir_output;
  8293. if (!empty($object->photo)) {
  8294. if (dolIsAllowedForPreview($object->photo)) {
  8295. if ((string) $imagesize == 'mini') {
  8296. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8297. } elseif ((string) $imagesize == 'small') {
  8298. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8299. } else {
  8300. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8301. }
  8302. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8303. }
  8304. }
  8305. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8306. $altfile = $object->id.".jpg"; // For backward compatibility
  8307. }
  8308. $email = $object->email;
  8309. $capture = 'user';
  8310. } elseif ($modulepart == 'memberphoto') {
  8311. $dir = $conf->adherent->dir_output;
  8312. if (!empty($object->photo)) {
  8313. if (dolIsAllowedForPreview($object->photo)) {
  8314. if ((string) $imagesize == 'mini') {
  8315. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8316. } elseif ((string) $imagesize == 'small') {
  8317. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8318. } else {
  8319. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8320. }
  8321. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8322. }
  8323. }
  8324. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8325. $altfile = $object->id.".jpg"; // For backward compatibility
  8326. }
  8327. $email = $object->email;
  8328. $capture = 'user';
  8329. } else {
  8330. // Generic case to show photos
  8331. $dir = $conf->$modulepart->dir_output;
  8332. if (!empty($object->photo)) {
  8333. if (dolIsAllowedForPreview($object->photo)) {
  8334. if ((string) $imagesize == 'mini') {
  8335. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8336. } elseif ((string) $imagesize == 'small') {
  8337. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8338. } else {
  8339. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8340. }
  8341. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8342. }
  8343. }
  8344. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8345. $altfile = $object->id.".jpg"; // For backward compatibility
  8346. }
  8347. $email = $object->email;
  8348. }
  8349. if ($forcecapture) {
  8350. $capture = $forcecapture;
  8351. }
  8352. if ($dir) {
  8353. if ($file && file_exists($dir."/".$file)) {
  8354. if ($addlinktofullsize) {
  8355. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8356. if ($urladvanced) {
  8357. $ret .= '<a href="'.$urladvanced.'">';
  8358. } else {
  8359. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8360. }
  8361. }
  8362. $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.'">';
  8363. if ($addlinktofullsize) {
  8364. $ret .= '</a>';
  8365. }
  8366. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8367. if ($addlinktofullsize) {
  8368. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8369. if ($urladvanced) {
  8370. $ret .= '<a href="'.$urladvanced.'">';
  8371. } else {
  8372. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8373. }
  8374. }
  8375. $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.'">';
  8376. if ($addlinktofullsize) {
  8377. $ret .= '</a>';
  8378. }
  8379. } else {
  8380. $nophoto = '/public/theme/common/nophoto.png';
  8381. $defaultimg = 'identicon'; // For gravatar
  8382. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8383. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8384. $nophoto = 'company';
  8385. } else {
  8386. $nophoto = '/public/theme/common/user_anonymous.png';
  8387. if (!empty($object->gender) && $object->gender == 'man') {
  8388. $nophoto = '/public/theme/common/user_man.png';
  8389. }
  8390. if (!empty($object->gender) && $object->gender == 'woman') {
  8391. $nophoto = '/public/theme/common/user_woman.png';
  8392. }
  8393. }
  8394. }
  8395. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  8396. // see https://gravatar.com/site/implement/images/php/
  8397. $ret .= '<!-- Put link to gravatar -->';
  8398. $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
  8399. } else {
  8400. if ($nophoto == 'company') {
  8401. $ret .= '<div class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'">'.img_picto('', 'company').'</div>';
  8402. } else {
  8403. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8404. }
  8405. }
  8406. }
  8407. if ($caneditfield) {
  8408. if ($object->photo) {
  8409. $ret .= "<br>\n";
  8410. }
  8411. $ret .= '<table class="nobordernopadding centpercent">';
  8412. if ($object->photo) {
  8413. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8414. }
  8415. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  8416. $ret .= '</table>';
  8417. }
  8418. } else {
  8419. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8420. }
  8421. return $ret;
  8422. }
  8423. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8424. /**
  8425. * Return select list of groups
  8426. *
  8427. * @param string $selected Id group preselected
  8428. * @param string $htmlname Field name in form
  8429. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8430. * @param string $exclude Array list of groups id to exclude
  8431. * @param int $disabled If select list must be disabled
  8432. * @param string $include Array list of groups id to include
  8433. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8434. * @param string $force_entity '0' or Ids of environment to force
  8435. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8436. * @param string $morecss More css to add to html component
  8437. * @return string
  8438. * @see select_dolusers()
  8439. */
  8440. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8441. {
  8442. // phpcs:enable
  8443. global $conf, $user, $langs;
  8444. // Permettre l'exclusion de groupes
  8445. $excludeGroups = null;
  8446. if (is_array($exclude)) {
  8447. $excludeGroups = implode(",", $exclude);
  8448. }
  8449. // Permettre l'inclusion de groupes
  8450. $includeGroups = null;
  8451. if (is_array($include)) {
  8452. $includeGroups = implode(",", $include);
  8453. }
  8454. if (!is_array($selected)) {
  8455. $selected = array($selected);
  8456. }
  8457. $out = '';
  8458. // On recherche les groupes
  8459. $sql = "SELECT ug.rowid, ug.nom as name";
  8460. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8461. $sql .= ", e.label";
  8462. }
  8463. $sql .= " FROM ".$this->db->prefix()."usergroup as ug ";
  8464. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8465. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid=ug.entity";
  8466. if ($force_entity) {
  8467. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8468. } else {
  8469. $sql .= " WHERE ug.entity IS NOT NULL";
  8470. }
  8471. } else {
  8472. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8473. }
  8474. if (is_array($exclude) && $excludeGroups) {
  8475. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8476. }
  8477. if (is_array($include) && $includeGroups) {
  8478. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8479. }
  8480. $sql .= " ORDER BY ug.nom ASC";
  8481. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8482. $resql = $this->db->query($sql);
  8483. if ($resql) {
  8484. // Enhance with select2
  8485. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8486. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8487. $num = $this->db->num_rows($resql);
  8488. $i = 0;
  8489. if ($num) {
  8490. if ($show_empty && !$multiple) {
  8491. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8492. }
  8493. while ($i < $num) {
  8494. $obj = $this->db->fetch_object($resql);
  8495. $disableline = 0;
  8496. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8497. $disableline = 1;
  8498. }
  8499. $out .= '<option value="'.$obj->rowid.'"';
  8500. if ($disableline) {
  8501. $out .= ' disabled';
  8502. }
  8503. 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))) {
  8504. $out .= ' selected';
  8505. }
  8506. $out .= '>';
  8507. $out .= $obj->name;
  8508. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8509. $out .= " (".$obj->label.")";
  8510. }
  8511. $out .= '</option>';
  8512. $i++;
  8513. }
  8514. } else {
  8515. if ($show_empty) {
  8516. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8517. }
  8518. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8519. }
  8520. $out .= '</select>';
  8521. $out .= ajax_combobox($htmlname);
  8522. } else {
  8523. dol_print_error($this->db);
  8524. }
  8525. return $out;
  8526. }
  8527. /**
  8528. * Return HTML to show the search and clear seach button
  8529. *
  8530. * @param string $pos position colon on liste value left or right
  8531. * @return string
  8532. */
  8533. public function showFilterButtons($pos = '')
  8534. {
  8535. $out = '<div class="nowraponall">';
  8536. if ($pos == 'left') {
  8537. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8538. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8539. } else {
  8540. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8541. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8542. }
  8543. $out .= '</div>';
  8544. return $out;
  8545. }
  8546. /**
  8547. * Return HTML to show the search and clear search button
  8548. *
  8549. * @param string $cssclass CSS class
  8550. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8551. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8552. * @return string
  8553. */
  8554. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8555. {
  8556. global $conf, $langs;
  8557. $out = '';
  8558. if (!empty($conf->use_javascript_ajax)) {
  8559. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8560. }
  8561. $out .= '<script>
  8562. $(document).ready(function() {
  8563. $("#' . $cssclass.'s").click(function() {
  8564. if($(this).is(\':checked\')){
  8565. console.log("We check all '.$cssclass.' and trigger the change method");
  8566. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8567. }
  8568. else
  8569. {
  8570. console.log("We uncheck all");
  8571. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8572. }'."\n";
  8573. if ($calljsfunction) {
  8574. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8575. }
  8576. $out .= ' });
  8577. $(".' . $cssclass.'").change(function() {
  8578. $(this).closest("tr").toggleClass("highlight", this.checked);
  8579. });
  8580. });
  8581. </script>';
  8582. return $out;
  8583. }
  8584. /**
  8585. * Return HTML to show the search and clear seach button
  8586. *
  8587. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8588. * @param string $cssclass CSS class
  8589. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8590. * @param string $massactionname Mass action name
  8591. * @return string
  8592. */
  8593. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8594. {
  8595. $out = $this->showFilterButtons();
  8596. if ($addcheckuncheckall) {
  8597. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8598. }
  8599. return $out;
  8600. }
  8601. /**
  8602. * Return HTML to show the select of expense categories
  8603. *
  8604. * @param string $selected preselected category
  8605. * @param string $htmlname name of HTML select list
  8606. * @param integer $useempty 1=Add empty line
  8607. * @param array $excludeid id to exclude
  8608. * @param string $target htmlname of target select to bind event
  8609. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8610. * @param array $params param to give
  8611. * @param int $info_admin Show the tooltip help picto to setup list
  8612. * @return string
  8613. */
  8614. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8615. {
  8616. global $langs, $user;
  8617. $out = '';
  8618. $sql = "SELECT rowid, label FROM ".$this->db->prefix()."c_exp_tax_cat WHERE active = 1";
  8619. $sql .= " AND entity IN (0,".getEntity('exp_tax_cat').")";
  8620. if (!empty($excludeid)) {
  8621. $sql .= " AND rowid NOT IN (".$this->db->sanitize(implode(',', $excludeid)).")";
  8622. }
  8623. $sql .= " ORDER BY label";
  8624. $resql = $this->db->query($sql);
  8625. if ($resql) {
  8626. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8627. if ($useempty) {
  8628. $out .= '<option value="0">&nbsp;</option>';
  8629. }
  8630. while ($obj = $this->db->fetch_object($resql)) {
  8631. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8632. }
  8633. $out .= '</select>';
  8634. $out .= ajax_combobox('select_'.$htmlname);
  8635. if (!empty($htmlname) && $user->admin && $info_admin) {
  8636. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8637. }
  8638. if (!empty($target)) {
  8639. $sql = "SELECT c.id FROM ".$this->db->prefix()."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8640. $resql = $this->db->query($sql);
  8641. if ($resql) {
  8642. if ($this->db->num_rows($resql) > 0) {
  8643. $obj = $this->db->fetch_object($resql);
  8644. $out .= '<script>
  8645. $(function() {
  8646. $("select[name='.$target.']").on("change", function() {
  8647. var current_val = $(this).val();
  8648. if (current_val == '.$obj->id.') {';
  8649. if (!empty($default_selected) || !empty($selected)) {
  8650. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8651. }
  8652. $out .= '
  8653. $("select[name='.$htmlname.']").change();
  8654. }
  8655. });
  8656. $("select[name='.$htmlname.']").change(function() {
  8657. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8658. // get price of kilometer to fill the unit price
  8659. $.ajax({
  8660. method: "POST",
  8661. dataType: "json",
  8662. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8663. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.$params).'",
  8664. }).done(function( data, textStatus, jqXHR ) {
  8665. console.log(data);
  8666. if (typeof data.up != "undefined") {
  8667. $("input[name=value_unit]").val(data.up);
  8668. $("select[name='.$htmlname.']").attr("title", data.title);
  8669. } else {
  8670. $("input[name=value_unit]").val("");
  8671. $("select[name='.$htmlname.']").attr("title", "");
  8672. }
  8673. });
  8674. }
  8675. });
  8676. });
  8677. </script>';
  8678. }
  8679. }
  8680. }
  8681. } else {
  8682. dol_print_error($this->db);
  8683. }
  8684. return $out;
  8685. }
  8686. /**
  8687. * Return HTML to show the select ranges of expense range
  8688. *
  8689. * @param string $selected preselected category
  8690. * @param string $htmlname name of HTML select list
  8691. * @param integer $useempty 1=Add empty line
  8692. * @return string
  8693. */
  8694. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8695. {
  8696. global $conf, $langs;
  8697. $out = '';
  8698. $sql = "SELECT rowid, range_ik FROM ".$this->db->prefix()."c_exp_tax_range";
  8699. $sql .= " WHERE entity = ".$conf->entity." AND active = 1";
  8700. $resql = $this->db->query($sql);
  8701. if ($resql) {
  8702. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8703. if ($useempty) {
  8704. $out .= '<option value="0"></option>';
  8705. }
  8706. while ($obj = $this->db->fetch_object($resql)) {
  8707. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8708. }
  8709. $out .= '</select>';
  8710. } else {
  8711. dol_print_error($this->db);
  8712. }
  8713. return $out;
  8714. }
  8715. /**
  8716. * Return HTML to show a select of expense
  8717. *
  8718. * @param string $selected preselected category
  8719. * @param string $htmlname name of HTML select list
  8720. * @param integer $useempty 1=Add empty choice
  8721. * @param integer $allchoice 1=Add all choice
  8722. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8723. * @return string
  8724. */
  8725. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8726. {
  8727. global $langs;
  8728. $out = '';
  8729. $sql = "SELECT id, code, label FROM ".$this->db->prefix()."c_type_fees";
  8730. $sql .= " WHERE active = 1";
  8731. $resql = $this->db->query($sql);
  8732. if ($resql) {
  8733. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8734. if ($useempty) {
  8735. $out .= '<option value="0"></option>';
  8736. }
  8737. if ($allchoice) {
  8738. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8739. }
  8740. $field = 'code';
  8741. if ($useid) {
  8742. $field = 'id';
  8743. }
  8744. while ($obj = $this->db->fetch_object($resql)) {
  8745. $key = $langs->trans($obj->code);
  8746. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8747. }
  8748. $out .= '</select>';
  8749. } else {
  8750. dol_print_error($this->db);
  8751. }
  8752. return $out;
  8753. }
  8754. /**
  8755. * Output a combo list with invoices qualified for a third party
  8756. *
  8757. * @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)
  8758. * @param int $selected Id invoice preselected
  8759. * @param string $htmlname Name of HTML select
  8760. * @param int $maxlength Maximum length of label
  8761. * @param int $option_only Return only html options lines without the select tag
  8762. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8763. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8764. * @param int $forcefocus Force focus on field (works with javascript only)
  8765. * @param int $disabled Disabled
  8766. * @param string $morecss More css added to the select component
  8767. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8768. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8769. * @param User $usertofilter User object to use for filtering
  8770. * @return int Nbr of project if OK, <0 if KO
  8771. */
  8772. 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)
  8773. {
  8774. global $user, $conf, $langs;
  8775. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8776. if (is_null($usertofilter)) {
  8777. $usertofilter = $user;
  8778. }
  8779. $out = '';
  8780. $hideunselectables = false;
  8781. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8782. $hideunselectables = true;
  8783. }
  8784. if (empty($projectsListId)) {
  8785. if (empty($usertofilter->rights->projet->all->lire)) {
  8786. $projectstatic = new Project($this->db);
  8787. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8788. }
  8789. }
  8790. // Search all projects
  8791. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8792. p.title, p.fk_soc, p.fk_statut, p.public,";
  8793. $sql .= ' s.nom as name';
  8794. $sql .= ' FROM '.$this->db->prefix().'projet as p';
  8795. $sql .= ' LEFT JOIN '.$this->db->prefix().'societe as s ON s.rowid = p.fk_soc,';
  8796. $sql .= ' '.$this->db->prefix().'facture as f';
  8797. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  8798. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  8799. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  8800. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  8801. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  8802. $sql .= " ORDER BY p.ref, f.ref ASC";
  8803. $resql = $this->db->query($sql);
  8804. if ($resql) {
  8805. // Use select2 selector
  8806. if (!empty($conf->use_javascript_ajax)) {
  8807. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8808. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8809. $out .= $comboenhancement;
  8810. $morecss = 'minwidth200imp maxwidth500';
  8811. }
  8812. if (empty($option_only)) {
  8813. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  8814. }
  8815. if (!empty($show_empty)) {
  8816. $out .= '<option value="0" class="optiongrey">';
  8817. if (!is_numeric($show_empty)) {
  8818. $out .= $show_empty;
  8819. } else {
  8820. $out .= '&nbsp;';
  8821. }
  8822. $out .= '</option>';
  8823. }
  8824. $num = $this->db->num_rows($resql);
  8825. $i = 0;
  8826. if ($num) {
  8827. while ($i < $num) {
  8828. $obj = $this->db->fetch_object($resql);
  8829. // 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.
  8830. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  8831. // Do nothing
  8832. } else {
  8833. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  8834. $i++;
  8835. continue;
  8836. }
  8837. $labeltoshow = '';
  8838. if ($showproject == 'all') {
  8839. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  8840. if ($obj->name) {
  8841. $labeltoshow .= ' - '.$obj->name; // Soc name
  8842. }
  8843. $disabled = 0;
  8844. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  8845. $disabled = 1;
  8846. $labeltoshow .= ' - '.$langs->trans("Draft");
  8847. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  8848. if ($discard_closed == 2) {
  8849. $disabled = 1;
  8850. }
  8851. $labeltoshow .= ' - '.$langs->trans("Closed");
  8852. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  8853. $disabled = 1;
  8854. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  8855. }
  8856. }
  8857. if (!empty($selected) && $selected == $obj->rowid) {
  8858. $out .= '<option value="'.$obj->rowid.'" selected';
  8859. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8860. $out .= '>'.$labeltoshow.'</option>';
  8861. } else {
  8862. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8863. $resultat = '';
  8864. } else {
  8865. $resultat = '<option value="'.$obj->rowid.'"';
  8866. if ($disabled) {
  8867. $resultat .= ' disabled';
  8868. }
  8869. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  8870. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  8871. $resultat .= '>';
  8872. $resultat .= $labeltoshow;
  8873. $resultat .= '</option>';
  8874. }
  8875. $out .= $resultat;
  8876. }
  8877. }
  8878. $i++;
  8879. }
  8880. }
  8881. if (empty($option_only)) {
  8882. $out .= '</select>';
  8883. }
  8884. print $out;
  8885. $this->db->free($resql);
  8886. return $num;
  8887. } else {
  8888. dol_print_error($this->db);
  8889. return -1;
  8890. }
  8891. }
  8892. /**
  8893. * Output a combo list with invoices qualified for a third party
  8894. *
  8895. * @param int $selected Id invoice preselected
  8896. * @param string $htmlname Name of HTML select
  8897. * @param int $maxlength Maximum length of label
  8898. * @param int $option_only Return only html options lines without the select tag
  8899. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8900. * @param int $forcefocus Force focus on field (works with javascript only)
  8901. * @param int $disabled Disabled
  8902. * @param string $morecss More css added to the select component
  8903. * @return int Nbr of project if OK, <0 if KO
  8904. */
  8905. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  8906. {
  8907. global $user, $conf, $langs;
  8908. $out = '';
  8909. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  8910. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  8911. //$sql.= ', el.fk_source';
  8912. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  8913. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  8914. $sql .= " ORDER BY f.titre ASC";
  8915. $resql = $this->db->query($sql);
  8916. if ($resql) {
  8917. // Use select2 selector
  8918. if (!empty($conf->use_javascript_ajax)) {
  8919. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  8920. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8921. $out .= $comboenhancement;
  8922. $morecss = 'minwidth200imp maxwidth500';
  8923. }
  8924. if (empty($option_only)) {
  8925. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  8926. }
  8927. if (!empty($show_empty)) {
  8928. $out .= '<option value="0" class="optiongrey">';
  8929. if (!is_numeric($show_empty)) {
  8930. $out .= $show_empty;
  8931. } else {
  8932. $out .= '&nbsp;';
  8933. }
  8934. $out .= '</option>';
  8935. }
  8936. $num = $this->db->num_rows($resql);
  8937. if ($num) {
  8938. while ($obj = $this->db->fetch_object($resql)) {
  8939. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  8940. $disabled = 0;
  8941. if (!empty($obj->suspended)) {
  8942. $disabled = 1;
  8943. $labeltoshow .= ' - ' . $langs->trans("Closed");
  8944. }
  8945. if (!empty($selected) && $selected == $obj->rowid) {
  8946. $out .= '<option value="' . $obj->rowid . '" selected';
  8947. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8948. $out .= '>' . $labeltoshow . '</option>';
  8949. } else {
  8950. if ($disabled && ($selected != $obj->rowid)) {
  8951. $resultat = '';
  8952. } else {
  8953. $resultat = '<option value="' . $obj->rowid . '"';
  8954. if ($disabled) {
  8955. $resultat .= ' disabled';
  8956. }
  8957. $resultat .= '>';
  8958. $resultat .= $labeltoshow;
  8959. $resultat .= '</option>';
  8960. }
  8961. $out .= $resultat;
  8962. }
  8963. }
  8964. }
  8965. if (empty($option_only)) {
  8966. $out .= '</select>';
  8967. }
  8968. print $out;
  8969. $this->db->free($resql);
  8970. return $num;
  8971. } else {
  8972. $this->errors[]=$this->db->lasterror;
  8973. return -1;
  8974. }
  8975. }
  8976. /**
  8977. * Output the component to make advanced search criteries
  8978. *
  8979. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  8980. * @param array $search_component_params Array of selected search criterias
  8981. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  8982. * @param string $search_component_params_hidden String with $search_component_params criterias
  8983. * @return string HTML component for advanced search
  8984. */
  8985. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  8986. {
  8987. global $langs;
  8988. $ret = '';
  8989. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  8990. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8991. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  8992. $ret .= '<span class="fas fa-filter linkobject boxfilter pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Filters")).'" id="idsubimgproductdistribution"></span>';
  8993. //$ret .= $langs->trans("Filters");
  8994. $ret .= '</a>';
  8995. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  8996. // Show select fields as tags.
  8997. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  8998. if ($search_component_params_hidden) {
  8999. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9000. $search_component_params_hidden .= '('.$search_component_params_hidden.')';
  9001. }
  9002. $errormessage = '';
  9003. if (!dolCheckFilters($search_component_params_hidden, $errormessage)) {
  9004. print 'ERROR in parsing search string';
  9005. }
  9006. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9007. //var_dump($search_component_params_hidden);
  9008. $htmltags = preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $search_component_params_hidden);
  9009. //var_dump($htmltags);
  9010. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> '.$htmltags.'</span>';
  9011. }
  9012. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9013. //$ret .= search_component_params
  9014. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9015. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9016. $show_search_component_params_hidden = 1;
  9017. if ($show_search_component_params_hidden) {
  9018. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9019. }
  9020. $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%')) -->";
  9021. $ret .= '<input type="hidden" name="search_component_params_hidden" value="'.dol_escape_htmltag($search_component_params_hidden).'">';
  9022. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  9023. foreach ($arrayofcriterias as $criterias) {
  9024. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9025. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9026. continue;
  9027. }
  9028. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9029. continue;
  9030. }
  9031. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9032. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  9033. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  9034. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  9035. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  9036. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  9037. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  9038. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  9039. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  9040. } else {
  9041. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  9042. }
  9043. }
  9044. }
  9045. $ret .= '</div>';
  9046. $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";
  9047. $ret .= '<input type="text" placeholder="'.$langs->trans("Search").'" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9048. $ret .= '</div>';
  9049. $ret .= '</div>';
  9050. return $ret;
  9051. }
  9052. /**
  9053. * selectModelMail
  9054. *
  9055. * @param string $prefix Prefix
  9056. * @param string $modelType Model type
  9057. * @param int $default 1=Show also Default mail template
  9058. * @param int $addjscombo Add js combobox
  9059. * @return string HTML select string
  9060. */
  9061. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9062. {
  9063. global $langs, $user;
  9064. $retstring = '';
  9065. $TModels = array();
  9066. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  9067. $formmail = new FormMail($this->db);
  9068. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9069. if ($default) {
  9070. $TModels[0] = $langs->trans('DefaultMailModel');
  9071. }
  9072. if ($result > 0) {
  9073. foreach ($formmail->lines_model as $model) {
  9074. $TModels[$model->id] = $model->label;
  9075. }
  9076. }
  9077. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  9078. foreach ($TModels as $id_model => $label_model) {
  9079. $retstring .= '<option value="'.$id_model.'"';
  9080. $retstring .= ">".$label_model."</option>";
  9081. }
  9082. $retstring .= "</select>";
  9083. if ($addjscombo) {
  9084. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  9085. }
  9086. return $retstring;
  9087. }
  9088. /**
  9089. * Output the buttons to submit a creation/edit form
  9090. *
  9091. * @param string $save_label Alternative label for save button
  9092. * @param string $cancel_label Alternative label for cancel button
  9093. * @param array $morebuttons Add additional buttons between save and cancel
  9094. * @param bool $withoutdiv Option to remove enclosing centered div
  9095. * @param string $morecss More CSS
  9096. * @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.
  9097. * @return string Html code with the buttons
  9098. */
  9099. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9100. {
  9101. global $langs;
  9102. $buttons = array();
  9103. $save = array(
  9104. 'name' => 'save',
  9105. 'label_key' => $save_label,
  9106. );
  9107. if ($save_label == 'Create' || $save_label == 'Add' ) {
  9108. $save['name'] = 'add';
  9109. } elseif ($save_label == 'Modify') {
  9110. $save['name'] = 'edit';
  9111. }
  9112. $cancel = array(
  9113. 'name' => 'cancel',
  9114. 'label_key' => 'Cancel',
  9115. );
  9116. !empty($save_label) ? $buttons[] = $save : '';
  9117. if (!empty($morebuttons)) {
  9118. $buttons[] = $morebuttons;
  9119. }
  9120. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9121. $retstring = $withoutdiv ? '': '<div class="center">';
  9122. foreach ($buttons as $button) {
  9123. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9124. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  9125. }
  9126. $retstring .= $withoutdiv ? '': '</div>';
  9127. if ($dol_openinpopup) {
  9128. $retstring .= '<!-- buttons are shown into a $dol_openinpopup='.$dol_openinpopup.' context, so we enable the close of dialog on cancel -->'."\n";
  9129. $retstring .= '<script>';
  9130. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9131. e.preventDefault(); console.log(\'We click on cancel in iframe popup '.$dol_openinpopup.'\');
  9132. window.parent.jQuery(\'#idfordialog'.$dol_openinpopup.'\').dialog(\'close\');
  9133. });';
  9134. $retstring .= '</script>';
  9135. }
  9136. return $retstring;
  9137. }
  9138. }