html.form.class.php 342 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024
  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-2019 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 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2019 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_availability = array();
  68. public $cache_demand_reason = array();
  69. public $cache_types_fees = array();
  70. public $cache_vatrates = array();
  71. /**
  72. * Constructor
  73. *
  74. * @param DoliDB $db Database handler
  75. */
  76. public function __construct($db)
  77. {
  78. $this->db = $db;
  79. }
  80. /**
  81. * Output key field for an editable field
  82. *
  83. * @param string $text Text of label or key to translate
  84. * @param string $htmlname Name of select field ('edit' prefix will be added)
  85. * @param string $preselected Value to show/edit (not used in this function)
  86. * @param object $object Object
  87. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  88. * @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]'...)
  89. * @param string $moreparam More param to add on a href URL.
  90. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  91. * @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 ' '
  92. * @param string $paramid Key of parameter for id ('id', 'socid')
  93. * @param string $help Tooltip help
  94. * @return string HTML edit field
  95. */
  96. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  97. {
  98. global $conf, $langs;
  99. $ret = '';
  100. // TODO change for compatibility
  101. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata))
  102. {
  103. if (!empty($perm))
  104. {
  105. $tmp = explode(':', $typeofdata);
  106. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  107. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  108. if ($help) {
  109. $ret .= $this->textwithpicto($langs->trans($text), $help);
  110. } else {
  111. $ret .= $langs->trans($text);
  112. }
  113. if ($fieldrequired) $ret .= '</span>';
  114. $ret .= '</div>'."\n";
  115. } else {
  116. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  117. if ($help) {
  118. $ret .= $this->textwithpicto($langs->trans($text), $help);
  119. } else {
  120. $ret .= $langs->trans($text);
  121. }
  122. if ($fieldrequired) $ret .= '</span>';
  123. }
  124. } else {
  125. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  126. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  127. if ($help) {
  128. $ret .= $this->textwithpicto($langs->trans($text), $help);
  129. } else {
  130. $ret .= $langs->trans($text);
  131. }
  132. if ($fieldrequired) $ret .= '</span>';
  133. if (!empty($notabletag)) $ret .= ' ';
  134. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
  135. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<td class="right">';
  136. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  137. if (!empty($notabletag) && $notabletag == 1) $ret .= ' : ';
  138. if (!empty($notabletag) && $notabletag == 3) $ret .= ' ';
  139. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
  140. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</tr></table>';
  141. }
  142. return $ret;
  143. }
  144. /**
  145. * Output value of a field for an editable field
  146. *
  147. * @param string $text Text of label (not used in this function)
  148. * @param string $htmlname Name of select field
  149. * @param string $value Value to show/edit
  150. * @param object $object Object
  151. * @param boolean $perm Permission to allow button to edit parameter
  152. * @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,...')
  153. * @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 value). Use '' to use same than $value
  154. * @param object $extObject External object
  155. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  156. * @param string $moreparam More param to add on the form action href URL
  157. * @param int $notabletag Do no output table tags
  158. * @param string $formatfunc Call a specific function to output field
  159. * @param string $paramid Key of parameter for id ('id', 'socid')
  160. * @return string HTML edit field
  161. */
  162. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id')
  163. {
  164. global $conf, $langs, $db;
  165. $ret = '';
  166. // Check parameters
  167. if (empty($typeofdata)) return 'ErrorBadParameter';
  168. // When option to edit inline is activated
  169. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|datehourpicker/', $typeofdata)) // TODO add jquery timepicker and support select
  170. {
  171. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  172. } else {
  173. if (GETPOST('action', 'aZ09') == 'edit'.$htmlname)
  174. {
  175. $ret .= "\n";
  176. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  177. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  178. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  179. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  180. if (empty($notabletag)) $ret .= '<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
  181. if (empty($notabletag)) $ret .= '<tr><td>';
  182. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata))
  183. {
  184. $tmp = explode(':', $typeofdata);
  185. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  186. } elseif (preg_match('/^(numeric|amount)/', $typeofdata))
  187. {
  188. $tmp = explode(':', $typeofdata);
  189. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  190. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ?price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  191. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) // if wysiwyg is enabled $typeofdata = 'ckeditor'
  192. {
  193. $tmp = explode(':', $typeofdata);
  194. $cols = $tmp[2];
  195. $morealt = '';
  196. if (preg_match('/%/', $cols))
  197. {
  198. $morealt = ' style="width: '.$cols.'"';
  199. $cols = '';
  200. }
  201. $valuetoshow = ($editvalue ? $editvalue : $value);
  202. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  203. // textarea convert automatically entities chars into simple chars.
  204. // 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.
  205. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  206. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  207. $ret .= '</textarea>';
  208. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker')
  209. {
  210. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0);
  211. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
  212. {
  213. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0);
  214. } elseif (preg_match('/^select;/', $typeofdata))
  215. {
  216. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  217. $arraylist = array();
  218. foreach ($arraydata as $val)
  219. {
  220. $tmp = explode(':', $val);
  221. $tmpkey = str_replace('|', ':', $tmp[0]);
  222. $arraylist[$tmpkey] = $tmp[1];
  223. }
  224. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  225. } elseif (preg_match('/^ckeditor/', $typeofdata))
  226. {
  227. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  228. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  229. $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'));
  230. $ret .= $doleditor->Create(1);
  231. }
  232. if (empty($notabletag)) $ret .= '</td>';
  233. if (empty($notabletag)) $ret .= '<td class="left">';
  234. //else $ret.='<div class="clearboth"></div>';
  235. $ret .= '<input type="submit" class="button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  236. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) $ret .= '<br>'."\n";
  237. $ret .= '<input type="submit" class="button'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  238. if (empty($notabletag)) $ret .= '</td>';
  239. if (empty($notabletag)) $ret .= '</tr></table>'."\n";
  240. $ret .= '</form>'."\n";
  241. } else {
  242. if (preg_match('/^(email)/', $typeofdata)) $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  243. elseif (preg_match('/^(amount|numeric)/', $typeofdata)) $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  244. elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) $ret .= dol_htmlentitiesbr($value);
  245. elseif (preg_match('/^safehtmlstring/', $typeofdata)) $ret .= dol_string_onlythesehtmltags($value);
  246. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret .= dol_print_date($value, 'day');
  247. elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret .= dol_print_date($value, 'dayhour');
  248. elseif (preg_match('/^select;/', $typeofdata))
  249. {
  250. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  251. $arraylist = array();
  252. foreach ($arraydata as $val)
  253. {
  254. $tmp = explode(':', $val);
  255. $arraylist[$tmp[0]] = $tmp[1];
  256. }
  257. $ret .= $arraylist[$value];
  258. } elseif (preg_match('/^ckeditor/', $typeofdata))
  259. {
  260. $tmpcontent = dol_htmlentitiesbr($value);
  261. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB))
  262. {
  263. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  264. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  265. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  266. }
  267. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  268. // clean data from some dangerous html
  269. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  270. } else {
  271. $ret .= dol_escape_htmltag($value);
  272. }
  273. if ($formatfunc && method_exists($object, $formatfunc))
  274. {
  275. $ret = $object->$formatfunc($ret);
  276. }
  277. }
  278. }
  279. return $ret;
  280. }
  281. /**
  282. * Output edit in place form
  283. *
  284. * @param string $fieldname Name of the field
  285. * @param object $object Object
  286. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  287. * @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]'...)
  288. * @param string $check Same coe than $check parameter of GETPOST()
  289. * @param string $morecss More CSS
  290. * @return string HTML code for the edit of alternative language
  291. */
  292. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  293. {
  294. global $conf, $langs, $extralanguages;
  295. $result = '';
  296. // List of extra languages
  297. $arrayoflangcode = array();
  298. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  299. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  300. if (!is_object($extralanguages)) {
  301. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  302. $extralanguages = new ExtraLanguages($this->db);
  303. }
  304. $extralanguages->fetch_name_extralanguages('societe');
  305. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  306. return ''; // No extralang field to show
  307. }
  308. $result .= '<!-- Widget for translation -->'."\n";
  309. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  310. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  311. $result .= $s;
  312. $result .= '</div>';
  313. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  314. $resultforextrlang = '';
  315. foreach ($arrayoflangcode as $langcode)
  316. {
  317. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  318. if (empty($valuetoshow)) {
  319. $object->fetchValuesForExtraLanguages();
  320. //var_dump($object->array_languages);
  321. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  322. }
  323. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  324. $resultforextrlang .= $s;
  325. // TODO Use the showInputField() method of ExtraLanguages object
  326. if ($typeofdata == 'textarea') {
  327. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  328. $resultforextrlang .= $valuetoshow;
  329. $resultforextrlang .= '</textarea>';
  330. } else {
  331. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  332. }
  333. }
  334. $result .= $resultforextrlang;
  335. $result .= '</div>';
  336. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  337. }
  338. return $result;
  339. }
  340. /**
  341. * Output edit in place form
  342. *
  343. * @param object $object Object
  344. * @param string $value Value to show/edit
  345. * @param string $htmlname DIV ID (field name)
  346. * @param int $condition Condition to edit
  347. * @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')
  348. * @param string $editvalue When in edit mode, use this value as $value instead of value
  349. * @param object $extObject External object
  350. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  351. * @return string HTML edit in place
  352. */
  353. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  354. {
  355. global $conf;
  356. $out = '';
  357. // Check parameters
  358. if (preg_match('/^text/', $inputType)) $value = dol_nl2br($value);
  359. elseif (preg_match('/^numeric/', $inputType)) $value = price($value);
  360. elseif ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
  361. if ($condition)
  362. {
  363. $element = false;
  364. $table_element = false;
  365. $fk_element = false;
  366. $loadmethod = false;
  367. $savemethod = false;
  368. $ext_element = false;
  369. $button_only = false;
  370. $inputOption = '';
  371. if (is_object($object))
  372. {
  373. $element = $object->element;
  374. $table_element = $object->table_element;
  375. $fk_element = $object->id;
  376. }
  377. if (is_object($extObject))
  378. {
  379. $ext_element = $extObject->element;
  380. }
  381. if (preg_match('/^(string|email|numeric)/', $inputType))
  382. {
  383. $tmp = explode(':', $inputType);
  384. $inputType = $tmp[0];
  385. if (!empty($tmp[1])) $inputOption = $tmp[1];
  386. if (!empty($tmp[2])) $savemethod = $tmp[2];
  387. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  388. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType)))
  389. {
  390. $tmp = explode(':', $inputType);
  391. $inputType = $tmp[0];
  392. if (!empty($tmp[1])) $inputOption = $tmp[1];
  393. if (!empty($tmp[2])) $savemethod = $tmp[2];
  394. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  395. } elseif (preg_match('/^(select|autocomplete)/', $inputType))
  396. {
  397. $tmp = explode(':', $inputType);
  398. $inputType = $tmp[0]; $loadmethod = $tmp[1];
  399. if (!empty($tmp[2])) $savemethod = $tmp[2];
  400. if (!empty($tmp[3])) $button_only = true;
  401. } elseif (preg_match('/^textarea/', $inputType))
  402. {
  403. $tmp = explode(':', $inputType);
  404. $inputType = $tmp[0];
  405. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  406. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  407. } elseif (preg_match('/^ckeditor/', $inputType))
  408. {
  409. $tmp = explode(':', $inputType);
  410. $inputType = $tmp[0]; $toolbar = $tmp[1];
  411. if (!empty($tmp[2])) $width = $tmp[2];
  412. if (!empty($tmp[3])) $heigth = $tmp[3];
  413. if (!empty($tmp[4])) $savemethod = $tmp[4];
  414. if (!empty($conf->fckeditor->enabled))
  415. {
  416. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  417. } else {
  418. $inputType = 'textarea';
  419. }
  420. }
  421. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  422. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  423. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  424. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  425. if (!empty($savemethod)) $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  426. if (!empty($ext_element)) $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  427. if (!empty($custommsg))
  428. {
  429. if (is_array($custommsg))
  430. {
  431. if (!empty($custommsg['success']))
  432. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  433. if (!empty($custommsg['error']))
  434. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  435. } else $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  436. }
  437. if ($inputType == 'textarea') {
  438. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  439. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  440. }
  441. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  442. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  443. } else {
  444. $out = $value;
  445. }
  446. return $out;
  447. }
  448. /**
  449. * Show a text and picto with tooltip on text or picto.
  450. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  451. *
  452. * @param string $text Text to show
  453. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  454. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  455. * @param int $direction -1=image is before, 0=no image, 1=image is after
  456. * @param string $img Html code for image (use img_xxx() function to get it)
  457. * @param string $extracss Add a CSS style to td tags
  458. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  459. * @param string $incbefore Include code before the text
  460. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  461. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  462. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  463. * @return string Code html du tooltip (texte+picto)
  464. * @see textwithpicto() Use thisfunction if you can.
  465. * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
  466. */
  467. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  468. {
  469. if ($incbefore) $text = $incbefore.$text;
  470. if (!$htmltext) return $text;
  471. $tag = 'td';
  472. if ($notabs == 2) $tag = 'div';
  473. if ($notabs == 3) $tag = 'span';
  474. // Sanitize tooltip
  475. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  476. $extrastyle = '';
  477. if ($direction < 0) { $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : ''); $extrastyle = 'padding: 0px; padding-left: 3px !important;'; }
  478. if ($direction > 0) { $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : ''); $extrastyle = 'padding: 0px; padding-right: 3px !important;'; }
  479. $classfortooltip = 'classfortooltip';
  480. $s = ''; $textfordialog = '';
  481. if ($tooltiptrigger == '')
  482. {
  483. $htmltext = str_replace('"', '&quot;', $htmltext);
  484. } else {
  485. $classfortooltip = 'classfortooltiponclick';
  486. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  487. }
  488. if ($tooltipon == 2 || $tooltipon == 3)
  489. {
  490. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  491. if ($tooltiptrigger == '') $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  492. else $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  493. } else $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  494. if ($tooltipon == 1 || $tooltipon == 3)
  495. {
  496. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  497. if ($tooltiptrigger == '') $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  498. else $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  499. } else $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  500. if (empty($notabs)) $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  501. elseif ($notabs == 2) $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  502. // Define value if value is before
  503. if ($direction < 0) {
  504. $s .= '<'.$tag.$paramfortooltipimg;
  505. if ($tag == 'td') {
  506. $s .= ' class=valigntop" width="14"';
  507. }
  508. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  509. }
  510. // Use another method to help avoid having a space in value in order to use this value with jquery
  511. // Define label
  512. if ((string) $text != '') $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  513. // Define value if value is after
  514. if ($direction > 0) {
  515. $s .= '<'.$tag.$paramfortooltipimg;
  516. if ($tag == 'td') $s .= ' class="valignmiddle" width="14"';
  517. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  518. }
  519. if (empty($notabs)) $s .= '</tr></table>';
  520. elseif ($notabs == 2) $s .= '</div>';
  521. return $s;
  522. }
  523. /**
  524. * Show a text with a picto and a tooltip on picto
  525. *
  526. * @param string $text Text to show
  527. * @param string $htmltext Content of tooltip
  528. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  529. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  530. * @param string $extracss Add a CSS style to td, div or span tag
  531. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  532. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  533. * @param string $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')
  534. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  535. * @return string HTML code of text, picto, tooltip
  536. */
  537. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  538. {
  539. global $conf, $langs;
  540. $alt = '';
  541. if ($tooltiptrigger) $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  542. //For backwards compatibility
  543. if ($type == '0') $type = 'info';
  544. elseif ($type == '1') $type = 'help';
  545. // If info or help with no javascript, show only text
  546. if (empty($conf->use_javascript_ajax))
  547. {
  548. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') return $text;
  549. else {
  550. $alt = $htmltext;
  551. $htmltext = '';
  552. }
  553. }
  554. // If info or help with smartphone, show only text (tooltip hover can't works)
  555. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
  556. {
  557. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') return $text;
  558. }
  559. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  560. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  561. //{
  562. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  563. //}
  564. $img = '';
  565. if ($type == 'info') $img = img_help(0, $alt);
  566. elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  567. elseif ($type == 'helpclickable') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  568. elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
  569. elseif ($type == 'admin') $img = img_picto($alt, 'star');
  570. elseif ($type == 'warning') $img = img_warning($alt);
  571. elseif ($type != 'none') $img = img_picto($alt, $type); // $type can be an image path
  572. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  573. }
  574. /**
  575. * Generate select HTML to choose massaction
  576. *
  577. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  578. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  579. * @param int $alwaysvisible 1=select button always visible
  580. * @param string $name Name for massaction
  581. * @param string $cssclass CSS class used to check for select
  582. * @return string|void Select list
  583. */
  584. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  585. {
  586. global $conf, $langs, $hookmanager;
  587. $disabled = 0;
  588. $ret = '<div class="centpercent center">';
  589. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  590. // 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.
  591. $parameters = array();
  592. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  593. // check if there is a mass action
  594. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) return;
  595. if (empty($reshook))
  596. {
  597. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  598. foreach ($arrayofaction as $code => $label)
  599. {
  600. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  601. }
  602. }
  603. $ret .= $hookmanager->resPrint;
  604. $ret .= '</select>';
  605. if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.'.$name.'select');
  606. // 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
  607. $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.
  608. $ret .= '<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  609. $ret .= '</div>';
  610. if (!empty($conf->use_javascript_ajax))
  611. {
  612. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  613. <script>
  614. 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 */
  615. {
  616. atleastoneselected=0;
  617. jQuery("."+cssclass).each(function( index ) {
  618. /* console.log( index + ": " + $( this ).text() ); */
  619. if ($(this).is(\':checked\')) atleastoneselected++;
  620. });
  621. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  622. if (atleastoneselected || '.$alwaysvisible.')
  623. {
  624. jQuery("."+name).show();
  625. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  626. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  627. }
  628. else
  629. {
  630. jQuery("."+name).hide();
  631. jQuery("."+name+"other").hide();
  632. }
  633. }
  634. jQuery(document).ready(function () {
  635. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  636. jQuery(".' . $cssclass.'").click(function() {
  637. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  638. });
  639. jQuery(".' . $name.'select").change(function() {
  640. var massaction = $( this ).val();
  641. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  642. if (massaction == "builddoc")
  643. {
  644. urlform = urlform + "#show_files";
  645. }
  646. $( this ).closest("form").attr("action", urlform);
  647. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  648. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  649. if ($(this).val() != \'0\')
  650. {
  651. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  652. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  653. jQuery(".' . $name.'"+massaction).show();
  654. }
  655. else
  656. {
  657. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  658. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  659. }
  660. });
  661. });
  662. </script>
  663. ';
  664. }
  665. return $ret;
  666. }
  667. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  668. /**
  669. * Return combo list of activated countries, into language of user
  670. *
  671. * @param string $selected Id or Code or Label of preselected country
  672. * @param string $htmlname Name of html select object
  673. * @param string $htmloption More html options on select object
  674. * @param integer $maxlength Max length for labels (0=no limit)
  675. * @param string $morecss More css class
  676. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  677. * @param int $showempty Show empty choice
  678. * @param int $disablefavorites 1=Disable favorites,
  679. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  680. * @param array $exclude_country_code Array of country code (iso2) to exclude
  681. * @return string HTML string with select
  682. */
  683. public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array())
  684. {
  685. // phpcs:enable
  686. global $conf, $langs, $mysoc;
  687. $langs->load("dict");
  688. $out = '';
  689. $countryArray = array();
  690. $favorite = array();
  691. $label = array();
  692. $atleastonefavorite = 0;
  693. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
  694. $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
  695. $sql .= " WHERE active > 0";
  696. //$sql.= " ORDER BY code ASC";
  697. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  698. $resql = $this->db->query($sql);
  699. if ($resql)
  700. {
  701. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  702. $num = $this->db->num_rows($resql);
  703. $i = 0;
  704. if ($num)
  705. {
  706. $foundselected = false;
  707. while ($i < $num)
  708. {
  709. $obj = $this->db->fetch_object($resql);
  710. $countryArray[$i]['rowid'] = $obj->rowid;
  711. $countryArray[$i]['code_iso'] = $obj->code_iso;
  712. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  713. $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 : ''));
  714. $countryArray[$i]['favorite'] = $obj->favorite;
  715. $favorite[$i] = $obj->favorite;
  716. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  717. $i++;
  718. }
  719. if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  720. else $countryArray = dol_sort_array($countryArray, 'label');
  721. if ($showempty)
  722. {
  723. $out .= '<option value="">&nbsp;</option>'."\n";
  724. }
  725. if ($addspecialentries) // Add dedicated entries for groups of countries
  726. {
  727. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  728. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  729. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  730. if ($mysoc->isInEEC()) $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  731. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  732. $out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  733. }
  734. foreach ($countryArray as $row)
  735. {
  736. //if (empty($showempty) && empty($row['rowid'])) continue;
  737. if (empty($row['rowid'])) continue;
  738. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) continue; // exclude some countries
  739. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
  740. if (empty($row['favorite']) && $atleastonefavorite)
  741. {
  742. $atleastonefavorite = 0;
  743. $out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  744. }
  745. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']))
  746. {
  747. $foundselected = true;
  748. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected>';
  749. } else {
  750. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'">';
  751. }
  752. if ($row['label']) $out .= dol_trunc($row['label'], $maxlength, 'middle');
  753. else $out .= '&nbsp;';
  754. if ($row['code_iso']) $out .= ' ('.$row['code_iso'].')';
  755. $out .= '</option>';
  756. }
  757. }
  758. $out .= '</select>';
  759. } else {
  760. dol_print_error($this->db);
  761. }
  762. // Make select dynamic
  763. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  764. $out .= ajax_combobox('select'.$htmlname);
  765. return $out;
  766. }
  767. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  768. /**
  769. * Return select list of incoterms
  770. *
  771. * @param string $selected Id or Code of preselected incoterm
  772. * @param string $location_incoterms Value of input location
  773. * @param string $page Defined the form action
  774. * @param string $htmlname Name of html select object
  775. * @param string $htmloption Options html on select object
  776. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  777. * @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')))
  778. * @return string HTML string with select and input
  779. */
  780. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  781. {
  782. // phpcs:enable
  783. global $conf, $langs;
  784. $langs->load("dict");
  785. $out = '';
  786. $incotermArray = array();
  787. $sql = "SELECT rowid, code";
  788. $sql .= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  789. $sql .= " WHERE active > 0";
  790. $sql .= " ORDER BY code ASC";
  791. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  792. $resql = $this->db->query($sql);
  793. if ($resql)
  794. {
  795. if ($conf->use_javascript_ajax && !$forcecombo)
  796. {
  797. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  798. $out .= ajax_combobox($htmlname, $events);
  799. }
  800. if (!empty($page))
  801. {
  802. $out .= '<form method="post" action="'.$page.'">';
  803. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  804. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  805. }
  806. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
  807. $out .= '<option value="0">&nbsp;</option>';
  808. $num = $this->db->num_rows($resql);
  809. $i = 0;
  810. if ($num)
  811. {
  812. $foundselected = false;
  813. while ($i < $num)
  814. {
  815. $obj = $this->db->fetch_object($resql);
  816. $incotermArray[$i]['rowid'] = $obj->rowid;
  817. $incotermArray[$i]['code'] = $obj->code;
  818. $i++;
  819. }
  820. foreach ($incotermArray as $row)
  821. {
  822. if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
  823. {
  824. $out .= '<option value="'.$row['rowid'].'" selected>';
  825. } else {
  826. $out .= '<option value="'.$row['rowid'].'">';
  827. }
  828. if ($row['code']) $out .= $row['code'];
  829. $out .= '</option>';
  830. }
  831. }
  832. $out .= '</select>';
  833. $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
  834. if (!empty($page))
  835. {
  836. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
  837. }
  838. } else {
  839. dol_print_error($this->db);
  840. }
  841. return $out;
  842. }
  843. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  844. /**
  845. * Return list of types of lines (product or service)
  846. * Example: 0=product, 1=service, 9=other (for external module)
  847. *
  848. * @param string $selected Preselected type
  849. * @param string $htmlname Name of field in html form
  850. * @param int $showempty Add an empty field
  851. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  852. * @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')
  853. * @return void
  854. */
  855. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  856. {
  857. // phpcs:enable
  858. global $db, $langs, $user, $conf;
  859. // If product & services are enabled or both disabled.
  860. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  861. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)))
  862. {
  863. if (empty($hidetext)) print $langs->trans("Type").': ';
  864. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  865. if ($showempty)
  866. {
  867. print '<option value="-1"';
  868. if ($selected == -1) print ' selected';
  869. print '>&nbsp;</option>';
  870. }
  871. print '<option value="0"';
  872. if (0 == $selected) print ' selected';
  873. print '>'.$langs->trans("Product");
  874. print '<option value="1"';
  875. if (1 == $selected) print ' selected';
  876. print '>'.$langs->trans("Service");
  877. print '</select>';
  878. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  879. }
  880. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3)
  881. {
  882. print $langs->trans("Service");
  883. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  884. }
  885. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
  886. {
  887. print $langs->trans("Product");
  888. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  889. }
  890. if ($forceall < 0) // This should happened only for contracts when both predefined product and service are disabled.
  891. {
  892. 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
  893. }
  894. }
  895. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  896. /**
  897. * Load into cache cache_types_fees, array of types of fees
  898. *
  899. * @return int Nb of lines loaded, <0 if KO
  900. */
  901. public function load_cache_types_fees()
  902. {
  903. // phpcs:enable
  904. global $langs;
  905. $num = count($this->cache_types_fees);
  906. if ($num > 0) return 0; // Cache already loaded
  907. dol_syslog(__METHOD__, LOG_DEBUG);
  908. $langs->load("trips");
  909. $sql = "SELECT c.code, c.label";
  910. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  911. $sql .= " WHERE active > 0";
  912. $resql = $this->db->query($sql);
  913. if ($resql)
  914. {
  915. $num = $this->db->num_rows($resql);
  916. $i = 0;
  917. while ($i < $num)
  918. {
  919. $obj = $this->db->fetch_object($resql);
  920. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  921. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  922. $this->cache_types_fees[$obj->code] = $label;
  923. $i++;
  924. }
  925. asort($this->cache_types_fees);
  926. return $num;
  927. } else {
  928. dol_print_error($this->db);
  929. return -1;
  930. }
  931. }
  932. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  933. /**
  934. * Return list of types of notes
  935. *
  936. * @param string $selected Preselected type
  937. * @param string $htmlname Name of field in form
  938. * @param int $showempty Add an empty field
  939. * @return void
  940. */
  941. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  942. {
  943. // phpcs:enable
  944. global $user, $langs;
  945. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  946. $this->load_cache_types_fees();
  947. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  948. if ($showempty)
  949. {
  950. print '<option value="-1"';
  951. if ($selected == -1) print ' selected';
  952. print '>&nbsp;</option>';
  953. }
  954. foreach ($this->cache_types_fees as $key => $value)
  955. {
  956. print '<option value="'.$key.'"';
  957. if ($key == $selected) print ' selected';
  958. print '>';
  959. print $value;
  960. print '</option>';
  961. }
  962. print '</select>';
  963. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  964. }
  965. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  966. /**
  967. * Return HTML code to select a company.
  968. *
  969. * @param int $selected Preselected products
  970. * @param string $htmlname Name of HTML select field (must be unique in page)
  971. * @param int $filter Filter on thirdparty
  972. * @param int $limit Limit on number of returned lines
  973. * @param array $ajaxoptions Options for ajax_autocompleter
  974. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  975. * @return string Return select box for thirdparty.
  976. * @deprecated 3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
  977. */
  978. public function select_thirdparty($selected = '', $htmlname = 'socid', $filter = '', $limit = 20, $ajaxoptions = array(), $forcecombo = 0)
  979. {
  980. // phpcs:enable
  981. return $this->select_thirdparty_list($selected, $htmlname, $filter, 1, 0, $forcecombo, array(), '', 0, $limit);
  982. }
  983. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  984. /**
  985. * Output html form to select a third party
  986. *
  987. * @param string $selected Preselected type
  988. * @param string $htmlname Name of field in form
  989. * @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)')
  990. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  991. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  992. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  993. * @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')))
  994. * @param int $limit Maximum number of elements
  995. * @param string $morecss Add more css styles to the SELECT component
  996. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  997. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  998. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  999. * @param array $ajaxoptions Options for ajax_autocompleter
  1000. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1001. * @return string HTML string with select box for thirdparty.
  1002. */
  1003. 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)
  1004. {
  1005. // phpcs:enable
  1006. global $conf, $user, $langs;
  1007. $out = '';
  1008. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo)
  1009. {
  1010. // No immediate load of all database
  1011. $placeholder = '';
  1012. if ($selected && empty($selected_input_value))
  1013. {
  1014. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1015. $societetmp = new Societe($this->db);
  1016. $societetmp->fetch($selected);
  1017. $selected_input_value = $societetmp->name;
  1018. unset($societetmp);
  1019. }
  1020. // mode 1
  1021. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&filter='.urlencode($filter).($showtype ? '&showtype='.urlencode($showtype) : '');
  1022. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1023. $out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  1024. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1025. elseif ($hidelabel > 1) {
  1026. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  1027. if ($hidelabel == 2) {
  1028. $out .= img_picto($langs->trans("Search"), 'search');
  1029. }
  1030. }
  1031. $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1032. if ($hidelabel == 3) {
  1033. $out .= img_picto($langs->trans("Search"), 'search');
  1034. }
  1035. } else {
  1036. // Immediate load of all database
  1037. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
  1038. }
  1039. return $out;
  1040. }
  1041. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1042. /**
  1043. * Output html form to select a third party.
  1044. * 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.
  1045. *
  1046. * @param string $selected Preselected type
  1047. * @param string $htmlname Name of field in form
  1048. * @param string $filter Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
  1049. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1050. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1051. * @param int $forcecombo Force to use standard HTML select component without beautification
  1052. * @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')))
  1053. * @param string $filterkey Filter on key value
  1054. * @param int $outputmode 0=HTML select string, 1=Array
  1055. * @param int $limit Limit number of answers
  1056. * @param string $morecss Add more css styles to the SELECT component
  1057. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1058. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1059. * @return string HTML string with
  1060. */
  1061. 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)
  1062. {
  1063. // phpcs:enable
  1064. global $conf, $user, $langs;
  1065. $out = '';
  1066. $num = 0;
  1067. $outarray = array();
  1068. if ($selected === '') $selected = array();
  1069. elseif (!is_array($selected)) $selected = array($selected);
  1070. // Clean $filter that may contains sql conditions so sql code
  1071. if (function_exists('testSqlAndScriptInject')) {
  1072. if (testSqlAndScriptInject($filter, 3) > 0) {
  1073. $filter = '';
  1074. }
  1075. }
  1076. // On recherche les societes
  1077. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1078. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1079. $sql .= ", s.address, s.zip, s.town";
  1080. $sql .= ", dictp.code as country_code";
  1081. }
  1082. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  1083. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1084. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1085. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
  1086. }
  1087. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1088. if (!empty($user->socid)) $sql .= " AND s.rowid = ".$user->socid;
  1089. if ($filter) $sql .= " AND (".$filter.")";
  1090. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
  1091. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND s.status <> 0";
  1092. // Add criteria
  1093. if ($filterkey && $filterkey != '')
  1094. {
  1095. $sql .= " AND (";
  1096. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1097. // For natural search
  1098. $scrit = explode(' ', $filterkey);
  1099. $i = 0;
  1100. if (count($scrit) > 1) $sql .= "(";
  1101. foreach ($scrit as $crit) {
  1102. if ($i > 0) $sql .= " AND ";
  1103. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1104. $i++;
  1105. }
  1106. if (count($scrit) > 1) $sql .= ")";
  1107. if (!empty($conf->barcode->enabled))
  1108. {
  1109. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1110. }
  1111. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1112. $sql .= ")";
  1113. }
  1114. $sql .= $this->db->order("nom", "ASC");
  1115. $sql .= $this->db->plimit($limit, 0);
  1116. // Build output string
  1117. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1118. $resql = $this->db->query($sql);
  1119. if ($resql)
  1120. {
  1121. if (!$forcecombo)
  1122. {
  1123. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1124. $out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
  1125. }
  1126. // Construct $out and $outarray
  1127. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1128. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1129. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
  1130. {
  1131. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1132. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1133. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  1134. else $textifempty .= $langs->trans("All");
  1135. }
  1136. if ($showempty) $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  1137. $num = $this->db->num_rows($resql);
  1138. $i = 0;
  1139. if ($num)
  1140. {
  1141. while ($i < $num)
  1142. {
  1143. $obj = $this->db->fetch_object($resql);
  1144. $label = '';
  1145. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1146. if (($obj->client) && (!empty($obj->code_client))) {
  1147. $label = $obj->code_client.' - ';
  1148. }
  1149. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1150. $label .= $obj->code_fournisseur.' - ';
  1151. }
  1152. $label .= ' '.$obj->name;
  1153. } else {
  1154. $label = $obj->name;
  1155. }
  1156. if (!empty($obj->name_alias)) {
  1157. $label .= ' ('.$obj->name_alias.')';
  1158. }
  1159. if ($showtype)
  1160. {
  1161. if ($obj->client || $obj->fournisseur) $label .= ' (';
  1162. if ($obj->client == 1 || $obj->client == 3) $label .= $langs->trans("Customer");
  1163. if ($obj->client == 2 || $obj->client == 3) $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1164. if ($obj->fournisseur) $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1165. if ($obj->client || $obj->fournisseur) $label .= ')';
  1166. }
  1167. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1168. $label .= '-'.$obj->address.'-'.$obj->zip.' '.$obj->town;
  1169. if (!empty($obj->country_code)) {
  1170. $label .= ' '.$langs->trans('Country'.$obj->country_code);
  1171. }
  1172. }
  1173. if (empty($outputmode))
  1174. {
  1175. if (in_array($obj->rowid, $selected))
  1176. {
  1177. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1178. } else {
  1179. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1180. }
  1181. } else {
  1182. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1183. }
  1184. $i++;
  1185. if (($i % 10) == 0) $out .= "\n";
  1186. }
  1187. }
  1188. $out .= '</select>'."\n";
  1189. } else {
  1190. dol_print_error($this->db);
  1191. }
  1192. $this->result = array('nbofthirdparties'=>$num);
  1193. if ($outputmode) return $outarray;
  1194. return $out;
  1195. }
  1196. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1197. /**
  1198. * Return HTML combo list of absolute discounts
  1199. *
  1200. * @param string $selected Id remise fixe pre-selectionnee
  1201. * @param string $htmlname Nom champ formulaire
  1202. * @param string $filter Criteres optionnels de filtre
  1203. * @param int $socid Id of thirdparty
  1204. * @param int $maxvalue Max value for lines that can be selected
  1205. * @return int Return number of qualifed lines in list
  1206. */
  1207. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1208. {
  1209. // phpcs:enable
  1210. global $langs, $conf;
  1211. // On recherche les remises
  1212. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1213. $sql .= " re.description, re.fk_facture_source";
  1214. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  1215. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1216. $sql .= " AND re.entity = ".$conf->entity;
  1217. if ($filter) $sql .= " AND ".$filter;
  1218. $sql .= " ORDER BY re.description ASC";
  1219. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1220. $resql = $this->db->query($sql);
  1221. if ($resql)
  1222. {
  1223. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1224. $num = $this->db->num_rows($resql);
  1225. $qualifiedlines = $num;
  1226. $i = 0;
  1227. if ($num)
  1228. {
  1229. print '<option value="0">&nbsp;</option>';
  1230. while ($i < $num)
  1231. {
  1232. $obj = $this->db->fetch_object($resql);
  1233. $desc = dol_trunc($obj->description, 40);
  1234. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1235. if (preg_match('/\(DEPOSIT\)/', $desc)) $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1236. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1237. if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1238. $selectstring = '';
  1239. if ($selected > 0 && $selected == $obj->rowid) $selectstring = ' selected';
  1240. $disabled = '';
  1241. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  1242. {
  1243. $qualifiedlines--;
  1244. $disabled = ' disabled';
  1245. }
  1246. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
  1247. {
  1248. $tmpfac = new Facture($this->db);
  1249. if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc = $desc.' - '.$tmpfac->ref;
  1250. }
  1251. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1252. $i++;
  1253. }
  1254. }
  1255. print '</select>';
  1256. return $qualifiedlines;
  1257. } else {
  1258. dol_print_error($this->db);
  1259. return -1;
  1260. }
  1261. }
  1262. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1263. /**
  1264. * Return list of all contacts (for a third party or all)
  1265. *
  1266. * @param int $socid Id ot third party or 0 for all
  1267. * @param string $selected Id contact pre-selectionne
  1268. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1269. * @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
  1270. * @param string $exclude List of contacts id to exclude
  1271. * @param string $limitto Disable answers that are not id in this array list
  1272. * @param integer $showfunction Add function into label
  1273. * @param string $moreclass Add more class to class style
  1274. * @param integer $showsoc Add company into label
  1275. * @param int $forcecombo Force to use combo box
  1276. * @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')))
  1277. * @param bool $options_only Return options only (for ajax treatment)
  1278. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1279. * @param string $htmlid Html id to use instead of htmlname
  1280. * @return int <0 if KO, Nb of contact in list if OK
  1281. * @deprected You can use selectcontacts directly (warning order of param was changed)
  1282. */
  1283. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1284. {
  1285. // phpcs:enable
  1286. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1287. return $this->num;
  1288. }
  1289. /**
  1290. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1291. * This also set the number of contacts found into $this->num
  1292. *
  1293. * @since 9.0 Add afterSelectContactOptions hook
  1294. *
  1295. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1296. * @param array|int $selected Array of ID of pre-selected contact id
  1297. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1298. * @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
  1299. * @param string $exclude List of contacts id to exclude
  1300. * @param string $limitto Disable answers that are not id in this array list
  1301. * @param integer $showfunction Add function into label
  1302. * @param string $moreclass Add more class to class style
  1303. * @param bool $options_only Return options only (for ajax treatment)
  1304. * @param integer $showsoc Add company into label
  1305. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1306. * @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')))
  1307. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1308. * @param string $htmlid Html id to use instead of htmlname
  1309. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1310. * @return int <0 if KO, Nb of contact in list if OK
  1311. */
  1312. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false)
  1313. {
  1314. global $conf, $langs, $hookmanager, $action;
  1315. $langs->load('companies');
  1316. if (empty($htmlid)) $htmlid = $htmlname;
  1317. if ($selected === '') $selected = array();
  1318. elseif (!is_array($selected)) $selected = array($selected);
  1319. $out = '';
  1320. if (!is_object($hookmanager))
  1321. {
  1322. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1323. $hookmanager = new HookManager($this->db);
  1324. }
  1325. // We search third parties
  1326. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
  1327. if ($showsoc > 0) $sql .= " , s.nom as company";
  1328. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
  1329. if ($showsoc > 0) $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=sp.fk_soc";
  1330. $sql .= " WHERE sp.entity IN (".getEntity('socpeople').")";
  1331. if ($socid > 0 || $socid == -1) $sql .= " AND sp.fk_soc=".$socid;
  1332. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND sp.statut <> 0";
  1333. $sql .= " ORDER BY sp.lastname ASC";
  1334. dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
  1335. $resql = $this->db->query($sql);
  1336. if ($resql)
  1337. {
  1338. $num = $this->db->num_rows($resql);
  1339. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only)
  1340. {
  1341. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1342. $out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
  1343. }
  1344. if ($htmlname != 'none' && !$options_only) $out .= '<select class="flat'.($moreclass ? ' '.$moreclass : '').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1345. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1346. if ($showempty == 2) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1347. $num = $this->db->num_rows($resql);
  1348. $i = 0;
  1349. if ($num)
  1350. {
  1351. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1352. $contactstatic = new Contact($this->db);
  1353. while ($i < $num)
  1354. {
  1355. $obj = $this->db->fetch_object($resql);
  1356. $contactstatic->id = $obj->rowid;
  1357. $contactstatic->lastname = $obj->lastname;
  1358. $contactstatic->firstname = $obj->firstname;
  1359. if ($obj->statut == 1) {
  1360. if ($htmlname != 'none')
  1361. {
  1362. $disabled = 0;
  1363. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) $disabled = 1;
  1364. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) $disabled = 1;
  1365. if (!empty($selected) && in_array($obj->rowid, $selected))
  1366. {
  1367. $out .= '<option value="'.$obj->rowid.'"';
  1368. if ($disabled) $out .= ' disabled';
  1369. $out .= ' selected>';
  1370. $out .= $contactstatic->getFullName($langs);
  1371. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1372. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1373. $out .= '</option>';
  1374. } else {
  1375. $out .= '<option value="'.$obj->rowid.'"';
  1376. if ($disabled) $out .= ' disabled';
  1377. $out .= '>';
  1378. $out .= $contactstatic->getFullName($langs);
  1379. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1380. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1381. $out .= '</option>';
  1382. }
  1383. } else {
  1384. if (in_array($obj->rowid, $selected))
  1385. {
  1386. $out .= $contactstatic->getFullName($langs);
  1387. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1388. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1389. }
  1390. }
  1391. }
  1392. $i++;
  1393. }
  1394. } else {
  1395. $out .= '<option value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled>';
  1396. $out .= ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1397. $out .= '</option>';
  1398. }
  1399. $parameters = array(
  1400. 'socid'=>$socid,
  1401. 'htmlname'=>$htmlname,
  1402. 'resql'=>$resql,
  1403. 'out'=>&$out,
  1404. 'showfunction'=>$showfunction,
  1405. 'showsoc'=>$showsoc,
  1406. );
  1407. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1408. if ($htmlname != 'none' && !$options_only)
  1409. {
  1410. $out .= '</select>';
  1411. }
  1412. $this->num = $num;
  1413. return $out;
  1414. } else {
  1415. dol_print_error($this->db);
  1416. return -1;
  1417. }
  1418. }
  1419. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1420. /**
  1421. * Return the HTML select list of users
  1422. *
  1423. * @param string $selected Id user preselected
  1424. * @param string $htmlname Field name in form
  1425. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1426. * @param array $exclude Array list of users id to exclude
  1427. * @param int $disabled If select list must be disabled
  1428. * @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
  1429. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1430. * @param string $force_entity '0' or Ids of environment to force
  1431. * @return void
  1432. * @deprecated Use select_dolusers instead
  1433. * @see select_dolusers()
  1434. */
  1435. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1436. {
  1437. // phpcs:enable
  1438. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1439. }
  1440. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1441. /**
  1442. * Return select list of users
  1443. *
  1444. * @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)
  1445. * @param string $htmlname Field name in form
  1446. * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list
  1447. * @param array $exclude Array list of users id to exclude
  1448. * @param int $disabled If select list must be disabled
  1449. * @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
  1450. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1451. * @param string $force_entity '0' or Ids of environment to force
  1452. * @param int $maxlength Maximum length of string into list (0=no limit)
  1453. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1454. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1')
  1455. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1456. * @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.
  1457. * @param string $morecss More css
  1458. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1459. * @param int $outputmode 0=HTML select string, 1=Array
  1460. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1461. * @return string HTML select string
  1462. * @see select_dolgroups()
  1463. */
  1464. 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)
  1465. {
  1466. // phpcs:enable
  1467. global $conf, $user, $langs, $hookmanager;
  1468. // If no preselected user defined, we take current user
  1469. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected = $user->id;
  1470. if ($selected === '') $selected = array();
  1471. elseif (!is_array($selected)) $selected = array($selected);
  1472. $excludeUsers = null;
  1473. $includeUsers = null;
  1474. // Permettre l'exclusion d'utilisateurs
  1475. if (is_array($exclude)) $excludeUsers = implode(",", $exclude);
  1476. // Permettre l'inclusion d'utilisateurs
  1477. if (is_array($include)) $includeUsers = implode(",", $include);
  1478. elseif ($include == 'hierarchy')
  1479. {
  1480. // Build list includeUsers to have only hierarchy
  1481. $includeUsers = implode(",", $user->getAllChildIds(0));
  1482. } elseif ($include == 'hierarchyme')
  1483. {
  1484. // Build list includeUsers to have only hierarchy and current user
  1485. $includeUsers = implode(",", $user->getAllChildIds(1));
  1486. }
  1487. $out = '';
  1488. $outarray = array();
  1489. // Forge request to select users
  1490. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
  1491. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  1492. {
  1493. $sql .= ", e.label";
  1494. }
  1495. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  1496. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  1497. {
  1498. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=u.entity";
  1499. if ($force_entity) $sql .= " WHERE u.entity IN (0,".$force_entity.")";
  1500. else $sql .= " WHERE u.entity IS NOT NULL";
  1501. } else {
  1502. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
  1503. {
  1504. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1505. $sql .= " ON ug.fk_user = u.rowid";
  1506. $sql .= " WHERE ug.entity = ".$conf->entity;
  1507. } else {
  1508. $sql .= " WHERE u.entity IN (0,".$conf->entity.")";
  1509. }
  1510. }
  1511. if (!empty($user->socid)) $sql .= " AND u.fk_soc = ".$user->socid;
  1512. if (is_array($exclude) && $excludeUsers) $sql .= " AND u.rowid NOT IN (".$excludeUsers.")";
  1513. if ($includeUsers) $sql .= " AND u.rowid IN (".$includeUsers.")";
  1514. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql .= " AND u.statut <> 0";
  1515. if (!empty($morefilter)) $sql .= " ".$morefilter;
  1516. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1517. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1518. if (!empty($reshook)) $sql .= $hookmanager->resPrint;
  1519. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1520. {
  1521. $sql .= " ORDER BY u.firstname ASC";
  1522. } else {
  1523. $sql .= " ORDER BY u.lastname ASC";
  1524. }
  1525. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1526. $resql = $this->db->query($sql);
  1527. if ($resql)
  1528. {
  1529. $num = $this->db->num_rows($resql);
  1530. $i = 0;
  1531. if ($num)
  1532. {
  1533. // Enhance with select2
  1534. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1535. $out .= ajax_combobox($htmlname);
  1536. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1537. $out .= '<select class="flat'.($morecss ? ' minwidth100imp '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1538. if ($show_empty && !$multiple) $out .= '<option value="-1"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>&nbsp;</option>'."\n";
  1539. if ($show_every) $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1540. $userstatic = new User($this->db);
  1541. while ($i < $num)
  1542. {
  1543. $obj = $this->db->fetch_object($resql);
  1544. $userstatic->id = $obj->rowid;
  1545. $userstatic->lastname = $obj->lastname;
  1546. $userstatic->firstname = $obj->firstname;
  1547. $disableline = '';
  1548. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = ($enableonlytext ? $enableonlytext : '1');
  1549. $labeltoshow = '';
  1550. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1551. $fullNameMode = 0;
  1552. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
  1553. {
  1554. $fullNameMode = 1; //Firstname+lastname
  1555. }
  1556. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1557. // Complete name with more info
  1558. $moreinfo = '';
  1559. if (!empty($conf->global->MAIN_SHOW_LOGIN))
  1560. {
  1561. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1562. }
  1563. if ($showstatus >= 0)
  1564. {
  1565. if ($obj->statut == 1 && $showstatus == 1)
  1566. {
  1567. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1568. }
  1569. if ($obj->statut == 0 && $showstatus == 1)
  1570. {
  1571. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1572. }
  1573. }
  1574. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity)
  1575. {
  1576. if (!$obj->entity)
  1577. {
  1578. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1579. } else {
  1580. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1581. }
  1582. }
  1583. $moreinfo .= ($moreinfo ? ')' : '');
  1584. if ($disableline && $disableline != '1')
  1585. {
  1586. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1587. }
  1588. $labeltoshow .= $moreinfo;
  1589. $out .= '<option value="'.$obj->rowid.'"';
  1590. if ($disableline) $out .= ' disabled';
  1591. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1592. $out .= ' selected';
  1593. }
  1594. if ($showstatus >= 0 && $obj->statut == 0) {
  1595. $out .= ' data-html="'.dol_escape_htmltag('<strike class="opacitymediumxxx">'.$labeltoshow.'</strike>').'"';
  1596. }
  1597. $out .= '>';
  1598. $out .= $labeltoshow;
  1599. $out .= '</option>';
  1600. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1601. $i++;
  1602. }
  1603. } else {
  1604. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1605. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1606. }
  1607. $out .= '</select>';
  1608. } else {
  1609. dol_print_error($this->db);
  1610. }
  1611. if ($outputmode) return $outarray;
  1612. return $out;
  1613. }
  1614. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1615. /**
  1616. * Return select list of users. Selected users are stored into session.
  1617. * List of users are provided into $_SESSION['assignedtouser'].
  1618. *
  1619. * @param string $action Value for $action
  1620. * @param string $htmlname Field name in form
  1621. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1622. * @param array $exclude Array list of users id to exclude
  1623. * @param int $disabled If select list must be disabled
  1624. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1625. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1626. * @param int $force_entity '0' or Ids of environment to force
  1627. * @param int $maxlength Maximum length of string into list (0=no limit)
  1628. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1629. * @param string $morefilter Add more filters into sql request
  1630. * @param int $showproperties Show properties of each attendees
  1631. * @param array $listofuserid Array with properties of each user
  1632. * @param array $listofcontactid Array with properties of each contact
  1633. * @param array $listofotherid Array with properties of each other contact
  1634. * @return string HTML select string
  1635. * @see select_dolgroups()
  1636. */
  1637. 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())
  1638. {
  1639. // phpcs:enable
  1640. global $conf, $user, $langs;
  1641. $userstatic = new User($this->db);
  1642. $out = '';
  1643. $assignedtouser = array();
  1644. if (!empty($_SESSION['assignedtouser']))
  1645. {
  1646. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1647. }
  1648. $nbassignetouser = count($assignedtouser);
  1649. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1650. if ($nbassignetouser) $out .= '<ul class="attendees">';
  1651. $i = 0; $ownerid = 0;
  1652. foreach ($assignedtouser as $key => $value)
  1653. {
  1654. if ($value['id'] == $ownerid) continue;
  1655. $out .= '<li>';
  1656. $userstatic->fetch($value['id']);
  1657. $out .= $userstatic->getNomUrl(-1);
  1658. if ($i == 0) { $ownerid = $value['id']; $out .= ' ('.$langs->trans("Owner").')'; }
  1659. if ($nbassignetouser > 1 && $action != 'view')
  1660. {
  1661. $out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
  1662. }
  1663. // Show my availability
  1664. if ($showproperties)
  1665. {
  1666. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
  1667. {
  1668. $out .= '<div class="myavailability inline-block">';
  1669. $out .= '&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span> <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view' ? 'disabled' : '').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency'] ? ' checked' : '').'>'.$langs->trans("Busy");
  1670. $out .= '</div>';
  1671. }
  1672. }
  1673. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1674. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1675. $out .= '</li>';
  1676. $i++;
  1677. }
  1678. if ($nbassignetouser) $out .= '</ul>';
  1679. // Method with no ajax
  1680. if ($action != 'view')
  1681. {
  1682. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1683. $out .= '<script type="text/javascript" language="javascript">jQuery(document).ready(function () { jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });})</script>';
  1684. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1685. $out .= ' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1686. $out .= '<br>';
  1687. }
  1688. return $out;
  1689. }
  1690. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1691. /**
  1692. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1693. *
  1694. * @param int $selected Preselected products
  1695. * @param string $htmlname Name of HTML select field (must be unique in page)
  1696. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1697. * @param int $limit Limit on number of returned lines
  1698. * @param int $price_level Level of price to show
  1699. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1700. * @param int $finished 2=all, 1=finished, 0=raw material
  1701. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1702. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1703. * @param array $ajaxoptions Options for ajax_autocompleter
  1704. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1705. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1706. * @param int $forcecombo Force to use combo box
  1707. * @param string $morecss Add more css on select
  1708. * @param int $hidepriceinlabel 1=Hide prices in label
  1709. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  1710. * 'warehouseopen' = count products from open warehouses,
  1711. * 'warehouseclosed' = count products from closed warehouses,
  1712. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  1713. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  1714. * @param string $nooutput No print, return the output into a string
  1715. * @return void|string
  1716. */
  1717. public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $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 = array(), $nooutput = 0)
  1718. {
  1719. // phpcs:enable
  1720. global $langs, $conf;
  1721. $out = '';
  1722. // check parameters
  1723. $price_level = (!empty($price_level) ? $price_level : 0);
  1724. if (is_null($ajaxoptions)) $ajaxoptions = array();
  1725. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  1726. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  1727. $filtertype = '0';
  1728. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  1729. $filtertype = '1';
  1730. }
  1731. }
  1732. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1733. {
  1734. $placeholder = '';
  1735. if ($selected && empty($selected_input_value))
  1736. {
  1737. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1738. $producttmpselect = new Product($this->db);
  1739. $producttmpselect->fetch($selected);
  1740. $selected_input_value = $producttmpselect->ref;
  1741. unset($producttmpselect);
  1742. }
  1743. // handle case where product or service module is disabled + no filter specified
  1744. if ($filtertype == '')
  1745. {
  1746. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  1747. $filtertype = 1;
  1748. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  1749. $filtertype = 0;
  1750. }
  1751. }
  1752. // mode=1 means customers products
  1753. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  1754. //Price by customer
  1755. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1756. $urloption .= '&socid='.$socid;
  1757. }
  1758. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1759. if (!empty($conf->variants->enabled)) {
  1760. $out .= '
  1761. <script>
  1762. selected = '.json_encode($selected_combinations).';
  1763. combvalues = {};
  1764. jQuery(document).ready(function () {
  1765. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  1766. if (jQuery(this).val() == \'free\') {
  1767. jQuery(\'div#attributes_box\').empty();
  1768. }
  1769. });
  1770. jQuery("input#'.$htmlname.'").change(function () {
  1771. if (!jQuery(this).val()) {
  1772. jQuery(\'div#attributes_box\').empty();
  1773. return;
  1774. }
  1775. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  1776. id: jQuery(this).val()
  1777. }, function (data) {
  1778. jQuery(\'div#attributes_box\').empty();
  1779. jQuery.each(data, function (key, val) {
  1780. combvalues[val.id] = val.values;
  1781. var span = jQuery(document.createElement(\'div\')).css({
  1782. \'display\': \'table-row\'
  1783. });
  1784. span.append(
  1785. jQuery(document.createElement(\'div\')).text(val.label).css({
  1786. \'font-weight\': \'bold\',
  1787. \'display\': \'table-cell\',
  1788. \'text-align\': \'right\'
  1789. })
  1790. );
  1791. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  1792. \'margin-left\': \'15px\',
  1793. \'white-space\': \'pre\'
  1794. }).append(
  1795. jQuery(document.createElement(\'option\')).val(\'\')
  1796. );
  1797. jQuery.each(combvalues[val.id], function (key, val) {
  1798. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  1799. if (selected[val.fk_product_attribute] == val.id) {
  1800. tag.attr(\'selected\', \'selected\');
  1801. }
  1802. html.append(tag);
  1803. });
  1804. span.append(html);
  1805. jQuery(\'div#attributes_box\').append(span);
  1806. });
  1807. })
  1808. });
  1809. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  1810. });
  1811. </script>
  1812. ';
  1813. }
  1814. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  1815. elseif ($hidelabel > 1) {
  1816. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  1817. if ($hidelabel == 2) {
  1818. $out .= img_picto($langs->trans("Search"), 'search');
  1819. }
  1820. }
  1821. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1822. if ($hidelabel == 3) {
  1823. $out .= img_picto($langs->trans("Search"), 'search');
  1824. }
  1825. } else {
  1826. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus);
  1827. }
  1828. if (empty($nooutput)) print $out;
  1829. else return $out;
  1830. }
  1831. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1832. /**
  1833. * Return list of products for a customer.
  1834. * Called by select_produits.
  1835. *
  1836. * @param int $selected Preselected product
  1837. * @param string $htmlname Name of select html
  1838. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1839. * @param int $limit Limit on number of returned lines
  1840. * @param int $price_level Level of price to show
  1841. * @param string $filterkey Filter on product
  1842. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1843. * @param int $finished Filter on finished field: 2=No filter
  1844. * @param int $outputmode 0=HTML select string, 1=Array
  1845. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1846. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1847. * @param int $forcecombo Force to use combo box
  1848. * @param string $morecss Add more css on select
  1849. * @param int $hidepriceinlabel 1=Hide prices in label
  1850. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  1851. * 'warehouseopen' = count products from open warehouses,
  1852. * 'warehouseclosed' = count products from closed warehouses,
  1853. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  1854. * @return array Array of keys for json
  1855. */
  1856. 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 = '')
  1857. {
  1858. // phpcs:enable
  1859. global $langs, $conf, $user, $db;
  1860. $out = '';
  1861. $outarray = array();
  1862. // Units
  1863. if ($conf->global->PRODUCT_USE_UNITS) {
  1864. $langs->load('other');
  1865. }
  1866. $warehouseStatusArray = array();
  1867. if (!empty($warehouseStatus))
  1868. {
  1869. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  1870. if (preg_match('/warehouseclosed/', $warehouseStatus))
  1871. {
  1872. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  1873. }
  1874. if (preg_match('/warehouseopen/', $warehouseStatus))
  1875. {
  1876. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  1877. }
  1878. if (preg_match('/warehouseinternal/', $warehouseStatus))
  1879. {
  1880. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  1881. }
  1882. }
  1883. $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.duration, p.fk_price_expression";
  1884. if (count($warehouseStatusArray))
  1885. {
  1886. $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
  1887. } else {
  1888. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  1889. }
  1890. $sql = "SELECT ";
  1891. $sql .= $selectFields.$selectFieldsGrouped;
  1892. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
  1893. {
  1894. //Product category
  1895. $sql .= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
  1896. FROM ".MAIN_DB_PREFIX."categorie_product
  1897. WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
  1898. LIMIT 1
  1899. ) AS categorie_product_id ";
  1900. }
  1901. //Price by customer
  1902. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
  1903. {
  1904. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  1905. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
  1906. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
  1907. }
  1908. // Units
  1909. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1910. $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";
  1911. $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';
  1912. }
  1913. // Multilang : we add translation
  1914. if (!empty($conf->global->MAIN_MULTILANGS))
  1915. {
  1916. $sql .= ", pl.label as label_translated";
  1917. $selectFields .= ", label_translated";
  1918. }
  1919. // Price by quantity
  1920. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
  1921. {
  1922. $sql .= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1923. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
  1924. $sql .= " ORDER BY date_price";
  1925. $sql .= " DESC LIMIT 1) as price_rowid";
  1926. $sql .= ", (SELECT pp.price_by_qty FROM ".MAIN_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
  1927. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
  1928. $sql .= " ORDER BY date_price";
  1929. $sql .= " DESC LIMIT 1) as price_by_qty";
  1930. $selectFields .= ", price_rowid, price_by_qty";
  1931. }
  1932. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  1933. if (count($warehouseStatusArray))
  1934. {
  1935. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  1936. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  1937. $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.
  1938. }
  1939. // include search in supplier ref
  1940. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
  1941. {
  1942. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  1943. }
  1944. //Price by customer
  1945. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1946. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
  1947. }
  1948. // Units
  1949. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1950. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  1951. }
  1952. // Multilang : we add translation
  1953. if (!empty($conf->global->MAIN_MULTILANGS))
  1954. {
  1955. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='".$this->db->escape($langs->getDefaultLang())."'";
  1956. }
  1957. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1958. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  1959. }
  1960. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  1961. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1962. $sql .= " AND pac.rowid IS NULL";
  1963. }
  1964. if ($finished == 0)
  1965. {
  1966. $sql .= " AND p.finished = ".$finished;
  1967. } elseif ($finished == 1)
  1968. {
  1969. $sql .= " AND p.finished = ".$finished;
  1970. if ($status >= 0) $sql .= " AND p.tosell = ".$status;
  1971. } elseif ($status >= 0)
  1972. {
  1973. $sql .= " AND p.tosell = ".$status;
  1974. }
  1975. // Filter by product type
  1976. if (strval($filtertype) != '') $sql .= " AND p.fk_product_type = ".$filtertype;
  1977. elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  1978. $sql .= " AND p.fk_product_type = 1";
  1979. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  1980. $sql .= " AND p.fk_product_type = 0";
  1981. }
  1982. // Add criteria on ref/label
  1983. if ($filterkey != '')
  1984. {
  1985. $sql .= ' AND (';
  1986. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  1987. // For natural search
  1988. $scrit = explode(' ', $filterkey);
  1989. $i = 0;
  1990. if (count($scrit) > 1) $sql .= "(";
  1991. foreach ($scrit as $crit)
  1992. {
  1993. if ($i > 0) $sql .= " AND ";
  1994. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  1995. if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  1996. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
  1997. {
  1998. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  1999. if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2000. }
  2001. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2002. $sql .= ")";
  2003. $i++;
  2004. }
  2005. if (count($scrit) > 1) $sql .= ")";
  2006. if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2007. $sql .= ')';
  2008. }
  2009. if (count($warehouseStatusArray))
  2010. {
  2011. $sql .= ' GROUP BY'.$selectFields;
  2012. }
  2013. //Sort by category
  2014. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
  2015. {
  2016. $sql .= " ORDER BY categorie_product_id ";
  2017. //ASC OR DESC order
  2018. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2019. } else {
  2020. $sql .= $this->db->order("p.ref");
  2021. }
  2022. $sql .= $this->db->plimit($limit, 0);
  2023. // Build output string
  2024. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2025. $result = $this->db->query($sql);
  2026. if ($result)
  2027. {
  2028. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2029. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2030. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2031. $num = $this->db->num_rows($result);
  2032. $events = null;
  2033. if (!$forcecombo)
  2034. {
  2035. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2036. $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  2037. }
  2038. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2039. $textifempty = '';
  2040. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2041. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2042. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2043. {
  2044. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  2045. else $textifempty .= $langs->trans("All");
  2046. } else {
  2047. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  2048. }
  2049. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  2050. $i = 0;
  2051. while ($num && $i < $num)
  2052. {
  2053. $opt = '';
  2054. $optJson = array();
  2055. $objp = $this->db->fetch_object($result);
  2056. 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)
  2057. { // Price by quantity will return many prices for the same product
  2058. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2059. $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  2060. $sql .= " WHERE fk_product_price=".$objp->price_rowid;
  2061. $sql .= " ORDER BY quantity ASC";
  2062. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2063. $result2 = $this->db->query($sql);
  2064. if ($result2)
  2065. {
  2066. $nb_prices = $this->db->num_rows($result2);
  2067. $j = 0;
  2068. while ($nb_prices && $j < $nb_prices) {
  2069. $objp2 = $this->db->fetch_object($result2);
  2070. $objp->price_by_qty_rowid = $objp2->rowid;
  2071. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2072. $objp->price_by_qty_quantity = $objp2->quantity;
  2073. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2074. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2075. // For backward compatibility
  2076. $objp->quantity = $objp2->quantity;
  2077. $objp->price = $objp2->price;
  2078. $objp->unitprice = $objp2->unitprice;
  2079. $objp->remise_percent = $objp2->remise_percent;
  2080. $objp->remise = $objp2->remise;
  2081. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2082. $j++;
  2083. // Add new entry
  2084. // "key" value of json key array is used by jQuery automatically as selected value
  2085. // "label" value of json key array is used by jQuery automatically as text for combo box
  2086. $out .= $opt;
  2087. array_push($outarray, $optJson);
  2088. }
  2089. }
  2090. } else {
  2091. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2092. $price_product = new Product($this->db);
  2093. $price_product->fetch($objp->rowid, '', '', 1);
  2094. $priceparser = new PriceParser($this->db);
  2095. $price_result = $priceparser->parseProduct($price_product);
  2096. if ($price_result >= 0) {
  2097. $objp->price = $price_result;
  2098. $objp->unitprice = $price_result;
  2099. //Calculate the VAT
  2100. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2101. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2102. }
  2103. }
  2104. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2105. // Add new entry
  2106. // "key" value of json key array is used by jQuery automatically as selected value
  2107. // "label" value of json key array is used by jQuery automatically as text for combo box
  2108. $out .= $opt;
  2109. array_push($outarray, $optJson);
  2110. }
  2111. $i++;
  2112. }
  2113. $out .= '</select>';
  2114. $this->db->free($result);
  2115. if (empty($outputmode)) return $out;
  2116. return $outarray;
  2117. } else {
  2118. dol_print_error($db);
  2119. }
  2120. }
  2121. /**
  2122. * constructProductListOption.
  2123. * This define value for &$opt and &$optJson.
  2124. *
  2125. * @param resource $objp Resultset of fetch
  2126. * @param string $opt Option (var used for returned value in string option format)
  2127. * @param string $optJson Option (var used for returned value in json format)
  2128. * @param int $price_level Price level
  2129. * @param string $selected Preselected value
  2130. * @param int $hidepriceinlabel Hide price in label
  2131. * @param string $filterkey Filter key to highlight
  2132. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2133. * @return void
  2134. */
  2135. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2136. {
  2137. global $langs, $conf, $user, $db;
  2138. $outkey = '';
  2139. $outval = '';
  2140. $outref = '';
  2141. $outlabel = '';
  2142. $outdesc = '';
  2143. $outbarcode = '';
  2144. $outorigin = '';
  2145. $outtype = '';
  2146. $outprice_ht = '';
  2147. $outprice_ttc = '';
  2148. $outpricebasetype = '';
  2149. $outtva_tx = '';
  2150. $outqty = 1;
  2151. $outdiscount = 0;
  2152. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2153. $label = $objp->label;
  2154. if (!empty($objp->label_translated)) $label = $objp->label_translated;
  2155. if (!empty($filterkey) && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2156. $outkey = $objp->rowid;
  2157. $outref = $objp->ref;
  2158. $outlabel = $objp->label;
  2159. $outdesc = $objp->description;
  2160. $outbarcode = $objp->barcode;
  2161. $outorigin = $objp->fk_country;
  2162. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2163. $outtype = $objp->fk_product_type;
  2164. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2165. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2166. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2167. // Units
  2168. $outvalUnits = '';
  2169. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2170. if (!empty($objp->unit_short)) {
  2171. $outvalUnits .= ' - '.$objp->unit_short;
  2172. }
  2173. }
  2174. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2175. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2176. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2177. $outvalUnits .= ' - '.$unitToShow;
  2178. }
  2179. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2180. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2181. $outvalUnits .= ' - '.$unitToShow;
  2182. }
  2183. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2184. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2185. $outvalUnits .= ' - '.$unitToShow;
  2186. }
  2187. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2188. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2189. $outvalUnits .= ' - '.$unitToShow;
  2190. }
  2191. }
  2192. if ($outdurationvalue && $outdurationunit) {
  2193. $da = array(
  2194. 'h' => $langs->trans('Hour'),
  2195. 'd' => $langs->trans('Day'),
  2196. 'w' => $langs->trans('Week'),
  2197. 'm' => $langs->trans('Month'),
  2198. 'y' => $langs->trans('Year')
  2199. );
  2200. if (isset($da[$outdurationunit])) {
  2201. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2202. }
  2203. }
  2204. $opt = '<option value="'.$objp->rowid.'"';
  2205. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2206. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
  2207. {
  2208. $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.'"';
  2209. }
  2210. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)))
  2211. {
  2212. if (!empty($user->rights->stock->lire)) {
  2213. if ($objp->stock > 0) $opt .= ' class="product_line_stock_ok"';
  2214. elseif ($objp->stock <= 0) $opt .= ' class="product_line_stock_too_low"';
  2215. }
  2216. }
  2217. $opt .= '>';
  2218. $opt .= $objp->ref;
  2219. if ($outbarcode) $opt .= ' ('.$outbarcode.')';
  2220. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2221. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) $opt .= ' ('.getCountry($outorigin, 1).')';
  2222. $objRef = $objp->ref;
  2223. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2224. $outval .= $objRef;
  2225. if ($outbarcode) $outval .= ' ('.$outbarcode.')';
  2226. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2227. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) $outval .= ' ('.getCountry($outorigin, 1).')';
  2228. // Units
  2229. $opt .= $outvalUnits;
  2230. $outval .= $outvalUnits;
  2231. $found = 0;
  2232. // Multiprice
  2233. // If we need a particular price level (from 1 to 6)
  2234. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
  2235. {
  2236. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  2237. $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
  2238. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2239. $sql .= " AND entity IN (".getEntity('productprice').")";
  2240. $sql .= " AND price_level = ".((int) $price_level);
  2241. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2242. $sql .= " LIMIT 1";
  2243. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2244. $result2 = $this->db->query($sql);
  2245. if ($result2)
  2246. {
  2247. $objp2 = $this->db->fetch_object($result2);
  2248. if ($objp2)
  2249. {
  2250. $found = 1;
  2251. if ($objp2->price_base_type == 'HT')
  2252. {
  2253. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2254. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2255. } else {
  2256. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2257. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2258. }
  2259. $outprice_ht = price($objp2->price);
  2260. $outprice_ttc = price($objp2->price_ttc);
  2261. $outpricebasetype = $objp2->price_base_type;
  2262. $outtva_tx = $objp2->tva_tx;
  2263. }
  2264. } else {
  2265. dol_print_error($this->db);
  2266. }
  2267. }
  2268. // Price by quantity
  2269. 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)))
  2270. {
  2271. $found = 1;
  2272. $outqty = $objp->quantity;
  2273. $outdiscount = $objp->remise_percent;
  2274. if ($objp->quantity == 1)
  2275. {
  2276. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2277. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2278. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2279. $outval .= $langs->transnoentities("Unit");
  2280. } else {
  2281. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2282. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2283. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2284. $outval .= $langs->transnoentities("Units");
  2285. }
  2286. $outprice_ht = price($objp->unitprice);
  2287. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2288. $outpricebasetype = $objp->price_base_type;
  2289. $outtva_tx = $objp->tva_tx;
  2290. }
  2291. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
  2292. {
  2293. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2294. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2295. }
  2296. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
  2297. {
  2298. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2299. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2300. }
  2301. // Price by customer
  2302. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  2303. {
  2304. if (!empty($objp->idprodcustprice))
  2305. {
  2306. $found = 1;
  2307. if ($objp->custprice_base_type == 'HT')
  2308. {
  2309. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2310. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2311. } else {
  2312. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2313. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2314. }
  2315. $outprice_ht = price($objp->custprice);
  2316. $outprice_ttc = price($objp->custprice_ttc);
  2317. $outpricebasetype = $objp->custprice_base_type;
  2318. $outtva_tx = $objp->custtva_tx;
  2319. }
  2320. }
  2321. // If level no defined or multiprice not found, we used the default price
  2322. if (empty($hidepriceinlabel) && !$found)
  2323. {
  2324. if ($objp->price_base_type == 'HT')
  2325. {
  2326. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2327. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2328. } else {
  2329. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2330. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2331. }
  2332. $outprice_ht = price($objp->price);
  2333. $outprice_ttc = price($objp->price_ttc);
  2334. $outpricebasetype = $objp->price_base_type;
  2335. $outtva_tx = $objp->tva_tx;
  2336. }
  2337. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)))
  2338. {
  2339. if (!empty($user->rights->stock->lire)) {
  2340. $opt .= ' - '.$langs->trans("Stock").':'.$objp->stock;
  2341. if ($objp->stock > 0) {
  2342. $outval .= ' - <span class="product_line_stock_ok">';
  2343. } elseif ($objp->stock <= 0) {
  2344. $outval .= ' - <span class="product_line_stock_too_low">';
  2345. }
  2346. $outval .= $langs->transnoentities("Stock").':'.$objp->stock;
  2347. $outval .= '</span>';
  2348. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) // Warning, this option may slow down combo list generation
  2349. {
  2350. $langs->load("stocks");
  2351. $tmpproduct = new Product($this->db);
  2352. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2353. $tmpproduct->load_virtual_stock();
  2354. $virtualstock = $tmpproduct->stock_theorique;
  2355. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2356. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2357. if ($virtualstock > 0) {
  2358. $outval .= '<span class="product_line_stock_ok">';
  2359. } elseif ($virtualstock <= 0) {
  2360. $outval .= '<span class="product_line_stock_too_low">';
  2361. }
  2362. $outval .= $virtualstock;
  2363. $outval .= '</span>';
  2364. unset($tmpproduct);
  2365. }
  2366. }
  2367. }
  2368. $opt .= "</option>\n";
  2369. $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>price2num($outprice_ht), 'price_ttc'=>price2num($outprice_ttc), 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'pbq'=>$outpbq);
  2370. }
  2371. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2372. /**
  2373. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2374. *
  2375. * @param int $socid Id third party
  2376. * @param string $selected Preselected product
  2377. * @param string $htmlname Name of HTML Select
  2378. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2379. * @param string $filtre For a SQL filter
  2380. * @param array $ajaxoptions Options for ajax_autocompleter
  2381. * @param int $hidelabel Hide label (0=no, 1=yes)
  2382. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2383. * @param string $morecss More CSS
  2384. * @return void
  2385. */
  2386. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '')
  2387. {
  2388. // phpcs:enable
  2389. global $langs, $conf;
  2390. global $price_level, $status, $finished;
  2391. $selected_input_value = '';
  2392. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2393. {
  2394. if ($selected > 0)
  2395. {
  2396. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2397. $producttmpselect = new Product($this->db);
  2398. $producttmpselect->fetch($selected);
  2399. $selected_input_value = $producttmpselect->ref;
  2400. unset($producttmpselect);
  2401. }
  2402. // mode=2 means suppliers products
  2403. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2404. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2405. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
  2406. } else {
  2407. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', -1, 0, 0, $alsoproductwithnosupplierprice, $morecss);
  2408. }
  2409. }
  2410. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2411. /**
  2412. * Return list of suppliers products
  2413. *
  2414. * @param int $socid Id societe fournisseur (0 pour aucun filtre)
  2415. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2416. * @param string $htmlname Nom de la zone select
  2417. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2418. * @param string $filtre Pour filtre sql
  2419. * @param string $filterkey Filtre des produits
  2420. * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
  2421. * @param int $outputmode 0=HTML select string, 1=Array
  2422. * @param int $limit Limit of line number
  2423. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2424. * @param string $morecss Add more CSS
  2425. * @return array Array of keys for json
  2426. */
  2427. public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '')
  2428. {
  2429. // phpcs:enable
  2430. global $langs, $conf, $db;
  2431. $out = '';
  2432. $outarray = array();
  2433. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2434. $langs->load('stocks');
  2435. // Units
  2436. if ($conf->global->PRODUCT_USE_UNITS) {
  2437. $langs->load('other');
  2438. }
  2439. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type,";
  2440. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2441. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  2442. $sql .= " pfp.supplier_reputation";
  2443. // Units
  2444. if ($conf->global->PRODUCT_USE_UNITS) {
  2445. $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";
  2446. }
  2447. if (!empty($conf->barcode->enabled)) $sql .= ", pfp.barcode";
  2448. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2449. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2450. if ($socid) $sql .= " AND pfp.fk_soc = ".$socid;
  2451. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2452. // Units
  2453. if ($conf->global->PRODUCT_USE_UNITS) {
  2454. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  2455. }
  2456. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2457. $sql .= " AND p.tobuy = 1";
  2458. if (strval($filtertype) != '') $sql .= " AND p.fk_product_type=".$this->db->escape($filtertype);
  2459. if (!empty($filtre)) $sql .= " ".$filtre;
  2460. // Add criteria on ref/label
  2461. if ($filterkey != '')
  2462. {
  2463. $sql .= ' AND (';
  2464. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2465. // For natural search
  2466. $scrit = explode(' ', $filterkey);
  2467. $i = 0;
  2468. if (count($scrit) > 1) $sql .= "(";
  2469. foreach ($scrit as $crit)
  2470. {
  2471. if ($i > 0) $sql .= " AND ";
  2472. $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)."%')";
  2473. $i++;
  2474. }
  2475. if (count($scrit) > 1) $sql .= ")";
  2476. if (!empty($conf->barcode->enabled)) {
  2477. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2478. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2479. }
  2480. $sql .= ')';
  2481. }
  2482. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2483. $sql .= $this->db->plimit($limit, 0);
  2484. // Build output string
  2485. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2486. $result = $this->db->query($sql);
  2487. if ($result)
  2488. {
  2489. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2490. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2491. $num = $this->db->num_rows($result);
  2492. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2493. $out .= '<select class="flat maxwidthonsmartphone'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2494. if (!$selected) $out .= '<option value="0" selected>&nbsp;</option>';
  2495. else $out .= '<option value="0">&nbsp;</option>';
  2496. $i = 0;
  2497. while ($i < $num)
  2498. {
  2499. $objp = $this->db->fetch_object($result);
  2500. $outkey = $objp->idprodfournprice; // id in table of price
  2501. if (!$outkey && $alsoproductwithnosupplierprice) $outkey = 'idprod_'.$objp->rowid; // id of product
  2502. $outref = $objp->ref;
  2503. $outval = '';
  2504. $outbarcode = $objp->barcode;
  2505. $outqty = 1;
  2506. $outdiscount = 0;
  2507. $outtype = $objp->fk_product_type;
  2508. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2509. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2510. // Units
  2511. $outvalUnits = '';
  2512. if ($conf->global->PRODUCT_USE_UNITS) {
  2513. if (!empty($objp->unit_short)) {
  2514. $outvalUnits .= ' - '.$objp->unit_short;
  2515. }
  2516. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2517. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2518. $outvalUnits .= ' - '.$unitToShow;
  2519. }
  2520. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2521. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2522. $outvalUnits .= ' - '.$unitToShow;
  2523. }
  2524. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2525. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2526. $outvalUnits .= ' - '.$unitToShow;
  2527. }
  2528. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2529. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2530. $outvalUnits .= ' - '.$unitToShow;
  2531. }
  2532. if ($outdurationvalue && $outdurationunit) {
  2533. $da = array(
  2534. 'h' => $langs->trans('Hour'),
  2535. 'd' => $langs->trans('Day'),
  2536. 'w' => $langs->trans('Week'),
  2537. 'm' => $langs->trans('Month'),
  2538. 'y' => $langs->trans('Year')
  2539. );
  2540. if (isset($da[$outdurationunit])) {
  2541. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2542. }
  2543. }
  2544. }
  2545. $objRef = $objp->ref;
  2546. if ($filterkey && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2547. $objRefFourn = $objp->ref_fourn;
  2548. if ($filterkey && $filterkey != '') $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  2549. $label = $objp->label;
  2550. if ($filterkey && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2551. $optlabel = $objp->ref;
  2552. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2553. $optlabel .= ' <span class=\'opacitymedium\'>('.$objp->ref_fourn.')</span>';
  2554. }
  2555. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2556. $optlabel .= ' ('.$outbarcode.')';
  2557. }
  2558. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2559. $outvallabel = $objRef;
  2560. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2561. $outvallabel .= ' ('.$objRefFourn.')';
  2562. }
  2563. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2564. $outvallabel .= ' ('.$outbarcode.')';
  2565. }
  2566. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2567. // Units
  2568. $optlabel .= $outvalUnits;
  2569. $outvallabel .= $outvalUnits;
  2570. if (!empty($objp->idprodfournprice))
  2571. {
  2572. $outqty = $objp->quantity;
  2573. $outdiscount = $objp->remise_percent;
  2574. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2575. $prod_supplier = new ProductFournisseur($this->db);
  2576. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2577. $prod_supplier->id = $objp->fk_product;
  2578. $prod_supplier->fourn_qty = $objp->quantity;
  2579. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2580. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2581. $priceparser = new PriceParser($this->db);
  2582. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2583. if ($price_result >= 0) {
  2584. $objp->fprice = $price_result;
  2585. if ($objp->quantity >= 1)
  2586. {
  2587. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  2588. }
  2589. }
  2590. }
  2591. if ($objp->quantity == 1)
  2592. {
  2593. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2594. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  2595. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2596. $outvallabel .= $langs->transnoentities("Unit");
  2597. } else {
  2598. $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;
  2599. $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;
  2600. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2601. $outvallabel .= ' '.$langs->transnoentities("Units");
  2602. }
  2603. if ($objp->quantity > 1)
  2604. {
  2605. $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
  2606. $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
  2607. }
  2608. if ($objp->remise_percent >= 1)
  2609. {
  2610. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2611. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2612. }
  2613. if ($objp->duration)
  2614. {
  2615. $optlabel .= " - ".$objp->duration;
  2616. $outvallabel .= " - ".$objp->duration;
  2617. }
  2618. if (!$socid)
  2619. {
  2620. $optlabel .= " - ".dol_trunc($objp->name, 8);
  2621. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  2622. }
  2623. if ($objp->supplier_reputation)
  2624. {
  2625. //TODO dictionary
  2626. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  2627. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  2628. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  2629. }
  2630. } else {
  2631. if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier
  2632. {
  2633. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  2634. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2635. } else // No supplier price defined for product, even on other suppliers
  2636. {
  2637. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  2638. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2639. }
  2640. }
  2641. $opt = '<option value="'.$outkey.'"';
  2642. if ($selected && $selected == $objp->idprodfournprice) $opt .= ' selected';
  2643. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt .= ' disabled';
  2644. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
  2645. {
  2646. $opt .= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqup="'.$objp->unitprice.'" data-pbqpercent="'.$objp->remise_percent.'"';
  2647. }
  2648. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  2649. $opt .= '>';
  2650. $opt .= $optlabel;
  2651. $outval .= $outvallabel;
  2652. $opt .= "</option>\n";
  2653. // Add new entry
  2654. // "key" value of json key array is used by jQuery automatically as selected value
  2655. // "label" value of json key array is used by jQuery automatically as text for combo box
  2656. $out .= $opt;
  2657. array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'up'=>$objp->unitprice, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false)));
  2658. // Exemple of var_dump $outarray
  2659. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  2660. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  2661. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  2662. //}
  2663. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2664. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  2665. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2666. $i++;
  2667. }
  2668. $out .= '</select>';
  2669. $this->db->free($result);
  2670. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2671. $out .= ajax_combobox($htmlname);
  2672. if (empty($outputmode)) return $out;
  2673. return $outarray;
  2674. } else {
  2675. dol_print_error($this->db);
  2676. }
  2677. }
  2678. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2679. /**
  2680. * Return list of suppliers prices for a product
  2681. *
  2682. * @param int $productid Id of product
  2683. * @param string $htmlname Name of HTML field
  2684. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  2685. * @return string
  2686. */
  2687. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  2688. {
  2689. // phpcs:enable
  2690. global $langs, $conf;
  2691. $langs->load('stocks');
  2692. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  2693. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  2694. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  2695. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2696. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2697. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2698. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  2699. $sql .= " AND p.tobuy = 1";
  2700. $sql .= " AND s.fournisseur = 1";
  2701. $sql .= " AND p.rowid = ".$productid;
  2702. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  2703. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  2704. $result = $this->db->query($sql);
  2705. if ($result)
  2706. {
  2707. $num = $this->db->num_rows($result);
  2708. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2709. if (!$num)
  2710. {
  2711. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  2712. } else {
  2713. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2714. $form .= '<option value="0">&nbsp;</option>';
  2715. $i = 0;
  2716. while ($i < $num)
  2717. {
  2718. $objp = $this->db->fetch_object($result);
  2719. $opt = '<option value="'.$objp->idprodfournprice.'"';
  2720. //if there is only one supplier, preselect it
  2721. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  2722. $opt .= ' selected';
  2723. }
  2724. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  2725. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2726. $prod_supplier = new ProductFournisseur($this->db);
  2727. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2728. $prod_supplier->id = $productid;
  2729. $prod_supplier->fourn_qty = $objp->quantity;
  2730. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2731. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2732. $priceparser = new PriceParser($this->db);
  2733. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2734. if ($price_result >= 0) {
  2735. $objp->fprice = $price_result;
  2736. if ($objp->quantity >= 1)
  2737. {
  2738. $objp->unitprice = $objp->fprice / $objp->quantity;
  2739. }
  2740. }
  2741. }
  2742. if ($objp->quantity == 1)
  2743. {
  2744. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2745. }
  2746. $opt .= $objp->quantity.' ';
  2747. if ($objp->quantity == 1)
  2748. {
  2749. $opt .= $langs->trans("Unit");
  2750. } else {
  2751. $opt .= $langs->trans("Units");
  2752. }
  2753. if ($objp->quantity > 1)
  2754. {
  2755. $opt .= " - ";
  2756. $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");
  2757. }
  2758. if ($objp->duration) $opt .= " - ".$objp->duration;
  2759. $opt .= "</option>\n";
  2760. $form .= $opt;
  2761. $i++;
  2762. }
  2763. }
  2764. $form .= '</select>';
  2765. $this->db->free($result);
  2766. return $form;
  2767. } else {
  2768. dol_print_error($this->db);
  2769. }
  2770. }
  2771. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2772. /**
  2773. * Return list of delivery address
  2774. *
  2775. * @param string $selected Id contact pre-selectionn
  2776. * @param int $socid Id of company
  2777. * @param string $htmlname Name of HTML field
  2778. * @param int $showempty Add an empty field
  2779. * @return integer|null
  2780. */
  2781. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  2782. {
  2783. // phpcs:enable
  2784. // looking for users
  2785. $sql = "SELECT a.rowid, a.label";
  2786. $sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a";
  2787. $sql .= " WHERE a.fk_soc = ".$socid;
  2788. $sql .= " ORDER BY a.label ASC";
  2789. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  2790. $resql = $this->db->query($sql);
  2791. if ($resql)
  2792. {
  2793. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2794. if ($showempty) print '<option value="0">&nbsp;</option>';
  2795. $num = $this->db->num_rows($resql);
  2796. $i = 0;
  2797. if ($num)
  2798. {
  2799. while ($i < $num)
  2800. {
  2801. $obj = $this->db->fetch_object($resql);
  2802. if ($selected && $selected == $obj->rowid)
  2803. {
  2804. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  2805. } else {
  2806. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  2807. }
  2808. $i++;
  2809. }
  2810. }
  2811. print '</select>';
  2812. return $num;
  2813. } else {
  2814. dol_print_error($this->db);
  2815. }
  2816. }
  2817. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2818. /**
  2819. * Load into cache list of payment terms
  2820. *
  2821. * @return int Nb of lines loaded, <0 if KO
  2822. */
  2823. public function load_cache_conditions_paiements()
  2824. {
  2825. // phpcs:enable
  2826. global $langs;
  2827. $num = count($this->cache_conditions_paiements);
  2828. if ($num > 0) return 0; // Cache already loaded
  2829. dol_syslog(__METHOD__, LOG_DEBUG);
  2830. $sql = "SELECT rowid, code, libelle as label";
  2831. $sql .= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  2832. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  2833. $sql .= " AND active > 0";
  2834. $sql .= " ORDER BY sortorder";
  2835. $resql = $this->db->query($sql);
  2836. if ($resql)
  2837. {
  2838. $num = $this->db->num_rows($resql);
  2839. $i = 0;
  2840. while ($i < $num)
  2841. {
  2842. $obj = $this->db->fetch_object($resql);
  2843. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2844. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  2845. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  2846. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  2847. $i++;
  2848. }
  2849. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  2850. return $num;
  2851. } else {
  2852. dol_print_error($this->db);
  2853. return -1;
  2854. }
  2855. }
  2856. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2857. /**
  2858. * Charge dans cache la liste des délais de livraison possibles
  2859. *
  2860. * @return int Nb of lines loaded, <0 if KO
  2861. */
  2862. public function load_cache_availability()
  2863. {
  2864. // phpcs:enable
  2865. global $langs;
  2866. $num = count($this->cache_availability);
  2867. if ($num > 0) return 0; // Cache already loaded
  2868. dol_syslog(__METHOD__, LOG_DEBUG);
  2869. $langs->load('propal');
  2870. $sql = "SELECT rowid, code, label";
  2871. $sql .= " FROM ".MAIN_DB_PREFIX.'c_availability';
  2872. $sql .= " WHERE active > 0";
  2873. $resql = $this->db->query($sql);
  2874. if ($resql)
  2875. {
  2876. $num = $this->db->num_rows($resql);
  2877. $i = 0;
  2878. while ($i < $num)
  2879. {
  2880. $obj = $this->db->fetch_object($resql);
  2881. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2882. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  2883. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  2884. $this->cache_availability[$obj->rowid]['label'] = $label;
  2885. $i++;
  2886. }
  2887. $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
  2888. return $num;
  2889. } else {
  2890. dol_print_error($this->db);
  2891. return -1;
  2892. }
  2893. }
  2894. /**
  2895. * Retourne la liste des types de delais de livraison possibles
  2896. *
  2897. * @param int $selected Id du type de delais pre-selectionne
  2898. * @param string $htmlname Nom de la zone select
  2899. * @param string $filtertype To add a filter
  2900. * @param int $addempty Add empty entry
  2901. * @return void
  2902. */
  2903. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0)
  2904. {
  2905. global $langs, $user;
  2906. $this->load_cache_availability();
  2907. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2908. print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  2909. if ($addempty) print '<option value="0">&nbsp;</option>';
  2910. foreach ($this->cache_availability as $id => $arrayavailability)
  2911. {
  2912. if ($selected == $id)
  2913. {
  2914. print '<option value="'.$id.'" selected>';
  2915. } else {
  2916. print '<option value="'.$id.'">';
  2917. }
  2918. print $arrayavailability['label'];
  2919. print '</option>';
  2920. }
  2921. print '</select>';
  2922. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  2923. }
  2924. /**
  2925. * Load into cache cache_demand_reason, array of input reasons
  2926. *
  2927. * @return int Nb of lines loaded, <0 if KO
  2928. */
  2929. public function loadCacheInputReason()
  2930. {
  2931. global $langs;
  2932. $num = count($this->cache_demand_reason);
  2933. if ($num > 0) return 0; // Cache already loaded
  2934. $sql = "SELECT rowid, code, label";
  2935. $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  2936. $sql .= " WHERE active > 0";
  2937. $resql = $this->db->query($sql);
  2938. if ($resql)
  2939. {
  2940. $num = $this->db->num_rows($resql);
  2941. $i = 0;
  2942. $tmparray = array();
  2943. while ($i < $num)
  2944. {
  2945. $obj = $this->db->fetch_object($resql);
  2946. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2947. $label = ($obj->label != '-' ? $obj->label : '');
  2948. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  2949. if ($langs->trans($obj->code) != $obj->code) $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  2950. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  2951. $tmparray[$obj->rowid]['code'] = $obj->code;
  2952. $tmparray[$obj->rowid]['label'] = $label;
  2953. $i++;
  2954. }
  2955. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  2956. unset($tmparray);
  2957. return $num;
  2958. } else {
  2959. dol_print_error($this->db);
  2960. return -1;
  2961. }
  2962. }
  2963. /**
  2964. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  2965. * List found into table c_input_reason loaded by loadCacheInputReason
  2966. *
  2967. * @param int $selected Id or code of type origin to select by default
  2968. * @param string $htmlname Nom de la zone select
  2969. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  2970. * @param int $addempty Add an empty entry
  2971. * @return void
  2972. */
  2973. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0)
  2974. {
  2975. global $langs, $user;
  2976. $this->loadCacheInputReason();
  2977. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2978. if ($addempty) print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  2979. foreach ($this->cache_demand_reason as $id => $arraydemandreason)
  2980. {
  2981. if ($arraydemandreason['code'] == $exclude) continue;
  2982. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
  2983. {
  2984. print '<option value="'.$arraydemandreason['id'].'" selected>';
  2985. } else {
  2986. print '<option value="'.$arraydemandreason['id'].'">';
  2987. }
  2988. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  2989. print $langs->trans($label);
  2990. print '</option>';
  2991. }
  2992. print '</select>';
  2993. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  2994. }
  2995. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2996. /**
  2997. * Charge dans cache la liste des types de paiements possibles
  2998. *
  2999. * @return int Nb of lines loaded, <0 if KO
  3000. */
  3001. public function load_cache_types_paiements()
  3002. {
  3003. // phpcs:enable
  3004. global $langs;
  3005. $num = count($this->cache_types_paiements);
  3006. if ($num > 0) return $num; // Cache already loaded
  3007. dol_syslog(__METHOD__, LOG_DEBUG);
  3008. $this->cache_types_paiements = array();
  3009. $sql = "SELECT id, code, libelle as label, type, active";
  3010. $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement";
  3011. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3012. //if ($active >= 0) $sql.= " AND active = ".$active;
  3013. $resql = $this->db->query($sql);
  3014. if ($resql)
  3015. {
  3016. $num = $this->db->num_rows($resql);
  3017. $i = 0;
  3018. while ($i < $num)
  3019. {
  3020. $obj = $this->db->fetch_object($resql);
  3021. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3022. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3023. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3024. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3025. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3026. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3027. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3028. $i++;
  3029. }
  3030. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3031. return $num;
  3032. } else {
  3033. dol_print_error($this->db);
  3034. return -1;
  3035. }
  3036. }
  3037. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3038. /**
  3039. * Return list of payment modes.
  3040. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3041. * See instead to force the default value by the caller.
  3042. *
  3043. * @param int $selected Id of payment term to preselect by default
  3044. * @param string $htmlname Nom de la zone select
  3045. * @param int $filtertype Not used
  3046. * @param int $addempty Add an empty entry
  3047. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3048. * @param string $morecss Add more CSS on select tag
  3049. * @return void
  3050. */
  3051. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
  3052. {
  3053. // phpcs:enable
  3054. global $langs, $user, $conf;
  3055. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3056. $this->load_cache_conditions_paiements();
  3057. // Set default value if not already set by caller
  3058. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3059. print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3060. if ($addempty) print '<option value="0">&nbsp;</option>';
  3061. foreach ($this->cache_conditions_paiements as $id => $arrayconditions)
  3062. {
  3063. if ($selected == $id)
  3064. {
  3065. print '<option value="'.$id.'" selected>';
  3066. } else {
  3067. print '<option value="'.$id.'">';
  3068. }
  3069. print $arrayconditions['label'];
  3070. print '</option>';
  3071. }
  3072. print '</select>';
  3073. if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3074. }
  3075. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3076. /**
  3077. * Return list of payment methods
  3078. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3079. *
  3080. * @param string $selected Id or code or preselected payment mode
  3081. * @param string $htmlname Name of select field
  3082. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3083. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3084. * @param int $empty 1=can be empty, 0 otherwise
  3085. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3086. * @param int $maxlength Max length of label
  3087. * @param int $active Active or not, -1 = all
  3088. * @param string $morecss Add more CSS on select tag
  3089. * @return void
  3090. */
  3091. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3092. {
  3093. // phpcs:enable
  3094. global $langs, $user, $conf;
  3095. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3096. $filterarray = array();
  3097. if ($filtertype == 'CRDT') $filterarray = array(0, 2, 3);
  3098. elseif ($filtertype == 'DBIT') $filterarray = array(1, 2, 3);
  3099. elseif ($filtertype != '' && $filtertype != '-1') $filterarray = explode(',', $filtertype);
  3100. $this->load_cache_types_paiements();
  3101. // Set default value if not already set by caller
  3102. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3103. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3104. if ($empty) print '<option value="">&nbsp;</option>';
  3105. foreach ($this->cache_types_paiements as $id => $arraytypes)
  3106. {
  3107. // If not good status
  3108. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  3109. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3110. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) continue;
  3111. // We discard empty line if showempty is on because an empty line has already been output.
  3112. if ($empty && empty($arraytypes['code'])) continue;
  3113. if ($format == 0) print '<option value="'.$id.'"';
  3114. elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  3115. elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  3116. elseif ($format == 3) print '<option value="'.$id.'"';
  3117. // Print attribute selected or not
  3118. if ($format == 1 || $format == 2) {
  3119. if ($selected == $arraytypes['code']) print ' selected';
  3120. } else {
  3121. if ($selected == $id) print ' selected';
  3122. }
  3123. print '>';
  3124. if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3125. elseif ($format == 1) $value = $arraytypes['code'];
  3126. elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3127. elseif ($format == 3) $value = $arraytypes['code'];
  3128. print $value ? $value : '&nbsp;';
  3129. print '</option>';
  3130. }
  3131. print '</select>';
  3132. if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3133. }
  3134. /**
  3135. * Selection HT or TTC
  3136. *
  3137. * @param string $selected Id pre-selectionne
  3138. * @param string $htmlname Nom de la zone select
  3139. * @return string Code of HTML select to chose tax or not
  3140. */
  3141. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type')
  3142. {
  3143. global $langs;
  3144. $return = '';
  3145. $return .= '<select class="flat maxwidth75" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3146. $options = array(
  3147. 'HT'=>$langs->trans("HT"),
  3148. 'TTC'=>$langs->trans("TTC")
  3149. );
  3150. foreach ($options as $id => $value)
  3151. {
  3152. if ($selected == $id)
  3153. {
  3154. $return .= '<option value="'.$id.'" selected>'.$value;
  3155. } else {
  3156. $return .= '<option value="'.$id.'">'.$value;
  3157. }
  3158. $return .= '</option>';
  3159. }
  3160. $return .= '</select>';
  3161. return $return;
  3162. }
  3163. /**
  3164. * Return a HTML select list of shipping mode
  3165. *
  3166. * @param string $selected Id shipping mode pre-selected
  3167. * @param string $htmlname Name of select zone
  3168. * @param string $filtre To filter list
  3169. * @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.
  3170. * @param string $moreattrib To add more attribute on select
  3171. * @return void
  3172. */
  3173. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '')
  3174. {
  3175. global $langs, $conf, $user;
  3176. $langs->load("admin");
  3177. $langs->load("deliveries");
  3178. $sql = "SELECT rowid, code, libelle as label";
  3179. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  3180. $sql .= " WHERE active > 0";
  3181. if ($filtre) $sql .= " AND ".$filtre;
  3182. $sql .= " ORDER BY libelle ASC";
  3183. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3184. $result = $this->db->query($sql);
  3185. if ($result) {
  3186. $num = $this->db->num_rows($result);
  3187. $i = 0;
  3188. if ($num) {
  3189. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3190. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3191. print '<option value="-1">&nbsp;</option>';
  3192. }
  3193. while ($i < $num) {
  3194. $obj = $this->db->fetch_object($result);
  3195. if ($selected == $obj->rowid) {
  3196. print '<option value="'.$obj->rowid.'" selected>';
  3197. } else {
  3198. print '<option value="'.$obj->rowid.'">';
  3199. }
  3200. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3201. print '</option>';
  3202. $i++;
  3203. }
  3204. print "</select>";
  3205. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3206. } else {
  3207. print $langs->trans("NoShippingMethodDefined");
  3208. }
  3209. } else {
  3210. dol_print_error($this->db);
  3211. }
  3212. }
  3213. /**
  3214. * Display form to select shipping mode
  3215. *
  3216. * @param string $page Page
  3217. * @param int $selected Id of shipping mode
  3218. * @param string $htmlname Name of select html field
  3219. * @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.
  3220. * @return void
  3221. */
  3222. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3223. {
  3224. global $langs, $db;
  3225. $langs->load("deliveries");
  3226. if ($htmlname != "none") {
  3227. print '<form method="POST" action="'.$page.'">';
  3228. print '<input type="hidden" name="action" value="setshippingmethod">';
  3229. print '<input type="hidden" name="token" value="'.newToken().'">';
  3230. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3231. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3232. print '</form>';
  3233. } else {
  3234. if ($selected) {
  3235. $code = $langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3236. print $langs->trans("SendingMethod".strtoupper($code));
  3237. } else {
  3238. print "&nbsp;";
  3239. }
  3240. }
  3241. }
  3242. /**
  3243. * Creates HTML last in cycle situation invoices selector
  3244. *
  3245. * @param string $selected Preselected ID
  3246. * @param int $socid Company ID
  3247. *
  3248. * @return string HTML select
  3249. */
  3250. public function selectSituationInvoices($selected = '', $socid = 0)
  3251. {
  3252. global $langs;
  3253. $langs->load('bills');
  3254. $opt = '<option value ="" selected></option>';
  3255. $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc';
  3256. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture';
  3257. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  3258. $sql .= ' AND situation_counter >= 1';
  3259. $sql .= ' AND fk_soc = '.(int) $socid;
  3260. $sql .= ' AND type <> 2';
  3261. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  3262. $resql = $this->db->query($sql);
  3263. if ($resql && $this->db->num_rows($resql) > 0) {
  3264. // Last seen cycle
  3265. $ref = 0;
  3266. while ($obj = $this->db->fetch_object($resql)) {
  3267. //Same cycle ?
  3268. if ($obj->situation_cycle_ref != $ref) {
  3269. // Just seen this cycle
  3270. $ref = $obj->situation_cycle_ref;
  3271. //not final ?
  3272. if ($obj->situation_final != 1) {
  3273. //Not prov?
  3274. if (substr($obj->ref, 1, 4) != 'PROV') {
  3275. if ($selected == $obj->rowid) {
  3276. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  3277. } else {
  3278. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  3279. }
  3280. }
  3281. }
  3282. }
  3283. }
  3284. } else {
  3285. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  3286. }
  3287. if ($opt == '<option value ="" selected></option>')
  3288. {
  3289. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  3290. }
  3291. return $opt;
  3292. }
  3293. /**
  3294. * Creates HTML units selector (code => label)
  3295. *
  3296. * @param string $selected Preselected Unit ID
  3297. * @param string $htmlname Select name
  3298. * @param int $showempty Add a nempty line
  3299. * @return string HTML select
  3300. */
  3301. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0)
  3302. {
  3303. global $langs;
  3304. $langs->load('products');
  3305. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  3306. $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
  3307. $sql .= ' WHERE active > 0';
  3308. $resql = $this->db->query($sql);
  3309. if ($resql && $this->db->num_rows($resql) > 0)
  3310. {
  3311. if ($showempty) $return .= '<option value="none"></option>';
  3312. while ($res = $this->db->fetch_object($resql))
  3313. {
  3314. $unitLabel = $res->label;
  3315. if (!empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before
  3316. {
  3317. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  3318. }
  3319. if ($selected == $res->rowid)
  3320. {
  3321. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  3322. } else {
  3323. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  3324. }
  3325. }
  3326. $return .= '</select>';
  3327. }
  3328. return $return;
  3329. }
  3330. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3331. /**
  3332. * Return a HTML select list of bank accounts
  3333. *
  3334. * @param string $selected Id account pre-selected
  3335. * @param string $htmlname Name of select zone
  3336. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  3337. * @param string $filtre To filter list
  3338. * @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.
  3339. * @param string $moreattrib To add more attribute on select
  3340. * @param int $showcurrency Show currency in label
  3341. * @param string $morecss More CSS
  3342. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  3343. */
  3344. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '')
  3345. {
  3346. // phpcs:enable
  3347. global $langs, $conf;
  3348. $langs->load("admin");
  3349. $num = 0;
  3350. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  3351. $sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
  3352. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  3353. if ($status != 2) $sql .= " AND clos = ".(int) $status;
  3354. if ($filtre) $sql .= " AND ".$filtre;
  3355. $sql .= " ORDER BY label";
  3356. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  3357. $result = $this->db->query($sql);
  3358. if ($result)
  3359. {
  3360. $num = $this->db->num_rows($result);
  3361. $i = 0;
  3362. if ($num)
  3363. {
  3364. print '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3365. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  3366. {
  3367. print '<option value="-1">&nbsp;</option>';
  3368. }
  3369. while ($i < $num)
  3370. {
  3371. $obj = $this->db->fetch_object($result);
  3372. if ($selected == $obj->rowid)
  3373. {
  3374. print '<option value="'.$obj->rowid.'" selected>';
  3375. } else {
  3376. print '<option value="'.$obj->rowid.'">';
  3377. }
  3378. print trim($obj->label);
  3379. if ($showcurrency) print ' ('.$obj->currency_code.')';
  3380. if ($status == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3381. print '</option>';
  3382. $i++;
  3383. }
  3384. print "</select>";
  3385. } else {
  3386. if ($status == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  3387. else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  3388. }
  3389. } else {
  3390. dol_print_error($this->db);
  3391. }
  3392. return $num;
  3393. }
  3394. /**
  3395. * Return a HTML select list of establishment
  3396. *
  3397. * @param string $selected Id establishment pre-selected
  3398. * @param string $htmlname Name of select zone
  3399. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  3400. * @param string $filtre To filter list
  3401. * @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.
  3402. * @param string $moreattrib To add more attribute on select
  3403. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  3404. */
  3405. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  3406. {
  3407. // phpcs:enable
  3408. global $langs, $conf;
  3409. $langs->load("admin");
  3410. $num = 0;
  3411. $sql = "SELECT rowid, name, fk_country, status, entity";
  3412. $sql .= " FROM ".MAIN_DB_PREFIX."establishment";
  3413. $sql .= " WHERE 1=1";
  3414. if ($status != 2) $sql .= " AND status = ".(int) $status;
  3415. if ($filtre) $sql .= " AND ".$filtre;
  3416. $sql .= " ORDER BY name";
  3417. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  3418. $result = $this->db->query($sql);
  3419. if ($result)
  3420. {
  3421. $num = $this->db->num_rows($result);
  3422. $i = 0;
  3423. if ($num)
  3424. {
  3425. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3426. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  3427. {
  3428. print '<option value="-1">&nbsp;</option>';
  3429. }
  3430. while ($i < $num)
  3431. {
  3432. $obj = $this->db->fetch_object($result);
  3433. if ($selected == $obj->rowid)
  3434. {
  3435. print '<option value="'.$obj->rowid.'" selected>';
  3436. } else {
  3437. print '<option value="'.$obj->rowid.'">';
  3438. }
  3439. print trim($obj->name);
  3440. if ($status == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3441. print '</option>';
  3442. $i++;
  3443. }
  3444. print "</select>";
  3445. } else {
  3446. if ($status == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  3447. else print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  3448. }
  3449. } else {
  3450. dol_print_error($this->db);
  3451. }
  3452. }
  3453. /**
  3454. * Display form to select bank account
  3455. *
  3456. * @param string $page Page
  3457. * @param int $selected Id of bank account
  3458. * @param string $htmlname Name of select html field
  3459. * @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.
  3460. * @return void
  3461. */
  3462. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  3463. {
  3464. global $langs;
  3465. if ($htmlname != "none") {
  3466. print '<form method="POST" action="'.$page.'">';
  3467. print '<input type="hidden" name="action" value="setbankaccount">';
  3468. print '<input type="hidden" name="token" value="'.newToken().'">';
  3469. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  3470. if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3471. print '</form>';
  3472. } else {
  3473. $langs->load('banks');
  3474. if ($selected) {
  3475. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  3476. $bankstatic = new Account($this->db);
  3477. $result = $bankstatic->fetch($selected);
  3478. if ($result) print $bankstatic->getNomUrl(1);
  3479. } else {
  3480. print "&nbsp;";
  3481. }
  3482. }
  3483. }
  3484. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3485. /**
  3486. * Return list of categories having choosed type
  3487. *
  3488. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  3489. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  3490. * @param string $htmlname HTML field name
  3491. * @param int $maxlength Maximum length for labels
  3492. * @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.
  3493. * $markafterid can be an :
  3494. * - int (id of category)
  3495. * - string (categories ids seprated by comma)
  3496. * - array (list of categories ids)
  3497. * @param int $outputmode 0=HTML select string, 1=Array
  3498. * @param int $include [=0] Removed or 1=Keep only
  3499. * @param string $morecss More CSS
  3500. * @return string
  3501. * @see select_categories()
  3502. */
  3503. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  3504. {
  3505. // phpcs:enable
  3506. global $conf, $langs;
  3507. $langs->load("categories");
  3508. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  3509. // For backward compatibility
  3510. if (is_numeric($type))
  3511. {
  3512. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  3513. }
  3514. if ($type === Categorie::TYPE_BANK_LINE)
  3515. {
  3516. // TODO Move this into common category feature
  3517. $cate_arbo = array();
  3518. $sql = "SELECT c.label, c.rowid";
  3519. $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  3520. $sql .= " WHERE entity = ".$conf->entity;
  3521. $sql .= " ORDER BY c.label";
  3522. $result = $this->db->query($sql);
  3523. if ($result)
  3524. {
  3525. $num = $this->db->num_rows($result);
  3526. $i = 0;
  3527. while ($i < $num)
  3528. {
  3529. $objp = $this->db->fetch_object($result);
  3530. if ($objp) $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  3531. $i++;
  3532. }
  3533. $this->db->free($result);
  3534. } else dol_print_error($this->db);
  3535. } else {
  3536. $cat = new Categorie($this->db);
  3537. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  3538. }
  3539. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  3540. $outarray = array();
  3541. if (is_array($cate_arbo))
  3542. {
  3543. if (!count($cate_arbo)) $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  3544. else {
  3545. $output .= '<option value="-1">&nbsp;</option>';
  3546. foreach ($cate_arbo as $key => $value)
  3547. {
  3548. if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
  3549. {
  3550. $add = 'selected ';
  3551. } else {
  3552. $add = '';
  3553. }
  3554. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  3555. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  3556. }
  3557. }
  3558. }
  3559. $output .= '</select>';
  3560. $output .= "\n";
  3561. if ($outputmode) return $outarray;
  3562. return $output;
  3563. }
  3564. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3565. /**
  3566. * Show a confirmation HTML form or AJAX popup
  3567. *
  3568. * @param string $page Url of page to call if confirmation is OK
  3569. * @param string $title Title
  3570. * @param string $question Question
  3571. * @param string $action Action
  3572. * @param array $formquestion An array with forms complementary inputs
  3573. * @param string $selectedchoice "" or "no" or "yes"
  3574. * @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
  3575. * @param int $height Force height of box
  3576. * @param int $width Force width of box
  3577. * @return void
  3578. * @deprecated
  3579. * @see formconfirm()
  3580. */
  3581. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  3582. {
  3583. // phpcs:enable
  3584. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  3585. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  3586. }
  3587. /**
  3588. * Show a confirmation HTML form or AJAX popup.
  3589. * Easiest way to use this is with useajax=1.
  3590. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  3591. * just after calling this method. For example:
  3592. * print '<script type="text/javascript">'."\n";
  3593. * print 'jQuery(document).ready(function() {'."\n";
  3594. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  3595. * print '});'."\n";
  3596. * print '</script>'."\n";
  3597. *
  3598. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  3599. * @param string $title Title
  3600. * @param string $question Question
  3601. * @param string $action Action
  3602. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  3603. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
  3604. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  3605. * @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
  3606. * @param int|string $height Force height of box (0 = auto)
  3607. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  3608. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  3609. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  3610. */
  3611. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  3612. {
  3613. global $langs, $conf;
  3614. $more = '<!-- formconfirm for page='.dol_escape_htmltag($page).' -->';
  3615. $formconfirm = '';
  3616. $inputok = array();
  3617. $inputko = array();
  3618. // Clean parameters
  3619. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  3620. if ($conf->browser->layout == 'phone') $width = '95%';
  3621. // Set height automatically if not defined
  3622. if (empty($height)) {
  3623. $height = 220;
  3624. if (is_array($formquestion) && count($formquestion) > 2) {
  3625. $height += ((count($formquestion) - 2) * 24);
  3626. }
  3627. }
  3628. if (is_array($formquestion) && !empty($formquestion))
  3629. {
  3630. // First add hidden fields and value
  3631. foreach ($formquestion as $key => $input)
  3632. {
  3633. if (is_array($input) && !empty($input))
  3634. {
  3635. if ($input['type'] == 'hidden')
  3636. {
  3637. $more .= '<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  3638. }
  3639. }
  3640. }
  3641. // Now add questions
  3642. $moreonecolumn = '';
  3643. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  3644. foreach ($formquestion as $key => $input)
  3645. {
  3646. if (is_array($input) && !empty($input))
  3647. {
  3648. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : '');
  3649. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  3650. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  3651. if ($input['type'] == 'text')
  3652. {
  3653. $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="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  3654. } elseif ($input['type'] == 'password')
  3655. {
  3656. $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="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  3657. } elseif ($input['type'] == 'select')
  3658. {
  3659. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  3660. if (!empty($input['label'])) $more .= $input['label'].'</div><div class="tagtd left">';
  3661. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], 1, 0, 0, $moreattr, 0, 0, 0, '', $morecss);
  3662. $more .= '</div></div>'."\n";
  3663. } elseif ($input['type'] == 'checkbox')
  3664. {
  3665. $more .= '<div class="tagtr">';
  3666. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  3667. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
  3668. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more .= ' checked';
  3669. if (is_bool($input['value']) && $input['value']) $more .= ' checked';
  3670. if (isset($input['disabled'])) $more .= ' disabled';
  3671. $more .= ' /></div>';
  3672. $more .= '</div>'."\n";
  3673. } elseif ($input['type'] == 'radio')
  3674. {
  3675. $i = 0;
  3676. foreach ($input['values'] as $selkey => $selval)
  3677. {
  3678. $more .= '<div class="tagtr">';
  3679. if ($i == 0) $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  3680. else $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  3681. $more .= '<div class="tagtd"><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
  3682. if ($input['disabled']) $more .= ' disabled';
  3683. $more .= ' /> ';
  3684. $more .= $selval;
  3685. $more .= '</div></div>'."\n";
  3686. $i++;
  3687. }
  3688. } elseif ($input['type'] == 'date')
  3689. {
  3690. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  3691. $more .= '<div class="tagtd">';
  3692. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, 0);
  3693. $more .= '</div></div>'."\n";
  3694. $formquestion[] = array('name'=>$input['name'].'day');
  3695. $formquestion[] = array('name'=>$input['name'].'month');
  3696. $formquestion[] = array('name'=>$input['name'].'year');
  3697. $formquestion[] = array('name'=>$input['name'].'hour');
  3698. $formquestion[] = array('name'=>$input['name'].'min');
  3699. } elseif ($input['type'] == 'other')
  3700. {
  3701. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  3702. if (!empty($input['label'])) $more .= $input['label'].'</div><div class="tagtd">';
  3703. $more .= $input['value'];
  3704. $more .= '</div></div>'."\n";
  3705. } elseif ($input['type'] == 'onecolumn')
  3706. {
  3707. $moreonecolumn .= '<div class="margintoponly">';
  3708. $moreonecolumn .= $input['value'];
  3709. $moreonecolumn .= '</div>'."\n";
  3710. }
  3711. }
  3712. }
  3713. $more .= '</div>'."\n";
  3714. $more .= $moreonecolumn;
  3715. }
  3716. // JQUI method dialog is broken with jmobile, we use standard HTML.
  3717. // 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
  3718. // See page product/card.php for example
  3719. if (!empty($conf->dol_use_jmobile)) $useajax = 0;
  3720. if (empty($conf->use_javascript_ajax)) $useajax = 0;
  3721. if ($useajax)
  3722. {
  3723. $autoOpen = true;
  3724. $dialogconfirm = 'dialog-confirm';
  3725. $button = '';
  3726. if (!is_numeric($useajax))
  3727. {
  3728. $button = $useajax;
  3729. $useajax = 1;
  3730. $autoOpen = false;
  3731. $dialogconfirm .= '-'.$button;
  3732. }
  3733. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes';
  3734. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : '');
  3735. // Add input fields into list of fields to read during submit (inputok and inputko)
  3736. if (is_array($formquestion))
  3737. {
  3738. foreach ($formquestion as $key => $input)
  3739. {
  3740. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  3741. if (is_array($input) && isset($input['name'])) array_push($inputok, $input['name']);
  3742. if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko, $input['name']);
  3743. }
  3744. }
  3745. // Show JQuery confirm box.
  3746. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  3747. if (is_array($formquestion) && !empty($formquestion['text'])) {
  3748. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  3749. }
  3750. if (!empty($more)) {
  3751. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  3752. }
  3753. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  3754. $formconfirm .= '</div>'."\n";
  3755. $formconfirm .= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
  3756. $formconfirm .= '<script type="text/javascript">'."\n";
  3757. $formconfirm .= 'jQuery(document).ready(function() {
  3758. $(function() {
  3759. $( "#'.$dialogconfirm.'" ).dialog(
  3760. {
  3761. autoOpen: '.($autoOpen ? "true" : "false").',';
  3762. if ($newselectedchoice == 'no')
  3763. {
  3764. $formconfirm .= '
  3765. open: function() {
  3766. $(this).parent().find("button.ui-button:eq(2)").focus();
  3767. },';
  3768. }
  3769. $formconfirm .= '
  3770. resizable: false,
  3771. height: "'.$height.'",
  3772. width: "'.$width.'",
  3773. modal: true,
  3774. closeOnEscape: false,
  3775. buttons: {
  3776. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  3777. var options = "&token='.urlencode(newToken()).'";
  3778. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  3779. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  3780. if (inputok.length>0) {
  3781. $.each(inputok, function(i, inputname) {
  3782. var more = "";
  3783. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3784. if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
  3785. var inputvalue = $("#" + inputname + more).val();
  3786. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3787. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3788. });
  3789. }
  3790. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  3791. if (pageyes.length > 0) { location.href = urljump; }
  3792. $(this).dialog("close");
  3793. },
  3794. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  3795. var options = "&token='.urlencode(newToken()).'";
  3796. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  3797. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  3798. if (inputko.length>0) {
  3799. $.each(inputko, function(i, inputname) {
  3800. var more = "";
  3801. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3802. var inputvalue = $("#" + inputname + more).val();
  3803. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3804. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3805. });
  3806. }
  3807. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  3808. //alert(urljump);
  3809. if (pageno.length > 0) { location.href = urljump; }
  3810. $(this).dialog("close");
  3811. }
  3812. }
  3813. }
  3814. );
  3815. var button = "'.$button.'";
  3816. if (button.length > 0) {
  3817. $( "#" + button ).click(function() {
  3818. $("#'.$dialogconfirm.'").dialog("open");
  3819. });
  3820. }
  3821. });
  3822. });
  3823. </script>';
  3824. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  3825. } else {
  3826. $formconfirm .= "\n<!-- begin formconfirm page=".$page." -->\n";
  3827. if (empty($disableformtag)) $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  3828. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  3829. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  3830. $formconfirm .= '<table class="valid centpercent">'."\n";
  3831. // Line title
  3832. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('', 'recent').' '.$title.'</td></tr>'."\n";
  3833. // Line text
  3834. if (is_array($formquestion) && !empty($formquestion['text'])) {
  3835. $formconfirm .= '<tr class="valid"><td class="valid" colspan="3">'.$formquestion['text'].'</td></tr>'."\n";
  3836. }
  3837. // Line form fields
  3838. if ($more)
  3839. {
  3840. $formconfirm .= '<tr class="valid"><td class="valid" colspan="3">'."\n";
  3841. $formconfirm .= $more;
  3842. $formconfirm .= '</td></tr>'."\n";
  3843. }
  3844. // Line with question
  3845. $formconfirm .= '<tr class="valid">';
  3846. $formconfirm .= '<td class="valid">'.$question.'</td>';
  3847. $formconfirm .= '<td class="valid">';
  3848. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice);
  3849. $formconfirm .= '</td>';
  3850. $formconfirm .= '<td class="valid center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
  3851. $formconfirm .= '</tr>'."\n";
  3852. $formconfirm .= '</table>'."\n";
  3853. if (empty($disableformtag)) $formconfirm .= "</form>\n";
  3854. $formconfirm .= '<br>';
  3855. $formconfirm .= "<!-- end formconfirm -->\n";
  3856. }
  3857. return $formconfirm;
  3858. }
  3859. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3860. /**
  3861. * Show a form to select a project
  3862. *
  3863. * @param int $page Page
  3864. * @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)
  3865. * @param int $selected Id pre-selected project
  3866. * @param string $htmlname Name of select field
  3867. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  3868. * @param int $maxlength Max length
  3869. * @param int $forcefocus Force focus on field (works with javascript only)
  3870. * @param int $nooutput No print is done. String is returned.
  3871. * @return string Return html content
  3872. */
  3873. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  3874. {
  3875. // phpcs:enable
  3876. global $langs;
  3877. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  3878. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  3879. $out = '';
  3880. $formproject = new FormProjets($this->db);
  3881. $langs->load("project");
  3882. if ($htmlname != "none")
  3883. {
  3884. $out .= "\n";
  3885. $out .= '<form method="post" action="'.$page.'">';
  3886. $out .= '<input type="hidden" name="action" value="classin">';
  3887. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  3888. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  3889. $out .= '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3890. $out .= '</form>';
  3891. } else {
  3892. if ($selected)
  3893. {
  3894. $projet = new Project($this->db);
  3895. $projet->fetch($selected);
  3896. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  3897. $out .= $projet->getNomUrl(0, '', 1);
  3898. } else {
  3899. $out .= "&nbsp;";
  3900. }
  3901. }
  3902. if (empty($nooutput))
  3903. {
  3904. print $out;
  3905. return '';
  3906. }
  3907. return $out;
  3908. }
  3909. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3910. /**
  3911. * Show a form to select payment conditions
  3912. *
  3913. * @param int $page Page
  3914. * @param string $selected Id condition pre-selectionne
  3915. * @param string $htmlname Name of select html field
  3916. * @param int $addempty Add empty entry
  3917. * @return void
  3918. */
  3919. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0)
  3920. {
  3921. // phpcs:enable
  3922. global $langs;
  3923. if ($htmlname != "none")
  3924. {
  3925. print '<form method="post" action="'.$page.'">';
  3926. print '<input type="hidden" name="action" value="setconditions">';
  3927. print '<input type="hidden" name="token" value="'.newToken().'">';
  3928. $this->select_conditions_paiements($selected, $htmlname, -1, $addempty);
  3929. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3930. print '</form>';
  3931. } else {
  3932. if ($selected)
  3933. {
  3934. $this->load_cache_conditions_paiements();
  3935. print $this->cache_conditions_paiements[$selected]['label'];
  3936. } else {
  3937. print "&nbsp;";
  3938. }
  3939. }
  3940. }
  3941. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3942. /**
  3943. * Show a form to select a delivery delay
  3944. *
  3945. * @param int $page Page
  3946. * @param string $selected Id condition pre-selectionne
  3947. * @param string $htmlname Name of select html field
  3948. * @param int $addempty Ajoute entree vide
  3949. * @return void
  3950. */
  3951. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  3952. {
  3953. // phpcs:enable
  3954. global $langs;
  3955. if ($htmlname != "none")
  3956. {
  3957. print '<form method="post" action="'.$page.'">';
  3958. print '<input type="hidden" name="action" value="setavailability">';
  3959. print '<input type="hidden" name="token" value="'.newToken().'">';
  3960. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  3961. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3962. print '</form>';
  3963. } else {
  3964. if ($selected)
  3965. {
  3966. $this->load_cache_availability();
  3967. print $this->cache_availability[$selected]['label'];
  3968. } else {
  3969. print "&nbsp;";
  3970. }
  3971. }
  3972. }
  3973. /**
  3974. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3975. * List found into table c_input_reason loaded by loadCacheInputReason
  3976. *
  3977. * @param string $page Page
  3978. * @param string $selected Id condition pre-selectionne
  3979. * @param string $htmlname Name of select html field
  3980. * @param int $addempty Add empty entry
  3981. * @return void
  3982. */
  3983. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  3984. {
  3985. global $langs;
  3986. if ($htmlname != "none")
  3987. {
  3988. print '<form method="post" action="'.$page.'">';
  3989. print '<input type="hidden" name="action" value="setdemandreason">';
  3990. print '<input type="hidden" name="token" value="'.newToken().'">';
  3991. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  3992. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3993. print '</form>';
  3994. } else {
  3995. if ($selected)
  3996. {
  3997. $this->loadCacheInputReason();
  3998. foreach ($this->cache_demand_reason as $key => $val)
  3999. {
  4000. if ($val['id'] == $selected)
  4001. {
  4002. print $val['label'];
  4003. break;
  4004. }
  4005. }
  4006. } else {
  4007. print "&nbsp;";
  4008. }
  4009. }
  4010. }
  4011. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4012. /**
  4013. * Show a form + html select a date
  4014. *
  4015. * @param string $page Page
  4016. * @param string $selected Date preselected
  4017. * @param string $htmlname Html name of date input fields or 'none'
  4018. * @param int $displayhour Display hour selector
  4019. * @param int $displaymin Display minutes selector
  4020. * @param int $nooutput 1=No print output, return string
  4021. * @return string
  4022. * @see selectDate()
  4023. */
  4024. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0)
  4025. {
  4026. // phpcs:enable
  4027. global $langs;
  4028. $ret = '';
  4029. if ($htmlname != "none")
  4030. {
  4031. $ret .= '<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  4032. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4033. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4034. $ret .= '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  4035. $ret .= '<tr><td>';
  4036. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4037. $ret .= '</td>';
  4038. $ret .= '<td class="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  4039. $ret .= '</tr></table></form>';
  4040. } else {
  4041. if ($displayhour) $ret .= dol_print_date($selected, 'dayhour');
  4042. else $ret .= dol_print_date($selected, 'day');
  4043. }
  4044. if (empty($nooutput)) print $ret;
  4045. return $ret;
  4046. }
  4047. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4048. /**
  4049. * Show a select form to choose a user
  4050. *
  4051. * @param string $page Page
  4052. * @param string $selected Id of user preselected
  4053. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4054. * @param array $exclude List of users id to exclude
  4055. * @param array $include List of users id to include
  4056. * @return void
  4057. */
  4058. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4059. {
  4060. // phpcs:enable
  4061. global $langs;
  4062. if ($htmlname != "none")
  4063. {
  4064. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4065. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4066. print '<input type="hidden" name="token" value="'.newToken().'">';
  4067. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4068. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4069. print '</form>';
  4070. } else {
  4071. if ($selected)
  4072. {
  4073. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4074. $theuser = new User($this->db);
  4075. $theuser->fetch($selected);
  4076. print $theuser->getNomUrl(1);
  4077. } else {
  4078. print "&nbsp;";
  4079. }
  4080. }
  4081. }
  4082. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4083. /**
  4084. * Show form with payment mode
  4085. *
  4086. * @param string $page Page
  4087. * @param int $selected Id mode pre-selectionne
  4088. * @param string $htmlname Name of select html field
  4089. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  4090. * @param int $active Active or not, -1 = all
  4091. * @param int $addempty 1=Add empty entry
  4092. * @return void
  4093. */
  4094. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0)
  4095. {
  4096. // phpcs:enable
  4097. global $langs;
  4098. if ($htmlname != "none")
  4099. {
  4100. print '<form method="POST" action="'.$page.'">';
  4101. print '<input type="hidden" name="action" value="setmode">';
  4102. print '<input type="hidden" name="token" value="'.newToken().'">';
  4103. $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active);
  4104. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4105. print '</form>';
  4106. } else {
  4107. if ($selected)
  4108. {
  4109. $this->load_cache_types_paiements();
  4110. print $this->cache_types_paiements[$selected]['label'];
  4111. } else {
  4112. print "&nbsp;";
  4113. }
  4114. }
  4115. }
  4116. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4117. /**
  4118. * Show form with multicurrency code
  4119. *
  4120. * @param string $page Page
  4121. * @param string $selected code pre-selectionne
  4122. * @param string $htmlname Name of select html field
  4123. * @return void
  4124. */
  4125. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  4126. {
  4127. // phpcs:enable
  4128. global $langs;
  4129. if ($htmlname != "none")
  4130. {
  4131. print '<form method="POST" action="'.$page.'">';
  4132. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  4133. print '<input type="hidden" name="token" value="'.newToken().'">';
  4134. print $this->selectMultiCurrency($selected, $htmlname, 0);
  4135. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4136. print '</form>';
  4137. } else {
  4138. dol_include_once('/core/lib/company.lib.php');
  4139. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  4140. }
  4141. }
  4142. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4143. /**
  4144. * Show form with multicurrency rate
  4145. *
  4146. * @param string $page Page
  4147. * @param double $rate Current rate
  4148. * @param string $htmlname Name of select html field
  4149. * @param string $currency Currency code to explain the rate
  4150. * @return void
  4151. */
  4152. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  4153. {
  4154. // phpcs:enable
  4155. global $langs, $mysoc, $conf;
  4156. if ($htmlname != "none")
  4157. {
  4158. print '<form method="POST" action="'.$page.'">';
  4159. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  4160. print '<input type="hidden" name="token" value="'.newToken().'">';
  4161. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CR')) : 1).'" /> ';
  4162. print '<select name="calculation_mode">';
  4163. print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
  4164. print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
  4165. print '</select> ';
  4166. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4167. print '</form>';
  4168. } else {
  4169. if (!empty($rate))
  4170. {
  4171. print price($rate, 1, $langs, 1, 0);
  4172. if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  4173. } else {
  4174. print 1;
  4175. }
  4176. }
  4177. }
  4178. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4179. /**
  4180. * Show a select box with available absolute discounts
  4181. *
  4182. * @param string $page Page URL where form is shown
  4183. * @param int $selected Value pre-selected
  4184. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  4185. * @param int $socid Third party id
  4186. * @param float $amount Total amount available
  4187. * @param string $filter SQL filter on discounts
  4188. * @param int $maxvalue Max value for lines that can be selected
  4189. * @param string $more More string to add
  4190. * @param int $hidelist 1=Hide list
  4191. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  4192. * @return void
  4193. */
  4194. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  4195. {
  4196. // phpcs:enable
  4197. global $conf, $langs;
  4198. if ($htmlname != "none")
  4199. {
  4200. print '<form method="post" action="'.$page.'">';
  4201. print '<input type="hidden" name="action" value="setabsolutediscount">';
  4202. print '<input type="hidden" name="token" value="'.newToken().'">';
  4203. print '<div class="inline-block">';
  4204. if (!empty($discount_type)) {
  4205. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  4206. {
  4207. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4208. else $translationKey = 'HasCreditNoteFromSupplier';
  4209. } else {
  4210. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
  4211. else $translationKey = 'HasCreditNoteFromSupplier';
  4212. }
  4213. } else {
  4214. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  4215. {
  4216. if (!$filter || $filter == "fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4217. else $translationKey = 'CompanyHasCreditNote';
  4218. } else {
  4219. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
  4220. else $translationKey = 'CompanyHasCreditNote';
  4221. }
  4222. }
  4223. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  4224. if (empty($hidelist)) print ': ';
  4225. print '</div>';
  4226. if (empty($hidelist))
  4227. {
  4228. print '<div class="inline-block" style="padding-right: 10px">';
  4229. $newfilter = 'discount_type='.intval($discount_type);
  4230. if (!empty($discount_type)) {
  4231. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  4232. } else {
  4233. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  4234. }
  4235. if ($filter) $newfilter .= ' AND ('.$filter.')';
  4236. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  4237. if ($nbqualifiedlines > 0)
  4238. {
  4239. print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  4240. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
  4241. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4242. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
  4243. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4244. print '>';
  4245. }
  4246. print '</div>';
  4247. }
  4248. if ($more)
  4249. {
  4250. print '<div class="inline-block">';
  4251. print $more;
  4252. print '</div>';
  4253. }
  4254. print '</form>';
  4255. } else {
  4256. if ($selected)
  4257. {
  4258. print $selected;
  4259. } else {
  4260. print "0";
  4261. }
  4262. }
  4263. }
  4264. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4265. /**
  4266. * Show forms to select a contact
  4267. *
  4268. * @param string $page Page
  4269. * @param Societe $societe Filter on third party
  4270. * @param int $selected Id contact pre-selectionne
  4271. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  4272. * @return void
  4273. */
  4274. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  4275. {
  4276. // phpcs:enable
  4277. global $langs, $conf;
  4278. if ($htmlname != "none")
  4279. {
  4280. print '<form method="post" action="'.$page.'">';
  4281. print '<input type="hidden" name="action" value="set_contact">';
  4282. print '<input type="hidden" name="token" value="'.newToken().'">';
  4283. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  4284. print '<tr><td>';
  4285. $num = $this->select_contacts($societe->id, $selected, $htmlname);
  4286. if ($num == 0)
  4287. {
  4288. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  4289. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  4290. }
  4291. print '</td>';
  4292. print '<td class="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  4293. print '</tr></table></form>';
  4294. } else {
  4295. if ($selected)
  4296. {
  4297. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  4298. $contact = new Contact($this->db);
  4299. $contact->fetch($selected);
  4300. print $contact->getFullName($langs);
  4301. } else {
  4302. print "&nbsp;";
  4303. }
  4304. }
  4305. }
  4306. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4307. /**
  4308. * Output html select to select thirdparty
  4309. *
  4310. * @param string $page Page
  4311. * @param string $selected Id preselected
  4312. * @param string $htmlname Name of HTML select
  4313. * @param string $filter optional filters criteras
  4314. * @param int $showempty Add an empty field
  4315. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  4316. * @param int $forcecombo Force to use combo box
  4317. * @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')))
  4318. * @param int $nooutput No print output. Return it only.
  4319. * @return void|string
  4320. */
  4321. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0)
  4322. {
  4323. // phpcs:enable
  4324. global $langs;
  4325. $out = '';
  4326. if ($htmlname != "none")
  4327. {
  4328. $out .= '<form method="post" action="'.$page.'">';
  4329. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  4330. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4331. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
  4332. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4333. $out .= '</form>';
  4334. } else {
  4335. if ($selected)
  4336. {
  4337. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  4338. $soc = new Societe($this->db);
  4339. $soc->fetch($selected);
  4340. $out .= $soc->getNomUrl($langs);
  4341. } else {
  4342. $out .= "&nbsp;";
  4343. }
  4344. }
  4345. if ($nooutput) return $out;
  4346. else print $out;
  4347. }
  4348. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4349. /**
  4350. * Retourne la liste des devises, dans la langue de l'utilisateur
  4351. *
  4352. * @param string $selected preselected currency code
  4353. * @param string $htmlname name of HTML select list
  4354. * @deprecated
  4355. * @return void
  4356. */
  4357. public function select_currency($selected = '', $htmlname = 'currency_id')
  4358. {
  4359. // phpcs:enable
  4360. print $this->selectCurrency($selected, $htmlname);
  4361. }
  4362. /**
  4363. * Retourne la liste des devises, dans la langue de l'utilisateur
  4364. *
  4365. * @param string $selected preselected currency code
  4366. * @param string $htmlname name of HTML select list
  4367. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  4368. * @return string
  4369. */
  4370. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  4371. {
  4372. global $conf, $langs, $user;
  4373. $langs->loadCacheCurrencies('');
  4374. $out = '';
  4375. if ($selected == 'euro' || $selected == 'euros') $selected = 'EUR'; // Pour compatibilite
  4376. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  4377. foreach ($langs->cache_currencies as $code_iso => $currency)
  4378. {
  4379. if ($selected && $selected == $code_iso)
  4380. {
  4381. $out .= '<option value="'.$code_iso.'" selected>';
  4382. } else {
  4383. $out .= '<option value="'.$code_iso.'">';
  4384. }
  4385. $out .= $currency['label'];
  4386. if ($mode == 1)
  4387. {
  4388. $out .= ' ('.$code_iso.')';
  4389. } else {
  4390. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  4391. }
  4392. $out .= '</option>';
  4393. }
  4394. $out .= '</select>';
  4395. if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4396. // Make select dynamic
  4397. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  4398. $out .= ajax_combobox($htmlname);
  4399. return $out;
  4400. }
  4401. /**
  4402. * Return array of currencies in user language
  4403. *
  4404. * @param string $selected preselected currency code
  4405. * @param string $htmlname name of HTML select list
  4406. * @param integer $useempty 1=Add empty line
  4407. * @return string
  4408. */
  4409. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0)
  4410. {
  4411. global $db, $conf, $langs, $user;
  4412. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  4413. $TCurrency = array();
  4414. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  4415. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  4416. $resql = $this->db->query($sql);
  4417. if ($resql)
  4418. {
  4419. while ($obj = $this->db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
  4420. }
  4421. $out = '';
  4422. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  4423. if ($useempty) $out .= '<option value="">&nbsp;</option>';
  4424. // If company current currency not in table, we add it into list. Should always be available.
  4425. if (!in_array($conf->currency, $TCurrency))
  4426. {
  4427. $TCurrency[$conf->currency] = $conf->currency;
  4428. }
  4429. if (count($TCurrency) > 0)
  4430. {
  4431. foreach ($langs->cache_currencies as $code_iso => $currency)
  4432. {
  4433. if (isset($TCurrency[$code_iso]))
  4434. {
  4435. if (!empty($selected) && $selected == $code_iso) $out .= '<option value="'.$code_iso.'" selected="selected">';
  4436. else $out .= '<option value="'.$code_iso.'">';
  4437. $out .= $currency['label'];
  4438. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  4439. $out .= '</option>';
  4440. }
  4441. }
  4442. }
  4443. $out .= '</select>';
  4444. // Make select dynamic
  4445. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  4446. $out .= ajax_combobox($htmlname);
  4447. return $out;
  4448. }
  4449. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4450. /**
  4451. * Load into the cache vat rates of a country
  4452. *
  4453. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  4454. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  4455. */
  4456. public function load_cache_vatrates($country_code)
  4457. {
  4458. // phpcs:enable
  4459. global $langs;
  4460. $num = count($this->cache_vatrates);
  4461. if ($num > 0) return $num; // Cache already loaded
  4462. dol_syslog(__METHOD__, LOG_DEBUG);
  4463. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  4464. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4465. $sql .= " WHERE t.fk_pays = c.rowid";
  4466. $sql .= " AND t.active > 0";
  4467. $sql .= " AND c.code IN (".$country_code.")";
  4468. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  4469. $resql = $this->db->query($sql);
  4470. if ($resql)
  4471. {
  4472. $num = $this->db->num_rows($resql);
  4473. if ($num)
  4474. {
  4475. for ($i = 0; $i < $num; $i++)
  4476. {
  4477. $obj = $this->db->fetch_object($resql);
  4478. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  4479. $this->cache_vatrates[$i]['code'] = $obj->code;
  4480. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  4481. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  4482. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  4483. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  4484. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  4485. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  4486. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  4487. $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
  4488. $positiverates = '';
  4489. if ($obj->taux) $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  4490. if ($obj->localtax1) $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  4491. if ($obj->localtax2) $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  4492. if (empty($positiverates)) $positiverates = '0';
  4493. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  4494. }
  4495. return $num;
  4496. } else {
  4497. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</font>';
  4498. return -1;
  4499. }
  4500. } else {
  4501. $this->error = '<font class="error">'.$this->db->error().'</font>';
  4502. return -2;
  4503. }
  4504. }
  4505. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4506. /**
  4507. * Output an HTML select vat rate.
  4508. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  4509. *
  4510. * @param string $htmlname Name of HTML select field
  4511. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  4512. * @param Societe $societe_vendeuse Thirdparty seller
  4513. * @param Societe $societe_acheteuse Thirdparty buyer
  4514. * @param int $idprod Id product. O if unknown of NA.
  4515. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  4516. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  4517. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4518. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4519. * 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.
  4520. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  4521. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  4522. * Sinon la TVA proposee par defaut=0. Fin de regle.
  4523. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  4524. * @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
  4525. * @return string
  4526. */
  4527. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  4528. {
  4529. // phpcs:enable
  4530. global $langs, $conf, $mysoc;
  4531. $langs->load('errors');
  4532. $return = '';
  4533. // Define defaultnpr, defaultttx and defaultcode
  4534. $defaultnpr = ($info_bits & 0x01);
  4535. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  4536. $defaulttx = str_replace('*', '', $selectedrate);
  4537. $defaultcode = '';
  4538. if (preg_match('/\((.*)\)/', $defaulttx, $reg))
  4539. {
  4540. $defaultcode = $reg[1];
  4541. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  4542. }
  4543. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  4544. // Check parameters
  4545. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code)
  4546. {
  4547. if ($societe_vendeuse->id == $mysoc->id)
  4548. {
  4549. $return .= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</font>';
  4550. } else {
  4551. $return .= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</font>';
  4552. }
  4553. return $return;
  4554. }
  4555. //var_dump($societe_acheteuse);
  4556. //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";
  4557. //exit;
  4558. // Define list of countries to use to search VAT rates to show
  4559. // First we defined code_country to use to find list
  4560. if (is_object($societe_vendeuse))
  4561. {
  4562. $code_country = "'".$societe_vendeuse->country_code."'";
  4563. } else {
  4564. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  4565. }
  4566. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  4567. {
  4568. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4569. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany())))
  4570. {
  4571. // We also add the buyer
  4572. if (is_numeric($type))
  4573. {
  4574. if ($type == 1) // We know product is a service
  4575. {
  4576. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4577. }
  4578. } elseif (!$idprod) // We don't know type of product
  4579. {
  4580. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4581. } else {
  4582. $prodstatic = new Product($this->db);
  4583. $prodstatic->fetch($idprod);
  4584. if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service
  4585. {
  4586. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4587. }
  4588. }
  4589. }
  4590. }
  4591. // Now we get list
  4592. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  4593. if ($num > 0)
  4594. {
  4595. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  4596. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4597. {
  4598. $tmpthirdparty = new Societe($this->db);
  4599. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  4600. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  4601. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  4602. $defaultcode = $reg[1];
  4603. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  4604. }
  4605. if (empty($defaulttx)) $defaultnpr = 0;
  4606. }
  4607. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  4608. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  4609. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4610. {
  4611. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  4612. else $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  4613. }
  4614. // Disabled if seller is not subject to VAT
  4615. $disabled = false; $title = '';
  4616. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
  4617. {
  4618. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  4619. // of using supplier invoices (this is a very bad idea !)
  4620. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT))
  4621. {
  4622. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  4623. $disabled = true;
  4624. }
  4625. }
  4626. if (!$options_only) $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  4627. $selectedfound = false;
  4628. foreach ($this->cache_vatrates as $rate)
  4629. {
  4630. // Keep only 0 if seller is not subject to VAT
  4631. if ($disabled && $rate['txtva'] != 0) continue;
  4632. // Define key to use into select list
  4633. $key = $rate['txtva'];
  4634. $key .= $rate['nprtva'] ? '*' : '';
  4635. if ($mode > 0 && $rate['code']) $key .= ' ('.$rate['code'].')';
  4636. if ($mode < 0) $key = $rate['rowid'];
  4637. $return .= '<option value="'.$key.'"';
  4638. if (!$selectedfound)
  4639. {
  4640. if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  4641. {
  4642. if ($defaultcode == $rate['code'])
  4643. {
  4644. $return .= ' selected';
  4645. $selectedfound = true;
  4646. }
  4647. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
  4648. {
  4649. $return .= ' selected';
  4650. $selectedfound = true;
  4651. }
  4652. }
  4653. $return .= '>';
  4654. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  4655. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
  4656. {
  4657. $return .= $rate['labelpositiverates'];
  4658. } else {
  4659. $return .= vatrate($rate['label']);
  4660. }
  4661. //$return.=($rate['code']?' '.$rate['code']:'');
  4662. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  4663. $return .= '</option>';
  4664. }
  4665. if (!$options_only) $return .= '</select>';
  4666. } else {
  4667. $return .= $this->error;
  4668. }
  4669. $this->num = $num;
  4670. return $return;
  4671. }
  4672. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4673. /**
  4674. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4675. * Fields are preselected with :
  4676. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4677. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4678. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4679. *
  4680. * @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).
  4681. * @param string $prefix Prefix for fields name
  4682. * @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
  4683. * @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
  4684. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4685. * @param string $form_name Not used
  4686. * @param int $d 1=Show days, month, years
  4687. * @param int $addnowlink Add a link "Now"
  4688. * @param int $nooutput Do not output html string but return it
  4689. * @param int $disabled Disable input fields
  4690. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  4691. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  4692. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  4693. * @return string|void Nothing or string if nooutput is 1
  4694. * @deprecated
  4695. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  4696. */
  4697. 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 = '')
  4698. {
  4699. // phpcs:enable
  4700. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  4701. if (!empty($nooutput)) {
  4702. return $retstring;
  4703. }
  4704. print $retstring;
  4705. return;
  4706. }
  4707. /**
  4708. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4709. * Fields are preselected with :
  4710. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4711. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4712. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4713. *
  4714. * @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).
  4715. * @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).
  4716. * @param string $prefix Prefix for fields name
  4717. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4718. * @return string Html for selectDate
  4719. * @see form_date(), select_month(), select_year(), select_dayofweek()
  4720. */
  4721. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0)
  4722. {
  4723. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty);
  4724. $ret .= '<br/>';
  4725. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty);
  4726. return $ret;
  4727. }
  4728. /**
  4729. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4730. * Fields are preselected with :
  4731. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4732. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4733. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4734. *
  4735. * @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).
  4736. * @param string $prefix Prefix for fields name
  4737. * @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
  4738. * @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
  4739. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4740. * @param string $form_name Not used
  4741. * @param int $d 1=Show days, month, years
  4742. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  4743. * @param int $disabled Disable input fields
  4744. * @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')
  4745. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  4746. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  4747. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  4748. * @param int $stepminutes Specify step for minutes between 1 and 30
  4749. * @param string $labeladddateof Label to use for the $adddateof parameter.
  4750. * @param string $placeholder Placeholder
  4751. * @return string Html for selectDate
  4752. * @see form_date(), select_month(), select_year(), select_dayofweek()
  4753. */
  4754. 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 = '')
  4755. {
  4756. global $conf, $langs;
  4757. $retstring = '';
  4758. if ($prefix == '') $prefix = 're';
  4759. if ($h == '') $h = 0;
  4760. if ($m == '') $m = 0;
  4761. $emptydate = 0;
  4762. $emptyhours = 0;
  4763. if ($stepminutes <= 0 || $stepminutes > 30) $stepminutes = 1;
  4764. if ($empty == 1) { $emptydate = 1; $emptyhours = 1; }
  4765. if ($empty == 2) { $emptydate = 0; $emptyhours = 1; }
  4766. $orig_set_time = $set_time;
  4767. if ($set_time === '' && $emptydate == 0)
  4768. {
  4769. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4770. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  4771. }
  4772. // Analysis of the pre-selection date
  4773. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) // deprecated usage
  4774. {
  4775. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  4776. $syear = (!empty($reg[1]) ? $reg[1] : '');
  4777. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  4778. $sday = (!empty($reg[3]) ? $reg[3] : '');
  4779. $shour = (!empty($reg[4]) ? $reg[4] : '');
  4780. $smin = (!empty($reg[5]) ? $reg[5] : '');
  4781. } elseif (strval($set_time) != '' && $set_time != -1)
  4782. {
  4783. // set_time est un timestamps (0 possible)
  4784. $syear = dol_print_date($set_time, "%Y");
  4785. $smonth = dol_print_date($set_time, "%m");
  4786. $sday = dol_print_date($set_time, "%d");
  4787. if ($orig_set_time != '')
  4788. {
  4789. $shour = dol_print_date($set_time, "%H");
  4790. $smin = dol_print_date($set_time, "%M");
  4791. $ssec = dol_print_date($set_time, "%S");
  4792. } else {
  4793. $shour = '';
  4794. $smin = '';
  4795. $ssec = '';
  4796. }
  4797. } else {
  4798. // Date est '' ou vaut -1
  4799. $syear = '';
  4800. $smonth = '';
  4801. $sday = '';
  4802. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  4803. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  4804. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  4805. }
  4806. if ($h == 3) $shour = '';
  4807. if ($m == 3) $smin = '';
  4808. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  4809. $usecalendar = 'combo';
  4810. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  4811. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  4812. }
  4813. if ($d)
  4814. {
  4815. // Show date with popup
  4816. if ($usecalendar != 'combo')
  4817. {
  4818. $formated_date = '';
  4819. //print "e".$set_time." t ".$conf->format_date_short;
  4820. if (strval($set_time) != '' && $set_time != -1)
  4821. {
  4822. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  4823. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4824. }
  4825. // Calendrier popup version eldy
  4826. if ($usecalendar == "eldy")
  4827. {
  4828. // Zone de saisie manuelle de la date
  4829. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  4830. $retstring .= ($disabled ? ' disabled' : '');
  4831. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4832. $retstring .= '>';
  4833. // Icone calendrier
  4834. if (!$disabled)
  4835. {
  4836. $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  4837. $base = DOL_URL_ROOT.'/core/';
  4838. $retstring .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  4839. $retstring .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  4840. } else $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  4841. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4842. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4843. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4844. } elseif ($usecalendar == 'jquery')
  4845. {
  4846. if (!$disabled)
  4847. {
  4848. // Output javascript for datepicker
  4849. $retstring .= "<script type='text/javascript'>";
  4850. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  4851. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  4852. autoclose: true,
  4853. todayHighlight: true,";
  4854. if (!empty($conf->dol_use_jmobile))
  4855. {
  4856. $retstring .= "
  4857. beforeShow: function (input, datePicker) {
  4858. input.disabled = true;
  4859. },
  4860. onClose: function (dateText, datePicker) {
  4861. this.disabled = false;
  4862. },
  4863. ";
  4864. }
  4865. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  4866. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
  4867. {
  4868. $retstring .= "
  4869. showOn: 'button',
  4870. buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
  4871. buttonImageOnly: true";
  4872. }
  4873. $retstring .= "
  4874. }) });";
  4875. $retstring .= "</script>";
  4876. }
  4877. // Zone de saisie manuelle de la date
  4878. $retstring .= '<div class="nowrap inline-block">';
  4879. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  4880. $retstring .= ($disabled ? ' disabled' : '');
  4881. $retstring .= ($placeholder ? ' placeholder="'.$placeholder.'"' : '');
  4882. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4883. $retstring .= '>';
  4884. // Icone calendrier
  4885. if (!$disabled)
  4886. {
  4887. /* Not required. Managed by option buttonImage of jquery
  4888. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  4889. $retstring.="<script type='text/javascript'>";
  4890. $retstring.="jQuery(document).ready(function() {";
  4891. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  4892. $retstring.=" jQuery('#".$prefix."').focus();";
  4893. $retstring.=' });';
  4894. $retstring.='});';
  4895. $retstring.="</script>";*/
  4896. } else {
  4897. $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  4898. }
  4899. $retstring .= '</div>';
  4900. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4901. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4902. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4903. } else {
  4904. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  4905. }
  4906. }
  4907. // Show date with combo selects
  4908. else {
  4909. //$retstring.='<div class="inline-block">';
  4910. // Day
  4911. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  4912. if ($emptydate || $set_time == -1)
  4913. {
  4914. $retstring .= '<option value="0" selected>&nbsp;</option>';
  4915. }
  4916. for ($day = 1; $day <= 31; $day++)
  4917. {
  4918. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  4919. }
  4920. $retstring .= "</select>";
  4921. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  4922. if ($emptydate || $set_time == -1)
  4923. {
  4924. $retstring .= '<option value="0" selected>&nbsp;</option>';
  4925. }
  4926. // Month
  4927. for ($month = 1; $month <= 12; $month++)
  4928. {
  4929. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  4930. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  4931. $retstring .= "</option>";
  4932. }
  4933. $retstring .= "</select>";
  4934. // Year
  4935. if ($emptydate || $set_time == -1)
  4936. {
  4937. $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.'">';
  4938. } else {
  4939. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  4940. for ($year = $syear - 10; $year < $syear + 10; $year++)
  4941. {
  4942. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  4943. }
  4944. $retstring .= "</select>\n";
  4945. }
  4946. //$retstring.='</div>';
  4947. }
  4948. }
  4949. if ($d && $h) $retstring .= ($h == 2 ? '<br>' : ' ');
  4950. if ($h)
  4951. {
  4952. $hourstart = 0;
  4953. $hourend = 24;
  4954. if ($openinghours != '') {
  4955. $openinghours = explode(',', $openinghours);
  4956. $hourstart = $openinghours[0];
  4957. $hourend = $openinghours[1];
  4958. if ($hourend < $hourstart) $hourend = $hourstart;
  4959. }
  4960. // Show hour
  4961. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  4962. if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
  4963. for ($hour = $hourstart; $hour < $hourend; $hour++)
  4964. {
  4965. if (strlen($hour) < 2) $hour = "0".$hour;
  4966. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour.(empty($conf->dol_optimize_smallscreen) ? '' : 'H').'</option>';
  4967. }
  4968. $retstring .= '</select>';
  4969. if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  4970. }
  4971. if ($m)
  4972. {
  4973. // Show minutes
  4974. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  4975. if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
  4976. for ($min = 0; $min < 60; $min += $stepminutes)
  4977. {
  4978. if (strlen($min) < 2) $min = "0".$min;
  4979. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  4980. }
  4981. $retstring .= '</select>';
  4982. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  4983. }
  4984. // Add a "Now" link
  4985. if ($conf->use_javascript_ajax && $addnowlink)
  4986. {
  4987. // Script which will be inserted in the onClick of the "Now" link
  4988. $reset_scripts = "";
  4989. if ($addnowlink == 2) // local computer time
  4990. {
  4991. // pad add leading 0 on numbers
  4992. $reset_scripts .= "Number.prototype.pad = function(size) {
  4993. var s = String(this);
  4994. while (s.length < (size || 2)) {s = '0' + s;}
  4995. return s;
  4996. };
  4997. var d = new Date();";
  4998. }
  4999. // Generate the date part, depending on the use or not of the javascript calendar
  5000. if ($addnowlink == 1) // server time expressed in user time setup
  5001. {
  5002. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');';
  5003. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');';
  5004. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');';
  5005. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');';
  5006. } elseif ($addnowlink == 2)
  5007. {
  5008. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5009. * This break application for foreign languages.
  5010. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5011. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5012. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5013. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5014. */
  5015. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');';
  5016. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');';
  5017. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');';
  5018. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');';
  5019. }
  5020. /*if ($usecalendar == "eldy")
  5021. {
  5022. $base=DOL_URL_ROOT.'/core/';
  5023. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5024. }
  5025. else
  5026. {
  5027. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5028. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5029. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5030. }*/
  5031. // Update the hour part
  5032. if ($h)
  5033. {
  5034. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5035. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5036. if ($addnowlink == 1)
  5037. {
  5038. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');';
  5039. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5040. } elseif ($addnowlink == 2)
  5041. {
  5042. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5043. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5044. }
  5045. if ($fullday) $reset_scripts .= ' } ';
  5046. }
  5047. // Update the minute part
  5048. if ($m)
  5049. {
  5050. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5051. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  5052. if ($addnowlink == 1)
  5053. {
  5054. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');';
  5055. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5056. } elseif ($addnowlink == 2)
  5057. {
  5058. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  5059. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5060. }
  5061. if ($fullday) $reset_scripts .= ' } ';
  5062. }
  5063. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5064. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  5065. {
  5066. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  5067. $retstring .= $langs->trans("Now");
  5068. $retstring .= '</button> ';
  5069. }
  5070. }
  5071. // Add a "Plus one hour" link
  5072. if ($conf->use_javascript_ajax && $addplusone)
  5073. {
  5074. // Script which will be inserted in the onClick of the "Add plusone" link
  5075. $reset_scripts = "";
  5076. // Generate the date part, depending on the use or not of the javascript calendar
  5077. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day').'\');';
  5078. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d').'\');';
  5079. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m').'\');';
  5080. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y').'\');';
  5081. // Update the hour part
  5082. if ($h)
  5083. {
  5084. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5085. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H').'\');';
  5086. if ($fullday) $reset_scripts .= ' } ';
  5087. }
  5088. // Update the minute part
  5089. if ($m)
  5090. {
  5091. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5092. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M').'\');';
  5093. if ($fullday) $reset_scripts .= ' } ';
  5094. }
  5095. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5096. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  5097. {
  5098. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  5099. $retstring .= $langs->trans("DateStartPlusOne");
  5100. $retstring .= '</button> ';
  5101. }
  5102. }
  5103. // Add a "Plus one hour" link
  5104. if ($conf->use_javascript_ajax && $adddateof)
  5105. {
  5106. $tmparray = dol_getdate($adddateof);
  5107. if (empty($labeladddateof)) $labeladddateof = $langs->trans("DateInvoice");
  5108. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  5109. }
  5110. return $retstring;
  5111. }
  5112. /**
  5113. * selectTypeDuration
  5114. *
  5115. * @param string $prefix Prefix
  5116. * @param string $selected Selected type
  5117. * @return string HTML select string
  5118. */
  5119. public function selectTypeDuration($prefix, $selected = 'i')
  5120. {
  5121. global $langs;
  5122. $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes'));
  5123. $retstring = '<select class="flat" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  5124. foreach ($TDurationTypes as $key=>$typeduration) {
  5125. $retstring .= '<option value="'.$key.'"';
  5126. if ($key == $selected) {
  5127. $retstring .= " selected";
  5128. }
  5129. $retstring .= ">".$typeduration."</option>";
  5130. }
  5131. $retstring .= "</select>";
  5132. return $retstring;
  5133. }
  5134. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5135. /**
  5136. * Function to show a form to select a duration on a page
  5137. *
  5138. * @param string $prefix Prefix for input fields
  5139. * @param int $iSecond Default preselected duration (number of seconds or '')
  5140. * @param int $disabled Disable the combo box
  5141. * @param string $typehour If 'select' then input hour and input min is a combo,
  5142. * If 'text' input hour is in text and input min is a text,
  5143. * If 'textselect' input hour is in text and input min is a combo
  5144. * @param integer $minunderhours If 1, show minutes selection under the hours
  5145. * @param int $nooutput Do not output html string but return it
  5146. * @return string|void
  5147. */
  5148. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  5149. {
  5150. // phpcs:enable
  5151. global $langs;
  5152. $retstring = '';
  5153. $hourSelected = 0; $minSelected = 0;
  5154. // Hours
  5155. if ($iSecond != '')
  5156. {
  5157. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5158. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  5159. $minSelected = convertSecondToTime($iSecond, 'min');
  5160. }
  5161. if ($typehour == 'select') {
  5162. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  5163. for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours
  5164. {
  5165. $retstring .= '<option value="'.$hour.'"';
  5166. if ($hourSelected == $hour)
  5167. {
  5168. $retstring .= " selected";
  5169. }
  5170. $retstring .= ">".$hour."</option>";
  5171. }
  5172. $retstring .= "</select>";
  5173. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  5174. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  5175. } else {
  5176. return 'BadValueForParameterTypeHour';
  5177. }
  5178. if ($typehour != 'text') $retstring .= ' '.$langs->trans('HourShort');
  5179. else $retstring .= '<span class="hideonsmartphone">:</span>';
  5180. // Minutes
  5181. if ($minunderhours) $retstring .= '<br>';
  5182. else $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  5183. if ($typehour == 'select' || $typehour == 'textselect')
  5184. {
  5185. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  5186. for ($min = 0; $min <= 55; $min = $min + 5)
  5187. {
  5188. $retstring .= '<option value="'.$min.'"';
  5189. if ($minSelected == $min) $retstring .= ' selected';
  5190. $retstring .= '>'.$min.'</option>';
  5191. }
  5192. $retstring .= "</select>";
  5193. } elseif ($typehour == 'text')
  5194. {
  5195. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  5196. }
  5197. if ($typehour != 'text') $retstring .= ' '.$langs->trans('MinuteShort');
  5198. //$retstring.="&nbsp;";
  5199. if (!empty($nooutput)) return $retstring;
  5200. print $retstring;
  5201. return;
  5202. }
  5203. /**
  5204. * Generic method to select a component from a combo list.
  5205. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  5206. * This is the generic method that will replace all specific existing methods.
  5207. *
  5208. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]
  5209. * @param string $htmlname Name of HTML select component
  5210. * @param int $preselectedvalue Preselected value (ID of element)
  5211. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  5212. * @param string $searchkey Search criteria
  5213. * @param string $placeholder Place holder
  5214. * @param string $morecss More CSS
  5215. * @param string $moreparams More params provided to ajax call
  5216. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  5217. * @param int $disabled 1=Html component is disabled
  5218. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  5219. * @return string Return HTML string
  5220. * @see selectForFormsList() select_thirdparty()
  5221. */
  5222. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  5223. {
  5224. global $conf, $user;
  5225. $objecttmp = null;
  5226. $InfoFieldList = explode(":", $objectdesc);
  5227. $classname = $InfoFieldList[0];
  5228. $classpath = $InfoFieldList[1];
  5229. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  5230. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  5231. if (!empty($classpath))
  5232. {
  5233. dol_include_once($classpath);
  5234. if ($classname && class_exists($classname))
  5235. {
  5236. $objecttmp = new $classname($this->db);
  5237. // Make some replacement
  5238. $sharedentities = getEntity(strtolower($classname));
  5239. $objecttmp->filter = str_replace(
  5240. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  5241. array($conf->entity, $sharedentities, $user->id),
  5242. $filter);
  5243. }
  5244. }
  5245. if (!is_object($objecttmp))
  5246. {
  5247. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  5248. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  5249. }
  5250. //var_dump($objecttmp->filter);
  5251. $prefixforautocompletemode = $objecttmp->element;
  5252. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
  5253. if ($prefixforautocompletemode == 'product') $prefixforautocompletemode = 'produit';
  5254. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  5255. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  5256. $out = '';
  5257. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo)
  5258. {
  5259. // No immediate load of all database
  5260. $placeholder = '';
  5261. if ($preselectedvalue && empty($selected_input_value))
  5262. {
  5263. $objecttmp->fetch($preselectedvalue);
  5264. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  5265. //unset($objecttmp);
  5266. }
  5267. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  5268. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  5269. // No immediate load of all database
  5270. $urloption = 'htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.'&filter='.urlencode($objecttmp->filter);
  5271. // Activate the auto complete using ajax call.
  5272. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  5273. $out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  5274. if ($placeholder) $placeholder = ' placeholder="'.$placeholder.'"';
  5275. $out .= '<input type="text" class="'.$morecss.'"'.($disabled ? ' disabled="disabled"' : '').' name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
  5276. } else {
  5277. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  5278. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled);
  5279. }
  5280. return $out;
  5281. }
  5282. /**
  5283. * Function to forge a SQL criteria
  5284. *
  5285. * @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"
  5286. * @return string Forged criteria. Example: "t.field like 'abc%'"
  5287. */
  5288. protected static function forgeCriteriaCallback($matches)
  5289. {
  5290. global $db;
  5291. //dol_syslog("Convert matches ".$matches[1]);
  5292. if (empty($matches[1])) return '';
  5293. $tmp = explode(':', $matches[1]);
  5294. if (count($tmp) < 3) return '';
  5295. $tmpescaped = $tmp[2];
  5296. $regbis = array();
  5297. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis))
  5298. {
  5299. $tmpescaped = "'".$db->escape($regbis[1])."'";
  5300. } else {
  5301. $tmpescaped = $db->escape($tmpescaped);
  5302. }
  5303. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  5304. }
  5305. /**
  5306. * Output html form to select an object.
  5307. * Note, this function is called by selectForForms or by ajax selectobject.php
  5308. *
  5309. * @param Object $objecttmp Object to knwo the table to scan for combo.
  5310. * @param string $htmlname Name of HTML select component
  5311. * @param int $preselectedvalue Preselected value (ID of element)
  5312. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  5313. * @param string $searchkey Search value
  5314. * @param string $placeholder Place holder
  5315. * @param string $morecss More CSS
  5316. * @param string $moreparams More params provided to ajax call
  5317. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  5318. * @param int $outputmode 0=HTML select string, 1=Array
  5319. * @param int $disabled 1=Html component is disabled
  5320. * @return string|array Return HTML string
  5321. * @see selectForForms()
  5322. */
  5323. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0)
  5324. {
  5325. global $conf, $langs, $user;
  5326. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  5327. $prefixforautocompletemode = $objecttmp->element;
  5328. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
  5329. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  5330. if (!empty($objecttmp->fields)) // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  5331. {
  5332. $tmpfieldstoshow = '';
  5333. foreach ($objecttmp->fields as $key => $val)
  5334. {
  5335. if ($val['showoncombobox']) $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  5336. }
  5337. if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
  5338. } else {
  5339. // For backward compatibility
  5340. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  5341. }
  5342. if (empty($fieldstoshow))
  5343. {
  5344. if (isset($objecttmp->fields['ref'])) {
  5345. $fieldstoshow = 't.ref';
  5346. } else {
  5347. $langs->load("errors");
  5348. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  5349. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  5350. }
  5351. }
  5352. $out = '';
  5353. $outarray = array();
  5354. $num = 0;
  5355. // Search data
  5356. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX.$objecttmp->table_element." as t";
  5357. if (isset($objecttmp->ismultientitymanaged) && !is_numeric($objecttmp->ismultientitymanaged)) {
  5358. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  5359. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.$tmparray[1].' as parenttable ON parenttable.rowid = t.'.$tmparray[0];
  5360. }
  5361. if ($objecttmp->ismultientitymanaged == 'fk_soc@societe')
  5362. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  5363. $sql .= " WHERE 1=1";
  5364. if (isset($objecttmp->ismultientitymanaged) && $objecttmp->ismultientitymanaged == 1) $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  5365. if (isset($objecttmp->ismultientitymanaged) && !is_numeric($objecttmp->ismultientitymanaged)) {
  5366. $sql .= ' AND parenttable.entity = t.'.$tmparray[0];
  5367. }
  5368. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  5369. if ($objecttmp->element == 'societe') $sql .= " AND t.rowid = ".$user->socid;
  5370. else $sql .= " AND t.fk_soc = ".$user->socid;
  5371. }
  5372. if ($searchkey != '') $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  5373. if ($objecttmp->ismultientitymanaged == 'fk_soc@societe') {
  5374. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
  5375. }
  5376. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  5377. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  5378. {
  5379. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  5380. }*/
  5381. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  5382. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  5383. }
  5384. $sql .= $this->db->order($fieldstoshow, "ASC");
  5385. //$sql.=$this->db->plimit($limit, 0);
  5386. //print $sql;
  5387. // Build output string
  5388. $resql = $this->db->query($sql);
  5389. if ($resql)
  5390. {
  5391. if (!$forcecombo)
  5392. {
  5393. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5394. $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
  5395. }
  5396. // Construct $out and $outarray
  5397. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  5398. // 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
  5399. $textifempty = '&nbsp;';
  5400. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  5401. if (!empty($conf->global->$confkeyforautocompletemode))
  5402. {
  5403. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  5404. else $textifempty .= $langs->trans("All");
  5405. }
  5406. if ($showempty) $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  5407. $num = $this->db->num_rows($resql);
  5408. $i = 0;
  5409. if ($num)
  5410. {
  5411. while ($i < $num)
  5412. {
  5413. $obj = $this->db->fetch_object($resql);
  5414. $label = '';
  5415. $tmparray = explode(',', $fieldstoshow);
  5416. foreach ($tmparray as $key => $val)
  5417. {
  5418. $val = preg_replace('/t\./', '', $val);
  5419. $label .= (($label && $obj->$val) ? ' - ' : '').$obj->$val;
  5420. }
  5421. if (empty($outputmode))
  5422. {
  5423. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
  5424. {
  5425. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  5426. } else {
  5427. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  5428. }
  5429. } else {
  5430. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  5431. }
  5432. $i++;
  5433. if (($i % 10) == 0) $out .= "\n";
  5434. }
  5435. }
  5436. $out .= '</select>'."\n";
  5437. } else {
  5438. dol_print_error($this->db);
  5439. }
  5440. $this->result = array('nbofelement'=>$num);
  5441. if ($outputmode) return $outarray;
  5442. return $out;
  5443. }
  5444. /**
  5445. * Return a HTML select string, built from an array of key+value.
  5446. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  5447. *
  5448. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  5449. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>...))
  5450. * @param string|string[] $id Preselected key or preselected keys for multiselect
  5451. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
  5452. * @param int $key_in_label 1 to show key into label with format "[key] value"
  5453. * @param int $value_as_key 1 to use value as key
  5454. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  5455. * @param int $translate 1=Translate and encode value
  5456. * @param int $maxlen Length maximum for labels
  5457. * @param int $disabled Html select box is disabled
  5458. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  5459. * @param string $morecss Add more class to css styles
  5460. * @param int $addjscombo Add js combo
  5461. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  5462. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  5463. * @param int $nohtmlescape No html escaping.
  5464. * @return string HTML select string.
  5465. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  5466. */
  5467. 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 = 0, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  5468. {
  5469. global $conf, $langs;
  5470. // Do we want a multiselect ?
  5471. //$jsbeautify = 0;
  5472. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  5473. $jsbeautify = 1;
  5474. if ($value_as_key) $array = array_combine($array, $array);
  5475. $out = '';
  5476. // Add code for jquery to use multiselect
  5477. if ($addjscombo && $jsbeautify)
  5478. {
  5479. $minLengthToAutocomplete = 0;
  5480. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? (constant('REQUIRE_JQUERY_MULTISELECT') ?constant('REQUIRE_JQUERY_MULTISELECT') : 'select2') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5481. // Enhance with select2
  5482. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5483. $out .= ajax_combobox($htmlname);
  5484. }
  5485. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  5486. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  5487. $out .= '>';
  5488. if ($show_empty)
  5489. {
  5490. $textforempty = ' ';
  5491. if (!empty($conf->use_javascript_ajax)) $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  5492. if (!is_numeric($show_empty)) $textforempty = $show_empty;
  5493. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  5494. }
  5495. if (is_array($array))
  5496. {
  5497. // Translate
  5498. if ($translate)
  5499. {
  5500. foreach ($array as $key => $value)
  5501. {
  5502. if (!is_array($value)) $array[$key] = $langs->trans($value);
  5503. else $array[$key]['label'] = $langs->trans($value['label']);
  5504. }
  5505. }
  5506. // Sort
  5507. if ($sort == 'ASC') asort($array);
  5508. elseif ($sort == 'DESC') arsort($array);
  5509. foreach ($array as $key => $tmpvalue)
  5510. {
  5511. if (is_array($tmpvalue)) $value = $tmpvalue['label'];
  5512. else $value = $tmpvalue;
  5513. $disabled = ''; $style = '';
  5514. if (!empty($disablebademail))
  5515. {
  5516. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  5517. || ($disablebademail == 2 && preg_match('/---/', $value)))
  5518. {
  5519. $disabled = ' disabled';
  5520. $style = ' class="warning"';
  5521. }
  5522. }
  5523. if ($key_in_label)
  5524. {
  5525. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  5526. else $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  5527. } else {
  5528. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  5529. else $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  5530. if ($value == '' || $value == '-') $selectOptionValue = '&nbsp;';
  5531. }
  5532. $out .= '<option value="'.$key.'"';
  5533. $out .= $style.$disabled;
  5534. if (is_array($id)) {
  5535. if (in_array($key, $id) && !$disabled) $out .= ' selected'; // To preselect a value
  5536. } else {
  5537. $id = (string) $id; // if $id = 0, then $id = '0'
  5538. if ($id != '' && $id == $key && !$disabled) $out .= ' selected'; // To preselect a value
  5539. }
  5540. if ($nohtmlescape) $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  5541. if (is_array($tmpvalue))
  5542. {
  5543. foreach ($tmpvalue as $keyforvalue => $valueforvalue)
  5544. {
  5545. if (preg_match('/^data-/', $keyforvalue)) $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  5546. }
  5547. }
  5548. $out .= '>';
  5549. //var_dump($selectOptionValue);
  5550. $out .= $selectOptionValue;
  5551. $out .= "</option>\n";
  5552. }
  5553. }
  5554. $out .= "</select>";
  5555. return $out;
  5556. }
  5557. /**
  5558. * 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.
  5559. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5560. *
  5561. * @param string $htmlname Name of html select area
  5562. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5563. * @param string $id Preselected key
  5564. * @param string $moreparam Add more parameters onto the select tag
  5565. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  5566. * @param int $disabled Html select box is disabled
  5567. * @param int $minimumInputLength Minimum Input Length
  5568. * @param string $morecss Add more class to css styles
  5569. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5570. * @param string $placeholder String to use as placeholder
  5571. * @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)
  5572. * @return string HTML select string
  5573. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  5574. */
  5575. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  5576. {
  5577. global $conf, $langs;
  5578. global $delayedhtmlcontent;
  5579. // TODO Use an internal dolibarr component instead of select2
  5580. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5581. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  5582. $tmpplugin = 'select2';
  5583. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5584. <script>
  5585. $(document).ready(function () {
  5586. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  5587. $(".'.$htmlname.'").select2({
  5588. ajax: {
  5589. dir: "ltr",
  5590. url: "'.$url.'",
  5591. dataType: \'json\',
  5592. delay: 250,
  5593. data: function (params) {
  5594. return {
  5595. q: params.term, // search term
  5596. page: params.page
  5597. };
  5598. },
  5599. processResults: function (data) {
  5600. // parse the results into the format expected by Select2.
  5601. // since we are using custom formatting functions we do not need to alter the remote JSON data
  5602. //console.log(data);
  5603. saveRemoteData = data;
  5604. /* format json result for select2 */
  5605. result = []
  5606. $.each( data, function( key, value ) {
  5607. result.push({id: key, text: value.text});
  5608. });
  5609. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  5610. //console.log(result);
  5611. return {results: result, more: false}
  5612. },
  5613. cache: true
  5614. },
  5615. language: select2arrayoflanguage,
  5616. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5617. placeholder: "'.dol_escape_js($placeholder).'",
  5618. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5619. minimumInputLength: '.$minimumInputLength.',
  5620. formatResult: function(result, container, query, escapeMarkup) {
  5621. return escapeMarkup(result.text);
  5622. },
  5623. });
  5624. '.($callurlonselect ? '
  5625. /* Code to execute a GET when we select a value */
  5626. $(".'.$htmlname.'").change(function() {
  5627. var selected = $(".'.$htmlname.'").val();
  5628. console.log("We select in selectArrayAjax the entry "+selected)
  5629. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5630. $.each( saveRemoteData, function( key, value ) {
  5631. if (key == selected)
  5632. {
  5633. console.log("selectArrayAjax - Do a redirect to "+value.url)
  5634. location.assign(value.url);
  5635. }
  5636. });
  5637. });' : '').'
  5638. });
  5639. </script>';
  5640. if ($acceptdelayedhtml)
  5641. {
  5642. $delayedhtmlcontent .= $outdelayed;
  5643. } else {
  5644. $out .= $outdelayed;
  5645. }
  5646. return $out;
  5647. }
  5648. /**
  5649. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  5650. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5651. *
  5652. * @param string $htmlname Name of html select area
  5653. * @param string $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5654. * @param string $id Preselected key
  5655. * @param string $moreparam Add more parameters onto the select tag
  5656. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  5657. * @param int $disabled Html select box is disabled
  5658. * @param int $minimumInputLength Minimum Input Length
  5659. * @param string $morecss Add more class to css styles
  5660. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5661. * @param string $placeholder String to use as placeholder
  5662. * @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)
  5663. * @return string HTML select string
  5664. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  5665. */
  5666. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  5667. {
  5668. global $conf, $langs;
  5669. global $delayedhtmlcontent;
  5670. // TODO Use an internal dolibarr component instead of select2
  5671. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5672. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  5673. $formattedarrayresult = array();
  5674. foreach ($array as $key => $value) {
  5675. $o = new stdClass();
  5676. $o->id = $key;
  5677. $o->text = $value['text'];
  5678. $o->url = $value['url'];
  5679. $formattedarrayresult[] = $o;
  5680. }
  5681. $tmpplugin = 'select2';
  5682. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5683. <script>
  5684. $(document).ready(function () {
  5685. var data = '.json_encode($formattedarrayresult).';
  5686. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  5687. $(".'.$htmlname.'").select2({
  5688. data: data,
  5689. language: select2arrayoflanguage,
  5690. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5691. placeholder: "'.dol_escape_js($placeholder).'",
  5692. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5693. minimumInputLength: '.$minimumInputLength.',
  5694. formatResult: function(result, container, query, escapeMarkup) {
  5695. return escapeMarkup(result.text);
  5696. },
  5697. matcher: function (params, data) {
  5698. if(! data.id) return null;';
  5699. if ($callurlonselect) {
  5700. $outdelayed .= '
  5701. var urlBase = data.url;
  5702. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  5703. /* console.log("params.term="+params.term); */
  5704. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  5705. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term);';
  5706. }
  5707. if (!$disableFiltering) {
  5708. $outdelayed .= '
  5709. if(data.text.match(new RegExp(params.term))) {
  5710. return data;
  5711. }
  5712. return null;';
  5713. } else {
  5714. $outdelayed .= '
  5715. return data;';
  5716. }
  5717. $outdelayed .= '
  5718. }
  5719. });
  5720. '.($callurlonselect ? '
  5721. /* Code to execute a GET when we select a value */
  5722. $(".'.$htmlname.'").change(function() {
  5723. var selected = $(".'.$htmlname.'").val();
  5724. console.log("We select "+selected)
  5725. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5726. $.each( saveRemoteData, function( key, value ) {
  5727. if (key == selected)
  5728. {
  5729. console.log("selectArrayAjax - Do a redirect to "+value.url)
  5730. location.assign(value.url);
  5731. }
  5732. });
  5733. });' : '').'
  5734. });
  5735. </script>';
  5736. if ($acceptdelayedhtml)
  5737. {
  5738. $delayedhtmlcontent .= $outdelayed;
  5739. } else {
  5740. $out .= $outdelayed;
  5741. }
  5742. return $out;
  5743. }
  5744. /**
  5745. * Show a multiselect form from an array.
  5746. *
  5747. * @param string $htmlname Name of select
  5748. * @param array $array Array with key+value
  5749. * @param array $selected Array with key+value preselected
  5750. * @param int $key_in_label 1 to show key like in "[key] value"
  5751. * @param int $value_as_key 1 to use value as key
  5752. * @param string $morecss Add more css style
  5753. * @param int $translate Translate and encode value
  5754. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  5755. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  5756. * @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.
  5757. * @param string $placeholder String to use as placeholder
  5758. * @param int $addjscombo Add js combo
  5759. * @return string HTML multiselect string
  5760. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  5761. */
  5762. 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)
  5763. {
  5764. global $conf, $langs;
  5765. $out = '';
  5766. if ($addjscombo < 0) {
  5767. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $addjscombo = 1;
  5768. else $addjscombo = 0;
  5769. }
  5770. // Add code for jquery to use multiselect
  5771. if (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
  5772. {
  5773. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.' -->
  5774. <script>'."\n";
  5775. if ($addjscombo == 1)
  5776. {
  5777. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5778. $out .= 'function formatResult(record) {'."\n";
  5779. if ($elemtype == 'category')
  5780. {
  5781. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  5782. } else {
  5783. $out .= 'return record.text;';
  5784. }
  5785. $out .= '};'."\n";
  5786. $out .= 'function formatSelection(record) {'."\n";
  5787. if ($elemtype == 'category')
  5788. {
  5789. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  5790. } else {
  5791. $out .= 'return record.text;';
  5792. }
  5793. $out .= '};'."\n";
  5794. $out .= '$(document).ready(function () {
  5795. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  5796. dir: \'ltr\',
  5797. // Specify format function for dropdown item
  5798. formatResult: formatResult,
  5799. templateResult: formatResult, /* For 4.0 */
  5800. // Specify format function for selected item
  5801. formatSelection: formatSelection,
  5802. templateSelection: formatSelection /* For 4.0 */
  5803. });
  5804. });'."\n";
  5805. } elseif ($addjscombo == 2 && ! defined('DISABLE_MULTISELECT'))
  5806. {
  5807. // Add other js lib
  5808. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  5809. // ...
  5810. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  5811. $out .= '$(document).ready(function () {
  5812. $(\'#'.$htmlname.'\').multiSelect({
  5813. containerHTML: \'<div class="multi-select-container">\',
  5814. menuHTML: \'<div class="multi-select-menu">\',
  5815. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  5816. menuItemHTML: \'<label class="multi-select-menuitem">\',
  5817. activeClass: \'multi-select-container--open\',
  5818. noneText: \''.$placeholder.'\'
  5819. });
  5820. })';
  5821. }
  5822. $out .= '</script>';
  5823. }
  5824. // Try also magic suggest
  5825. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  5826. if (is_array($array) && !empty($array))
  5827. {
  5828. if ($value_as_key) $array = array_combine($array, $array);
  5829. if (!empty($array))
  5830. {
  5831. foreach ($array as $key => $value)
  5832. {
  5833. $newval = ($translate ? $langs->trans($value) : $value);
  5834. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  5835. $out .= '<option value="'.$key.'"';
  5836. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != ''))
  5837. {
  5838. $out .= ' selected';
  5839. }
  5840. $out .= ' data-html="'.$newval.'"';
  5841. $out .= '>';
  5842. $out .= dol_htmlentitiesbr($newval);
  5843. $out .= '</option>'."\n";
  5844. }
  5845. }
  5846. }
  5847. $out .= '</select>'."\n";
  5848. return $out;
  5849. }
  5850. /**
  5851. * Show a multiselect dropbox from an array.
  5852. *
  5853. * @param string $htmlname Name of HTML field
  5854. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  5855. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  5856. * @return string HTML multiselect string
  5857. * @see selectarray()
  5858. */
  5859. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  5860. {
  5861. global $conf, $langs, $user, $extrafields;
  5862. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
  5863. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved seleteced properties
  5864. if (!empty($user->conf->$tmpvar))
  5865. {
  5866. $tmparray = explode(',', $user->conf->$tmpvar);
  5867. foreach ($array as $key => $val)
  5868. {
  5869. //var_dump($key);
  5870. //var_dump($tmparray);
  5871. if (in_array($key, $tmparray)) $array[$key]['checked'] = 1;
  5872. else $array[$key]['checked'] = 0;
  5873. }
  5874. }
  5875. $lis = '';
  5876. $listcheckedstring = '';
  5877. foreach ($array as $key => $val)
  5878. {
  5879. /* var_dump($val);
  5880. var_dump(array_key_exists('enabled', $val));
  5881. var_dump(!$val['enabled']);*/
  5882. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled'])
  5883. {
  5884. unset($array[$key]); // We don't want this field
  5885. continue;
  5886. }
  5887. if ($val['label'])
  5888. {
  5889. if (!empty($val['langfile']) && is_object($langs)) {
  5890. $langs->load($val['langfile']);
  5891. }
  5892. $lis .= '<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked']) ? '' : ' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
  5893. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  5894. }
  5895. }
  5896. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  5897. <dl class="dropdown">
  5898. <dt>
  5899. <a href="#'.$htmlname.'">
  5900. '.img_picto('', 'list').'
  5901. </a>
  5902. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  5903. </dt>
  5904. <dd class="dropdowndd">
  5905. <div class="multiselectcheckbox'.$htmlname.'">
  5906. <ul class="ul'.$htmlname.'">
  5907. '.$lis.'
  5908. </ul>
  5909. </div>
  5910. </dd>
  5911. </dl>
  5912. <script type="text/javascript">
  5913. jQuery(document).ready(function () {
  5914. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  5915. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  5916. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  5917. var title = $(this).val() + ",";
  5918. if ($(this).is(\':checked\')) {
  5919. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  5920. }
  5921. else {
  5922. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  5923. }
  5924. // Now, we submit page
  5925. //$(this).parents(\'form:first\').submit();
  5926. });
  5927. });
  5928. </script>
  5929. ';
  5930. return $out;
  5931. }
  5932. /**
  5933. * Render list of categories linked to object with id $id and type $type
  5934. *
  5935. * @param int $id Id of object
  5936. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  5937. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  5938. * @param int $nolink 1=Do not add html links
  5939. * @return string String with categories
  5940. */
  5941. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  5942. {
  5943. global $db;
  5944. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  5945. $cat = new Categorie($db);
  5946. $categories = $cat->containing($id, $type);
  5947. if ($rendermode == 1)
  5948. {
  5949. $toprint = array();
  5950. foreach ($categories as $c)
  5951. {
  5952. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  5953. foreach ($ways as $way)
  5954. {
  5955. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #aaa"').'>'.$way.'</li>';
  5956. }
  5957. }
  5958. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5959. }
  5960. if ($rendermode == 0)
  5961. {
  5962. $arrayselected = array();
  5963. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  5964. foreach ($categories as $c) {
  5965. $arrayselected[] = $c->id;
  5966. }
  5967. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  5968. }
  5969. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  5970. }
  5971. /**
  5972. * Show linked object block.
  5973. *
  5974. * @param CommonObject $object Object we want to show links to
  5975. * @param string $morehtmlright More html to show on right of title
  5976. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  5977. * @return int <0 if KO, >=0 if OK
  5978. */
  5979. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  5980. {
  5981. global $conf, $langs, $hookmanager;
  5982. global $bc, $action;
  5983. $object->fetchObjectLinked();
  5984. // Bypass the default method
  5985. $hookmanager->initHooks(array('commonobject'));
  5986. $parameters = array(
  5987. 'morehtmlright' => $morehtmlright,
  5988. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  5989. );
  5990. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  5991. if (empty($reshook))
  5992. {
  5993. $nbofdifferenttypes = count($object->linkedObjects);
  5994. print '<!-- showLinkedObjectBlock -->';
  5995. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  5996. print '<div class="div-table-responsive-no-min">';
  5997. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  5998. print '<tr class="liste_titre">';
  5999. print '<td>'.$langs->trans("Type").'</td>';
  6000. print '<td>'.$langs->trans("Ref").'</td>';
  6001. print '<td class="center"></td>';
  6002. print '<td class="center">'.$langs->trans("Date").'</td>';
  6003. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  6004. print '<td class="right">'.$langs->trans("Status").'</td>';
  6005. print '<td></td>';
  6006. print '</tr>';
  6007. $nboftypesoutput = 0;
  6008. foreach ($object->linkedObjects as $objecttype => $objects)
  6009. {
  6010. $tplpath = $element = $subelement = $objecttype;
  6011. // to display inport button on tpl
  6012. $showImportButton = false;
  6013. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  6014. $showImportButton = true;
  6015. }
  6016. $regs = array();
  6017. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
  6018. {
  6019. $element = $regs[1];
  6020. $subelement = $regs[2];
  6021. $tplpath = $element.'/'.$subelement;
  6022. }
  6023. $tplname = 'linkedobjectblock';
  6024. // To work with non standard path
  6025. if ($objecttype == 'facture') {
  6026. $tplpath = 'compta/'.$element;
  6027. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  6028. } elseif ($objecttype == 'facturerec') {
  6029. $tplpath = 'compta/facture';
  6030. $tplname = 'linkedobjectblockForRec';
  6031. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  6032. } elseif ($objecttype == 'propal') {
  6033. $tplpath = 'comm/'.$element;
  6034. if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
  6035. } elseif ($objecttype == 'supplier_proposal') {
  6036. if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
  6037. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  6038. $tplpath = 'expedition';
  6039. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  6040. } elseif ($objecttype == 'reception') {
  6041. $tplpath = 'reception';
  6042. if (empty($conf->reception->enabled)) continue; // Do not show if module disabled
  6043. } elseif ($objecttype == 'delivery') {
  6044. $tplpath = 'delivery';
  6045. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  6046. } elseif ($objecttype == 'invoice_supplier') {
  6047. $tplpath = 'fourn/facture';
  6048. } elseif ($objecttype == 'order_supplier') {
  6049. $tplpath = 'fourn/commande';
  6050. } elseif ($objecttype == 'expensereport') {
  6051. $tplpath = 'expensereport';
  6052. } elseif ($objecttype == 'subscription') {
  6053. $tplpath = 'adherents';
  6054. }
  6055. global $linkedObjectBlock;
  6056. $linkedObjectBlock = $objects;
  6057. // Output template part (modules that overwrite templates must declare this into descriptor)
  6058. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  6059. foreach ($dirtpls as $reldir)
  6060. {
  6061. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after
  6062. {
  6063. global $noMoreLinkedObjectBlockAfter;
  6064. $noMoreLinkedObjectBlockAfter = 1;
  6065. }
  6066. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  6067. if ($res)
  6068. {
  6069. $nboftypesoutput++;
  6070. break;
  6071. }
  6072. }
  6073. }
  6074. if (!$nboftypesoutput)
  6075. {
  6076. print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
  6077. }
  6078. print '</table>';
  6079. if (!empty($compatibleImportElementsList))
  6080. {
  6081. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  6082. }
  6083. print '</div>';
  6084. return $nbofdifferenttypes;
  6085. }
  6086. }
  6087. /**
  6088. * Show block with links to link to other objects.
  6089. *
  6090. * @param CommonObject $object Object we want to show links to
  6091. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  6092. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  6093. * @return string <0 if KO, >0 if OK
  6094. */
  6095. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  6096. {
  6097. global $conf, $langs, $hookmanager;
  6098. global $bc, $action;
  6099. $linktoelem = '';
  6100. $linktoelemlist = '';
  6101. $listofidcompanytoscan = '';
  6102. if (!is_object($object->thirdparty)) $object->fetch_thirdparty();
  6103. $possiblelinks = array();
  6104. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0)
  6105. {
  6106. $listofidcompanytoscan = $object->thirdparty->id;
  6107. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  6108. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
  6109. {
  6110. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6111. $tmpproject = new Project($this->db);
  6112. $tmpproject->fetch($object->fk_project);
  6113. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan .= ','.$tmpproject->socid;
  6114. unset($tmpproject);
  6115. }
  6116. $possiblelinks = array(
  6117. 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
  6118. 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
  6119. 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
  6120. 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
  6121. 'contrat'=>array('enabled'=>$conf->contrat->enabled, 'perms'=>1, 'label'=>'LinkToContract',
  6122. '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, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
  6123. 'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
  6124. 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
  6125. 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
  6126. 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled, 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')'),
  6127. 'ticket'=>array('enabled'=>$conf->ticket->enabled, 'perms'=>1, 'label'=>'LinkToTicket', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('ticket').')')
  6128. );
  6129. }
  6130. // Can complete the possiblelink array
  6131. $hookmanager->initHooks(array('commonobject'));
  6132. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan);
  6133. if (!empty($listofidcompanytoscan)) // If empty, we don't have criteria to scan the object we can link to
  6134. {
  6135. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  6136. }
  6137. if (empty($reshook))
  6138. {
  6139. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  6140. {
  6141. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  6142. }
  6143. } elseif ($reshook > 0)
  6144. {
  6145. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  6146. {
  6147. $possiblelinks = $hookmanager->resArray;
  6148. }
  6149. }
  6150. foreach ($possiblelinks as $key => $possiblelink)
  6151. {
  6152. $num = 0;
  6153. if (empty($possiblelink['enabled'])) continue;
  6154. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto)))
  6155. {
  6156. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  6157. $sql = $possiblelink['sql'];
  6158. $resqllist = $this->db->query($sql);
  6159. if ($resqllist)
  6160. {
  6161. $num = $this->db->num_rows($resqllist);
  6162. $i = 0;
  6163. print '<br>';
  6164. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  6165. print '<input type="hidden" name="action" value="addlink">';
  6166. print '<input type="hidden" name="token" value="'.newToken().'">';
  6167. print '<input type="hidden" name="id" value="'.$object->id.'">';
  6168. print '<input type="hidden" name="addlink" value="'.$key.'">';
  6169. print '<table class="noborder">';
  6170. print '<tr class="liste_titre">';
  6171. print '<td class="nowrap"></td>';
  6172. print '<td class="center">'.$langs->trans("Ref").'</td>';
  6173. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  6174. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  6175. print '<td class="left">'.$langs->trans("Company").'</td>';
  6176. print '</tr>';
  6177. while ($i < $num)
  6178. {
  6179. $objp = $this->db->fetch_object($resqllist);
  6180. print '<tr class="oddeven">';
  6181. print '<td class="left">';
  6182. print '<input type="radio" name="idtolinkto" value='.$objp->rowid.'>';
  6183. print '</td>';
  6184. print '<td class="center">'.$objp->ref.'</td>';
  6185. print '<td>'.$objp->ref_client.'</td>';
  6186. print '<td class="right">'.price($objp->total_ht).'</td>';
  6187. print '<td>'.$objp->name.'</td>';
  6188. print '</tr>';
  6189. $i++;
  6190. }
  6191. print '</table>';
  6192. print '<div class="center"><input type="submit" class="button valignmiddle" value="'.$langs->trans('ToLink').'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="'.$langs->trans('Cancel').'"></div>';
  6193. print '</form>';
  6194. $this->db->free($resqllist);
  6195. } else {
  6196. dol_print_error($this->db);
  6197. }
  6198. print '</div>';
  6199. if ($num > 0)
  6200. {
  6201. }
  6202. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  6203. if ($num > 0) $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  6204. //else $linktoelem.=$langs->trans($possiblelink['label']);
  6205. else $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  6206. }
  6207. }
  6208. if ($linktoelemlist)
  6209. {
  6210. $linktoelem = '
  6211. <dl class="dropdown" id="linktoobjectname">
  6212. ';
  6213. if (!empty($conf->use_javascript_ajax)) $linktoelem .= '<dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>';
  6214. $linktoelem .= '<dd>
  6215. <div class="multiselectlinkto">
  6216. <ul class="ulselectedfields">'.$linktoelemlist.'
  6217. </ul>
  6218. </div>
  6219. </dd>
  6220. </dl>';
  6221. } else {
  6222. $linktoelem = '';
  6223. }
  6224. if (!empty($conf->use_javascript_ajax))
  6225. {
  6226. print '<!-- Add js to show linkto box -->
  6227. <script>
  6228. jQuery(document).ready(function() {
  6229. jQuery(".linkto").click(function() {
  6230. console.log("We choose to show/hide link for rel="+jQuery(this).attr(\'rel\'));
  6231. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  6232. });
  6233. });
  6234. </script>
  6235. ';
  6236. }
  6237. return $linktoelem;
  6238. }
  6239. /**
  6240. * Return an html string with a select combo box to choose yes or no
  6241. *
  6242. * @param string $htmlname Name of html select field
  6243. * @param string $value Pre-selected value
  6244. * @param int $option 0 return yes/no, 1 return 1/0
  6245. * @param bool $disabled true or false
  6246. * @param int $useempty 1=Add empty line
  6247. * @return string See option
  6248. */
  6249. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0)
  6250. {
  6251. global $langs;
  6252. $yes = "yes"; $no = "no";
  6253. if ($option)
  6254. {
  6255. $yes = "1";
  6256. $no = "0";
  6257. }
  6258. $disabled = ($disabled ? ' disabled' : '');
  6259. $resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  6260. if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  6261. if (("$value" == 'yes') || ($value == 1))
  6262. {
  6263. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  6264. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  6265. } else {
  6266. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  6267. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  6268. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  6269. }
  6270. $resultyesno .= '</select>'."\n";
  6271. return $resultyesno;
  6272. }
  6273. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6274. /**
  6275. * Return list of export templates
  6276. *
  6277. * @param string $selected Id modele pre-selectionne
  6278. * @param string $htmlname Name of HTML select
  6279. * @param string $type Type of searched templates
  6280. * @param int $useempty Affiche valeur vide dans liste
  6281. * @return void
  6282. */
  6283. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  6284. {
  6285. // phpcs:enable
  6286. $sql = "SELECT rowid, label";
  6287. $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
  6288. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  6289. $sql .= " ORDER BY rowid";
  6290. $result = $this->db->query($sql);
  6291. if ($result)
  6292. {
  6293. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  6294. if ($useempty)
  6295. {
  6296. print '<option value="-1">&nbsp;</option>';
  6297. }
  6298. $num = $this->db->num_rows($result);
  6299. $i = 0;
  6300. while ($i < $num)
  6301. {
  6302. $obj = $this->db->fetch_object($result);
  6303. if ($selected == $obj->rowid)
  6304. {
  6305. print '<option value="'.$obj->rowid.'" selected>';
  6306. } else {
  6307. print '<option value="'.$obj->rowid.'">';
  6308. }
  6309. print $obj->label;
  6310. print '</option>';
  6311. $i++;
  6312. }
  6313. print "</select>";
  6314. } else {
  6315. dol_print_error($this->db);
  6316. }
  6317. }
  6318. /**
  6319. * Return a HTML area with the reference of object and a navigation bar for a business object
  6320. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  6321. *
  6322. * @param object $object Object to show.
  6323. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  6324. * @param string $morehtml More html content to output just before the nav bar.
  6325. * @param int $shownav Show Condition (navigation is shown if value is 1).
  6326. * @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.
  6327. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  6328. * @param string $morehtmlref More html to show after ref.
  6329. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  6330. * @param int $nodbprefix Do not include DB prefix to forge table name.
  6331. * @param string $morehtmlleft More html code to show before ref.
  6332. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  6333. * @param string $morehtmlright More html code to show after ref.
  6334. * @return string Portion HTML with ref + navigation buttons
  6335. */
  6336. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  6337. {
  6338. global $langs, $conf, $hookmanager, $extralanguages;
  6339. $ret = '';
  6340. if (empty($fieldid)) $fieldid = 'rowid';
  6341. if (empty($fieldref)) $fieldref = 'ref';
  6342. // Add where from hooks
  6343. if (is_object($hookmanager))
  6344. {
  6345. $parameters = array();
  6346. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  6347. $object->next_prev_filter .= $hookmanager->resPrint;
  6348. }
  6349. $previous_ref = $next_ref = '';
  6350. if ($shownav)
  6351. {
  6352. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  6353. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  6354. $navurl = $_SERVER["PHP_SELF"];
  6355. // Special case for project/task page
  6356. if ($paramid == 'project_ref')
  6357. {
  6358. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) // TODO Remove this when nav with project_ref on task pages are ok
  6359. {
  6360. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  6361. $paramid = 'ref';
  6362. }
  6363. }
  6364. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  6365. // accesskey is for Mac: CTRL + key for all browsers
  6366. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  6367. if ($conf->browser->name == 'chrome')
  6368. {
  6369. $stringforfirstkey .= ' ALT +';
  6370. } elseif ($conf->browser->name == 'firefox')
  6371. {
  6372. $stringforfirstkey .= ' ALT + SHIFT +';
  6373. } else {
  6374. $stringforfirstkey .= ' CTL +';
  6375. }
  6376. $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>';
  6377. $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>';
  6378. }
  6379. //print "xx".$previous_ref."x".$next_ref;
  6380. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  6381. // Right part of banner
  6382. if ($morehtmlright) $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  6383. if ($previous_ref || $next_ref || $morehtml)
  6384. {
  6385. $ret .= '<div class="pagination paginationref"><ul class="right">';
  6386. }
  6387. if ($morehtml)
  6388. {
  6389. $ret .= '<li class="noborder litext">'.$morehtml.'</li>';
  6390. }
  6391. if ($shownav && ($previous_ref || $next_ref))
  6392. {
  6393. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  6394. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  6395. }
  6396. if ($previous_ref || $next_ref || $morehtml)
  6397. {
  6398. $ret .= '</ul></div>';
  6399. }
  6400. $parameters = array();
  6401. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  6402. if (empty($reshook)) $morehtmlstatus .= $hookmanager->resPrint;
  6403. else $morehtmlstatus = $hookmanager->resPrint;
  6404. if ($morehtmlstatus) $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  6405. $parameters = array();
  6406. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  6407. if (empty($reshook)) $morehtmlref .= $hookmanager->resPrint;
  6408. elseif ($reshook > 0) $morehtmlref = $hookmanager->resPrint;
  6409. // Left part of banner
  6410. if ($morehtmlleft)
  6411. {
  6412. if ($conf->browser->layout == 'phone') $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  6413. else $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  6414. }
  6415. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  6416. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  6417. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  6418. if ($object->element == 'societe')
  6419. {
  6420. $ret .= dol_htmlentities($object->name);
  6421. // List of extra languages
  6422. $arrayoflangcode = array();
  6423. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  6424. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  6425. if (!is_object($extralanguages)) {
  6426. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  6427. $extralanguages = new ExtraLanguages($this->db);
  6428. }
  6429. $extralanguages->fetch_name_extralanguages('societe');
  6430. if (!empty($extralanguages->attributes['societe']['name']))
  6431. {
  6432. $object->fetchValuesForExtraLanguages();
  6433. $htmltext = '';
  6434. // If there is extra languages
  6435. foreach ($arrayoflangcode as $extralangcode) {
  6436. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  6437. if ($object->array_languages['name'][$extralangcode]) {
  6438. $htmltext .= $object->array_languages['name'][$extralangcode];
  6439. } else {
  6440. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  6441. }
  6442. }
  6443. $ret .= '<!-- Show translations of name -->'."\n";
  6444. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  6445. }
  6446. }
  6447. } elseif ($object->element == 'member')
  6448. {
  6449. $ret .= $object->ref.'<br>';
  6450. $fullname = $object->getFullName($langs);
  6451. if ($object->morphy == 'mor' && $object->societe) {
  6452. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).')' : '');
  6453. } else {
  6454. $ret .= dol_htmlentities($fullname).((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  6455. }
  6456. } elseif (in_array($object->element, array('contact', 'user', 'usergroup')))
  6457. {
  6458. $ret .= dol_htmlentities($object->getFullName($langs));
  6459. } elseif (in_array($object->element, array('action', 'agenda')))
  6460. {
  6461. $ret .= $object->ref.'<br>'.$object->label;
  6462. } elseif (in_array($object->element, array('adherent_type')))
  6463. {
  6464. $ret .= $object->label;
  6465. } elseif ($object->element == 'ecm_directories')
  6466. {
  6467. $ret .= '';
  6468. } elseif ($fieldref != 'none')
  6469. {
  6470. $ret .= dol_htmlentities($object->$fieldref);
  6471. }
  6472. if ($morehtmlref)
  6473. {
  6474. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  6475. if (substr($morehtmlref, 0, 4) != '<div')
  6476. {
  6477. $ret .= ' ';
  6478. }
  6479. $ret .= $morehtmlref;
  6480. }
  6481. $ret .= '</div>';
  6482. $ret .= '</div><!-- End banner content -->';
  6483. return $ret;
  6484. }
  6485. /**
  6486. * Return HTML code to output a barcode
  6487. *
  6488. * @param Object $object Object containing data to retrieve file name
  6489. * @param int $width Width of photo
  6490. * @return string HTML code to output barcode
  6491. */
  6492. public function showbarcode(&$object, $width = 100)
  6493. {
  6494. global $conf;
  6495. //Check if barcode is filled in the card
  6496. if (empty($object->barcode)) return '';
  6497. // Complete object if not complete
  6498. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
  6499. {
  6500. $result = $object->fetch_barcode();
  6501. //Check if fetch_barcode() failed
  6502. if ($result < 1) return '<!-- ErrorFetchBarcode -->';
  6503. }
  6504. // Barcode image
  6505. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  6506. $out = '<!-- url barcode = '.$url.' -->';
  6507. $out .= '<img src="'.$url.'">';
  6508. return $out;
  6509. }
  6510. /**
  6511. * Return HTML code to output a photo
  6512. *
  6513. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  6514. * @param object $object Object containing data to retrieve file name
  6515. * @param int $width Width of photo
  6516. * @param int $height Height of photo (auto if 0)
  6517. * @param int $caneditfield Add edit fields
  6518. * @param string $cssclass CSS name to use on img for photo
  6519. * @param string $imagesize 'mini', 'small' or '' (original)
  6520. * @param int $addlinktofullsize Add link to fullsize image
  6521. * @param int $cache 1=Accept to use image in cache
  6522. * @param string $forcecapture Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
  6523. * @return string HTML code to output photo
  6524. */
  6525. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '')
  6526. {
  6527. global $conf, $langs;
  6528. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  6529. $id = (!empty($object->id) ? $object->id : $object->rowid);
  6530. $ret = ''; $dir = ''; $file = ''; $originalfile = ''; $altfile = ''; $email = ''; $capture = '';
  6531. if ($modulepart == 'societe')
  6532. {
  6533. $dir = $conf->societe->multidir_output[$entity];
  6534. if (!empty($object->logo))
  6535. {
  6536. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  6537. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
  6538. else $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6539. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6540. }
  6541. $email = $object->email;
  6542. } elseif ($modulepart == 'contact')
  6543. {
  6544. $dir = $conf->societe->multidir_output[$entity].'/contact';
  6545. if (!empty($object->photo))
  6546. {
  6547. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
  6548. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
  6549. else $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6550. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6551. }
  6552. $email = $object->email;
  6553. $capture = 'user';
  6554. } elseif ($modulepart == 'userphoto')
  6555. {
  6556. $dir = $conf->user->dir_output;
  6557. if (!empty($object->photo))
  6558. {
  6559. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
  6560. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
  6561. else $file = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6562. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6563. }
  6564. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6565. $email = $object->email;
  6566. $capture = 'user';
  6567. } elseif ($modulepart == 'memberphoto')
  6568. {
  6569. $dir = $conf->adherent->dir_output;
  6570. if (!empty($object->photo))
  6571. {
  6572. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6573. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  6574. else $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6575. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6576. }
  6577. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6578. $email = $object->email;
  6579. $capture = 'user';
  6580. } else {
  6581. // Generic case to show photos
  6582. $dir = $conf->$modulepart->dir_output;
  6583. if (!empty($object->photo))
  6584. {
  6585. if ((string) $imagesize == 'mini') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6586. elseif ((string) $imagesize == 'small') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  6587. else $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6588. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6589. }
  6590. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6591. $email = $object->email;
  6592. }
  6593. if ($forcecapture) $capture = $forcecapture;
  6594. if ($dir)
  6595. {
  6596. if ($file && file_exists($dir."/".$file))
  6597. {
  6598. if ($addlinktofullsize)
  6599. {
  6600. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6601. if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
  6602. else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6603. }
  6604. $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.'">';
  6605. if ($addlinktofullsize) $ret .= '</a>';
  6606. } elseif ($altfile && file_exists($dir."/".$altfile))
  6607. {
  6608. if ($addlinktofullsize)
  6609. {
  6610. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6611. if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
  6612. else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6613. }
  6614. $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.'">';
  6615. if ($addlinktofullsize) $ret .= '</a>';
  6616. } else {
  6617. $nophoto = '/public/theme/common/nophoto.png';
  6618. if (in_array($modulepart, array('userphoto', 'contact', 'memberphoto'))) // For module that are "physical" users
  6619. {
  6620. if ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor') !== false) {
  6621. $nophoto = '/public/theme/common/company.png';
  6622. } else {
  6623. $nophoto = '/public/theme/common/user_anonymous.png';
  6624. if ($object->gender == 'man') $nophoto = '/public/theme/common/user_man.png';
  6625. if ($object->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png';
  6626. }
  6627. }
  6628. if (!empty($conf->gravatar->enabled) && $email)
  6629. {
  6630. /**
  6631. * @see https://gravatar.com/site/implement/images/php/
  6632. */
  6633. global $dolibarr_main_url_root;
  6634. $ret .= '<!-- Put link to gravatar -->';
  6635. //$defaultimg=urlencode(dol_buildpath($nophoto,3));
  6636. $defaultimg = 'mm';
  6637. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="https://www.gravatar.com/avatar/'.md5(strtolower(trim($email))).'?s='.$width.'&d='.$defaultimg.'">'; // gravatar need md5 hash
  6638. } else {
  6639. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  6640. }
  6641. }
  6642. if ($caneditfield)
  6643. {
  6644. if ($object->photo) $ret .= "<br>\n";
  6645. $ret .= '<table class="nobordernopadding centpercent">';
  6646. if ($object->photo) $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  6647. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  6648. $ret .= '</table>';
  6649. }
  6650. } else dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  6651. return $ret;
  6652. }
  6653. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6654. /**
  6655. * Return select list of groups
  6656. *
  6657. * @param string $selected Id group preselected
  6658. * @param string $htmlname Field name in form
  6659. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  6660. * @param string $exclude Array list of groups id to exclude
  6661. * @param int $disabled If select list must be disabled
  6662. * @param string $include Array list of groups id to include
  6663. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  6664. * @param string $force_entity '0' or Ids of environment to force
  6665. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  6666. * @param string $morecss More css to add to html component
  6667. * @return string
  6668. * @see select_dolusers()
  6669. */
  6670. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  6671. {
  6672. // phpcs:enable
  6673. global $conf, $user, $langs;
  6674. // Permettre l'exclusion de groupes
  6675. if (is_array($exclude)) $excludeGroups = implode("','", $exclude);
  6676. // Permettre l'inclusion de groupes
  6677. if (is_array($include)) $includeGroups = implode("','", $include);
  6678. if (!is_array($selected)) $selected = array($selected);
  6679. $out = '';
  6680. // On recherche les groupes
  6681. $sql = "SELECT ug.rowid, ug.nom as name";
  6682. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  6683. {
  6684. $sql .= ", e.label";
  6685. }
  6686. $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  6687. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  6688. {
  6689. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  6690. if ($force_entity) $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  6691. else $sql .= " WHERE ug.entity IS NOT NULL";
  6692. } else {
  6693. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  6694. }
  6695. if (is_array($exclude) && $excludeGroups) $sql .= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  6696. if (is_array($include) && $includeGroups) $sql .= " AND ug.rowid IN ('".$includeGroups."')";
  6697. $sql .= " ORDER BY ug.nom ASC";
  6698. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  6699. $resql = $this->db->query($sql);
  6700. if ($resql)
  6701. {
  6702. // Enhance with select2
  6703. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6704. $out .= ajax_combobox($htmlname);
  6705. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  6706. $num = $this->db->num_rows($resql);
  6707. $i = 0;
  6708. if ($num)
  6709. {
  6710. if ($show_empty && !$multiple) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  6711. while ($i < $num)
  6712. {
  6713. $obj = $this->db->fetch_object($resql);
  6714. $disableline = 0;
  6715. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = 1;
  6716. $out .= '<option value="'.$obj->rowid.'"';
  6717. if ($disableline) $out .= ' disabled';
  6718. if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (!is_object($selected[0]) && in_array($obj->rowid, $selected)))
  6719. {
  6720. $out .= ' selected';
  6721. }
  6722. $out .= '>';
  6723. $out .= $obj->name;
  6724. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
  6725. {
  6726. $out .= " (".$obj->label.")";
  6727. }
  6728. $out .= '</option>';
  6729. $i++;
  6730. }
  6731. } else {
  6732. if ($show_empty) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  6733. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  6734. }
  6735. $out .= '</select>';
  6736. } else {
  6737. dol_print_error($this->db);
  6738. }
  6739. return $out;
  6740. }
  6741. /**
  6742. * Return HTML to show the search and clear seach button
  6743. *
  6744. * @return string
  6745. */
  6746. public function showFilterButtons()
  6747. {
  6748. $out = '<div class="nowrap">';
  6749. $out .= '<button type="submit" class="liste_titre button_search" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  6750. $out .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  6751. $out .= '</div>';
  6752. return $out;
  6753. }
  6754. /**
  6755. * Return HTML to show the search and clear search button
  6756. *
  6757. * @param string $cssclass CSS class
  6758. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  6759. * @param string $massactionname Mass action button name that will launch an action on the selected items
  6760. * @return string
  6761. */
  6762. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  6763. {
  6764. global $conf, $langs;
  6765. $out = '';
  6766. if (!empty($conf->use_javascript_ajax)) $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  6767. $out .= '<script>
  6768. $(document).ready(function() {
  6769. $("#' . $cssclass.'s").click(function() {
  6770. if($(this).is(\':checked\')){
  6771. console.log("We check all '.$cssclass.'");
  6772. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  6773. }
  6774. else
  6775. {
  6776. console.log("We uncheck all");
  6777. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  6778. }'."\n";
  6779. if ($calljsfunction) $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  6780. $out .= ' });
  6781. $(".' . $cssclass.'").change(function() {
  6782. $(this).closest("tr").toggleClass("highlight", this.checked);
  6783. });
  6784. });
  6785. </script>';
  6786. return $out;
  6787. }
  6788. /**
  6789. * Return HTML to show the search and clear seach button
  6790. *
  6791. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  6792. * @param string $cssclass CSS class
  6793. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  6794. * @param string $massactionname Mass action name
  6795. * @return string
  6796. */
  6797. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  6798. {
  6799. $out = $this->showFilterButtons();
  6800. if ($addcheckuncheckall)
  6801. {
  6802. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  6803. }
  6804. return $out;
  6805. }
  6806. /**
  6807. * Return HTML to show the select of expense categories
  6808. *
  6809. * @param string $selected preselected category
  6810. * @param string $htmlname name of HTML select list
  6811. * @param integer $useempty 1=Add empty line
  6812. * @param array $excludeid id to exclude
  6813. * @param string $target htmlname of target select to bind event
  6814. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  6815. * @param array $params param to give
  6816. * @param int $info_admin Show the tooltip help picto to setup list
  6817. * @return string
  6818. */
  6819. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  6820. {
  6821. global $db, $langs, $user;
  6822. $out = '';
  6823. $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
  6824. $sql .= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
  6825. if (!empty($excludeid)) $sql .= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
  6826. $sql .= ' ORDER BY label';
  6827. $resql = $db->query($sql);
  6828. if ($resql)
  6829. {
  6830. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  6831. if ($useempty) $out .= '<option value="0">&nbsp;</option>';
  6832. while ($obj = $db->fetch_object($resql))
  6833. {
  6834. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  6835. }
  6836. $out .= '</select>';
  6837. $out .= ajax_combobox('select_'.$htmlname);
  6838. if (!empty($htmlname) && $user->admin && $info_admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  6839. if (!empty($target))
  6840. {
  6841. $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  6842. $resql = $db->query($sql);
  6843. if ($resql)
  6844. {
  6845. if ($db->num_rows($resql) > 0)
  6846. {
  6847. $obj = $db->fetch_object($resql);
  6848. $out .= '<script>
  6849. $(function() {
  6850. $("select[name='.$target.']").on("change", function() {
  6851. var current_val = $(this).val();
  6852. if (current_val == '.$obj->id.') {';
  6853. if (!empty($default_selected) || !empty($selected)) $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  6854. $out .= '
  6855. $("select[name='.$htmlname.']").change();
  6856. }
  6857. });
  6858. $("select[name='.$htmlname.']").change(function() {
  6859. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  6860. // get price of kilometer to fill the unit price
  6861. var data = '.json_encode($params).';
  6862. data.fk_c_exp_tax_cat = $(this).val();
  6863. $.ajax({
  6864. method: "POST",
  6865. dataType: "json",
  6866. data: data,
  6867. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php').'",
  6868. }).done(function( data, textStatus, jqXHR ) {
  6869. console.log(data);
  6870. if (typeof data.up != "undefined") {
  6871. $("input[name=value_unit]").val(data.up);
  6872. $("select[name='.$htmlname.']").attr("title", data.title);
  6873. } else {
  6874. $("input[name=value_unit]").val("");
  6875. $("select[name='.$htmlname.']").attr("title", "");
  6876. }
  6877. });
  6878. }
  6879. });
  6880. });
  6881. </script>';
  6882. }
  6883. }
  6884. }
  6885. } else {
  6886. dol_print_error($db);
  6887. }
  6888. return $out;
  6889. }
  6890. /**
  6891. * Return HTML to show the select ranges of expense range
  6892. *
  6893. * @param string $selected preselected category
  6894. * @param string $htmlname name of HTML select list
  6895. * @param integer $useempty 1=Add empty line
  6896. * @return string
  6897. */
  6898. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  6899. {
  6900. global $db, $conf, $langs;
  6901. $out = '';
  6902. $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
  6903. $sql .= ' WHERE entity = '.$conf->entity.' AND active = 1';
  6904. $resql = $db->query($sql);
  6905. if ($resql)
  6906. {
  6907. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6908. if ($useempty) $out .= '<option value="0"></option>';
  6909. while ($obj = $db->fetch_object($resql))
  6910. {
  6911. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  6912. }
  6913. $out .= '</select>';
  6914. } else {
  6915. dol_print_error($db);
  6916. }
  6917. return $out;
  6918. }
  6919. /**
  6920. * Return HTML to show a select of expense
  6921. *
  6922. * @param string $selected preselected category
  6923. * @param string $htmlname name of HTML select list
  6924. * @param integer $useempty 1=Add empty choice
  6925. * @param integer $allchoice 1=Add all choice
  6926. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  6927. * @return string
  6928. */
  6929. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  6930. {
  6931. global $db, $langs;
  6932. $out = '';
  6933. $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
  6934. $sql .= ' WHERE active = 1';
  6935. $resql = $db->query($sql);
  6936. if ($resql)
  6937. {
  6938. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6939. if ($useempty) $out .= '<option value="0"></option>';
  6940. if ($allchoice) $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  6941. $field = 'code';
  6942. if ($useid) $field = 'id';
  6943. while ($obj = $db->fetch_object($resql))
  6944. {
  6945. $key = $langs->trans($obj->code);
  6946. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  6947. }
  6948. $out .= '</select>';
  6949. } else {
  6950. dol_print_error($db);
  6951. }
  6952. return $out;
  6953. }
  6954. /**
  6955. * Output a combo list with invoices qualified for a third party
  6956. *
  6957. * @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)
  6958. * @param int $selected Id invoice preselected
  6959. * @param string $htmlname Name of HTML select
  6960. * @param int $maxlength Maximum length of label
  6961. * @param int $option_only Return only html options lines without the select tag
  6962. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  6963. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  6964. * @param int $forcefocus Force focus on field (works with javascript only)
  6965. * @param int $disabled Disabled
  6966. * @param string $morecss More css added to the select component
  6967. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  6968. * @param string $showproject 'all' = Show project info, ''=Hide project info
  6969. * @param User $usertofilter User object to use for filtering
  6970. * @return int Nbr of project if OK, <0 if KO
  6971. */
  6972. 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)
  6973. {
  6974. global $user, $conf, $langs;
  6975. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6976. if (is_null($usertofilter))
  6977. {
  6978. $usertofilter = $user;
  6979. }
  6980. $out = '';
  6981. $hideunselectables = false;
  6982. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
  6983. if (empty($projectsListId))
  6984. {
  6985. if (empty($usertofilter->rights->projet->all->lire))
  6986. {
  6987. $projectstatic = new Project($this->db);
  6988. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  6989. }
  6990. }
  6991. // Search all projects
  6992. $sql = 'SELECT f.rowid, f.ref as fref, "nolabel" as flabel, p.rowid as pid, f.ref,
  6993. p.title, p.fk_soc, p.fk_statut, p.public,';
  6994. $sql .= ' s.nom as name';
  6995. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p';
  6996. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
  6997. $sql .= ' '.MAIN_DB_PREFIX.'facture as f';
  6998. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  6999. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  7000. //if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
  7001. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  7002. //if ($socid > 0) $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
  7003. $sql .= " GROUP BY f.ref ORDER BY p.ref, f.ref ASC";
  7004. $resql = $this->db->query($sql);
  7005. if ($resql)
  7006. {
  7007. // Use select2 selector
  7008. if (!empty($conf->use_javascript_ajax))
  7009. {
  7010. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7011. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  7012. $out .= $comboenhancement;
  7013. $morecss = 'minwidth200imp maxwidth500';
  7014. }
  7015. if (empty($option_only)) {
  7016. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  7017. }
  7018. if (!empty($show_empty)) {
  7019. $out .= '<option value="0" class="optiongrey">';
  7020. if (!is_numeric($show_empty)) $out .= $show_empty;
  7021. else $out .= '&nbsp;';
  7022. $out .= '</option>';
  7023. }
  7024. $num = $this->db->num_rows($resql);
  7025. $i = 0;
  7026. if ($num)
  7027. {
  7028. while ($i < $num)
  7029. {
  7030. $obj = $this->db->fetch_object($resql);
  7031. // 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.
  7032. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire))
  7033. {
  7034. // Do nothing
  7035. } else {
  7036. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED)
  7037. {
  7038. $i++;
  7039. continue;
  7040. }
  7041. $labeltoshow = '';
  7042. if ($showproject == 'all')
  7043. {
  7044. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  7045. if ($obj->name) $labeltoshow .= ' - '.$obj->name; // Soc name
  7046. $disabled = 0;
  7047. if ($obj->fk_statut == Project::STATUS_DRAFT)
  7048. {
  7049. $disabled = 1;
  7050. $labeltoshow .= ' - '.$langs->trans("Draft");
  7051. } elseif ($obj->fk_statut == Project::STATUS_CLOSED)
  7052. {
  7053. if ($discard_closed == 2) $disabled = 1;
  7054. $labeltoshow .= ' - '.$langs->trans("Closed");
  7055. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid))
  7056. {
  7057. $disabled = 1;
  7058. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  7059. }
  7060. }
  7061. if (!empty($selected) && $selected == $obj->rowid)
  7062. {
  7063. $out .= '<option value="'.$obj->rowid.'" selected';
  7064. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  7065. $out .= '>'.$labeltoshow.'</option>';
  7066. } else {
  7067. if ($hideunselectables && $disabled && ($selected != $obj->rowid))
  7068. {
  7069. $resultat = '';
  7070. } else {
  7071. $resultat = '<option value="'.$obj->rowid.'"';
  7072. if ($disabled) $resultat .= ' disabled';
  7073. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  7074. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  7075. $resultat .= '>';
  7076. $resultat .= $labeltoshow;
  7077. $resultat .= '</option>';
  7078. }
  7079. $out .= $resultat;
  7080. }
  7081. }
  7082. $i++;
  7083. }
  7084. }
  7085. if (empty($option_only)) {
  7086. $out .= '</select>';
  7087. }
  7088. print $out;
  7089. $this->db->free($resql);
  7090. return $num;
  7091. } else {
  7092. dol_print_error($this->db);
  7093. return -1;
  7094. }
  7095. }
  7096. /**
  7097. * Output the component to make advanced search criteries
  7098. *
  7099. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  7100. * @param array $search_component_params Array of selected search criterias
  7101. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  7102. * @return string HTML component for advanced search
  7103. */
  7104. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array())
  7105. {
  7106. global $langs;
  7107. $ret = '';
  7108. $ret .= '<div class="nowrap centpercent">';
  7109. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  7110. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor paddingright">';
  7111. $ret .= '<span class="fas fa-filter linkobject boxfilter" title="Filter" id="idsubimgproductdistribution"></span>';
  7112. $ret .= $langs->trans("Filters");
  7113. $ret .= '</a>';
  7114. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  7115. $ret .= '<div name="search_component_params" class="search_component_params inline-block minwidth500 maxwidth300onsmartphone valignmiddle">';
  7116. $texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  7117. $ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  7118. $ret .= '</div>';
  7119. $ret .= '<input type="hidden" name="search_component_params_hidden" class="search_component_params_hidden" value="'.GETPOST("search_component_params_hidden").'">';
  7120. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  7121. foreach ($arrayofcriterias as $criterias) {
  7122. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  7123. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) continue;
  7124. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) continue;
  7125. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  7126. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  7127. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  7128. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  7129. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  7130. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  7131. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  7132. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  7133. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  7134. } else {
  7135. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  7136. }
  7137. }
  7138. }
  7139. $ret .= '</div>';
  7140. return $ret;
  7141. }
  7142. /**
  7143. * selectModelMail
  7144. *
  7145. * @param string $prefix Prefix
  7146. * @param string $modelType Model type
  7147. * @param int $default 1=Show also Default mail template
  7148. * @return string HTML select string
  7149. */
  7150. public function selectModelMail($prefix, $modelType = '', $default = 0)
  7151. {
  7152. global $langs, $db, $user;
  7153. $retstring = '';
  7154. $TModels = array();
  7155. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  7156. $formmail = new FormMail($db);
  7157. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  7158. if ($default) $TModels[0] = $langs->trans('DefaultMailModel');
  7159. if ($result > 0) {
  7160. foreach ($formmail->lines_model as $model) {
  7161. $TModels[$model->id] = $model->label;
  7162. }
  7163. }
  7164. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  7165. foreach ($TModels as $id_model=>$label_model) {
  7166. $retstring .= '<option value="'.$id_model.'"';
  7167. $retstring .= ">".$label_model."</option>";
  7168. }
  7169. $retstring .= "</select>";
  7170. return $retstring;
  7171. }
  7172. }