html.form.class.php 258 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960
  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-2014 Regis Houssin <regis.houssin@capnetworks.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-2014 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2014 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.dolibarr@gmail.com>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/html.form.class.php
  35. * \ingroup core
  36. * \brief File of class with all html predefined components
  37. */
  38. /**
  39. * Class to manage generation of HTML components
  40. * Only common components must be here.
  41. *
  42. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  43. */
  44. class Form
  45. {
  46. var $db;
  47. var $error;
  48. var $num;
  49. // Cache arrays
  50. var $cache_types_paiements=array();
  51. var $cache_conditions_paiements=array();
  52. var $cache_availability=array();
  53. var $cache_demand_reason=array();
  54. var $cache_types_fees=array();
  55. var $cache_vatrates=array();
  56. /**
  57. * Constructor
  58. *
  59. * @param DoliDB $db Database handler
  60. */
  61. public function __construct($db)
  62. {
  63. $this->db = $db;
  64. }
  65. /**
  66. * Output key field for an editable field
  67. *
  68. * @param string $text Text of label or key to translate
  69. * @param string $htmlname Name of select field ('edit' prefix will be added)
  70. * @param string $preselected Value to show/edit (not used in this function)
  71. * @param object $object Object
  72. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  73. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'day' or 'datepicker', 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  74. * @param string $moreparam More param to add on a href URL*
  75. * @param int $fieldrequired 1 if we want to show field as mandatory using the fieldrequired CSS.
  76. * @return string HTML edit field
  77. */
  78. function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0)
  79. {
  80. global $conf,$langs;
  81. $ret='';
  82. // TODO change for compatibility
  83. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
  84. {
  85. if (! empty($perm))
  86. {
  87. $tmp=explode(':',$typeofdata);
  88. $ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  89. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  90. $ret.= $langs->trans($text);
  91. if ($fieldrequired) $ret.='</span>';
  92. $ret.= '</div>'."\n";
  93. }
  94. else
  95. {
  96. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  97. $ret.= $langs->trans($text);
  98. if ($fieldrequired) $ret.='</span>';
  99. }
  100. }
  101. else
  102. {
  103. if (GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
  104. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  105. $ret.=$langs->trans($text);
  106. if ($fieldrequired) $ret.='</span>';
  107. if (GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='</td>';
  108. if (GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;id='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'),1).'</a></td>';
  109. if (GETPOST('action') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
  110. }
  111. return $ret;
  112. }
  113. /**
  114. * Output val field for an editable field
  115. *
  116. * @param string $text Text of label (not used in this function)
  117. * @param string $htmlname Name of select field
  118. * @param string $value Value to show/edit
  119. * @param object $object Object
  120. * @param boolean $perm Permission to allow button to edit parameter
  121. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'day' or 'datepicker', 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)
  122. * @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
  123. * @param object $extObject External object
  124. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  125. * @param string $moreparam More param to add on a href URL
  126. * @return string HTML edit field
  127. */
  128. function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='')
  129. {
  130. global $conf,$langs,$db;
  131. $ret='';
  132. // Check parameters
  133. if (empty($typeofdata)) return 'ErrorBadParameter';
  134. // When option to edit inline is activated
  135. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
  136. {
  137. $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  138. }
  139. else
  140. {
  141. if (GETPOST('action') == 'edit'.$htmlname)
  142. {
  143. $ret.="\n";
  144. $ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
  145. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  146. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  147. $ret.='<input type="hidden" name="id" value="'.$object->id.'">';
  148. $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  149. $ret.='<tr><td>';
  150. if (preg_match('/^(string|email)/',$typeofdata))
  151. {
  152. $tmp=explode(':',$typeofdata);
  153. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  154. }
  155. else if (preg_match('/^(numeric|amount)/',$typeofdata))
  156. {
  157. $tmp=explode(':',$typeofdata);
  158. $valuetoshow=price2num($editvalue?$editvalue:$value);
  159. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  160. }
  161. else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
  162. {
  163. $tmp=explode(':',$typeofdata);
  164. $ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'" cols="'.($tmp[2]?$tmp[2]:'100').'">'.($editvalue?$editvalue:$value).'</textarea>';
  165. }
  166. else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
  167. {
  168. $ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1);
  169. }
  170. else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
  171. {
  172. $ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1);
  173. }
  174. else if (preg_match('/^select;/',$typeofdata))
  175. {
  176. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  177. foreach($arraydata as $val)
  178. {
  179. $tmp=explode(':',$val);
  180. $arraylist[$tmp[0]]=$tmp[1];
  181. }
  182. $ret.=$this->selectarray($htmlname,$arraylist,$value);
  183. }
  184. else if (preg_match('/^ckeditor/',$typeofdata))
  185. {
  186. $tmp=explode(':',$typeofdata);
  187. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  188. $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), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
  189. $ret.=$doleditor->Create(1);
  190. }
  191. $ret.='</td>';
  192. $ret.='<td align="left">';
  193. $ret.='<input type="submit" class="button" name="modify" value="'.$langs->trans("Modify").'">';
  194. if (preg_match('/ckeditor|textarea/',$typeofdata)) $ret.='<br>'."\n";
  195. $ret.='<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
  196. $ret.='</td>';
  197. $ret.='</tr></table>'."\n";
  198. $ret.='</form>'."\n";
  199. }
  200. else
  201. {
  202. if (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1);
  203. elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
  204. elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value);
  205. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
  206. elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
  207. else if (preg_match('/^select;/',$typeofdata))
  208. {
  209. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  210. foreach($arraydata as $val)
  211. {
  212. $tmp=explode(':',$val);
  213. $arraylist[$tmp[0]]=$tmp[1];
  214. }
  215. $ret.=$arraylist[$value];
  216. }
  217. else if (preg_match('/^ckeditor/',$typeofdata))
  218. {
  219. $tmpcontent=dol_htmlentitiesbr($value);
  220. if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
  221. {
  222. $firstline=preg_replace('/<br>.*/','',$tmpcontent);
  223. $firstline=preg_replace('/[\n\r].*/','',$firstline);
  224. $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
  225. }
  226. $ret.=$tmpcontent;
  227. }
  228. else $ret.=$value;
  229. }
  230. }
  231. return $ret;
  232. }
  233. /**
  234. * Output edit in place form
  235. *
  236. * @param object $object Object
  237. * @param string $value Value to show/edit
  238. * @param string $htmlname DIV ID (field name)
  239. * @param int $condition Condition to edit
  240. * @param string $inputType Type of input ('string', 'numeric', 'datepicker', 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')
  241. * @param string $editvalue When in edit mode, use this value as $value instead of value
  242. * @param object $extObject External object
  243. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  244. * @return string HTML edit in place
  245. */
  246. private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
  247. {
  248. global $conf;
  249. $out='';
  250. // Check parameters
  251. if ($inputType == 'textarea') $value = dol_nl2br($value);
  252. else if (preg_match('/^numeric/',$inputType)) $value = price($value);
  253. else if ($inputType == 'datepicker') $value = dol_print_date($value, 'day');
  254. if ($condition)
  255. {
  256. $element = false;
  257. $table_element = false;
  258. $fk_element = false;
  259. $loadmethod = false;
  260. $savemethod = false;
  261. $ext_element = false;
  262. $button_only = false;
  263. $inputOption = '';
  264. if (is_object($object))
  265. {
  266. $element = $object->element;
  267. $table_element = $object->table_element;
  268. $fk_element = $object->id;
  269. }
  270. if (is_object($extObject))
  271. {
  272. $ext_element = $extObject->element;
  273. }
  274. if (preg_match('/^(string|email|numeric)/',$inputType))
  275. {
  276. $tmp=explode(':',$inputType);
  277. $inputType=$tmp[0];
  278. if (! empty($tmp[1])) $inputOption=$tmp[1];
  279. if (! empty($tmp[2])) $savemethod=$tmp[2];
  280. $out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  281. }
  282. else if ((preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
  283. {
  284. $tmp=explode(':',$inputType);
  285. $inputType=$tmp[0];
  286. if (! empty($tmp[1])) $inputOption=$tmp[1];
  287. if (! empty($tmp[2])) $savemethod=$tmp[2];
  288. $out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  289. }
  290. else if (preg_match('/^(select|autocomplete)/',$inputType))
  291. {
  292. $tmp=explode(':',$inputType);
  293. $inputType=$tmp[0]; $loadmethod=$tmp[1];
  294. if (! empty($tmp[2])) $savemethod=$tmp[2];
  295. if (! empty($tmp[3])) $button_only=true;
  296. }
  297. else if (preg_match('/^textarea/',$inputType))
  298. {
  299. $tmp=explode(':',$inputType);
  300. $inputType=$tmp[0];
  301. $rows=(empty($tmp[1])?'8':$tmp[1]);
  302. $cols=(empty($tmp[2])?'80':$tmp[2]);
  303. }
  304. else if (preg_match('/^ckeditor/',$inputType))
  305. {
  306. $tmp=explode(':',$inputType);
  307. $inputType=$tmp[0]; $toolbar=$tmp[1];
  308. if (! empty($tmp[2])) $width=$tmp[2];
  309. if (! empty($tmp[3])) $heigth=$tmp[3];
  310. if (! empty($tmp[4])) $savemethod=$tmp[4];
  311. if (! empty($conf->fckeditor->enabled))
  312. {
  313. $out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  314. }
  315. else
  316. {
  317. $inputType = 'textarea';
  318. }
  319. }
  320. $out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  321. $out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  322. $out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  323. $out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  324. if (! empty($savemethod)) $out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  325. if (! empty($ext_element)) $out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  326. if (! empty($custommsg))
  327. {
  328. if (is_array($custommsg))
  329. {
  330. if (!empty($custommsg['success']))
  331. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  332. if (!empty($custommsg['error']))
  333. $out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  334. }
  335. else
  336. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  337. }
  338. if ($inputType == 'textarea') {
  339. $out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  340. $out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  341. }
  342. $out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  343. $out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  344. }
  345. else
  346. {
  347. $out = $value;
  348. }
  349. return $out;
  350. }
  351. /**
  352. * Show a text and picto with tooltip on text or picto.
  353. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  354. *
  355. * @param string $text Text to show
  356. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  357. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  358. * @param int $direction -1=image is before, 0=no image, 1=image is after
  359. * @param string $img Html code for image (use img_xxx() function to get it)
  360. * @param string $extracss Add a CSS style to td tags
  361. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  362. * @param string $incbefore Include code before the text
  363. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  364. * @return string Code html du tooltip (texte+picto)
  365. * @see Use function textwithpicto if you can.
  366. * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
  367. */
  368. function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0)
  369. {
  370. global $conf;
  371. if ($incbefore) $text = $incbefore.$text;
  372. if (! $htmltext) return $text;
  373. $tag='td';
  374. if ($notabs == 2) $tag='div';
  375. if ($notabs == 3) $tag='span';
  376. // Sanitize tooltip
  377. $htmltext=str_replace("\\","\\\\",$htmltext);
  378. $htmltext=str_replace("\r","",$htmltext);
  379. $htmltext=str_replace("\n","",$htmltext);
  380. $extrastyle='';
  381. if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
  382. if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
  383. $htmltext=str_replace('"',"&quot;",$htmltext);
  384. if ($tooltipon == 2 || $tooltipon == 3) $paramfortooltipimg=' class="classfortooltip inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
  385. else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  386. if ($tooltipon == 1 || $tooltipon == 3) $paramfortooltiptd=' class="classfortooltip inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
  387. else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  388. $s="";
  389. if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
  390. elseif ($notabs == 2) $s.='<div class="inline-block">';
  391. // Define value if value is before
  392. if ($direction < 0) {
  393. $s.='<'.$tag.$paramfortooltipimg;
  394. if ($tag == 'td') {
  395. $s .= ' valign="top" width="14"';
  396. }
  397. $s.= '>'.$img.'</'.$tag.'>';
  398. }
  399. // Use another method to help avoid having a space in value in order to use this value with jquery
  400. // Define label
  401. if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  402. // Define value if value is after
  403. if ($direction > 0) {
  404. $s.='<'.$tag.$paramfortooltipimg;
  405. if ($tag == 'td') $s .= ' valign="middle" width="14"';
  406. $s.= '>'.$img.'</'.$tag.'>';
  407. }
  408. if (empty($notabs)) $s.='</tr></table>';
  409. elseif ($notabs == 2) $s.='</div>';
  410. return $s;
  411. }
  412. /**
  413. * Show a text with a picto and a tooltip on picto
  414. *
  415. * @param string $text Text to show
  416. * @param string $htmltext Content of tooltip
  417. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  418. * @param string $type Type of picto (info, help, warning, superadmin...)
  419. * @param string $extracss Add a CSS style to td tags
  420. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  421. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  422. * @return string HTML code of text, picto, tooltip
  423. */
  424. function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2)
  425. {
  426. global $conf;
  427. $alt = '';
  428. //For backwards compatibility
  429. if ($type == '0') $type = 'info';
  430. elseif ($type == '1') $type = 'help';
  431. // If info or help with no javascript, show only text
  432. if (empty($conf->use_javascript_ajax))
  433. {
  434. if ($type == 'info' || $type == 'help') return $text;
  435. else
  436. {
  437. $alt = $htmltext;
  438. $htmltext = '';
  439. }
  440. }
  441. // If info or help with smartphone, show only text (tooltip can't works)
  442. if (! empty($conf->dol_no_mouse_hover))
  443. {
  444. if ($type == 'info' || $type == 'help') return $text;
  445. }
  446. if ($type == 'info') $img = img_help(0, $alt);
  447. elseif ($type == 'help') $img = img_help(1, $alt);
  448. elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
  449. elseif ($type == 'admin') $img = img_picto($alt, 'star');
  450. elseif ($type == 'warning') $img = img_warning($alt);
  451. return $this->textwithtooltip($text, $htmltext, 2, $direction, $img, $extracss, $notabs, '', $noencodehtmltext);
  452. }
  453. /**
  454. * Generate select HTML to choose massaction
  455. *
  456. * @param string $selected Selected value
  457. * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  458. * @return string Select list
  459. */
  460. function selectMassAction($selected, $arrayofaction)
  461. {
  462. global $conf,$langs,$hookmanager;
  463. if (count($arrayofaction) == 0) return;
  464. $disabled=0;
  465. $ret='<div class="centpercent center"><select class="flat hideobject massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
  466. $ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
  467. foreach($arrayofaction as $code => $label)
  468. {
  469. $ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
  470. }
  471. $ret.='</select>';
  472. // Warning: if you set submit button to disabled, post using Enter will no more work
  473. $ret.='<input type="submit" name="confirmmassaction" class="button hideobject massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  474. $ret.='</div>';
  475. $ret.='<!-- JS CODE TO ENABLE mass action select -->
  476. <script type="text/javascript">
  477. function initCheckForSelect()
  478. {
  479. atleastoneselected=0;
  480. jQuery(".checkforselect").each(function( index ) {
  481. /* console.log( index + ": " + $( this ).text() ); */
  482. if ($(this).is(\':checked\')) atleastoneselected++;
  483. });
  484. if (atleastoneselected)
  485. {
  486. jQuery(".massaction").show();
  487. }
  488. else
  489. {
  490. jQuery(".massaction").hide();
  491. }
  492. }
  493. jQuery(document).ready(function () {
  494. initCheckForSelect();
  495. jQuery(".checkforselect").click(function() {
  496. initCheckForSelect();
  497. });
  498. /* Warning: if you set submit button to disabled, post using Enter will no more work
  499. jQuery(".massactionselect").change(function() {
  500. console.log( $( this ).val() );
  501. if ($(this).val() != \'0\')
  502. {
  503. jQuery(".massactionconfirmed").prop(\'disabled\', false);
  504. }
  505. else
  506. {
  507. jQuery(".massactionconfirmed").prop(\'disabled\', true);
  508. }
  509. });
  510. */
  511. });
  512. </script>
  513. ';
  514. return $ret;
  515. }
  516. /**
  517. * Return combo list of activated countries, into language of user
  518. *
  519. * @param string $selected Id or Code or Label of preselected country
  520. * @param string $htmlname Name of html select object
  521. * @param string $htmloption Options html on select object
  522. * @param integer $maxlength Max length for labels (0=no limit)
  523. * @param string $morecss More css class
  524. * @return string HTML string with select
  525. */
  526. function select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300')
  527. {
  528. global $conf,$langs;
  529. $langs->load("dict");
  530. $out='';
  531. $countryArray=array();
  532. $favorite=array();
  533. $label=array();
  534. $atleastonefavorite=0;
  535. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
  536. $sql.= " FROM ".MAIN_DB_PREFIX."c_country";
  537. $sql.= " WHERE active > 0";
  538. //$sql.= " ORDER BY code ASC";
  539. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  540. $resql=$this->db->query($sql);
  541. if ($resql)
  542. {
  543. $out.= '<select id="select'.$htmlname.'" class="flat selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
  544. $num = $this->db->num_rows($resql);
  545. $i = 0;
  546. if ($num)
  547. {
  548. $foundselected=false;
  549. while ($i < $num)
  550. {
  551. $obj = $this->db->fetch_object($resql);
  552. $countryArray[$i]['rowid'] = $obj->rowid;
  553. $countryArray[$i]['code_iso'] = $obj->code_iso;
  554. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  555. $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:''));
  556. $countryArray[$i]['favorite'] = $obj->favorite;
  557. $favorite[$i] = $obj->favorite;
  558. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  559. $i++;
  560. }
  561. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  562. foreach ($countryArray as $row)
  563. {
  564. if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++;
  565. if (empty($row['favorite']) && $atleastonefavorite)
  566. {
  567. $atleastonefavorite=0;
  568. $out.= '<option value="" disabled class="selectoptiondisabledwhite">----------------------</option>';
  569. }
  570. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
  571. {
  572. $foundselected=true;
  573. $out.= '<option value="'.$row['rowid'].'" selected>';
  574. }
  575. else
  576. {
  577. $out.= '<option value="'.$row['rowid'].'">';
  578. }
  579. $out.= dol_trunc($row['label'],$maxlength,'middle');
  580. if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
  581. $out.= '</option>';
  582. }
  583. }
  584. $out.= '</select>';
  585. }
  586. else
  587. {
  588. dol_print_error($this->db);
  589. }
  590. // Make select dynamic
  591. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  592. $out .= ajax_combobox('select'.$htmlname);
  593. return $out;
  594. }
  595. /**
  596. * Return select list of incoterms
  597. *
  598. * @param string $selected Id or Code of preselected incoterm
  599. * @param string $location_incoterms Value of input location
  600. * @param string $page Defined the form action
  601. * @param string $htmlname Name of html select object
  602. * @param string $htmloption Options html on select object
  603. * @param int $forcecombo Force to use standard combo box (no ajax use)
  604. * @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')))
  605. * @return string HTML string with select and input
  606. */
  607. function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
  608. {
  609. global $conf,$langs;
  610. $langs->load("dict");
  611. $out='';
  612. $incotermArray=array();
  613. $sql = "SELECT rowid, code";
  614. $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  615. $sql.= " WHERE active > 0";
  616. $sql.= " ORDER BY code ASC";
  617. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  618. $resql=$this->db->query($sql);
  619. if ($resql)
  620. {
  621. if ($conf->use_javascript_ajax && ! $forcecombo)
  622. {
  623. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  624. $out .= ajax_combobox($htmlname, $events);
  625. }
  626. if (!empty($page))
  627. {
  628. $out .= '<form method="post" action="'.$page.'">';
  629. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  630. $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  631. }
  632. $out.= '<select id="'.$htmlname.'" class="flat selectincoterm noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
  633. $out.= '<option value="0">&nbsp;</option>';
  634. $num = $this->db->num_rows($resql);
  635. $i = 0;
  636. if ($num)
  637. {
  638. $foundselected=false;
  639. while ($i < $num)
  640. {
  641. $obj = $this->db->fetch_object($resql);
  642. $incotermArray[$i]['rowid'] = $obj->rowid;
  643. $incotermArray[$i]['code'] = $obj->code;
  644. $i++;
  645. }
  646. foreach ($incotermArray as $row)
  647. {
  648. if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
  649. {
  650. $out.= '<option value="'.$row['rowid'].'" selected>';
  651. }
  652. else
  653. {
  654. $out.= '<option value="'.$row['rowid'].'">';
  655. }
  656. if ($row['code']) $out.= $row['code'];
  657. $out.= '</option>';
  658. }
  659. }
  660. $out.= '</select>';
  661. $out .= '<input id="location_incoterms" name="location_incoterms" size="14" value="'.$location_incoterms.'">';
  662. if (!empty($page))
  663. {
  664. $out .= '<input type="submit" class="button" value="'.$langs->trans("Modify").'"></form>';
  665. }
  666. }
  667. else
  668. {
  669. dol_print_error($this->db);
  670. }
  671. return $out;
  672. }
  673. /**
  674. * Return list of types of lines (product or service)
  675. * Example: 0=product, 1=service, 9=other (for external module)
  676. *
  677. * @param string $selected Preselected type
  678. * @param string $htmlname Name of field in html form
  679. * @param int $showempty Add an empty field
  680. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  681. * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service')
  682. * @return void
  683. */
  684. function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
  685. {
  686. global $db,$langs,$user,$conf;
  687. // If product & services are enabled or both disabled.
  688. if ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
  689. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
  690. {
  691. if (empty($hidetext)) print $langs->trans("Type").': ';
  692. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  693. if ($showempty)
  694. {
  695. print '<option value="-1"';
  696. if ($selected == -1) print ' selected';
  697. print '>&nbsp;</option>';
  698. }
  699. print '<option value="0"';
  700. if (0 == $selected) print ' selected';
  701. print '>'.$langs->trans("Product");
  702. print '<option value="1"';
  703. if (1 == $selected) print ' selected';
  704. print '>'.$langs->trans("Service");
  705. print '</select>';
  706. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  707. }
  708. if (empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled))
  709. {
  710. print $langs->trans("Service");
  711. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  712. }
  713. if (empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled))
  714. {
  715. print $langs->trans("Product");
  716. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  717. }
  718. if ($forceall < 0) // This should happened only for contracts when both predefined product and service are disabled.
  719. {
  720. 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
  721. }
  722. }
  723. /**
  724. * Load into cache cache_types_fees, array of types of fees
  725. *
  726. * @return int Nb of lines loaded, <0 if KO
  727. */
  728. function load_cache_types_fees()
  729. {
  730. global $langs;
  731. $num = count($this->cache_types_fees);
  732. if ($num > 0) return 0; // Cache already loaded
  733. dol_syslog(__METHOD__, LOG_DEBUG);
  734. $langs->load("trips");
  735. $sql = "SELECT c.code, c.label";
  736. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  737. $sql.= " WHERE active > 0";
  738. $resql=$this->db->query($sql);
  739. if ($resql)
  740. {
  741. $num = $this->db->num_rows($resql);
  742. $i = 0;
  743. while ($i < $num)
  744. {
  745. $obj = $this->db->fetch_object($resql);
  746. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  747. $label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  748. $this->cache_types_fees[$obj->code] = $label;
  749. $i++;
  750. }
  751. asort($this->cache_types_fees);
  752. return $num;
  753. }
  754. else
  755. {
  756. dol_print_error($this->db);
  757. return -1;
  758. }
  759. }
  760. /**
  761. * Return list of types of notes
  762. *
  763. * @param string $selected Preselected type
  764. * @param string $htmlname Name of field in form
  765. * @param int $showempty Add an empty field
  766. * @return void
  767. */
  768. function select_type_fees($selected='',$htmlname='type',$showempty=0)
  769. {
  770. global $user, $langs;
  771. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  772. $this->load_cache_types_fees();
  773. print '<select class="flat" name="'.$htmlname.'">';
  774. if ($showempty)
  775. {
  776. print '<option value="-1"';
  777. if ($selected == -1) print ' selected';
  778. print '>&nbsp;</option>';
  779. }
  780. foreach($this->cache_types_fees as $key => $value)
  781. {
  782. print '<option value="'.$key.'"';
  783. if ($key == $selected) print ' selected';
  784. print '>';
  785. print $value;
  786. print '</option>';
  787. }
  788. print '</select>';
  789. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  790. }
  791. /**
  792. * Return HTML code to select a company.
  793. *
  794. * @param int $selected Preselected products
  795. * @param string $htmlname Name of HTML select field (must be unique in page)
  796. * @param int $filter Filter on thirdparty
  797. * @param int $limit Limit on number of returned lines
  798. * @param array $ajaxoptions Options for ajax_autocompleter
  799. * @param int $forcecombo Force to use combo box
  800. * @return string Return select box for thirdparty.
  801. * @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)
  802. */
  803. function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
  804. {
  805. return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0,$limit);
  806. }
  807. /**
  808. * Output html form to select a third party
  809. *
  810. * @param string $selected Preselected type
  811. * @param string $htmlname Name of field in form
  812. * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
  813. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  814. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  815. * @param int $forcecombo Force to use combo box
  816. * @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')))
  817. * @param int $limit Maximum number of elements
  818. * @param string $morecss Add more css styles to the SELECT component
  819. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  820. * @return string HTML string with select box for thirdparty.
  821. */
  822. function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='')
  823. {
  824. $out='';
  825. /* TODO Use ajax_autocompleter like for products (not finished)
  826. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
  827. {
  828. $placeholder='';
  829. if ($selected && empty($selected_input_value))
  830. {
  831. require_once DOL_DOCUMENT_ROOT.'/societe/ajaxcompanies.php';
  832. $societe = new Societe($this->db);
  833. $societe->fetch($selected);
  834. $selected_input_value=$societe->ref;
  835. }
  836. // mode=1 means customers products
  837. $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished;
  838. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  839. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  840. else if ($hidelabel > 1) {
  841. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  842. else $placeholder=' title="'.$langs->trans("RefOrLabel").'"';
  843. if ($hidelabel == 2) {
  844. print img_picto($langs->trans("Search"), 'search');
  845. }
  846. }
  847. print '<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
  848. if ($hidelabel == 3) {
  849. print img_picto($langs->trans("Search"), 'search');
  850. }
  851. }
  852. else
  853. {*/
  854. $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam);
  855. //}
  856. return $out;
  857. }
  858. /**
  859. * Output html form to select a third party
  860. *
  861. * @param string $selected Preselected type
  862. * @param string $htmlname Name of field in form
  863. * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
  864. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  865. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  866. * @param int $forcecombo Force to use combo box
  867. * @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')))
  868. * @param string $filterkey Filter on key value
  869. * @param int $outputmode 0=HTML select string, 1=Array
  870. * @param int $limit Limit number of answers
  871. * @param string $morecss Add more css styles to the SELECT component
  872. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  873. * @return string HTML string with
  874. */
  875. function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='')
  876. {
  877. global $conf,$user,$langs;
  878. $out=''; $num=0;
  879. $outarray=array();
  880. // On recherche les societes
  881. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  882. $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s";
  883. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  884. $sql.= " WHERE s.entity IN (".getEntity('societe', 1).")";
  885. if (! empty($user->societe_id)) $sql.= " AND s.rowid = ".$user->societe_id;
  886. if ($filter) $sql.= " AND (".$filter.")";
  887. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  888. if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
  889. // Add criteria
  890. if ($filterkey && $filterkey != '')
  891. {
  892. $sql.=" AND (";
  893. if (! empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)) // Can use index
  894. {
  895. $sql.="(s.name LIKE '".$this->db->escape($filterkey)."%')";
  896. }
  897. else
  898. {
  899. // For natural search
  900. $scrit = explode(' ', $filterkey);
  901. foreach ($scrit as $crit) {
  902. $sql.=" AND (s.name LIKE '%".$this->db->escape($crit)."%')";
  903. }
  904. }
  905. if (! empty($conf->barcode->enabled))
  906. {
  907. $sql .= " OR s.barcode LIKE '".$this->db->escape($filterkey)."%'";
  908. }
  909. $sql.=")";
  910. }
  911. $sql.=$this->db->order("nom","ASC");
  912. if ($limit > 0) $sql.=$this->db->plimit($limit);
  913. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  914. $resql=$this->db->query($sql);
  915. if ($resql)
  916. {
  917. if ($conf->use_javascript_ajax && ! $forcecombo)
  918. {
  919. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  920. $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
  921. $out.= $comboenhancement;
  922. $nodatarole=($comboenhancement?' data-role="none"':'');
  923. }
  924. // Construct $out and $outarray
  925. $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.'"'.$nodatarole.'>'."\n";
  926. $textifempty='';
  927. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  928. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  929. if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
  930. {
  931. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  932. else $textifempty.=$langs->trans("All");
  933. }
  934. if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
  935. $num = $this->db->num_rows($resql);
  936. $i = 0;
  937. if ($num)
  938. {
  939. while ($i < $num)
  940. {
  941. $obj = $this->db->fetch_object($resql);
  942. $label='';
  943. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  944. if (($obj->client) && (!empty($obj->code_client))) {
  945. $label = $obj->code_client. ' - ';
  946. }
  947. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  948. $label .= $obj->code_fournisseur. ' - ';
  949. }
  950. $label.=' '.$obj->name;
  951. }
  952. else
  953. {
  954. $label=$obj->name;
  955. }
  956. if(!empty($obj->name_alias)) {
  957. $label.=' ('.$obj->name_alias.')';
  958. }
  959. if ($showtype)
  960. {
  961. if ($obj->client || $obj->fournisseur) $label.=' (';
  962. if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
  963. if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
  964. if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
  965. if ($obj->client || $obj->fournisseur) $label.=')';
  966. }
  967. if ($selected > 0 && $selected == $obj->rowid)
  968. {
  969. $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  970. }
  971. else
  972. {
  973. $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  974. }
  975. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$obj->rowid, 'label'=>$label));
  976. $i++;
  977. if (($i % 10) == 0) $out.="\n";
  978. }
  979. }
  980. $out.= '</select>'."\n";
  981. }
  982. else
  983. {
  984. dol_print_error($this->db);
  985. }
  986. $this->result=array('nbofthirdparties'=>$num);
  987. if ($outputmode) return $outarray;
  988. return $out;
  989. }
  990. /**
  991. * Return HTML combo list of absolute discounts
  992. *
  993. * @param string $selected Id remise fixe pre-selectionnee
  994. * @param string $htmlname Nom champ formulaire
  995. * @param string $filter Criteres optionnels de filtre
  996. * @param int $socid Id of thirdparty
  997. * @param int $maxvalue Max value for lines that can be selected
  998. * @return int Return number of qualifed lines in list
  999. */
  1000. function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
  1001. {
  1002. global $langs,$conf;
  1003. // On recherche les remises
  1004. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1005. $sql.= " re.description, re.fk_facture_source";
  1006. $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
  1007. $sql.= " WHERE fk_soc = ".(int) $socid;
  1008. if ($filter) $sql.= " AND ".$filter;
  1009. $sql.= " ORDER BY re.description ASC";
  1010. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1011. $resql=$this->db->query($sql);
  1012. if ($resql)
  1013. {
  1014. print '<select class="flat" name="'.$htmlname.'">';
  1015. $num = $this->db->num_rows($resql);
  1016. $qualifiedlines=$num;
  1017. $i = 0;
  1018. if ($num)
  1019. {
  1020. print '<option value="0">&nbsp;</option>';
  1021. while ($i < $num)
  1022. {
  1023. $obj = $this->db->fetch_object($resql);
  1024. $desc=dol_trunc($obj->description,40);
  1025. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1026. if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1027. $selectstring='';
  1028. if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
  1029. $disabled='';
  1030. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  1031. {
  1032. $qualifiedlines--;
  1033. $disabled=' disabled';
  1034. }
  1035. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1036. $i++;
  1037. }
  1038. }
  1039. print '</select>';
  1040. return $qualifiedlines;
  1041. }
  1042. else
  1043. {
  1044. dol_print_error($this->db);
  1045. return -1;
  1046. }
  1047. }
  1048. /**
  1049. * Return list of all contacts (for a third party or all)
  1050. *
  1051. * @param int $socid Id ot third party or 0 for all
  1052. * @param string $selected Id contact pre-selectionne
  1053. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1054. * @param int $showempty 0=no empty value, 1=add an empty value
  1055. * @param string $exclude List of contacts id to exclude
  1056. * @param string $limitto Disable answers that are not id in this array list
  1057. * @param integer $showfunction Add function into label
  1058. * @param string $moreclass Add more class to class style
  1059. * @param integer $showsoc Add company into label
  1060. * @param int $forcecombo Force to use combo box
  1061. * @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')))
  1062. * @param bool $options_only Return options only (for ajax treatment)
  1063. * @return int <0 if KO, Nb of contact in list if OK
  1064. */
  1065. function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false)
  1066. {
  1067. print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events);
  1068. return $this->num;
  1069. }
  1070. /**
  1071. * Return list of all contacts (for a third party or all)
  1072. *
  1073. * @param int $socid Id ot third party or 0 for all
  1074. * @param string $selected Id contact pre-selectionne
  1075. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1076. * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit)
  1077. * @param string $exclude List of contacts id to exclude
  1078. * @param string $limitto Disable answers that are not id in this array list
  1079. * @param integer $showfunction Add function into label
  1080. * @param string $moreclass Add more class to class style
  1081. * @param bool $options_only Return options only (for ajax treatment)
  1082. * @param integer $showsoc Add company into label
  1083. * @param int $forcecombo Force to use combo box
  1084. * @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')))
  1085. * @return int <0 if KO, Nb of contact in list if OK
  1086. */
  1087. function selectcontacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array())
  1088. {
  1089. global $conf,$langs;
  1090. $langs->load('companies');
  1091. $out='';
  1092. // On recherche les societes
  1093. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
  1094. if ($showsoc > 0) $sql.= " , s.nom as company";
  1095. $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
  1096. if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
  1097. $sql.= " WHERE sp.entity IN (".getEntity('societe', 1).")";
  1098. if ($socid > 0) $sql.= " AND sp.fk_soc=".$socid;
  1099. if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
  1100. $sql.= " ORDER BY sp.lastname ASC";
  1101. dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
  1102. $resql=$this->db->query($sql);
  1103. if ($resql)
  1104. {
  1105. $num=$this->db->num_rows($resql);
  1106. if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
  1107. {
  1108. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1109. $comboenhancement = ajax_combobox($htmlname, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
  1110. $out.= $comboenhancement;
  1111. $nodatarole=($comboenhancement?' data-role="none"':'');
  1112. }
  1113. if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$nodatarole.'>';
  1114. if ($showempty == 1) $out.= '<option value="0"'.($selected=='0'?' selected':'').'></option>';
  1115. if ($showempty == 2) $out.= '<option value="0"'.($selected=='0'?' selected':'').'>'.$langs->trans("Internal").'</option>';
  1116. $num = $this->db->num_rows($resql);
  1117. $i = 0;
  1118. if ($num)
  1119. {
  1120. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1121. $contactstatic=new Contact($this->db);
  1122. while ($i < $num)
  1123. {
  1124. $obj = $this->db->fetch_object($resql);
  1125. $contactstatic->id=$obj->rowid;
  1126. $contactstatic->lastname=$obj->lastname;
  1127. $contactstatic->firstname=$obj->firstname;
  1128. if ($obj->statut == 1){
  1129. if ($htmlname != 'none')
  1130. {
  1131. $disabled=0;
  1132. if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
  1133. if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
  1134. if ($selected && $selected == $obj->rowid)
  1135. {
  1136. $out.= '<option value="'.$obj->rowid.'"';
  1137. if ($disabled) $out.= ' disabled';
  1138. $out.= ' selected>';
  1139. $out.= $contactstatic->getFullName($langs);
  1140. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1141. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1142. $out.= '</option>';
  1143. }
  1144. else
  1145. {
  1146. $out.= '<option value="'.$obj->rowid.'"';
  1147. if ($disabled) $out.= ' disabled';
  1148. $out.= '>';
  1149. $out.= $contactstatic->getFullName($langs);
  1150. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1151. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1152. $out.= '</option>';
  1153. }
  1154. }
  1155. else
  1156. {
  1157. if ($selected == $obj->rowid)
  1158. {
  1159. $out.= $contactstatic->getFullName($langs);
  1160. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1161. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1162. }
  1163. }
  1164. }
  1165. $i++;
  1166. }
  1167. }
  1168. else
  1169. {
  1170. $out.= '<option value="-1"'.($showempty==2?'':' selected').' disabled>'.$langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined").'</option>';
  1171. }
  1172. if ($htmlname != 'none' || $options_only)
  1173. {
  1174. $out.= '</select>';
  1175. }
  1176. $this->num = $num;
  1177. return $out;
  1178. }
  1179. else
  1180. {
  1181. dol_print_error($this->db);
  1182. return -1;
  1183. }
  1184. }
  1185. /**
  1186. * Return select list of users
  1187. *
  1188. * @param string $selected Id user preselected
  1189. * @param string $htmlname Field name in form
  1190. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1191. * @param array $exclude Array list of users id to exclude
  1192. * @param int $disabled If select list must be disabled
  1193. * @param array $include Array list of users id to include
  1194. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1195. * @param int $force_entity 0 or Id of environment to force
  1196. * @return void
  1197. * @deprecated
  1198. * @see select_dolusers()
  1199. */
  1200. function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude='',$disabled=0,$include='',$enableonly='',$force_entity=0)
  1201. {
  1202. print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
  1203. }
  1204. /**
  1205. * Return select list of users
  1206. *
  1207. * @param string $selected User id or user object of user preselected. If -1, we use id of current user.
  1208. * @param string $htmlname Field name in form
  1209. * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list
  1210. * @param array $exclude Array list of users id to exclude
  1211. * @param int $disabled If select list must be disabled
  1212. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1213. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1214. * @param int $force_entity 0 or Id of environment to force
  1215. * @param int $maxlength Maximum length of string into list (0=no limit)
  1216. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1217. * @param string $morefilter Add more filters into sql request
  1218. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1219. * @param string $enableonlytext If option $enableonly is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
  1220. * @param string $morecss More css
  1221. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1222. * @return string HTML select string
  1223. * @see select_dolgroups
  1224. */
  1225. function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0)
  1226. {
  1227. global $conf,$user,$langs;
  1228. // If no preselected user defined, we take current user
  1229. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
  1230. $excludeUsers=null;
  1231. $includeUsers=null;
  1232. // Permettre l'exclusion d'utilisateurs
  1233. if (is_array($exclude)) $excludeUsers = implode("','",$exclude);
  1234. // Permettre l'inclusion d'utilisateurs
  1235. if (is_array($include)) $includeUsers = implode("','",$include);
  1236. else if ($include == 'hierarchy')
  1237. {
  1238. // Build list includeUsers to have only hierarchy
  1239. $userid=$user->id;
  1240. $include=array();
  1241. if (empty($user->users) || ! is_array($user->users)) $user->get_full_tree();
  1242. foreach($user->users as $key => $val)
  1243. {
  1244. if (preg_match('/_'.$userid.'/',$val['fullpath'])) $include[]=$val['id'];
  1245. }
  1246. $includeUsers = implode("','",$include);
  1247. //var_dump($includeUsers);exit;
  1248. //var_dump($user->users);exit;
  1249. }
  1250. $out='';
  1251. // On recherche les utilisateurs
  1252. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
  1253. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1254. {
  1255. $sql.= ", e.label";
  1256. }
  1257. $sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
  1258. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1259. {
  1260. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
  1261. if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
  1262. else $sql.= " WHERE u.entity IS NOT NULL";
  1263. }
  1264. else
  1265. {
  1266. if (! empty($conf->multicompany->transverse_mode))
  1267. {
  1268. $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
  1269. $sql.= " WHERE ug.fk_user = u.rowid";
  1270. $sql.= " AND ug.entity = ".$conf->entity;
  1271. }
  1272. else
  1273. {
  1274. $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
  1275. }
  1276. }
  1277. if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
  1278. if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN ('".$excludeUsers."')";
  1279. if (is_array($include) && $includeUsers) $sql.= " AND u.rowid IN ('".$includeUsers."')";
  1280. if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
  1281. if (! empty($morefilter)) $sql.=" ".$morefilter;
  1282. $sql.= " ORDER BY u.lastname ASC";
  1283. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1284. $resql=$this->db->query($sql);
  1285. if ($resql)
  1286. {
  1287. $num = $this->db->num_rows($resql);
  1288. $i = 0;
  1289. if ($num)
  1290. {
  1291. // Enhance with select2
  1292. $nodatarole='';
  1293. if ($conf->use_javascript_ajax)
  1294. {
  1295. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1296. $comboenhancement = ajax_combobox($htmlname);
  1297. $out.=$comboenhancement;
  1298. $nodatarole=($comboenhancement?' data-role="none"':'');
  1299. }
  1300. $out.= '<select class="flat minwidth200'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$nodatarole.'>';
  1301. if ($show_empty) $out.= '<option value="-1"'.((empty($selected) || $selected==-1)?' selected':'').'>&nbsp;</option>'."\n";
  1302. if ($show_every) $out.= '<option value="-2"'.(($selected==-2)?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1303. $userstatic=new User($this->db);
  1304. while ($i < $num)
  1305. {
  1306. $obj = $this->db->fetch_object($resql);
  1307. $userstatic->id=$obj->rowid;
  1308. $userstatic->lastname=$obj->lastname;
  1309. $userstatic->firstname=$obj->firstname;
  1310. $disableline='';
  1311. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
  1312. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  1313. {
  1314. $out.= '<option value="'.$obj->rowid.'"';
  1315. if ($disableline) $out.= ' disabled';
  1316. $out.= ' selected>';
  1317. }
  1318. else
  1319. {
  1320. $out.= '<option value="'.$obj->rowid.'"';
  1321. if ($disableline) $out.= ' disabled';
  1322. $out.= '>';
  1323. }
  1324. $out.= $userstatic->getFullName($langs, 0, -1, $maxlength);
  1325. // Complete name with more info
  1326. $moreinfo=0;
  1327. if (! empty($conf->global->MAIN_SHOW_LOGIN))
  1328. {
  1329. $out.= ($moreinfo?' - ':' (').$obj->login;
  1330. $moreinfo++;
  1331. }
  1332. if ($showstatus >= 0)
  1333. {
  1334. if ($obj->statut == 1 && $showstatus == 1)
  1335. {
  1336. $out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
  1337. $moreinfo++;
  1338. }
  1339. if ($obj->statut == 0)
  1340. {
  1341. $out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
  1342. $moreinfo++;
  1343. }
  1344. }
  1345. if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1346. {
  1347. if ($obj->admin && ! $obj->entity)
  1348. {
  1349. $out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
  1350. $moreinfo++;
  1351. }
  1352. else
  1353. {
  1354. $out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
  1355. $moreinfo++;
  1356. }
  1357. }
  1358. $out.=($moreinfo?')':'');
  1359. if ($disableline && $disableline != '1')
  1360. {
  1361. $out.=' - '.$disableline; // This is text from $enableonlytext parameter
  1362. }
  1363. $out.= '</option>';
  1364. $i++;
  1365. }
  1366. }
  1367. else
  1368. {
  1369. $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1370. $out.= '<option value="">'.$langs->trans("None").'</option>';
  1371. }
  1372. $out.= '</select>';
  1373. }
  1374. else
  1375. {
  1376. dol_print_error($this->db);
  1377. }
  1378. return $out;
  1379. }
  1380. /**
  1381. * Return select list of users. Selected users are stored into session.
  1382. * List of users are provided into $_SESSION['assignedtouser'].
  1383. *
  1384. * @param string $action Value for $action
  1385. * @param string $htmlname Field name in form
  1386. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1387. * @param array $exclude Array list of users id to exclude
  1388. * @param int $disabled If select list must be disabled
  1389. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1390. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1391. * @param int $force_entity 0 or Id of environment to force
  1392. * @param int $maxlength Maximum length of string into list (0=no limit)
  1393. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1394. * @param string $morefilter Add more filters into sql request
  1395. * @return string HTML select string
  1396. * @see select_dolgroups
  1397. */
  1398. function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='')
  1399. {
  1400. global $conf,$user,$langs;
  1401. $userstatic=new User($this->db);
  1402. $out='';
  1403. // Method with no ajax
  1404. //$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  1405. if ($action == 'view')
  1406. {
  1407. $out.='';
  1408. }
  1409. else
  1410. {
  1411. $out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1412. $out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () { jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });})</script>';
  1413. $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1414. $out.=' <input type="submit" class="button" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1415. }
  1416. $assignedtouser=array();
  1417. if (!empty($_SESSION['assignedtouser']))
  1418. {
  1419. $assignedtouser=json_decode($_SESSION['assignedtouser'], true);
  1420. }
  1421. $nbassignetouser=count($assignedtouser);
  1422. if ($nbassignetouser && $action != 'view') $out.='<br>';
  1423. $i=0; $ownerid=0;
  1424. foreach($assignedtouser as $key => $value)
  1425. {
  1426. if ($value['id'] == $ownerid) continue;
  1427. $userstatic->fetch($value['id']);
  1428. $out.=$userstatic->getNomUrl(1);
  1429. if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
  1430. if ($nbassignetouser > 1 && $action != 'view') $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.'">';
  1431. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1432. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1433. $out.='<br>';
  1434. $i++;
  1435. }
  1436. //$out.='</form>';
  1437. return $out;
  1438. }
  1439. /**
  1440. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1441. *
  1442. * @param int $selected Preselected products
  1443. * @param string $htmlname Name of HTML select field (must be unique in page)
  1444. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1445. * @param int $limit Limit on number of returned lines
  1446. * @param int $price_level Level of price to show
  1447. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1448. * @param int $finished 2=all, 1=finished, 0=raw material
  1449. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1450. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1451. * @param array $ajaxoptions Options for ajax_autocompleter
  1452. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1453. * @return void
  1454. */
  1455. 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)
  1456. {
  1457. global $langs,$conf;
  1458. $price_level = (! empty($price_level) ? $price_level : 0);
  1459. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1460. {
  1461. $placeholder='';
  1462. if ($selected && empty($selected_input_value))
  1463. {
  1464. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1465. $producttmpselect = new Product($this->db);
  1466. $producttmpselect->fetch($selected);
  1467. $selected_input_value=$producttmpselect->ref;
  1468. unset($producttmpselect);
  1469. }
  1470. // mode=1 means customers products
  1471. $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished;
  1472. //Price by customer
  1473. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1474. $urloption.='&socid='.$socid;
  1475. }
  1476. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1477. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1478. else if ($hidelabel > 1) {
  1479. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  1480. else $placeholder=' title="'.$langs->trans("RefOrLabel").'"';
  1481. if ($hidelabel == 2) {
  1482. print img_picto($langs->trans("Search"), 'search');
  1483. }
  1484. }
  1485. print '<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1486. if ($hidelabel == 3) {
  1487. print img_picto($langs->trans("Search"), 'search');
  1488. }
  1489. }
  1490. else
  1491. {
  1492. print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid);
  1493. }
  1494. }
  1495. /**
  1496. * Return list of products for a customer
  1497. *
  1498. * @param int $selected Preselected product
  1499. * @param string $htmlname Name of select html
  1500. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1501. * @param int $limit Limit on number of returned lines
  1502. * @param int $price_level Level of price to show
  1503. * @param string $filterkey Filter on product
  1504. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1505. * @param int $finished Filter on finished field: 2=No filter
  1506. * @param int $outputmode 0=HTML select string, 1=Array
  1507. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1508. * @return array Array of keys for json
  1509. */
  1510. function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0)
  1511. {
  1512. global $langs,$conf,$user,$db;
  1513. $out='';
  1514. $outarray=array();
  1515. $sql = "SELECT ";
  1516. $sql.= " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.stock, p.fk_price_expression";
  1517. //Price by customer
  1518. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1519. $sql.=' ,pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  1520. $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
  1521. }
  1522. // Multilang : we add translation
  1523. if (! empty($conf->global->MAIN_MULTILANGS))
  1524. {
  1525. $sql.= ", pl.label as label_translated";
  1526. }
  1527. // Price by quantity
  1528. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
  1529. {
  1530. $sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1531. if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1532. $sql.= " ORDER BY date_price";
  1533. $sql.= " DESC LIMIT 1) as price_rowid";
  1534. $sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1535. if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1536. $sql.= " ORDER BY date_price";
  1537. $sql.= " DESC LIMIT 1) as price_by_qty";
  1538. }
  1539. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1540. //Price by customer
  1541. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1542. $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
  1543. }
  1544. // Multilang : we add translation
  1545. if (! empty($conf->global->MAIN_MULTILANGS))
  1546. {
  1547. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
  1548. }
  1549. $sql.= ' WHERE p.entity IN ('.getEntity('product', 1).')';
  1550. if ($finished == 0)
  1551. {
  1552. $sql.= " AND p.finished = ".$finished;
  1553. }
  1554. elseif ($finished == 1)
  1555. {
  1556. $sql.= " AND p.finished = ".$finished;
  1557. if ($status >= 0) $sql.= " AND p.tosell = ".$status;
  1558. }
  1559. elseif ($status >= 0)
  1560. {
  1561. $sql.= " AND p.tosell = ".$status;
  1562. }
  1563. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
  1564. // Add criteria on ref/label
  1565. if ($filterkey != '')
  1566. {
  1567. $sql.=' AND (';
  1568. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  1569. // For natural search
  1570. $scrit = explode(' ', $filterkey);
  1571. $i=0;
  1572. if (count($scrit) > 1) $sql.="(";
  1573. foreach ($scrit as $crit)
  1574. {
  1575. if ($i > 0) $sql.=" AND ";
  1576. $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
  1577. if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
  1578. $sql.=")";
  1579. $i++;
  1580. }
  1581. if (count($scrit) > 1) $sql.=")";
  1582. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
  1583. $sql.=')';
  1584. }
  1585. $sql.= $db->order("p.ref");
  1586. $sql.= $db->plimit($limit);
  1587. // Build output string
  1588. dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
  1589. $result=$this->db->query($sql);
  1590. if ($result)
  1591. {
  1592. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1593. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1594. $num = $this->db->num_rows($result);
  1595. $out.='<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  1596. $out.='<option value="0" selected>&nbsp;</option>';
  1597. $i = 0;
  1598. while ($num && $i < $num)
  1599. {
  1600. $opt = '';
  1601. $optJson = array();
  1602. $objp = $this->db->fetch_object($result);
  1603. if (!empty($objp->price_by_qty) && $objp->price_by_qty == 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
  1604. { // Price by quantity will return many prices for the same product
  1605. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise";
  1606. $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  1607. $sql.= " WHERE fk_product_price=".$objp->price_rowid;
  1608. $sql.= " ORDER BY quantity ASC";
  1609. dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
  1610. $result2 = $this->db->query($sql);
  1611. if ($result2)
  1612. {
  1613. $nb_prices = $this->db->num_rows($result2);
  1614. $j = 0;
  1615. while ($nb_prices && $j < $nb_prices) {
  1616. $objp2 = $this->db->fetch_object($result2);
  1617. $objp->quantity = $objp2->quantity;
  1618. $objp->price = $objp2->price;
  1619. $objp->unitprice = $objp2->unitprice;
  1620. $objp->remise_percent = $objp2->remise_percent;
  1621. $objp->remise = $objp2->remise;
  1622. $objp->price_by_qty_rowid = $objp2->rowid;
  1623. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected);
  1624. $j++;
  1625. // Add new entry
  1626. // "key" value of json key array is used by jQuery automatically as selected value
  1627. // "label" value of json key array is used by jQuery automatically as text for combo box
  1628. $out.=$opt;
  1629. array_push($outarray, $optJson);
  1630. }
  1631. }
  1632. }
  1633. else
  1634. {
  1635. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  1636. $price_product = new Product($this->db);
  1637. $price_product->fetch($objp->rowid, '', '', 1);
  1638. $priceparser = new PriceParser($this->db);
  1639. $price_result = $priceparser->parseProduct($price_product);
  1640. if ($price_result >= 0) {
  1641. $objp->price = $price_result;
  1642. $objp->unitprice = $price_result;
  1643. //Calculate the VAT
  1644. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  1645. $objp->price_ttc = price2num($objp->price_ttc,'MU');
  1646. }
  1647. }
  1648. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected);
  1649. // Add new entry
  1650. // "key" value of json key array is used by jQuery automatically as selected value
  1651. // "label" value of json key array is used by jQuery automatically as text for combo box
  1652. $out.=$opt;
  1653. array_push($outarray, $optJson);
  1654. }
  1655. $i++;
  1656. }
  1657. $out.='</select>';
  1658. $this->db->free($result);
  1659. if (empty($outputmode)) return $out;
  1660. return $outarray;
  1661. }
  1662. else
  1663. {
  1664. dol_print_error($db);
  1665. }
  1666. }
  1667. /**
  1668. * constructProductListOption
  1669. *
  1670. * @param resultset $objp Resultset of fetch
  1671. * @param string $opt Option (var used for returned value in string option format)
  1672. * @param string $optJson Option (var used for returned value in json format)
  1673. * @param int $price_level Price level
  1674. * @param string $selected Preselected value
  1675. * @param int $hidepriceinlabel Hide price in label
  1676. * @return void
  1677. */
  1678. private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
  1679. {
  1680. global $langs,$conf,$user,$db;
  1681. $outkey='';
  1682. $outval='';
  1683. $outref='';
  1684. $outlabel='';
  1685. $outdesc='';
  1686. $outbarcode='';
  1687. $outtype='';
  1688. $outprice_ht='';
  1689. $outprice_ttc='';
  1690. $outpricebasetype='';
  1691. $outtva_tx='';
  1692. $outqty=1;
  1693. $outdiscount=0;
  1694. $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
  1695. $label=$objp->label;
  1696. if (! empty($objp->label_translated)) $label=$objp->label_translated;
  1697. if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  1698. $outkey=$objp->rowid;
  1699. $outref=$objp->ref;
  1700. $outlabel=$objp->label;
  1701. $outdesc=$objp->description;
  1702. $outbarcode=$objp->barcode;
  1703. $outtype=$objp->fk_product_type;
  1704. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  1705. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  1706. $opt = '<option value="'.$objp->rowid.'"';
  1707. $opt.= ($objp->rowid == $selected)?' selected':'';
  1708. $opt.= (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)?' pbq="'.$objp->price_by_qty_rowid.'"':'';
  1709. if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
  1710. {
  1711. if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
  1712. else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
  1713. }
  1714. $opt.= '>';
  1715. $opt.= $objp->ref;
  1716. if ($outbarcode) $opt.=' ('.$outbarcode.')';
  1717. $opt.=' - '.dol_trunc($label,$maxlengtharticle).' - ';
  1718. $objRef = $objp->ref;
  1719. if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  1720. $outval.=$objRef;
  1721. if ($outbarcode) $outval.=' ('.$outbarcode.')';
  1722. $outval.=' - '.dol_trunc($label,$maxlengtharticle).' - ';
  1723. $found=0;
  1724. // Multiprice
  1725. if (empty($hidepriceinlabel) && $price_level >= 1 && $conf->global->PRODUIT_MULTIPRICES) // If we need a particular price level (from 1 to 6)
  1726. {
  1727. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  1728. $sql.= " FROM ".MAIN_DB_PREFIX."product_price";
  1729. $sql.= " WHERE fk_product='".$objp->rowid."'";
  1730. $sql.= " AND entity IN (".getEntity('productprice', 1).")";
  1731. $sql.= " AND price_level=".$price_level;
  1732. $sql.= " ORDER BY date_price, rowid";
  1733. $sql.= " DESC LIMIT 1";
  1734. dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
  1735. $result2 = $this->db->query($sql);
  1736. if ($result2)
  1737. {
  1738. $objp2 = $this->db->fetch_object($result2);
  1739. if ($objp2)
  1740. {
  1741. $found=1;
  1742. if ($objp2->price_base_type == 'HT')
  1743. {
  1744. $opt.= price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  1745. $outval.= price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  1746. }
  1747. else
  1748. {
  1749. $opt.= price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  1750. $outval.= price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  1751. }
  1752. $outprice_ht=price($objp2->price);
  1753. $outprice_ttc=price($objp2->price_ttc);
  1754. $outpricebasetype=$objp2->price_base_type;
  1755. $outtva_tx=$objp2->tva_tx;
  1756. }
  1757. }
  1758. else
  1759. {
  1760. dol_print_error($this->db);
  1761. }
  1762. }
  1763. // Price by quantity
  1764. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
  1765. {
  1766. $found = 1;
  1767. $outqty=$objp->quantity;
  1768. $outdiscount=$objp->remise_percent;
  1769. if ($objp->quantity == 1)
  1770. {
  1771. $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
  1772. $outval.= price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
  1773. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  1774. $outval.=$langs->transnoentities("Unit");
  1775. }
  1776. else
  1777. {
  1778. $opt.= price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  1779. $outval.= price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  1780. $opt.= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  1781. $outval.=$langs->transnoentities("Units");
  1782. }
  1783. $outprice_ht=price($objp->unitprice);
  1784. $outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  1785. $outpricebasetype=$objp->price_base_type;
  1786. $outtva_tx=$objp->tva_tx;
  1787. }
  1788. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
  1789. {
  1790. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  1791. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  1792. }
  1793. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
  1794. {
  1795. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  1796. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  1797. }
  1798. // Price by customer
  1799. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  1800. {
  1801. if (!empty($objp->idprodcustprice))
  1802. {
  1803. $found = 1;
  1804. if ($objp->custprice_base_type == 'HT')
  1805. {
  1806. $opt.= price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  1807. $outval.= price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  1808. }
  1809. else
  1810. {
  1811. $opt.= price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  1812. $outval.= price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  1813. }
  1814. $outprice_ht=price($objp->custprice);
  1815. $outprice_ttc=price($objp->custprice_ttc);
  1816. $outpricebasetype=$objp->custprice_base_type;
  1817. $outtva_tx=$objp->custtva_tx;
  1818. }
  1819. }
  1820. // If level no defined or multiprice not found, we used the default price
  1821. if (empty($hidepriceinlabel) && ! $found)
  1822. {
  1823. if ($objp->price_base_type == 'HT')
  1824. {
  1825. $opt.= price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  1826. $outval.= price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  1827. }
  1828. else
  1829. {
  1830. $opt.= price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  1831. $outval.= price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  1832. }
  1833. $outprice_ht=price($objp->price);
  1834. $outprice_ttc=price($objp->price_ttc);
  1835. $outpricebasetype=$objp->price_base_type;
  1836. $outtva_tx=$objp->tva_tx;
  1837. }
  1838. if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
  1839. {
  1840. $opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
  1841. $outval.=' - '.$langs->transnoentities("Stock").':'.$objp->stock;
  1842. }
  1843. if ($outdurationvalue && $outdurationunit)
  1844. {
  1845. $da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
  1846. if (isset($da[$outdurationunit]))
  1847. {
  1848. $key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
  1849. $opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
  1850. $outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
  1851. }
  1852. }
  1853. $opt.= "</option>\n";
  1854. $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
  1855. }
  1856. /**
  1857. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  1858. *
  1859. * @param int $socid Id third party
  1860. * @param string $selected Preselected product
  1861. * @param string $htmlname Name of HTML Select
  1862. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1863. * @param string $filtre For a SQL filter
  1864. * @param array $ajaxoptions Options for ajax_autocompleter
  1865. * @param int $hidelabel Hide label (0=no, 1=yes)
  1866. * @return void
  1867. */
  1868. function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0)
  1869. {
  1870. global $langs,$conf;
  1871. global $price_level, $status, $finished;
  1872. $selected_input_value='';
  1873. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1874. {
  1875. if ($selected > 0)
  1876. {
  1877. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1878. $producttmpselect = new Product($this->db);
  1879. $producttmpselect->fetch($selected);
  1880. $selected_input_value=$producttmpselect->ref;
  1881. unset($producttmpselect);
  1882. }
  1883. if (!empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
  1884. {
  1885. print '<input type="hidden" id="idprod" name="idprod" value="0" />';
  1886. }
  1887. // mode=2 means suppliers products
  1888. $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished;
  1889. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1890. print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
  1891. }
  1892. else
  1893. {
  1894. if (!empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
  1895. {
  1896. print '<input type="hidden" id="idprod" name="idprod" value="0" />';
  1897. print '<script type="text/javascript">$("#'.$htmlname.'").change(function() { $("#idprod").val($(this).val());});</script>';
  1898. }
  1899. print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0);
  1900. }
  1901. }
  1902. /**
  1903. * Return list of suppliers products
  1904. *
  1905. * @param int $socid Id societe fournisseur (0 pour aucun filtre)
  1906. * @param int $selected Produit pre-selectionne
  1907. * @param string $htmlname Nom de la zone select
  1908. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1909. * @param string $filtre Pour filtre sql
  1910. * @param string $filterkey Filtre des produits
  1911. * @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)
  1912. * @param int $outputmode 0=HTML select string, 1=Array
  1913. * @param int $limit Limit of line number
  1914. * @return array Array of keys for json
  1915. */
  1916. function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100)
  1917. {
  1918. global $langs,$conf,$db;
  1919. $out='';
  1920. $outarray=array();
  1921. $langs->load('stocks');
  1922. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
  1923. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  1924. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  1925. $sql.= " pfp.supplier_reputation";
  1926. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1927. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  1928. if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
  1929. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  1930. $sql.= " WHERE p.entity IN (".getEntity('product', 1).")";
  1931. $sql.= " AND p.tobuy = 1";
  1932. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
  1933. if (! empty($filtre)) $sql.=" ".$filtre;
  1934. // Add criteria on ref/label
  1935. if ($filterkey != '')
  1936. {
  1937. $sql.=' AND (';
  1938. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  1939. // For natural search
  1940. $scrit = explode(' ', $filterkey);
  1941. $i=0;
  1942. if (count($scrit) > 1) $sql.="(";
  1943. foreach ($scrit as $crit)
  1944. {
  1945. if ($i > 0) $sql.=" AND ";
  1946. $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)."%')";
  1947. $i++;
  1948. }
  1949. if (count($scrit) > 1) $sql.=")";
  1950. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1951. $sql.=')';
  1952. }
  1953. $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  1954. $sql.= $db->plimit($limit);
  1955. // Build output string
  1956. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  1957. $result=$this->db->query($sql);
  1958. if ($result)
  1959. {
  1960. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1961. $num = $this->db->num_rows($result);
  1962. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  1963. $out.='<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  1964. if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
  1965. else $out.='<option value="0">&nbsp;</option>';
  1966. $i = 0;
  1967. while ($i < $num)
  1968. {
  1969. $objp = $this->db->fetch_object($result);
  1970. $outkey=$objp->idprodfournprice;
  1971. $outref=$objp->ref;
  1972. $outval='';
  1973. $outqty=1;
  1974. $outdiscount=0;
  1975. $outtype=$objp->fk_product_type;
  1976. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  1977. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  1978. $opt = '<option value="'.$objp->idprodfournprice.'"';
  1979. if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
  1980. if (empty($objp->idprodfournprice)) $opt.=' disabled';
  1981. $opt.= '>';
  1982. $objRef = $objp->ref;
  1983. if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  1984. $objRefFourn = $objp->ref_fourn;
  1985. if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
  1986. $label = $objp->label;
  1987. if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  1988. $opt.=$objp->ref;
  1989. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  1990. $opt.=' ('.$objp->ref_fourn.')';
  1991. $opt.=' - ';
  1992. $outval.=$objRef;
  1993. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  1994. $outval.=' ('.$objRefFourn.')';
  1995. $outval.=' - ';
  1996. $opt.=dol_trunc($label, 72).' - ';
  1997. $outval.=dol_trunc($label, 72).' - ';
  1998. if (! empty($objp->idprodfournprice))
  1999. {
  2000. $outqty=$objp->quantity;
  2001. $outdiscount=$objp->remise_percent;
  2002. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2003. $prod_supplier = new ProductFournisseur($this->db);
  2004. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2005. $prod_supplier->id = $objp->fk_product;
  2006. $prod_supplier->fourn_qty = $objp->quantity;
  2007. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2008. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2009. $priceparser = new PriceParser($this->db);
  2010. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2011. if ($price_result >= 0) {
  2012. $objp->fprice = $price_result;
  2013. if ($objp->quantity >= 1)
  2014. {
  2015. $objp->unitprice = $objp->fprice / $objp->quantity;
  2016. }
  2017. }
  2018. }
  2019. if ($objp->quantity == 1)
  2020. {
  2021. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2022. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
  2023. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2024. $outval.=$langs->transnoentities("Unit");
  2025. }
  2026. else
  2027. {
  2028. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2029. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2030. $opt.= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2031. $outval.= ' '.$langs->transnoentities("Units");
  2032. }
  2033. if ($objp->quantity >= 1)
  2034. {
  2035. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2036. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2037. }
  2038. if ($objp->remise_percent >= 1)
  2039. {
  2040. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2041. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2042. }
  2043. if ($objp->duration)
  2044. {
  2045. $opt .= " - ".$objp->duration;
  2046. $outval.=" - ".$objp->duration;
  2047. }
  2048. if (! $socid)
  2049. {
  2050. $opt .= " - ".dol_trunc($objp->name,8);
  2051. $outval.=" - ".dol_trunc($objp->name,8);
  2052. }
  2053. if ($objp->supplier_reputation)
  2054. {
  2055. //TODO dictionnary
  2056. $reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  2057. $opt .= " - ".$reputations[$objp->supplier_reputation];
  2058. $outval.=" - ".$reputations[$objp->supplier_reputation];
  2059. }
  2060. }
  2061. else
  2062. {
  2063. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  2064. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2065. }
  2066. $opt .= "</option>\n";
  2067. // Add new entry
  2068. // "key" value of json key array is used by jQuery automatically as selected value
  2069. // "label" value of json key array is used by jQuery automatically as text for combo box
  2070. $out.=$opt;
  2071. array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
  2072. // Exemple of var_dump $outarray
  2073. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  2074. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  2075. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  2076. //}
  2077. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2078. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  2079. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2080. $i++;
  2081. }
  2082. $out.='</select>';
  2083. $this->db->free($result);
  2084. if (empty($outputmode)) return $out;
  2085. return $outarray;
  2086. }
  2087. else
  2088. {
  2089. dol_print_error($this->db);
  2090. }
  2091. }
  2092. /**
  2093. * Return list of suppliers prices for a product
  2094. *
  2095. * @param int $productid Id of product
  2096. * @param string $htmlname Name of HTML field
  2097. * @return string|null
  2098. */
  2099. function select_product_fourn_price($productid,$htmlname='productfournpriceid')
  2100. {
  2101. global $langs,$conf;
  2102. $langs->load('stocks');
  2103. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration,";
  2104. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
  2105. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  2106. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  2107. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2108. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2109. $sql.= " WHERE p.entity IN (".getEntity('productprice', 1).")";
  2110. $sql.= " AND p.tobuy = 1";
  2111. $sql.= " AND s.fournisseur = 1";
  2112. $sql.= " AND p.rowid = ".$productid;
  2113. $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
  2114. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  2115. $result=$this->db->query($sql);
  2116. if ($result)
  2117. {
  2118. $num = $this->db->num_rows($result);
  2119. $form = '<select class="flat" name="'.$htmlname.'">';
  2120. if (! $num)
  2121. {
  2122. $form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  2123. }
  2124. else
  2125. {
  2126. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2127. $form.= '<option value="0">&nbsp;</option>';
  2128. $i = 0;
  2129. while ($i < $num)
  2130. {
  2131. $objp = $this->db->fetch_object($result);
  2132. $opt = '<option value="'.$objp->idprodfournprice.'"';
  2133. //if there is only one supplier, preselect it
  2134. if($num == 1) {
  2135. $opt .= ' selected';
  2136. }
  2137. $opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  2138. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2139. $prod_supplier = new ProductFournisseur($this->db);
  2140. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2141. $prod_supplier->id = $productid;
  2142. $prod_supplier->fourn_qty = $objp->quantity;
  2143. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2144. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2145. $priceparser = new PriceParser($this->db);
  2146. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2147. if ($price_result >= 0) {
  2148. $objp->fprice = $price_result;
  2149. if ($objp->quantity >= 1)
  2150. {
  2151. $objp->unitprice = $objp->fprice / $objp->quantity;
  2152. }
  2153. }
  2154. }
  2155. if ($objp->quantity == 1)
  2156. {
  2157. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2158. }
  2159. $opt.= $objp->quantity.' ';
  2160. if ($objp->quantity == 1)
  2161. {
  2162. $opt.= $langs->trans("Unit");
  2163. }
  2164. else
  2165. {
  2166. $opt.= $langs->trans("Units");
  2167. }
  2168. if ($objp->quantity > 1)
  2169. {
  2170. $opt.=" - ";
  2171. $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
  2172. }
  2173. if ($objp->duration) $opt .= " - ".$objp->duration;
  2174. $opt .= "</option>\n";
  2175. $form.= $opt;
  2176. $i++;
  2177. }
  2178. }
  2179. $form.= '</select>';
  2180. $this->db->free($result);
  2181. return $form;
  2182. }
  2183. else
  2184. {
  2185. dol_print_error($this->db);
  2186. }
  2187. }
  2188. /**
  2189. * Return list of delivery address
  2190. *
  2191. * @param string $selected Id contact pre-selectionn
  2192. * @param int $socid Id of company
  2193. * @param string $htmlname Name of HTML field
  2194. * @param int $showempty Add an empty field
  2195. * @return integer|null
  2196. */
  2197. function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
  2198. {
  2199. // On recherche les utilisateurs
  2200. $sql = "SELECT a.rowid, a.label";
  2201. $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
  2202. $sql .= " WHERE a.fk_soc = ".$socid;
  2203. $sql .= " ORDER BY a.label ASC";
  2204. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  2205. $resql=$this->db->query($sql);
  2206. if ($resql)
  2207. {
  2208. print '<select class="flat" name="'.$htmlname.'">';
  2209. if ($showempty) print '<option value="0">&nbsp;</option>';
  2210. $num = $this->db->num_rows($resql);
  2211. $i = 0;
  2212. if ($num)
  2213. {
  2214. while ($i < $num)
  2215. {
  2216. $obj = $this->db->fetch_object($resql);
  2217. if ($selected && $selected == $obj->rowid)
  2218. {
  2219. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  2220. }
  2221. else
  2222. {
  2223. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  2224. }
  2225. $i++;
  2226. }
  2227. }
  2228. print '</select>';
  2229. return $num;
  2230. }
  2231. else
  2232. {
  2233. dol_print_error($this->db);
  2234. }
  2235. }
  2236. /**
  2237. * Load into cache list of payment terms
  2238. *
  2239. * @return int Nb of lines loaded, <0 if KO
  2240. */
  2241. function load_cache_conditions_paiements()
  2242. {
  2243. global $langs;
  2244. $num = count($this->cache_conditions_paiements);
  2245. if ($num > 0) return 0; // Cache already loaded
  2246. dol_syslog(__METHOD__, LOG_DEBUG);
  2247. $sql = "SELECT rowid, code, libelle as label";
  2248. $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  2249. $sql.= " WHERE active > 0";
  2250. $sql.= " ORDER BY sortorder";
  2251. $resql = $this->db->query($sql);
  2252. if ($resql)
  2253. {
  2254. $num = $this->db->num_rows($resql);
  2255. $i = 0;
  2256. while ($i < $num)
  2257. {
  2258. $obj = $this->db->fetch_object($resql);
  2259. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2260. $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2261. $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
  2262. $this->cache_conditions_paiements[$obj->rowid]['label']=$label;
  2263. $i++;
  2264. }
  2265. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  2266. return $num;
  2267. }
  2268. else
  2269. {
  2270. dol_print_error($this->db);
  2271. return -1;
  2272. }
  2273. }
  2274. /**
  2275. * Charge dans cache la liste des délais de livraison possibles
  2276. *
  2277. * @return int Nb of lines loaded, <0 if KO
  2278. */
  2279. function load_cache_availability()
  2280. {
  2281. global $langs;
  2282. $num = count($this->cache_availability);
  2283. if ($num > 0) return 0; // Cache already loaded
  2284. dol_syslog(__METHOD__, LOG_DEBUG);
  2285. $langs->load('propal');
  2286. $sql = "SELECT rowid, code, label";
  2287. $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
  2288. $sql.= " WHERE active > 0";
  2289. $resql = $this->db->query($sql);
  2290. if ($resql)
  2291. {
  2292. $num = $this->db->num_rows($resql);
  2293. $i = 0;
  2294. while ($i < $num)
  2295. {
  2296. $obj = $this->db->fetch_object($resql);
  2297. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2298. $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
  2299. $this->cache_availability[$obj->rowid]['code'] =$obj->code;
  2300. $this->cache_availability[$obj->rowid]['label']=$label;
  2301. $i++;
  2302. }
  2303. $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
  2304. return $num;
  2305. }
  2306. else
  2307. {
  2308. dol_print_error($this->db);
  2309. return -1;
  2310. }
  2311. }
  2312. /**
  2313. * Retourne la liste des types de delais de livraison possibles
  2314. *
  2315. * @param int $selected Id du type de delais pre-selectionne
  2316. * @param string $htmlname Nom de la zone select
  2317. * @param string $filtertype To add a filter
  2318. * @param int $addempty Add empty entry
  2319. * @return void
  2320. */
  2321. function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
  2322. {
  2323. global $langs,$user;
  2324. $this->load_cache_availability();
  2325. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2326. print '<select class="flat" name="'.$htmlname.'">';
  2327. if ($addempty) print '<option value="0">&nbsp;</option>';
  2328. foreach($this->cache_availability as $id => $arrayavailability)
  2329. {
  2330. if ($selected == $id)
  2331. {
  2332. print '<option value="'.$id.'" selected>';
  2333. }
  2334. else
  2335. {
  2336. print '<option value="'.$id.'">';
  2337. }
  2338. print $arrayavailability['label'];
  2339. print '</option>';
  2340. }
  2341. print '</select>';
  2342. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2343. }
  2344. /**
  2345. * Load into cache cache_demand_reason, array of input reasons
  2346. *
  2347. * @return int Nb of lines loaded, <0 if KO
  2348. */
  2349. function loadCacheInputReason()
  2350. {
  2351. global $langs;
  2352. $num = count($this->cache_demand_reason);
  2353. if ($num > 0) return 0; // Cache already loaded
  2354. $sql = "SELECT rowid, code, label";
  2355. $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  2356. $sql.= " WHERE active > 0";
  2357. $resql = $this->db->query($sql);
  2358. if ($resql)
  2359. {
  2360. $num = $this->db->num_rows($resql);
  2361. $i = 0;
  2362. $tmparray=array();
  2363. while ($i < $num)
  2364. {
  2365. $obj = $this->db->fetch_object($resql);
  2366. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2367. $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:''));
  2368. $tmparray[$obj->rowid]['id'] =$obj->rowid;
  2369. $tmparray[$obj->rowid]['code'] =$obj->code;
  2370. $tmparray[$obj->rowid]['label']=$label;
  2371. $i++;
  2372. }
  2373. $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  2374. unset($tmparray);
  2375. return $num;
  2376. }
  2377. else
  2378. {
  2379. dol_print_error($this->db);
  2380. return -1;
  2381. }
  2382. }
  2383. /**
  2384. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  2385. * List found into table c_input_reason loaded by loadCacheInputReason
  2386. *
  2387. * @param int $selected Id or code of type origin to select by default
  2388. * @param string $htmlname Nom de la zone select
  2389. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  2390. * @param int $addempty Add an empty entry
  2391. * @return void
  2392. */
  2393. function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
  2394. {
  2395. global $langs,$user;
  2396. $this->loadCacheInputReason();
  2397. print '<select class="flat" name="'.$htmlname.'">';
  2398. if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
  2399. foreach($this->cache_demand_reason as $id => $arraydemandreason)
  2400. {
  2401. if ($arraydemandreason['code']==$exclude) continue;
  2402. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
  2403. {
  2404. print '<option value="'.$arraydemandreason['id'].'" selected>';
  2405. }
  2406. else
  2407. {
  2408. print '<option value="'.$arraydemandreason['id'].'">';
  2409. }
  2410. print $arraydemandreason['label'];
  2411. print '</option>';
  2412. }
  2413. print '</select>';
  2414. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2415. }
  2416. /**
  2417. * Charge dans cache la liste des types de paiements possibles
  2418. *
  2419. * @return int Nb of lines loaded, <0 if KO
  2420. */
  2421. function load_cache_types_paiements()
  2422. {
  2423. global $langs;
  2424. $num=count($this->cache_types_paiements);
  2425. if ($num > 0) return $num; // Cache already loaded
  2426. dol_syslog(__METHOD__, LOG_DEBUG);
  2427. $this->cache_types_paiements = array();
  2428. $sql = "SELECT id, code, libelle as label, type, active";
  2429. $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
  2430. //if ($active >= 0) $sql.= " WHERE active = ".$active;
  2431. $resql = $this->db->query($sql);
  2432. if ($resql)
  2433. {
  2434. $num = $this->db->num_rows($resql);
  2435. $i = 0;
  2436. while ($i < $num)
  2437. {
  2438. $obj = $this->db->fetch_object($resql);
  2439. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2440. $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2441. $this->cache_types_paiements[$obj->id]['id'] =$obj->id;
  2442. $this->cache_types_paiements[$obj->id]['code'] =$obj->code;
  2443. $this->cache_types_paiements[$obj->id]['label']=$label;
  2444. $this->cache_types_paiements[$obj->id]['type'] =$obj->type;
  2445. $this->cache_types_paiements[$obj->id]['active'] =$obj->active;
  2446. $i++;
  2447. }
  2448. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  2449. return $num;
  2450. }
  2451. else
  2452. {
  2453. dol_print_error($this->db);
  2454. return -1;
  2455. }
  2456. }
  2457. /**
  2458. * Retourne la liste des types de paiements possibles
  2459. *
  2460. * @param string $selected Id du type de paiement pre-selectionne
  2461. * @param string $htmlname Nom de la zone select
  2462. * @param string $filtertype Pour filtre
  2463. * @param int $addempty Ajoute entree vide
  2464. * @return void
  2465. */
  2466. function select_conditions_paiements($selected='',$htmlname='condid',$filtertype=-1,$addempty=0)
  2467. {
  2468. global $langs,$user;
  2469. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2470. $this->load_cache_conditions_paiements();
  2471. print '<select class="flat" name="'.$htmlname.'">';
  2472. if ($addempty) print '<option value="0">&nbsp;</option>';
  2473. foreach($this->cache_conditions_paiements as $id => $arrayconditions)
  2474. {
  2475. if ($selected == $id)
  2476. {
  2477. print '<option value="'.$id.'" selected>';
  2478. }
  2479. else
  2480. {
  2481. print '<option value="'.$id.'">';
  2482. }
  2483. print $arrayconditions['label'];
  2484. print '</option>';
  2485. }
  2486. print '</select>';
  2487. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2488. }
  2489. /**
  2490. * Return list of payment methods
  2491. *
  2492. * @param string $selected Id du mode de paiement pre-selectionne
  2493. * @param string $htmlname Nom de la zone select
  2494. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  2495. * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
  2496. * @param int $empty 1=peut etre vide, 0 sinon
  2497. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  2498. * @param int $maxlength Max length of label
  2499. * @param int $active Active or not, -1 = all
  2500. * @return void
  2501. */
  2502. function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1)
  2503. {
  2504. global $langs,$user;
  2505. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  2506. $filterarray=array();
  2507. if ($filtertype == 'CRDT') $filterarray=array(0,2,3);
  2508. elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3);
  2509. elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
  2510. $this->load_cache_types_paiements();
  2511. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes" name="'.$htmlname.'">';
  2512. if ($empty) print '<option value="">&nbsp;</option>';
  2513. foreach($this->cache_types_paiements as $id => $arraytypes)
  2514. {
  2515. // If not good status
  2516. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  2517. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  2518. if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
  2519. // We discard empty line if showempty is on because an empty line has already been output.
  2520. if ($empty && empty($arraytypes['code'])) continue;
  2521. if ($format == 0) print '<option value="'.$id.'"';
  2522. if ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  2523. if ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  2524. if ($format == 3) print '<option value="'.$id.'"';
  2525. // Si selected est text, on compare avec code, sinon avec id
  2526. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
  2527. elseif ($selected == $id) print ' selected';
  2528. print '>';
  2529. if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2530. if ($format == 1) $value=$arraytypes['code'];
  2531. if ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2532. if ($format == 3) $value=$arraytypes['code'];
  2533. print $value?$value:'&nbsp;';
  2534. print '</option>';
  2535. }
  2536. print '</select>';
  2537. if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2538. }
  2539. /**
  2540. * Selection HT or TTC
  2541. *
  2542. * @param string $selected Id pre-selectionne
  2543. * @param string $htmlname Nom de la zone select
  2544. * @return string Code of HTML select to chose tax or not
  2545. */
  2546. function selectPriceBaseType($selected='',$htmlname='price_base_type')
  2547. {
  2548. global $langs;
  2549. $return='';
  2550. $return.= '<select class="flat" name="'.$htmlname.'">';
  2551. $options = array(
  2552. 'HT'=>$langs->trans("HT"),
  2553. 'TTC'=>$langs->trans("TTC")
  2554. );
  2555. foreach($options as $id => $value)
  2556. {
  2557. if ($selected == $id)
  2558. {
  2559. $return.= '<option value="'.$id.'" selected>'.$value;
  2560. }
  2561. else
  2562. {
  2563. $return.= '<option value="'.$id.'">'.$value;
  2564. }
  2565. $return.= '</option>';
  2566. }
  2567. $return.= '</select>';
  2568. return $return;
  2569. }
  2570. /**
  2571. * Return a HTML select list of shipping mode
  2572. *
  2573. * @param string $selected Id shipping mode pre-selected
  2574. * @param string $htmlname Name of select zone
  2575. * @param string $filtre To filter list
  2576. * @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.
  2577. * @param string $moreattrib To add more attribute on select
  2578. * @return void
  2579. */
  2580. function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
  2581. {
  2582. global $langs, $conf, $user;
  2583. $langs->load("admin");
  2584. $langs->load("deliveries");
  2585. $sql = "SELECT rowid, code, libelle as label";
  2586. $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  2587. $sql.= " WHERE active > 0";
  2588. if ($filtre) $sql.=" AND ".$filtre;
  2589. $sql.= " ORDER BY libelle ASC";
  2590. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  2591. $result = $this->db->query($sql);
  2592. if ($result) {
  2593. $num = $this->db->num_rows($result);
  2594. $i = 0;
  2595. if ($num) {
  2596. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  2597. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  2598. print '<option value="-1">&nbsp;</option>';
  2599. }
  2600. while ($i < $num) {
  2601. $obj = $this->db->fetch_object($result);
  2602. if ($selected == $obj->rowid) {
  2603. print '<option value="'.$obj->rowid.'" selected>';
  2604. } else {
  2605. print '<option value="'.$obj->rowid.'">';
  2606. }
  2607. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  2608. print '</option>';
  2609. $i++;
  2610. }
  2611. print "</select>";
  2612. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2613. } else {
  2614. print $langs->trans("NoShippingMethodDefined");
  2615. }
  2616. } else {
  2617. dol_print_error($this->db);
  2618. }
  2619. }
  2620. /**
  2621. * Display form to select shipping mode
  2622. *
  2623. * @param string $page Page
  2624. * @param int $selected Id of shipping mode
  2625. * @param string $htmlname Name of select html field
  2626. * @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.
  2627. * @return void
  2628. */
  2629. function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
  2630. {
  2631. global $langs, $db;
  2632. $langs->load("deliveries");
  2633. if ($htmlname != "none") {
  2634. print '<form method="POST" action="'.$page.'">';
  2635. print '<input type="hidden" name="action" value="setshippingmethod">';
  2636. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2637. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2638. print '<tr><td>';
  2639. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  2640. print '</td>';
  2641. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2642. print '</tr></table></form>';
  2643. } else {
  2644. if ($selected) {
  2645. $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  2646. print $langs->trans("SendingMethod".strtoupper($code));
  2647. } else {
  2648. print "&nbsp;";
  2649. }
  2650. }
  2651. }
  2652. /**
  2653. * Creates HTML last in cycle situation invoices selector
  2654. *
  2655. * @param string $selected Preselected ID
  2656. * @param int $socid Company ID
  2657. *
  2658. * @return string HTML select
  2659. */
  2660. function selectSituationInvoices($selected = '', $socid = 0)
  2661. {
  2662. global $langs;
  2663. $langs->load('bills');
  2664. $opt = '<option value ="" selected></option>';
  2665. $sql = 'SELECT rowid, facnumber, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
  2666. $sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
  2667. $resql = $this->db->query($sql);
  2668. if ($resql && $this->db->num_rows($resql) > 0) {
  2669. // Last seen cycle
  2670. $ref = 0;
  2671. while ($res = $this->db->fetch_array($resql, MYSQL_NUM)) {
  2672. //Same company ?
  2673. if ($socid == $res[5]) {
  2674. //Same cycle ?
  2675. if ($res[2] != $ref) {
  2676. // Just seen this cycle
  2677. $ref = $res[2];
  2678. //not final ?
  2679. if ($res[4] != 1) {
  2680. //Not prov?
  2681. if (substr($res[1], 1, 4) != 'PROV') {
  2682. if ($selected == $res[0]) {
  2683. $opt .= '<option value="' . $res[0] . '" selected>' . $res[1] . '</option>';
  2684. } else {
  2685. $opt .= '<option value="' . $res[0] . '">' . $res[1] . '</option>';
  2686. }
  2687. }
  2688. }
  2689. }
  2690. }
  2691. }
  2692. }
  2693. else
  2694. {
  2695. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  2696. }
  2697. if ($opt == '<option value ="" selected></option>')
  2698. {
  2699. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  2700. }
  2701. return $opt;
  2702. }
  2703. /**
  2704. * Creates HTML units selector (code => label)
  2705. *
  2706. * @param string $selected Preselected Unit ID
  2707. * @param string $htmlname Select name
  2708. * @param int $showempty Add a nempty line
  2709. * @return string HTML select
  2710. */
  2711. function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
  2712. {
  2713. global $langs;
  2714. $langs->load('products');
  2715. $return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  2716. $sql = 'SELECT rowid, label from '.MAIN_DB_PREFIX.'c_units';
  2717. $sql.= ' WHERE active > 0';
  2718. $resql = $this->db->query($sql);
  2719. if($resql && $this->db->num_rows($resql) > 0)
  2720. {
  2721. if ($showempty) $return .= '<option value="none"></option>';
  2722. while($res = $this->db->fetch_object($resql))
  2723. {
  2724. if ($selected == $res->rowid)
  2725. {
  2726. $return.='<option value="'.$res->rowid.'" selected>'.$langs->trans($res->label).'</option>';
  2727. }
  2728. else
  2729. {
  2730. $return.='<option value="'.$res->rowid.'">'.$langs->trans($res->label).'</option>';
  2731. }
  2732. }
  2733. $return.='</select>';
  2734. }
  2735. return $return;
  2736. }
  2737. /**
  2738. * Return a HTML select list of bank accounts
  2739. *
  2740. * @param string $selected Id account pre-selected
  2741. * @param string $htmlname Name of select zone
  2742. * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both)
  2743. * @param string $filtre To filter list
  2744. * @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.
  2745. * @param string $moreattrib To add more attribute on select
  2746. * @return void
  2747. */
  2748. function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='')
  2749. {
  2750. global $langs, $conf;
  2751. $langs->load("admin");
  2752. $sql = "SELECT rowid, label, bank, clos as status";
  2753. $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
  2754. $sql.= " WHERE entity IN (".getEntity('bank_account', 1).")";
  2755. if ($statut != 2) $sql.= " AND clos = '".$statut."'";
  2756. if ($filtre) $sql.=" AND ".$filtre;
  2757. $sql.= " ORDER BY label";
  2758. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  2759. $result = $this->db->query($sql);
  2760. if ($result)
  2761. {
  2762. $num = $this->db->num_rows($result);
  2763. $i = 0;
  2764. if ($num)
  2765. {
  2766. print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  2767. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  2768. {
  2769. print '<option value="-1">&nbsp;</option>';
  2770. }
  2771. while ($i < $num)
  2772. {
  2773. $obj = $this->db->fetch_object($result);
  2774. if ($selected == $obj->rowid)
  2775. {
  2776. print '<option value="'.$obj->rowid.'" selected>';
  2777. }
  2778. else
  2779. {
  2780. print '<option value="'.$obj->rowid.'">';
  2781. }
  2782. print trim($obj->label);
  2783. if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  2784. print '</option>';
  2785. $i++;
  2786. }
  2787. print "</select>";
  2788. }
  2789. else
  2790. {
  2791. print $langs->trans("NoActiveBankAccountDefined");
  2792. }
  2793. }
  2794. else {
  2795. dol_print_error($this->db);
  2796. }
  2797. }
  2798. /**
  2799. * Display form to select bank account
  2800. *
  2801. * @param string $page Page
  2802. * @param int $selected Id of bank account
  2803. * @param string $htmlname Name of select html field
  2804. * @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.
  2805. * @return void
  2806. */
  2807. function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
  2808. {
  2809. global $langs;
  2810. if ($htmlname != "none") {
  2811. print '<form method="POST" action="'.$page.'">';
  2812. print '<input type="hidden" name="action" value="setbankaccount">';
  2813. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2814. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  2815. print '<tr><td>';
  2816. $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  2817. print '</td>';
  2818. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  2819. print '</tr></table></form>';
  2820. } else {
  2821. if ($selected) {
  2822. require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
  2823. $bankstatic=new Account($this->db);
  2824. $bankstatic->fetch($selected);
  2825. print $this->textwithpicto($bankstatic->label,$langs->trans("AccountCurrency").'&nbsp;'.$bankstatic->currency_code);
  2826. } else {
  2827. print "&nbsp;";
  2828. }
  2829. }
  2830. }
  2831. /**
  2832. * Return list of categories having choosed type
  2833. *
  2834. * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  2835. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element)
  2836. * @param string $htmlname HTML field name
  2837. * @param int $maxlength Maximum length for labels
  2838. * @param int $excludeafterid Exclude all categories after this leaf in category tree.
  2839. * @param int $outputmode 0=HTML select string, 1=Array
  2840. * @return string
  2841. * @see select_categories
  2842. */
  2843. function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
  2844. {
  2845. global $langs;
  2846. $langs->load("categories");
  2847. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  2848. // For backward compatibility
  2849. if (is_numeric($type))
  2850. {
  2851. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  2852. }
  2853. $cat = new Categorie($this->db);
  2854. $cate_arbo = $cat->get_full_arbo($type,$excludeafterid);
  2855. $output = '<select class="flat" name="'.$htmlname.'">';
  2856. $outarray=array();
  2857. if (is_array($cate_arbo))
  2858. {
  2859. if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  2860. else
  2861. {
  2862. $output.= '<option value="-1">&nbsp;</option>';
  2863. foreach($cate_arbo as $key => $value)
  2864. {
  2865. if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
  2866. {
  2867. $add = 'selected ';
  2868. }
  2869. else
  2870. {
  2871. $add = '';
  2872. }
  2873. $output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
  2874. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  2875. }
  2876. }
  2877. }
  2878. $output.= '</select>';
  2879. $output.= "\n";
  2880. if ($outputmode) return $outarray;
  2881. return $output;
  2882. }
  2883. /**
  2884. * Show a confirmation HTML form or AJAX popup
  2885. *
  2886. * @param string $page Url of page to call if confirmation is OK
  2887. * @param string $title Title
  2888. * @param string $question Question
  2889. * @param string $action Action
  2890. * @param array $formquestion An array with forms complementary inputs
  2891. * @param string $selectedchoice "" or "no" or "yes"
  2892. * @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
  2893. * @param int $height Force height of box
  2894. * @param int $width Force width of box
  2895. * @return void
  2896. * @deprecated
  2897. * @see formconfirm()
  2898. */
  2899. function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
  2900. {
  2901. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  2902. }
  2903. /**
  2904. * Show a confirmation HTML form or AJAX popup.
  2905. * Easiest way to use this is with useajax=1.
  2906. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  2907. * just after calling this method. For example:
  2908. * print '<script type="text/javascript">'."\n";
  2909. * print 'jQuery(document).ready(function() {'."\n";
  2910. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  2911. * print '});'."\n";
  2912. * print '</script>'."\n";
  2913. *
  2914. * @param string $page Url of page to call if confirmation is OK
  2915. * @param string $title Title
  2916. * @param string $question Question
  2917. * @param string $action Action
  2918. * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  2919. * @param string $selectedchoice "" or "no" or "yes"
  2920. * @param int $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
  2921. * @param int $height Force height of box
  2922. * @param int $width Force width of bow
  2923. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  2924. */
  2925. function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
  2926. {
  2927. global $langs,$conf;
  2928. global $useglobalvars;
  2929. $more='';
  2930. $formconfirm='';
  2931. $inputok=array();
  2932. $inputko=array();
  2933. // Clean parameters
  2934. $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
  2935. if (is_array($formquestion) && ! empty($formquestion))
  2936. {
  2937. // First add hidden fields and value
  2938. foreach ($formquestion as $key => $input)
  2939. {
  2940. if (is_array($input) && ! empty($input))
  2941. {
  2942. if ($input['type'] == 'hidden')
  2943. {
  2944. $more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  2945. }
  2946. }
  2947. }
  2948. // Now add questions
  2949. $more.='<table class="paddingrightonly" width="100%">'."\n";
  2950. $more.='<tr><td colspan="3">'.(! empty($formquestion['text'])?$formquestion['text']:'').'</td></tr>'."\n";
  2951. foreach ($formquestion as $key => $input)
  2952. {
  2953. if (is_array($input) && ! empty($input))
  2954. {
  2955. $size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
  2956. if ($input['type'] == 'text')
  2957. {
  2958. $more.='<tr><td>'.$input['label'].'</td><td colspan="2" align="left"><input type="text" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'" /></td></tr>'."\n";
  2959. }
  2960. else if ($input['type'] == 'password')
  2961. {
  2962. $more.='<tr><td>'.$input['label'].'</td><td colspan="2" align="left"><input type="password" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'" /></td></tr>'."\n";
  2963. }
  2964. else if ($input['type'] == 'select')
  2965. {
  2966. $more.='<tr><td>';
  2967. if (! empty($input['label'])) $more.=$input['label'].'</td><td valign="top" colspan="2" align="left">';
  2968. $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1);
  2969. $more.='</td></tr>'."\n";
  2970. }
  2971. else if ($input['type'] == 'checkbox')
  2972. {
  2973. $more.='<tr>';
  2974. $more.='<td>'.$input['label'].' </td><td align="left">';
  2975. $more.='<input type="checkbox" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"';
  2976. if (! is_bool($input['value']) && $input['value'] != 'false') $more.=' checked';
  2977. if (is_bool($input['value']) && $input['value']) $more.=' checked';
  2978. if (isset($input['disabled'])) $more.=' disabled';
  2979. $more.=' /></td>';
  2980. $more.='<td align="left">&nbsp;</td>';
  2981. $more.='</tr>'."\n";
  2982. }
  2983. else if ($input['type'] == 'radio')
  2984. {
  2985. $i=0;
  2986. foreach($input['values'] as $selkey => $selval)
  2987. {
  2988. $more.='<tr>';
  2989. if ($i==0) $more.='<td valign="top">'.$input['label'].'</td>';
  2990. else $more.='<td>&nbsp;</td>';
  2991. $more.='<td width="20"><input type="radio" class="flat" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"';
  2992. if ($input['disabled']) $more.=' disabled';
  2993. $more.=' /></td>';
  2994. $more.='<td align="left">';
  2995. $more.=$selval;
  2996. $more.='</td></tr>'."\n";
  2997. $i++;
  2998. }
  2999. }
  3000. else if ($input['type'] == 'date')
  3001. {
  3002. $more.='<tr><td>'.$input['label'].'</td>';
  3003. $more.='<td colspan="2" align="left">';
  3004. $more.=$this->select_date($input['value'],$input['name'],0,0,0,'',1,0,1);
  3005. $more.='</td></tr>'."\n";
  3006. $formquestion[] = array('name'=>$input['name'].'day');
  3007. $formquestion[] = array('name'=>$input['name'].'month');
  3008. $formquestion[] = array('name'=>$input['name'].'year');
  3009. $formquestion[] = array('name'=>$input['name'].'hour');
  3010. $formquestion[] = array('name'=>$input['name'].'min');
  3011. }
  3012. else if ($input['type'] == 'other')
  3013. {
  3014. $more.='<tr><td>';
  3015. if (! empty($input['label'])) $more.=$input['label'].'</td><td colspan="2" align="left">';
  3016. $more.=$input['value'];
  3017. $more.='</td></tr>'."\n";
  3018. }
  3019. }
  3020. }
  3021. $more.='</table>'."\n";
  3022. }
  3023. // JQUI method dialog is broken with jmobile, we use standard HTML.
  3024. // 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
  3025. // See page product/card.php for example
  3026. if (! empty($conf->dol_use_jmobile)) $useajax=0;
  3027. if (empty($conf->use_javascript_ajax)) $useajax=0;
  3028. if ($useajax)
  3029. {
  3030. $autoOpen=true;
  3031. $dialogconfirm='dialog-confirm';
  3032. $button='';
  3033. if (! is_numeric($useajax))
  3034. {
  3035. $button=$useajax;
  3036. $useajax=1;
  3037. $autoOpen=false;
  3038. $dialogconfirm.='-'.$button;
  3039. }
  3040. $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
  3041. $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
  3042. // Add input fields into list of fields to read during submit (inputok and inputko)
  3043. if (is_array($formquestion))
  3044. {
  3045. foreach ($formquestion as $key => $input)
  3046. {
  3047. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  3048. if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
  3049. if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
  3050. }
  3051. }
  3052. // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
  3053. $formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  3054. if (! empty($more)) {
  3055. $formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
  3056. }
  3057. $formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
  3058. $formconfirm.= '</div>'."\n";
  3059. $formconfirm.= "\n<!-- begin ajax form_confirm page=".$page." -->\n";
  3060. $formconfirm.= '<script type="text/javascript">'."\n";
  3061. $formconfirm.= 'jQuery(document).ready(function() {
  3062. $(function() {
  3063. $( "#'.$dialogconfirm.'" ).dialog(
  3064. {
  3065. autoOpen: '.($autoOpen ? "true" : "false").',';
  3066. if ($newselectedchoice == 'no')
  3067. {
  3068. $formconfirm.='
  3069. open: function() {
  3070. $(this).parent().find("button.ui-button:eq(2)").focus();
  3071. },';
  3072. }
  3073. $formconfirm.='
  3074. resizable: false,
  3075. height: "'.$height.'",
  3076. width: "'.$width.'",
  3077. modal: true,
  3078. closeOnEscape: false,
  3079. buttons: {
  3080. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  3081. var options="";
  3082. var inputok = '.json_encode($inputok).';
  3083. var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
  3084. if (inputok.length>0) {
  3085. $.each(inputok, function(i, inputname) {
  3086. var more = "";
  3087. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3088. if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
  3089. var inputvalue = $("#" + inputname + more).val();
  3090. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3091. options += "&" + inputname + "=" + inputvalue;
  3092. });
  3093. }
  3094. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  3095. //alert(urljump);
  3096. if (pageyes.length > 0) { location.href = urljump; }
  3097. $(this).dialog("close");
  3098. },
  3099. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  3100. var options = "";
  3101. var inputko = '.json_encode($inputko).';
  3102. var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
  3103. if (inputko.length>0) {
  3104. $.each(inputko, function(i, inputname) {
  3105. var more = "";
  3106. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3107. var inputvalue = $("#" + inputname + more).val();
  3108. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3109. options += "&" + inputname + "=" + inputvalue;
  3110. });
  3111. }
  3112. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  3113. //alert(urljump);
  3114. if (pageno.length > 0) { location.href = urljump; }
  3115. $(this).dialog("close");
  3116. }
  3117. }
  3118. }
  3119. );
  3120. var button = "'.$button.'";
  3121. if (button.length > 0) {
  3122. $( "#" + button ).click(function() {
  3123. $("#'.$dialogconfirm.'").dialog("open");
  3124. });
  3125. }
  3126. });
  3127. });
  3128. </script>';
  3129. $formconfirm.= "<!-- end ajax form_confirm -->\n";
  3130. }
  3131. else
  3132. {
  3133. $formconfirm.= "\n<!-- begin form_confirm page=".$page." -->\n";
  3134. $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  3135. $formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  3136. $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
  3137. $formconfirm.= '<table width="100%" class="valid">'."\n";
  3138. // Line title
  3139. $formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
  3140. // Line form fields
  3141. if ($more)
  3142. {
  3143. $formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
  3144. $formconfirm.=$more;
  3145. $formconfirm.='</td></tr>'."\n";
  3146. }
  3147. // Line with question
  3148. $formconfirm.= '<tr class="valid">';
  3149. $formconfirm.= '<td class="valid">'.$question.'</td>';
  3150. $formconfirm.= '<td class="valid">';
  3151. $formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
  3152. $formconfirm.= '</td>';
  3153. $formconfirm.= '<td class="valid" align="center"><input class="button" type="submit" value="'.$langs->trans("Validate").'"></td>';
  3154. $formconfirm.= '</tr>'."\n";
  3155. $formconfirm.= '</table>'."\n";
  3156. $formconfirm.= "</form>\n";
  3157. $formconfirm.= '<br>';
  3158. $formconfirm.= "<!-- end form_confirm -->\n";
  3159. }
  3160. return $formconfirm;
  3161. }
  3162. /**
  3163. * Show a form to select a project
  3164. *
  3165. * @param int $page Page
  3166. * @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)
  3167. * @param int $selected Id pre-selected project
  3168. * @param string $htmlname Name of select field
  3169. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  3170. * @param int $maxlength Max length
  3171. * @param int $forcefocus Force focus on field (works with javascript only)
  3172. * @return void
  3173. */
  3174. function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0)
  3175. {
  3176. global $langs;
  3177. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  3178. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  3179. $formproject=new FormProjets($this->db);
  3180. $langs->load("project");
  3181. if ($htmlname != "none")
  3182. {
  3183. print "\n";
  3184. print '<form method="post" action="'.$page.'">';
  3185. print '<input type="hidden" name="action" value="classin">';
  3186. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3187. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3188. print '<tr><td>';
  3189. $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus);
  3190. print '</td>';
  3191. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3192. print '</tr></table></form>';
  3193. }
  3194. else
  3195. {
  3196. if ($selected)
  3197. {
  3198. $projet = new Project($this->db);
  3199. $projet->fetch($selected);
  3200. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  3201. print $projet->getNomUrl(0,'',1);
  3202. }
  3203. else
  3204. {
  3205. print "&nbsp;";
  3206. }
  3207. }
  3208. }
  3209. /**
  3210. * Show a form to select payment conditions
  3211. *
  3212. * @param int $page Page
  3213. * @param string $selected Id condition pre-selectionne
  3214. * @param string $htmlname Name of select html field
  3215. * @param int $addempty Add empty entry
  3216. * @return void
  3217. */
  3218. function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
  3219. {
  3220. global $langs;
  3221. if ($htmlname != "none")
  3222. {
  3223. print '<form method="post" action="'.$page.'">';
  3224. print '<input type="hidden" name="action" value="setconditions">';
  3225. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3226. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3227. print '<tr><td>';
  3228. $this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
  3229. print '</td>';
  3230. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3231. print '</tr></table></form>';
  3232. }
  3233. else
  3234. {
  3235. if ($selected)
  3236. {
  3237. $this->load_cache_conditions_paiements();
  3238. print $this->cache_conditions_paiements[$selected]['label'];
  3239. } else {
  3240. print "&nbsp;";
  3241. }
  3242. }
  3243. }
  3244. /**
  3245. * Show a form to select a delivery delay
  3246. *
  3247. * @param int $page Page
  3248. * @param string $selected Id condition pre-selectionne
  3249. * @param string $htmlname Name of select html field
  3250. * @param int $addempty Ajoute entree vide
  3251. * @return void
  3252. */
  3253. function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
  3254. {
  3255. global $langs;
  3256. if ($htmlname != "none")
  3257. {
  3258. print '<form method="post" action="'.$page.'">';
  3259. print '<input type="hidden" name="action" value="setavailability">';
  3260. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3261. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3262. print '<tr><td>';
  3263. $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
  3264. print '</td>';
  3265. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3266. print '</tr></table></form>';
  3267. }
  3268. else
  3269. {
  3270. if ($selected)
  3271. {
  3272. $this->load_cache_availability();
  3273. print $this->cache_availability[$selected]['label'];
  3274. } else {
  3275. print "&nbsp;";
  3276. }
  3277. }
  3278. }
  3279. /**
  3280. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3281. * List found into table c_input_reason loaded by loadCacheInputReason
  3282. *
  3283. * @param string $page Page
  3284. * @param string $selected Id condition pre-selectionne
  3285. * @param string $htmlname Name of select html field
  3286. * @param int $addempty Add empty entry
  3287. * @return void
  3288. */
  3289. function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
  3290. {
  3291. global $langs;
  3292. if ($htmlname != "none")
  3293. {
  3294. print '<form method="post" action="'.$page.'">';
  3295. print '<input type="hidden" name="action" value="setdemandreason">';
  3296. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3297. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3298. print '<tr><td>';
  3299. $this->selectInputReason($selected,$htmlname,-1,$addempty);
  3300. print '</td>';
  3301. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3302. print '</tr></table></form>';
  3303. }
  3304. else
  3305. {
  3306. if ($selected)
  3307. {
  3308. $this->loadCacheInputReason();
  3309. foreach ($this->cache_demand_reason as $key => $val)
  3310. {
  3311. if ($val['id'] == $selected)
  3312. {
  3313. print $val['label'];
  3314. break;
  3315. }
  3316. }
  3317. } else {
  3318. print "&nbsp;";
  3319. }
  3320. }
  3321. }
  3322. /**
  3323. * Show a form + html select a date
  3324. *
  3325. * @param string $page Page
  3326. * @param string $selected Date preselected
  3327. * @param string $htmlname Html name of date input fields or 'none'
  3328. * @param int $displayhour Display hour selector
  3329. * @param int $displaymin Display minutes selector
  3330. * @param int $nooutput 1=No print output, return string
  3331. * @return string
  3332. * @see select_date
  3333. */
  3334. function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
  3335. {
  3336. global $langs;
  3337. $ret='';
  3338. if ($htmlname != "none")
  3339. {
  3340. $ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  3341. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  3342. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3343. $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3344. $ret.='<tr><td>';
  3345. $ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1);
  3346. $ret.='</td>';
  3347. $ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3348. $ret.='</tr></table></form>';
  3349. }
  3350. else
  3351. {
  3352. if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
  3353. else $ret.=dol_print_date($selected,'day');
  3354. }
  3355. if (empty($nooutput)) print $ret;
  3356. return $ret;
  3357. }
  3358. /**
  3359. * Show a select form to choose a user
  3360. *
  3361. * @param string $page Page
  3362. * @param string $selected Id of user preselected
  3363. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  3364. * @param array $exclude List of users id to exclude
  3365. * @param array $include List of users id to include
  3366. * @return void
  3367. */
  3368. function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
  3369. {
  3370. global $langs;
  3371. if ($htmlname != "none")
  3372. {
  3373. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  3374. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  3375. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3376. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3377. print '<tr><td>';
  3378. print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
  3379. print '</td>';
  3380. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3381. print '</tr></table></form>';
  3382. }
  3383. else
  3384. {
  3385. if ($selected)
  3386. {
  3387. require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
  3388. $theuser=new User($this->db);
  3389. $theuser->fetch($selected);
  3390. print $theuser->getNomUrl(1);
  3391. } else {
  3392. print "&nbsp;";
  3393. }
  3394. }
  3395. }
  3396. /**
  3397. * Show form with payment mode
  3398. *
  3399. * @param string $page Page
  3400. * @param int $selected Id mode pre-selectionne
  3401. * @param string $htmlname Name of select html field
  3402. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  3403. * @param int $active Active or not, -1 = all
  3404. * @return void
  3405. */
  3406. function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
  3407. {
  3408. global $langs;
  3409. if ($htmlname != "none")
  3410. {
  3411. print '<form method="POST" action="'.$page.'">';
  3412. print '<input type="hidden" name="action" value="setmode">';
  3413. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3414. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3415. print '<tr><td>';
  3416. $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
  3417. print '</td>';
  3418. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3419. print '</tr></table></form>';
  3420. }
  3421. else
  3422. {
  3423. if ($selected)
  3424. {
  3425. $this->load_cache_types_paiements();
  3426. print $this->cache_types_paiements[$selected]['label'];
  3427. } else {
  3428. print "&nbsp;";
  3429. }
  3430. }
  3431. }
  3432. /**
  3433. * Show form with multicurrency code
  3434. *
  3435. * @param string $page Page
  3436. * @param string $selected code pre-selectionne
  3437. * @param string $htmlname Name of select html field
  3438. * @return void
  3439. */
  3440. function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
  3441. {
  3442. global $langs;
  3443. if ($htmlname != "none")
  3444. {
  3445. print '<form method="POST" action="'.$page.'">';
  3446. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  3447. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3448. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3449. print '<tr><td>';
  3450. print $this->selectMultiCurrency($selected, $htmlname, 0);
  3451. print '</td>';
  3452. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3453. print '</tr></table></form>';
  3454. }
  3455. else
  3456. {
  3457. dol_include_once('/core/lib/company.lib.php');
  3458. print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
  3459. }
  3460. }
  3461. /**
  3462. * Show form with multicurrency rate
  3463. *
  3464. * @param string $page Page
  3465. * @param double $rate Current rate
  3466. * @param string $htmlname Name of select html field
  3467. * @param string $currency Currency code to explain the rate
  3468. * @return void
  3469. */
  3470. function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
  3471. {
  3472. global $langs, $mysoc, $conf;
  3473. if ($htmlname != "none")
  3474. {
  3475. print '<form method="POST" action="'.$page.'">';
  3476. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  3477. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3478. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3479. print '<tr><td>';
  3480. print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" />';
  3481. print '</td>';
  3482. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3483. print '</tr></table></form>';
  3484. }
  3485. else
  3486. {
  3487. if (! empty($rate))
  3488. {
  3489. print price($rate, 1, $langs, 1, 0);
  3490. if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  3491. }
  3492. else
  3493. {
  3494. print 1;
  3495. }
  3496. }
  3497. }
  3498. /**
  3499. * Show a select box with available absolute discounts
  3500. *
  3501. * @param string $page Page URL where form is shown
  3502. * @param int $selected Value pre-selected
  3503. * @param string $htmlname Nom du formulaire select. Si 'none', non modifiable. Example 'remise_id'.
  3504. * @param int $socid Third party id
  3505. * @param float $amount Total amount available
  3506. * @param string $filter SQL filter on discounts
  3507. * @param int $maxvalue Max value for lines that can be selected
  3508. * @param string $more More string to add
  3509. * @return void
  3510. */
  3511. function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='')
  3512. {
  3513. global $conf,$langs;
  3514. if ($htmlname != "none")
  3515. {
  3516. print '<form method="post" action="'.$page.'">';
  3517. print '<input type="hidden" name="action" value="setabsolutediscount">';
  3518. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3519. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3520. print '<tr><td class="nowrap">';
  3521. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  3522. {
  3523. if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)).': '; // If we want deposit to be substracted to payments only and not to total of final invoice
  3524. else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)).': ';
  3525. }
  3526. else
  3527. {
  3528. if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)).': ';
  3529. else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency)).': ';
  3530. }
  3531. $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles
  3532. if ($filter) $newfilter.=' AND ('.$filter.')';
  3533. $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
  3534. print '</td>';
  3535. print '<td class="nowrap">';
  3536. if ($nbqualifiedlines > 0)
  3537. {
  3538. print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  3539. if ($filter && $filter != "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')") print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  3540. print '>';
  3541. }
  3542. if ($more) print $more;
  3543. print '</td>';
  3544. print '</tr></table></form>';
  3545. }
  3546. else
  3547. {
  3548. if ($selected)
  3549. {
  3550. print $selected;
  3551. }
  3552. else
  3553. {
  3554. print "0";
  3555. }
  3556. }
  3557. }
  3558. /**
  3559. * Show forms to select a contact
  3560. *
  3561. * @param string $page Page
  3562. * @param Societe $societe Filter on third party
  3563. * @param int $selected Id contact pre-selectionne
  3564. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  3565. * @return void
  3566. */
  3567. function form_contacts($page, $societe, $selected='', $htmlname='contactid')
  3568. {
  3569. global $langs, $conf;
  3570. if ($htmlname != "none")
  3571. {
  3572. print '<form method="post" action="'.$page.'">';
  3573. print '<input type="hidden" name="action" value="set_contact">';
  3574. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3575. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3576. print '<tr><td>';
  3577. $num=$this->select_contacts($societe->id, $selected, $htmlname);
  3578. if ($num==0)
  3579. {
  3580. $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  3581. print '<font class="error">Cette societe n\'a pas de contact, veuillez en cr�er un avant de faire votre proposition commerciale</font><br>';
  3582. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  3583. }
  3584. print '</td>';
  3585. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3586. print '</tr></table></form>';
  3587. }
  3588. else
  3589. {
  3590. if ($selected)
  3591. {
  3592. require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
  3593. $contact=new Contact($this->db);
  3594. $contact->fetch($selected);
  3595. print $contact->getFullName($langs);
  3596. } else {
  3597. print "&nbsp;";
  3598. }
  3599. }
  3600. }
  3601. /**
  3602. * Output html select to select thirdparty
  3603. *
  3604. * @param string $page Page
  3605. * @param string $selected Id preselected
  3606. * @param string $htmlname Name of HTML select
  3607. * @param string $filter optional filters criteras
  3608. * @param int $showempty Add an empty field
  3609. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  3610. * @param int $forcecombo Force to use combo box
  3611. * @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')))
  3612. * @return void
  3613. */
  3614. function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array())
  3615. {
  3616. global $langs;
  3617. if ($htmlname != "none")
  3618. {
  3619. print '<form method="post" action="'.$page.'">';
  3620. print '<input type="hidden" name="action" value="set_thirdparty">';
  3621. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3622. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3623. print '<tr><td>';
  3624. print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
  3625. print '</td>';
  3626. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3627. print '</tr></table></form>';
  3628. }
  3629. else
  3630. {
  3631. if ($selected)
  3632. {
  3633. require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
  3634. $soc = new Societe($this->db);
  3635. $soc->fetch($selected);
  3636. print $soc->getNomUrl($langs);
  3637. }
  3638. else
  3639. {
  3640. print "&nbsp;";
  3641. }
  3642. }
  3643. }
  3644. /**
  3645. * Retourne la liste des devises, dans la langue de l'utilisateur
  3646. *
  3647. * @param string $selected preselected currency code
  3648. * @param string $htmlname name of HTML select list
  3649. * @return void
  3650. */
  3651. function select_currency($selected='',$htmlname='currency_id')
  3652. {
  3653. print $this->selectcurrency($selected,$htmlname);
  3654. }
  3655. /**
  3656. * Retourne la liste des devises, dans la langue de l'utilisateur
  3657. *
  3658. * @param string $selected preselected currency code
  3659. * @param string $htmlname name of HTML select list
  3660. * @return string
  3661. */
  3662. function selectCurrency($selected='',$htmlname='currency_id')
  3663. {
  3664. global $conf,$langs,$user;
  3665. $langs->loadCacheCurrencies('');
  3666. $out='';
  3667. if ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite
  3668. $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3669. foreach ($langs->cache_currencies as $code_iso => $currency)
  3670. {
  3671. if ($selected && $selected == $code_iso)
  3672. {
  3673. $out.= '<option value="'.$code_iso.'" selected>';
  3674. }
  3675. else
  3676. {
  3677. $out.= '<option value="'.$code_iso.'">';
  3678. }
  3679. $out.= $currency['label'];
  3680. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  3681. $out.= '</option>';
  3682. }
  3683. $out.= '</select>';
  3684. if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  3685. return $out;
  3686. }
  3687. /**
  3688. * Return array of currencies in user language
  3689. *
  3690. * @param string $selected preselected currency code
  3691. * @param string $htmlname name of HTML select list
  3692. * @param integer $useempty 1=Add empty line
  3693. * @return string
  3694. */
  3695. function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
  3696. {
  3697. global $db,$conf,$langs,$user;
  3698. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  3699. $TCurrency = array();
  3700. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  3701. $sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  3702. $resql = $db->query($sql);
  3703. if ($resql)
  3704. {
  3705. while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
  3706. }
  3707. $out='';
  3708. $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3709. if ($useempty) $out .= '<option value=""></option>';
  3710. if (count($TCurrency) > 0)
  3711. {
  3712. foreach ($langs->cache_currencies as $code_iso => $currency)
  3713. {
  3714. if (isset($TCurrency[$code_iso]))
  3715. {
  3716. if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
  3717. else $out.= '<option value="'.$code_iso.'">';
  3718. $out.= $currency['label'];
  3719. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  3720. $out.= '</option>';
  3721. }
  3722. }
  3723. }
  3724. $out.= '</select>';
  3725. return $out;
  3726. }
  3727. /**
  3728. * Load into the cache vat rates of a country
  3729. *
  3730. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  3731. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  3732. */
  3733. function load_cache_vatrates($country_code)
  3734. {
  3735. global $langs;
  3736. $num = count($this->cache_vatrates);
  3737. if ($num > 0) return $num; // Cache already loaded
  3738. dol_syslog(__METHOD__, LOG_DEBUG);
  3739. $sql = "SELECT DISTINCT t.code, t.taux, t.recuperableonly";
  3740. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3741. $sql.= " WHERE t.fk_pays = c.rowid";
  3742. $sql.= " AND t.active > 0";
  3743. $sql.= " AND c.code IN (".$country_code.")";
  3744. $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  3745. $resql=$this->db->query($sql);
  3746. if ($resql)
  3747. {
  3748. $num = $this->db->num_rows($resql);
  3749. if ($num)
  3750. {
  3751. for ($i = 0; $i < $num; $i++)
  3752. {
  3753. $obj = $this->db->fetch_object($resql);
  3754. $this->cache_vatrates[$i]['code'] = $obj->code;
  3755. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  3756. $this->cache_vatrates[$i]['libtva'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or *
  3757. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  3758. }
  3759. return $num;
  3760. }
  3761. else
  3762. {
  3763. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
  3764. return -1;
  3765. }
  3766. }
  3767. else
  3768. {
  3769. $this->error = '<font class="error">'.$this->db->error().'</font>';
  3770. return -2;
  3771. }
  3772. }
  3773. /**
  3774. * Output an HTML select vat rate.
  3775. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  3776. *
  3777. * @param string $htmlname Name of HTML select field
  3778. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  3779. * @param Societe $societe_vendeuse Thirdparty seller
  3780. * @param Societe $societe_acheteuse Thirdparty buyer
  3781. * @param int $idprod Id product
  3782. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  3783. * @param int $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  3784. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  3785. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  3786. * 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.
  3787. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  3788. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  3789. * Sinon la TVA proposee par defaut=0. Fin de regle.
  3790. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  3791. * @param int $addcode Add code into key in select list
  3792. * @return string
  3793. */
  3794. function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $addcode=0)
  3795. {
  3796. global $langs,$conf,$mysoc;
  3797. $return='';
  3798. // Define defaultnpr, defaultttx and defaultcode
  3799. $defaultnpr=($info_bits & 0x01);
  3800. $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
  3801. $defaulttx=str_replace('*','',$selectedrate);
  3802. $defaultcode='';
  3803. if (preg_match('/\s*\((.*)\)/', $defaulttx, $reg))
  3804. {
  3805. $defaultcode=$reg[1];
  3806. $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
  3807. }
  3808. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  3809. // Check parameters
  3810. if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
  3811. {
  3812. if ($societe_vendeuse->id == $mysoc->id)
  3813. {
  3814. $return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
  3815. }
  3816. else
  3817. {
  3818. $return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
  3819. }
  3820. return $return;
  3821. }
  3822. //var_dump($societe_acheteuse);
  3823. //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";
  3824. //exit;
  3825. // Define list of countries to use to search VAT rates to show
  3826. // First we defined code_country to use to find list
  3827. if (is_object($societe_vendeuse))
  3828. {
  3829. $code_country="'".$societe_vendeuse->country_code."'";
  3830. }
  3831. else
  3832. {
  3833. $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  3834. }
  3835. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  3836. {
  3837. if (! $societe_vendeuse->isInEEC() && (! is_object($societe_acheteuse) || ($societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany())))
  3838. {
  3839. // We also add the buyer
  3840. if (is_numeric($type))
  3841. {
  3842. if ($type == 1) // We know product is a service
  3843. {
  3844. $code_country.=",'".$societe_acheteuse->country_code."'";
  3845. }
  3846. }
  3847. else if (! $idprod) // We don't know type of product
  3848. {
  3849. $code_country.=",'".$societe_acheteuse->country_code."'";
  3850. }
  3851. else
  3852. {
  3853. $prodstatic=new Product($this->db);
  3854. $prodstatic->fetch($idprod);
  3855. if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service
  3856. {
  3857. $code_country.=",'".$societe_acheteuse->country_code."'";
  3858. }
  3859. }
  3860. }
  3861. }
  3862. // Now we get list
  3863. $num = $this->load_cache_vatrates($code_country);
  3864. if ($num > 0)
  3865. {
  3866. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  3867. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  3868. {
  3869. $tmpthirdparty=new Societe($this->db);
  3870. $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  3871. $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  3872. if (empty($defaulttx)) $defaultnpr=0;
  3873. }
  3874. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  3875. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  3876. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  3877. {
  3878. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
  3879. else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  3880. }
  3881. // Disabled if seller is not subject to VAT
  3882. $disabled=false; $title='';
  3883. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
  3884. {
  3885. $title=' title="'.$langs->trans('VATIsNotUsed').'"';
  3886. $disabled=true;
  3887. }
  3888. if (! $options_only) $return.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
  3889. foreach ($this->cache_vatrates as $rate)
  3890. {
  3891. // Keep only 0 if seller is not subject to VAT
  3892. if ($disabled && $rate['txtva'] != 0) continue;
  3893. $return.= '<option value="'.$rate['txtva'];
  3894. $return.= $rate['nprtva'] ? '*': '';
  3895. if ($addcode && $rate['code']) $return.=' ('.$rate['code'].')';
  3896. $return.= '"';
  3897. if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  3898. {
  3899. if ($defaultcode == $rate['code']) $return.= ' selected';
  3900. }
  3901. elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
  3902. {
  3903. $return.= ' selected';
  3904. }
  3905. $return.= '>'.vatrate($rate['libtva']);
  3906. //$return.=($rate['code']?' '.$rate['code']:'');
  3907. $return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': ''; // We show the * (old behaviour only if new vat code is not used)
  3908. $return.= '</option>';
  3909. }
  3910. if (! $options_only) $return.= '</select>';
  3911. }
  3912. else
  3913. {
  3914. $return.= $this->error;
  3915. }
  3916. $this->num = $num;
  3917. return $return;
  3918. }
  3919. /**
  3920. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  3921. * Fields are preselected with :
  3922. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  3923. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  3924. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  3925. *
  3926. * @param timestamp $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0).
  3927. * @param string $prefix Prefix for fields name
  3928. * @param int $h 1=Show also hours
  3929. * @param int $m 1=Show also minutes
  3930. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  3931. * @param string $form_name Not used
  3932. * @param int $d 1=Show days, month, years
  3933. * @param int $addnowlink Add a link "Now"
  3934. * @param int $nooutput Do not output html string but return it
  3935. * @param int $disabled Disable input fields
  3936. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  3937. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  3938. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  3939. * @return string|null Nothing or string if nooutput is 1
  3940. * @see form_date
  3941. */
  3942. 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='')
  3943. {
  3944. global $conf,$langs;
  3945. $retstring='';
  3946. if($prefix=='') $prefix='re';
  3947. if($h == '') $h=0;
  3948. if($m == '') $m=0;
  3949. $emptydate=0;
  3950. $emptyhours=0;
  3951. if ($empty == 1) { $emptydate=1; $emptyhours=1; }
  3952. if ($empty == 2) { $emptydate=0; $emptyhours=1; }
  3953. $orig_set_time=$set_time;
  3954. if ($set_time === '' && $emptydate == 0)
  3955. {
  3956. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  3957. $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
  3958. }
  3959. // Analysis of the pre-selection date
  3960. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))
  3961. {
  3962. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  3963. $syear = (! empty($reg[1])?$reg[1]:'');
  3964. $smonth = (! empty($reg[2])?$reg[2]:'');
  3965. $sday = (! empty($reg[3])?$reg[3]:'');
  3966. $shour = (! empty($reg[4])?$reg[4]:'');
  3967. $smin = (! empty($reg[5])?$reg[5]:'');
  3968. }
  3969. elseif (strval($set_time) != '' && $set_time != -1)
  3970. {
  3971. // set_time est un timestamps (0 possible)
  3972. $syear = dol_print_date($set_time, "%Y");
  3973. $smonth = dol_print_date($set_time, "%m");
  3974. $sday = dol_print_date($set_time, "%d");
  3975. if ($orig_set_time != '')
  3976. {
  3977. $shour = dol_print_date($set_time, "%H");
  3978. $smin = dol_print_date($set_time, "%M");
  3979. }
  3980. }
  3981. else
  3982. {
  3983. // Date est '' ou vaut -1
  3984. $syear = '';
  3985. $smonth = '';
  3986. $sday = '';
  3987. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? '' : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  3988. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? '' : $conf->global->MAIN_DEFAULT_DATE_MIN;
  3989. }
  3990. $usecalendar='combo';
  3991. if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) $usecalendar=empty($conf->global->MAIN_POPUP_CALENDAR)?'eldy':$conf->global->MAIN_POPUP_CALENDAR;
  3992. if ($conf->browser->phone) $usecalendar='combo';
  3993. if ($d)
  3994. {
  3995. // Show date with popup
  3996. if ($usecalendar != 'combo')
  3997. {
  3998. $formated_date='';
  3999. //print "e".$set_time." t ".$conf->format_date_short;
  4000. if (strval($set_time) != '' && $set_time != -1)
  4001. {
  4002. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  4003. $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4004. }
  4005. // Calendrier popup version eldy
  4006. if ($usecalendar == "eldy")
  4007. {
  4008. // Zone de saisie manuelle de la date
  4009. $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" size="9" maxlength="11" value="'.$formated_date.'"';
  4010. $retstring.=($disabled?' disabled':'');
  4011. $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4012. $retstring.='>';
  4013. // Icone calendrier
  4014. if (! $disabled)
  4015. {
  4016. $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  4017. $base=DOL_URL_ROOT.'/core/';
  4018. $retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');">'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
  4019. }
  4020. else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
  4021. $retstring.='<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4022. $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4023. $retstring.='<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4024. }
  4025. else
  4026. {
  4027. print "Bad value of MAIN_POPUP_CALENDAR";
  4028. }
  4029. }
  4030. // Show date with combo selects
  4031. else
  4032. {
  4033. //$retstring.='<div class="inline-block">';
  4034. // Day
  4035. $retstring.='<select'.($disabled?' disabled':'').' class="flat" id="'.$prefix.'day" name="'.$prefix.'day">';
  4036. if ($emptydate || $set_time == -1)
  4037. {
  4038. $retstring.='<option value="0" selected>&nbsp;</option>';
  4039. }
  4040. for ($day = 1 ; $day <= 31; $day++)
  4041. {
  4042. $retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
  4043. }
  4044. $retstring.="</select>";
  4045. $retstring.='<select'.($disabled?' disabled':'').' class="flat" id="'.$prefix.'month" name="'.$prefix.'month">';
  4046. if ($emptydate || $set_time == -1)
  4047. {
  4048. $retstring.='<option value="0" selected>&nbsp;</option>';
  4049. }
  4050. // Month
  4051. for ($month = 1 ; $month <= 12 ; $month++)
  4052. {
  4053. $retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
  4054. $retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
  4055. $retstring.="</option>";
  4056. }
  4057. $retstring.="</select>";
  4058. // Year
  4059. if ($emptydate || $set_time == -1)
  4060. {
  4061. $retstring.='<input'.($disabled?' disabled':'').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat" type="text" size="3" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
  4062. }
  4063. else
  4064. {
  4065. $retstring.='<select'.($disabled?' disabled':'').' class="flat" id="'.$prefix.'year" name="'.$prefix.'year">';
  4066. for ($year = $syear - 5; $year < $syear + 10 ; $year++)
  4067. {
  4068. $retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
  4069. }
  4070. $retstring.="</select>\n";
  4071. }
  4072. //$retstring.='</div>';
  4073. }
  4074. }
  4075. if ($d && $h) $retstring.='&nbsp;';
  4076. if ($h)
  4077. {
  4078. // Show hour
  4079. $retstring.='<select'.($disabled?' disabled':'').' class="flat '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  4080. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4081. for ($hour = 0; $hour < 24; $hour++)
  4082. {
  4083. if (strlen($hour) < 2) $hour = "0" . $hour;
  4084. $retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
  4085. }
  4086. $retstring.='</select>';
  4087. if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
  4088. }
  4089. if ($m)
  4090. {
  4091. // Show minutes
  4092. $retstring.='<select'.($disabled?' disabled':'').' class="flat '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  4093. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4094. for ($min = 0; $min < 60 ; $min++)
  4095. {
  4096. if (strlen($min) < 2) $min = "0" . $min;
  4097. $retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
  4098. }
  4099. $retstring.='</select>';
  4100. }
  4101. // Add a "Now" link
  4102. if ($conf->use_javascript_ajax && $addnowlink)
  4103. {
  4104. // Script which will be inserted in the onClick of the "Now" link
  4105. $reset_scripts = "";
  4106. // Generate the date part, depending on the use or not of the javascript calendar
  4107. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4108. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4109. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4110. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4111. /*if ($usecalendar == "eldy")
  4112. {
  4113. $base=DOL_URL_ROOT.'/core/';
  4114. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  4115. }
  4116. else
  4117. {
  4118. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  4119. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  4120. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  4121. }*/
  4122. // Update the hour part
  4123. if ($h)
  4124. {
  4125. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4126. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  4127. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4128. if ($fullday) $reset_scripts .= ' } ';
  4129. }
  4130. // Update the minute part
  4131. if ($m)
  4132. {
  4133. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4134. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  4135. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4136. if ($fullday) $reset_scripts .= ' } ';
  4137. }
  4138. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4139. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4140. {
  4141. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  4142. $retstring.=$langs->trans("Now");
  4143. $retstring.='</button> ';
  4144. }
  4145. }
  4146. // Add a "Plus one hour" link
  4147. if ($conf->use_javascript_ajax && $addplusone)
  4148. {
  4149. // Script which will be inserted in the onClick of the "Add plusone" link
  4150. $reset_scripts = "";
  4151. // Generate the date part, depending on the use or not of the javascript calendar
  4152. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4153. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4154. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4155. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4156. // Update the hour part
  4157. if ($h)
  4158. {
  4159. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4160. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4161. if ($fullday) $reset_scripts .= ' } ';
  4162. }
  4163. // Update the minute part
  4164. if ($m)
  4165. {
  4166. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4167. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4168. if ($fullday) $reset_scripts .= ' } ';
  4169. }
  4170. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4171. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4172. {
  4173. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  4174. $retstring.=$langs->trans("DateStartPlusOne");
  4175. $retstring.='</button> ';
  4176. }
  4177. }
  4178. // Add a "Plus one hour" link
  4179. if ($conf->use_javascript_ajax && $adddateof)
  4180. {
  4181. $tmparray=dol_getdate($adddateof);
  4182. $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'].'\');">'.$langs->trans("DateInvoice").'</a>';
  4183. }
  4184. if (! empty($nooutput)) return $retstring;
  4185. print $retstring;
  4186. return;
  4187. }
  4188. /**
  4189. * Function to show a form to select a duration on a page
  4190. *
  4191. * @param string $prefix Prefix for input fields
  4192. * @param int $iSecond Default preselected duration (number of seconds or '')
  4193. * @param int $disabled Disable the combo box
  4194. * @param string $typehour If 'select' then input hour and input min is a combo, if 'text' input hour is in text and input min is a combo
  4195. * @param integer $minunderhours If 1, show minutes selection under the hours
  4196. * @param int $nooutput Do not output html string but return it
  4197. * @return string|null
  4198. */
  4199. function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
  4200. {
  4201. global $langs;
  4202. $retstring='';
  4203. $hourSelected=0; $minSelected=0;
  4204. // Hours
  4205. if ($iSecond != '')
  4206. {
  4207. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4208. $hourSelected = convertSecondToTime($iSecond,'allhour');
  4209. $minSelected = convertSecondToTime($iSecond,'min');
  4210. }
  4211. if ($typehour=='select')
  4212. {
  4213. $retstring.='<select class="flat" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
  4214. for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours
  4215. {
  4216. $retstring.='<option value="'.$hour.'"';
  4217. if ($hourSelected == $hour)
  4218. {
  4219. $retstring.=" selected";
  4220. }
  4221. $retstring.=">".$hour."</option>";
  4222. }
  4223. $retstring.="</select>";
  4224. }
  4225. elseif ($typehour=='text')
  4226. {
  4227. $retstring.='<input type="text" size="2" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat" value="'.($hourSelected?((int) $hourSelected):'').'">';
  4228. }
  4229. else return 'BadValueForParameterTypeHour';
  4230. $retstring.=' '.$langs->trans('HourShort');
  4231. // Minutes
  4232. if ($minunderhours) $retstring.='<br>';
  4233. else $retstring.="&nbsp;";
  4234. if ($typehour=='select')
  4235. {
  4236. $retstring.='<select class="flat" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
  4237. for ($min = 0; $min <= 55; $min=$min+5)
  4238. {
  4239. $retstring.='<option value="'.$min.'"';
  4240. if ($minSelected == $min) $retstring.=' selected';
  4241. $retstring.='>'.$min.'</option>';
  4242. }
  4243. $retstring.="</select>";
  4244. }
  4245. elseif ($typehour=='text')
  4246. {
  4247. $retstring.='<input type="text" size="2" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat" value="'.($minSelected?((int) $minSelected):'').'">';
  4248. }
  4249. $retstring.=' '.$langs->trans('MinuteShort');
  4250. $retstring.="&nbsp;";
  4251. if (! empty($nooutput)) return $retstring;
  4252. print $retstring;
  4253. return;
  4254. }
  4255. /**
  4256. * Return a HTML select string, built from an array of key+value.
  4257. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  4258. *
  4259. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  4260. * @param array $array Array with key+value
  4261. * @param string|string[] $id Preselected key or preselected keys for multiselect
  4262. * @param int $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (value is '' or '&nbsp;' if 1), <0 to add an empty value with key that is this value.
  4263. * @param int $key_in_label 1 pour afficher la key dans la valeur "[key] value"
  4264. * @param int $value_as_key 1 to use value as key
  4265. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  4266. * @param int $translate Translate and encode value
  4267. * @param int $maxlen Length maximum for labels
  4268. * @param int $disabled Html select box is disabled
  4269. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  4270. * @param string $morecss Add more class to css styles
  4271. * @param int $addjscombo Add js combo
  4272. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set.
  4273. * @return string HTML select string.
  4274. * @see multiselectarray
  4275. */
  4276. 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='')
  4277. {
  4278. global $conf, $langs;
  4279. // Do we want a multiselect ?
  4280. //$jsbeautify = 0;
  4281. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  4282. $jsbeautify = 1;
  4283. if ($value_as_key) $array=array_combine($array, $array);
  4284. $out='';
  4285. // Add code for jquery to use multiselect
  4286. if ($addjscombo && empty($conf->dol_use_jmobile) && $jsbeautify)
  4287. {
  4288. $minLengthToAutocomplete=0;
  4289. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2':$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  4290. $out.='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  4291. <script type="text/javascript">
  4292. $(document).ready(function () {
  4293. $(\''.(preg_match('/^\./',$htmlname)?$htmlname:'#'.$htmlname).'\').'.$tmpplugin.'({
  4294. dir: \'ltr\',
  4295. width: \'resolve\', /* off or resolve */
  4296. minimumInputLength: '.$minLengthToAutocomplete.'
  4297. });
  4298. });
  4299. </script>';
  4300. }
  4301. $out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'" name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'').'>';
  4302. if ($show_empty)
  4303. {
  4304. $textforempty=' ';
  4305. 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.
  4306. if (! is_numeric($show_empty)) $textforempty=$show_empty;
  4307. $out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
  4308. }
  4309. if (is_array($array))
  4310. {
  4311. // Translate
  4312. if ($translate)
  4313. {
  4314. foreach($array as $key => $value) $array[$key]=$langs->trans($value);
  4315. }
  4316. // Sort
  4317. if ($sort == 'ASC') asort($array);
  4318. elseif ($sort == 'DESC') arsort($array);
  4319. foreach($array as $key => $value)
  4320. {
  4321. $out.='<option value="'.$key.'"';
  4322. if ($id != '' && $id == $key) $out.=' selected'; // To preselect a value
  4323. $out.='>';
  4324. if ($key_in_label)
  4325. {
  4326. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
  4327. }
  4328. else
  4329. {
  4330. $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
  4331. if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
  4332. }
  4333. $out.=$selectOptionValue;
  4334. $out.="</option>\n";
  4335. }
  4336. }
  4337. $out.="</select>";
  4338. return $out;
  4339. }
  4340. /**
  4341. * 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.
  4342. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  4343. *
  4344. * @param string $htmlname Name of html select area
  4345. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  4346. * @param string $id Preselected key
  4347. * @param string $moreparam Add more parameters onto the select tag
  4348. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  4349. * @param int $disabled Html select box is disabled
  4350. * @param int $minimumInputLength Minimum Input Length
  4351. * @param string $morecss Add more class to css styles
  4352. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  4353. * @param string $placeholder String to use as placeholder
  4354. * @param integer $acceptdelayedhtml 1 if caller request to have html delayed content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
  4355. * @return string HTML select string
  4356. */
  4357. static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
  4358. {
  4359. global $langs;
  4360. global $delayedhtmlcontent;
  4361. $tmpplugin='select2';
  4362. $out='<input type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'">';
  4363. // TODO Use an internal dolibarr component instead of select2
  4364. $outdelayed='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  4365. <script type="text/javascript">
  4366. $(document).ready(function () {
  4367. '.($callurlonselect ? 'var saveRemoteData = [];':'').'
  4368. $(".'.$htmlname.'").select2({
  4369. ajax: {
  4370. dir: "ltr",
  4371. url: "'.$url.'",
  4372. dataType: \'json\',
  4373. delay: 250,
  4374. data: function (searchTerm, pageNumber, context) {
  4375. return {
  4376. q: searchTerm, // search term
  4377. page: pageNumber
  4378. };
  4379. },
  4380. results: function (remoteData, pageNumber, query) {
  4381. console.log(remoteData);
  4382. saveRemoteData = remoteData;
  4383. /* format json result for select2 */
  4384. result = []
  4385. $.each( remoteData, function( key, value ) {
  4386. result.push({id: key, text: value.text});
  4387. });
  4388. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  4389. return {results: result, more:false}
  4390. },
  4391. /*processResults: function (data, page) {
  4392. // parse the results into the format expected by Select2.
  4393. // since we are using custom formatting functions we do not need to
  4394. // alter the remote JSON data
  4395. console.log(data);
  4396. return {
  4397. results: data.items
  4398. };
  4399. },*/
  4400. cache: true
  4401. },
  4402. dropdownCssClass: "css-'.$htmlname.'",
  4403. placeholder: "'.dol_escape_js($placeholder).'",
  4404. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  4405. minimumInputLength: '.$minimumInputLength.',
  4406. formatResult: function(result, container, query, escapeMarkup) {
  4407. return escapeMarkup(result.text);
  4408. }
  4409. });
  4410. '.($callurlonselect ? '
  4411. $(".'.$htmlname.'").change(function() {
  4412. var selected = $(".'.$htmlname.'").select2("val");
  4413. $(".'.$htmlname.'").select2("val",""); /* reset visible combo value */
  4414. $.each( saveRemoteData, function( key, value ) {
  4415. if (key == selected)
  4416. {
  4417. console.log("Do a redirect into selectArrayAjax to "+value.url)
  4418. location.assign(value.url);
  4419. }
  4420. });
  4421. });' : '' ) . '
  4422. });
  4423. </script>';
  4424. if ($acceptdelayedhtml)
  4425. {
  4426. $delayedhtmlcontent.=$outdelayed;
  4427. }
  4428. else
  4429. {
  4430. $out.=$outdelayed;
  4431. }
  4432. return $out;
  4433. }
  4434. /**
  4435. * Show a multiselect form from an array.
  4436. *
  4437. * @param string $htmlname Name of select
  4438. * @param array $array Array with key+value
  4439. * @param array $selected Array with key+value preselected
  4440. * @param int $key_in_label 1 pour afficher la key dans la valeur "[key] value"
  4441. * @param int $value_as_key 1 to use value as key
  4442. * @param string $morecss Add more css style
  4443. * @param int $translate Translate and encode value
  4444. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  4445. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  4446. * @param string $elemtype Type of element we show ('category', ...)
  4447. * @return string HTML multiselect string
  4448. * @see selectarray
  4449. */
  4450. static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='',$elemtype='')
  4451. {
  4452. global $conf, $langs;
  4453. $out = '';
  4454. // Add code for jquery to use multiselect
  4455. if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
  4456. {
  4457. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  4458. $out.='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  4459. <script type="text/javascript">
  4460. function formatResult(record) {'."\n";
  4461. if ($elemtype == 'category')
  4462. {
  4463. $out.=' //return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
  4464. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  4465. }
  4466. else
  4467. {
  4468. $out.='return record.text;';
  4469. }
  4470. $out.= ' };
  4471. function formatSelection(record) {'."\n";
  4472. if ($elemtype == 'category')
  4473. {
  4474. $out.=' //return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
  4475. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  4476. }
  4477. else
  4478. {
  4479. $out.='return record.text;';
  4480. }
  4481. $out.= ' };
  4482. $(document).ready(function () {
  4483. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  4484. dir: \'ltr\',
  4485. // Specify format function for dropdown item
  4486. formatResult: formatResult,
  4487. templateResult: formatResult, /* For 4.0 */
  4488. // Specify format function for selected item
  4489. formatSelection: formatSelection,
  4490. templateResult: formatSelection /* For 4.0 */
  4491. });
  4492. });
  4493. </script>';
  4494. }
  4495. // Try also magic suggest
  4496. // Add data-role="none" to disable jmobile decoration
  4497. $out .= '<select data-role="none" id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
  4498. if (is_array($array) && ! empty($array))
  4499. {
  4500. if ($value_as_key) $array=array_combine($array, $array);
  4501. if (! empty($array))
  4502. {
  4503. foreach ($array as $key => $value)
  4504. {
  4505. $out.= '<option value="'.$key.'"';
  4506. if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
  4507. {
  4508. $out.= ' selected';
  4509. }
  4510. $out.= '>';
  4511. $newval = ($translate ? $langs->trans($value) : $value);
  4512. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  4513. $out.= dol_htmlentitiesbr($newval);
  4514. $out.= '</option>'."\n";
  4515. }
  4516. }
  4517. }
  4518. $out.= '</select>'."\n";
  4519. return $out;
  4520. }
  4521. /**
  4522. * Show a multiselect form from an array.
  4523. *
  4524. * @param string $htmlname Name of select
  4525. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  4526. * @param string $varpage Id of context for page. Can be set with $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
  4527. * @return string HTML multiselect string
  4528. * @see selectarray
  4529. */
  4530. static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  4531. {
  4532. global $user;
  4533. $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
  4534. if (! empty($user->conf->$tmpvar))
  4535. {
  4536. $tmparray=explode(',', $user->conf->$tmpvar);
  4537. foreach($array as $key => $val)
  4538. {
  4539. //var_dump($key);
  4540. //var_dump($tmparray);
  4541. if (in_array($key, $tmparray)) $array[$key]['checked']=1;
  4542. else $array[$key]['checked']=0;
  4543. }
  4544. }
  4545. //var_dump($array);
  4546. $lis='';
  4547. $listcheckedstring='';
  4548. foreach($array as $key => $val)
  4549. {
  4550. /* var_dump($val);
  4551. var_dump(array_key_exists('enabled', $val));
  4552. var_dump(!$val['enabled']);*/
  4553. if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
  4554. {
  4555. unset($array[$key]); // We don't want this field
  4556. continue;
  4557. }
  4558. if ($val['label'])
  4559. {
  4560. $lis.='<li><input type="checkbox" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/>'.dol_escape_htmltag($val['label']).'</li>';
  4561. $listcheckedstring.=(empty($val['checked'])?'':$key.',');
  4562. }
  4563. }
  4564. $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  4565. <dl class="dropdown">
  4566. <dt>
  4567. <a href="#">
  4568. '.img_picto('','list').'
  4569. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  4570. </a>
  4571. </dt>
  4572. <dd>
  4573. <div class="multiselectcheckbox'.$htmlname.'">
  4574. <ul class="ul'.$htmlname.'">
  4575. '.$lis.'
  4576. </ul>
  4577. </div>
  4578. </dd>
  4579. </dl>
  4580. <script type="text/javascript">
  4581. $(".dropdown dt a").on(\'click\', function () {
  4582. $(".dropdown dd ul").slideToggle(\'fast\');
  4583. });
  4584. $(".dropdown dd ul li a").on(\'click\', function () {
  4585. $(".dropdown dd ul").hide();
  4586. });
  4587. function getSelectedValue(id) {
  4588. return $("#" + id).find("dt a span.value").html();
  4589. }
  4590. $(document).bind(\'click\', function (e) {
  4591. var $clicked = $(e.target);
  4592. if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
  4593. });
  4594. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  4595. console.log("A new field was added/removed")
  4596. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
  4597. var title = $(this).val() + ",";
  4598. if ($(this).is(\':checked\')) {
  4599. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  4600. }
  4601. else {
  4602. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  4603. }
  4604. // Now, we submit page
  4605. $(this).parents(\'form:first\').submit();
  4606. });
  4607. </script>
  4608. ';
  4609. return $out;
  4610. }
  4611. /**
  4612. * Render list of categories linked to object with id $id and type $type
  4613. *
  4614. * @param int $id Id of object
  4615. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  4616. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  4617. * @return mixed Array of category objects or < 0 if KO
  4618. */
  4619. function showCategories($id, $type, $rendermode=0)
  4620. {
  4621. global $db;
  4622. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4623. $cat = new Categorie($db);
  4624. $categories = $cat->containing($id, $type);
  4625. if ($rendermode == 1)
  4626. {
  4627. $toprint = array();
  4628. foreach($categories as $c)
  4629. {
  4630. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  4631. foreach($ways as $way)
  4632. {
  4633. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
  4634. }
  4635. }
  4636. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  4637. }
  4638. if ($rendermode == 0)
  4639. {
  4640. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  4641. foreach($categories as $c) {
  4642. $arrayselected[] = $c->id;
  4643. }
  4644. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  4645. }
  4646. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  4647. }
  4648. /**
  4649. * Show linked object block.
  4650. *
  4651. * @param CommonObject $object Object we want to show links to
  4652. * @return int <0 if KO, >0 if OK
  4653. */
  4654. function showLinkedObjectBlock($object)
  4655. {
  4656. global $conf,$langs,$hookmanager;
  4657. global $bc;
  4658. $object->fetchObjectLinked();
  4659. // Bypass the default method
  4660. $hookmanager->initHooks(array('commonobject'));
  4661. $parameters=array();
  4662. $reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
  4663. if (empty($reshook))
  4664. {
  4665. $num = count($object->linkedObjects);
  4666. $numoutput=0;
  4667. foreach($object->linkedObjects as $objecttype => $objects)
  4668. {
  4669. $tplpath = $element = $subelement = $objecttype;
  4670. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  4671. {
  4672. $element = $regs[1];
  4673. $subelement = $regs[2];
  4674. $tplpath = $element.'/'.$subelement;
  4675. }
  4676. $tplname='linkedobjectblock';
  4677. // To work with non standard path
  4678. if ($objecttype == 'facture') {
  4679. $tplpath = 'compta/'.$element;
  4680. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  4681. }
  4682. else if ($objecttype == 'facturerec') {
  4683. $tplpath = 'compta/facture';
  4684. $tplname = 'linkedobjectblockForRec';
  4685. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  4686. }
  4687. else if ($objecttype == 'propal') {
  4688. $tplpath = 'comm/'.$element;
  4689. if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
  4690. }
  4691. else if ($objecttype == 'supplier_proposal') {
  4692. if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
  4693. }
  4694. else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
  4695. $tplpath = 'expedition';
  4696. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  4697. }
  4698. else if ($objecttype == 'delivery') {
  4699. $tplpath = 'livraison';
  4700. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  4701. }
  4702. else if ($objecttype == 'invoice_supplier') {
  4703. $tplpath = 'fourn/facture';
  4704. }
  4705. else if ($objecttype == 'order_supplier') {
  4706. $tplpath = 'fourn/commande';
  4707. }
  4708. else if ($objecttype == 'expensereport') {
  4709. $tplpath = 'expensereport';
  4710. }
  4711. global $linkedObjectBlock;
  4712. $linkedObjectBlock = $objects;
  4713. if (empty($numoutput))
  4714. {
  4715. $numoutput++;
  4716. echo '<br>';
  4717. print load_fiche_titre($langs->trans('RelatedObjects'), '', '');
  4718. print '<table class="noborder allwidth">';
  4719. print '<tr class="liste_titre">';
  4720. print '<td>'.$langs->trans("Type").'</td>';
  4721. print '<td>'.$langs->trans("Ref").'</td>';
  4722. print '<td align="center"></td>';
  4723. print '<td align="center">'.$langs->trans("Date").'</td>';
  4724. print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
  4725. print '<td align="right">'.$langs->trans("Status").'</td>';
  4726. print '<td></td>';
  4727. print '</tr>';
  4728. }
  4729. // Output template part (modules that overwrite templates must declare this into descriptor)
  4730. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
  4731. foreach($dirtpls as $reldir)
  4732. {
  4733. $res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  4734. if ($res) break;
  4735. }
  4736. }
  4737. if ($numoutput)
  4738. {
  4739. print '</table>';
  4740. }
  4741. return $num;
  4742. }
  4743. }
  4744. /**
  4745. * Show block with links to link to other objects.
  4746. *
  4747. * @param CommonObject $object Object we want to show links to
  4748. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order')
  4749. * @return string <0 if KO, >0 if OK
  4750. */
  4751. function showLinkToObjectBlock($object, $restrictlinksto=array())
  4752. {
  4753. global $conf, $langs, $hookmanager;
  4754. global $bc;
  4755. $linktoelem='';
  4756. if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
  4757. if (((! is_array($restrictlinksto)) || in_array('order',$restrictlinksto))
  4758. && ! empty($conf->commande->enabled))
  4759. {
  4760. $linktoelem.=($linktoelem?' &nbsp; ':'').'<a href="#linktoorder" id="linktoorder">' . $langs->trans('LinkedOrder') . '</a>';
  4761. print '
  4762. <script type="text/javascript" language="javascript">
  4763. jQuery(document).ready(function() {
  4764. jQuery("#linktoorder").click(function() {
  4765. jQuery("#orderlist").toggle();
  4766. jQuery("#linktoorder").toggle();
  4767. });
  4768. });
  4769. </script>
  4770. ';
  4771. print '<div id="orderlist"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
  4772. $sql = "SELECT s.rowid as socid, s.nom as name, s.client, c.rowid, c.ref, c.ref_client, c.total_ht";
  4773. $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s";
  4774. $sql .= ", " . MAIN_DB_PREFIX . "commande as c";
  4775. $sql .= ' WHERE c.fk_soc = s.rowid AND c.fk_soc = ' . $object->thirdparty->id . '';
  4776. $resqlorderlist = $this->db->query($sql);
  4777. if ($resqlorderlist)
  4778. {
  4779. $num = $this->db->num_rows($resqlorderlist);
  4780. $i = 0;
  4781. print '<br><form action="" method="POST" name="LinkedOrder">';
  4782. print '<table class="noborder">';
  4783. print '<tr class="liste_titre">';
  4784. print '<td class="nowrap"></td>';
  4785. print '<td align="center">' . $langs->trans("Ref") . '</td>';
  4786. print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
  4787. print '<td align="left">' . $langs->trans("AmountHTShort") . '</td>';
  4788. print '<td align="left">' . $langs->trans("Company") . '</td>';
  4789. print '</tr>';
  4790. while ($i < $num)
  4791. {
  4792. $objp = $this->db->fetch_object($resqlorderlist);
  4793. $var = ! $var;
  4794. print '<tr ' . $bc [$var] . '>';
  4795. print '<td aling="left">';
  4796. print '<input type="radio" name="linkedOrder" value=' . $objp->rowid . '>';
  4797. print '</td>';
  4798. print '<td align="center">' . $objp->ref . '</td>';
  4799. print '<td>' . $objp->ref_client . '</td>';
  4800. print '<td>' . price($objp->total_ht) . '</td>';
  4801. print '<td>' . $objp->name . '</td>';
  4802. print '</tr>';
  4803. $i ++;
  4804. }
  4805. print '</table>';
  4806. print '<div class="center"><input type="submit" class="button" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
  4807. print '</form>';
  4808. $this->db->free($resqlorderlist);
  4809. } else {
  4810. dol_print_error($this->db);
  4811. }
  4812. print '</div>';
  4813. }
  4814. if ((in_array('fichinter',$restrictlinksto)) && ! empty($conf->ficheinter->enabled))
  4815. {
  4816. $linktoelem.=($linktoelem?' &nbsp; ':'').'<a href="#" id="linktoorder">' . $langs->trans('LinkedFichinter') . '</a>';
  4817. print '
  4818. <script type="text/javascript" language="javascript">
  4819. jQuery(document).ready(function() {
  4820. jQuery("#linktoorder").click(function() {
  4821. jQuery("#orderlist").toggle();
  4822. jQuery("#linktoorder").toggle();
  4823. });
  4824. });
  4825. </script>
  4826. ';
  4827. print '<div id="orderlist"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
  4828. $sql = "SELECT s.rowid as socid, s.nom as name, s.client, f.rowid, f.ref";
  4829. $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s";
  4830. $sql .= ", " . MAIN_DB_PREFIX . "fichinter as f";
  4831. $sql .= ' WHERE f.fk_soc = s.rowid';
  4832. $resqlorderlist = $this->db->query($sql);
  4833. if ($resqlorderlist)
  4834. {
  4835. $num = $this->db->num_rows($resqlorderlist);
  4836. $i = 0;
  4837. print '<br><form action="" method="POST" name="LinkedFichinter">';
  4838. print '<table class="noborder">';
  4839. print '<tr class="liste_titre">';
  4840. print '<td class="nowrap"></td>';
  4841. print '<td align="center">' . $langs->trans("Ref") . '</td>';
  4842. print '<td align="left">' . $langs->trans("Company") . '</td>';
  4843. print '</tr>';
  4844. while ($i < $num)
  4845. {
  4846. $objp = $this->db->fetch_object($resqlorderlist);
  4847. $var = ! $var;
  4848. print '<tr ' . $bc [$var] . '>';
  4849. print '<td aling="left">';
  4850. print '<input type="radio" name="LinkedFichinter" value=' . $objp->rowid . '>';
  4851. print '<td align="center">' . $objp->ref . '</td>';
  4852. print '<td>' . $objp->name . '</td>';
  4853. print '</td>';
  4854. print '</tr>';
  4855. $i ++;
  4856. }
  4857. print '</table>';
  4858. print '<div class="center"><input type="submit" class="button" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
  4859. print '</form>';
  4860. $this->db->free($resqlorderlist);
  4861. } else {
  4862. dol_print_error($this->db);
  4863. }
  4864. print '</div>';
  4865. }
  4866. if (((! is_array($restrictlinksto)) || in_array('supplier_order',$restrictlinksto))
  4867. && ! empty($conf->fournisseur->enabled))
  4868. {
  4869. $linktoelem.=($linktoelem?' &nbsp; ':'').'<a href="#linktoorder" id="linktoorder">' . $langs->trans('LinkedOrder') . '</a>';
  4870. print '
  4871. <script type="text/javascript" language="javascript">
  4872. jQuery(document).ready(function() {
  4873. jQuery("#linktoorder").click(function() {
  4874. jQuery("#orderlist").toggle();
  4875. jQuery("#linktoorder").toggle();
  4876. });
  4877. });
  4878. </script>
  4879. ';
  4880. print '<div id="orderlist"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
  4881. $sql = "SELECT s.rowid as socid, s.nom as name, s.client, c.rowid, c.ref, c.ref_supplier, c.total_ht";
  4882. $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s";
  4883. $sql .= ", " . MAIN_DB_PREFIX . "commande_fournisseur as c";
  4884. $sql .= ' WHERE c.fk_soc = s.rowid AND c.fk_soc = ' . $object->thirdparty->id;
  4885. $resqlorderlist = $this->db->query($sql);
  4886. if ($resqlorderlist)
  4887. {
  4888. $num = $this->db->num_rows($resqlorderlist);
  4889. $i = 0;
  4890. print '<br><form action="" method="POST" name="LinkedOrder">';
  4891. print '<table class="noborder">';
  4892. print '<tr class="liste_titre">';
  4893. print '<td class="nowrap"></td>';
  4894. print '<td align="center">' . $langs->trans("Ref") . '</td>';
  4895. print '<td align="left">' . $langs->trans("RefSupplier") . '</td>';
  4896. print '<td align="left">' . $langs->trans("AmountHTShort") . '</td>';
  4897. print '<td align="left">' . $langs->trans("Company") . '</td>';
  4898. print '</tr>';
  4899. while ($i < $num)
  4900. {
  4901. $objp = $this->db->fetch_object($resqlorderlist);
  4902. $var = ! $var;
  4903. print '<tr ' . $bc [$var] . '>';
  4904. print '<td aling="left">';
  4905. print '<input type="radio" name="linkedOrder" value=' . $objp->rowid . '>';
  4906. print '</td>';
  4907. print '<td align="center">' . $objp->ref . '</td>';
  4908. print '<td>' . $objp->ref_supplier . '</td>';
  4909. print '<td>' . price($objp->total_ht) . '</td>';
  4910. print '<td>' . $objp->name . '</td>';
  4911. print '</tr>';
  4912. $i ++;
  4913. }
  4914. print '</table>';
  4915. print '<br><div class="center"><input type="submit" class="button" value="' . $langs->trans('ToLink') . '"> &nbsp; <input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
  4916. print '</form>';
  4917. $this->db->free($resqlorderlist);
  4918. } else {
  4919. dol_print_error($this->db);
  4920. }
  4921. print '</div>';
  4922. }
  4923. return $linktoelem;
  4924. }
  4925. /**
  4926. * Return an html string with a select combo box to choose yes or no
  4927. *
  4928. * @param string $htmlname Name of html select field
  4929. * @param string $value Pre-selected value
  4930. * @param int $option 0 return yes/no, 1 return 1/0
  4931. * @param bool $disabled true or false
  4932. * @param int $useempty 1=Add empty line
  4933. * @return string See option
  4934. */
  4935. function selectyesno($htmlname,$value='',$option=0,$disabled=false,$useempty='')
  4936. {
  4937. global $langs;
  4938. $yes="yes"; $no="no";
  4939. if ($option)
  4940. {
  4941. $yes="1";
  4942. $no="0";
  4943. }
  4944. $disabled = ($disabled ? ' disabled' : '');
  4945. $resultyesno = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  4946. if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'></option>'."\n";
  4947. if (("$value" == 'yes') || ($value == 1))
  4948. {
  4949. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  4950. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  4951. }
  4952. else
  4953. {
  4954. $selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
  4955. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  4956. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  4957. }
  4958. $resultyesno .= '</select>'."\n";
  4959. return $resultyesno;
  4960. }
  4961. /**
  4962. * Return list of export templates
  4963. *
  4964. * @param string $selected Id modele pre-selectionne
  4965. * @param string $htmlname Name of HTML select
  4966. * @param string $type Type of searched templates
  4967. * @param int $useempty Affiche valeur vide dans liste
  4968. * @return void
  4969. */
  4970. function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
  4971. {
  4972. $sql = "SELECT rowid, label";
  4973. $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
  4974. $sql.= " WHERE type = '".$type."'";
  4975. $sql.= " ORDER BY rowid";
  4976. $result = $this->db->query($sql);
  4977. if ($result)
  4978. {
  4979. print '<select class="flat" name="'.$htmlname.'">';
  4980. if ($useempty)
  4981. {
  4982. print '<option value="-1">&nbsp;</option>';
  4983. }
  4984. $num = $this->db->num_rows($result);
  4985. $i = 0;
  4986. while ($i < $num)
  4987. {
  4988. $obj = $this->db->fetch_object($result);
  4989. if ($selected == $obj->rowid)
  4990. {
  4991. print '<option value="'.$obj->rowid.'" selected>';
  4992. }
  4993. else
  4994. {
  4995. print '<option value="'.$obj->rowid.'">';
  4996. }
  4997. print $obj->label;
  4998. print '</option>';
  4999. $i++;
  5000. }
  5001. print "</select>";
  5002. }
  5003. else {
  5004. dol_print_error($this->db);
  5005. }
  5006. }
  5007. /**
  5008. * Return a HTML area with the reference of object and a navigation bar for a business object
  5009. * To add a particular filter on select, you must set $object->next_prev_filter to SQL criteria.
  5010. *
  5011. * @param object $object Object to show
  5012. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  5013. * @param string $morehtml More html content to output just before the nav bar
  5014. * @param int $shownav Show Condition (navigation is shown if value is 1)
  5015. * @param string $fieldid Nom du champ en base a utiliser pour select next et previous (we make the select max and min on this field)
  5016. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  5017. * @param string $morehtmlref More html to show after ref
  5018. * @param string $moreparam More param to add in nav link url.
  5019. * @param int $nodbprefix Do not include DB prefix to forge table name
  5020. * @param string $morehtmlleft More html code to show before ref
  5021. * @param string $morehtmlright More html code to show before navigation arrows
  5022. * @return string Portion HTML avec ref + boutons nav
  5023. */
  5024. function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlright='')
  5025. {
  5026. global $langs,$conf;
  5027. $ret='';
  5028. if (empty($fieldid)) $fieldid='rowid';
  5029. if (empty($fieldref)) $fieldref='ref';
  5030. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  5031. $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''),$fieldid,$nodbprefix);
  5032. //$previous_ref = $object->ref_previous?'<a data-role="button" data-icon="arrow-l" data-iconpos="left" href="'.$_SERVER["PHP_SELF"].'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'">'.(empty($conf->dol_use_jmobile)?img_picto($langs->trans("Previous"),'previous.png'):'&nbsp;').'</a>':'';
  5033. //$next_ref = $object->ref_next?'<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="'.$_SERVER["PHP_SELF"].'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'">'.(empty($conf->dol_use_jmobile)?img_picto($langs->trans("Next"),'next.png'):'&nbsp;').'</a>':'';
  5034. $previous_ref = $object->ref_previous?'<a data-role="button" data-icon="arrow-l" data-iconpos="left" href="'.$_SERVER["PHP_SELF"].'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'">'.(empty($conf->dol_use_jmobile)?'&lt;':'&nbsp;').'</a>':'<span class="inactive">'.(empty($conf->dol_use_jmobile)?'&lt;':'&nbsp;').'</span>';
  5035. $next_ref = $object->ref_next?'<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="'.$_SERVER["PHP_SELF"].'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'">'.(empty($conf->dol_use_jmobile)?'&gt;':'&nbsp;').'</a>':'<span class="inactive">'.(empty($conf->dol_use_jmobile)?'&gt;':'&nbsp;').'</span>';
  5036. //print "xx".$previous_ref."x".$next_ref;
  5037. $ret.='<div style="vertical-align: middle">';
  5038. $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  5039. $ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
  5040. // For thirdparty and contact, the ref is the id, so we show something else
  5041. if ($object->element == 'societe')
  5042. {
  5043. $ret.=dol_htmlentities($object->name);
  5044. }
  5045. else if (in_array($object->element, array('contact', 'user', 'member')))
  5046. {
  5047. $ret.=dol_htmlentities($object->getFullName($langs));
  5048. }
  5049. else $ret.=dol_htmlentities($object->$fieldref);
  5050. if ($morehtmlref)
  5051. {
  5052. $ret.=' '.$morehtmlref;
  5053. }
  5054. $ret.='</div>';
  5055. if ($previous_ref || $next_ref || $morehtml)
  5056. {
  5057. $ret.='<div class="pagination"><ul>';
  5058. }
  5059. if ($morehtml)
  5060. {
  5061. $ret.='<li class="noborder litext">'.$morehtml.'</li>';
  5062. }
  5063. if ($shownav && ($previous_ref || $next_ref))
  5064. {
  5065. $ret.='<li class="pagination">'.$previous_ref.'</li>';
  5066. $ret.='<li class="pagination">'.$next_ref.'</li>';
  5067. }
  5068. if ($previous_ref || $next_ref || $morehtml)
  5069. {
  5070. $ret.='</ul></div>';
  5071. }
  5072. if ($morehtmlright) $ret.='<div class="statusref">'.$morehtmlright.'</div>';
  5073. $ret.='</div>';
  5074. return $ret;
  5075. }
  5076. /**
  5077. * Return HTML code to output a barcode
  5078. *
  5079. * @param Object $object Object containing data to retrieve file name
  5080. * @param int $width Width of photo
  5081. * @return string HTML code to output barcode
  5082. */
  5083. function showbarcode(&$object,$width=100)
  5084. {
  5085. global $conf;
  5086. //Check if barcode is filled in the card
  5087. if (empty($object->barcode)) return '';
  5088. // Complete object if not complete
  5089. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
  5090. {
  5091. $result = $object->fetch_barcode();
  5092. //Check if fetch_barcode() failed
  5093. if ($result < 1) return '<!-- ErrorFetchBarcode -->';
  5094. }
  5095. // Barcode image
  5096. $url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  5097. $out ='<!-- url barcode = '.$url.' -->';
  5098. $out.='<img src="'.$url.'">';
  5099. return $out;
  5100. }
  5101. /**
  5102. * Return HTML code to output a photo
  5103. *
  5104. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  5105. * @param object $object Object containing data to retrieve file name
  5106. * @param int $width Width of photo
  5107. * @param int $height Height of photo (auto if 0)
  5108. * @param int $caneditfield Add edit fields
  5109. * @param string $cssclass CSS name to use on img for photo
  5110. * @param string $imagesize 'mini', 'small' or '' (original)
  5111. * @param int $addlinktofullsize Add link to fullsize image
  5112. * @param int $cache 1=Accept to use image in cache
  5113. * @return string HTML code to output photo
  5114. */
  5115. static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0)
  5116. {
  5117. global $conf,$langs;
  5118. $entity = (! empty($object->entity) ? $object->entity : $conf->entity);
  5119. $id = (! empty($object->id) ? $object->id : $object->rowid);
  5120. $ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';
  5121. if ($modulepart=='societe')
  5122. {
  5123. $dir=$conf->societe->multidir_output[$entity];
  5124. if (! empty($object->logo))
  5125. {
  5126. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  5127. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
  5128. else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  5129. $originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  5130. }
  5131. }
  5132. else if ($modulepart=='contact')
  5133. {
  5134. $dir=$conf->societe->multidir_output[$entity].'/contact';
  5135. if (! empty($object->photo))
  5136. {
  5137. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
  5138. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
  5139. else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  5140. $originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  5141. }
  5142. }
  5143. else if ($modulepart=='userphoto')
  5144. {
  5145. $dir=$conf->user->dir_output;
  5146. if (! empty($object->photo))
  5147. {
  5148. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_mini');
  5149. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_small');
  5150. else $file=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;
  5151. $originalfile=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;
  5152. }
  5153. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5154. $email=$object->email;
  5155. }
  5156. else if ($modulepart=='memberphoto')
  5157. {
  5158. $dir=$conf->adherent->dir_output;
  5159. if (! empty($object->photo))
  5160. {
  5161. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  5162. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  5163. else $file=get_exdir($id, 2, 0, 0, $object, 'member').'photos/'.$object->photo;
  5164. $originalfile=get_exdir($id, 2, 0, 0, $object, 'member').'photos/'.$object->photo;
  5165. }
  5166. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5167. $email=$object->email;
  5168. }
  5169. else
  5170. {
  5171. $dir=$conf->$modulepart->dir_output;
  5172. if (! empty($object->photo))
  5173. {
  5174. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  5175. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  5176. else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  5177. $originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  5178. }
  5179. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5180. $email=$object->email;
  5181. }
  5182. if ($dir)
  5183. {
  5184. if ($file && file_exists($dir."/".$file))
  5185. {
  5186. if ($addlinktofullsize) $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  5187. $ret.='<img alt="Photo" 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($file).'&cache='.$cache.'">';
  5188. if ($addlinktofullsize) $ret.='</a>';
  5189. }
  5190. else if ($altfile && file_exists($dir."/".$altfile))
  5191. {
  5192. if ($addlinktofullsize) $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  5193. $ret.='<img 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.'">';
  5194. if ($addlinktofullsize) $ret.='</a>';
  5195. }
  5196. else
  5197. {
  5198. $nophoto='/public/theme/common/nophoto.png';
  5199. if (in_array($modulepart,array('userphoto','contact'))) // For module that are "physical" users
  5200. {
  5201. $nophoto='/public/theme/common/user_anonymous.png';
  5202. if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
  5203. if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
  5204. }
  5205. if (! empty($conf->gravatar->enabled) && $email)
  5206. {
  5207. /**
  5208. * @see https://gravatar.com/site/implement/images/php/
  5209. */
  5210. global $dolibarr_main_url_root;
  5211. $ret.='<!-- Put link to gravatar -->';
  5212. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" border="0"'.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.urlencode(dol_buildpath($nophoto,2)).'">'; // gravatar need md5 hash
  5213. }
  5214. else
  5215. {
  5216. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
  5217. }
  5218. }
  5219. if ($caneditfield)
  5220. {
  5221. if ($object->photo) $ret.="<br>\n";
  5222. $ret.='<table class="nobordernopadding">';
  5223. if ($object->photo) $ret.='<tr><td align="center"><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  5224. $ret.='<tr><td>'.$langs->trans("PhotoFile").'</td></tr>';
  5225. $ret.='<tr><td><input type="file" class="flat" name="photo" id="photoinput"></td></tr>';
  5226. $ret.='</table>';
  5227. }
  5228. }
  5229. else dol_print_error('','Call of showphoto with wrong parameters');
  5230. return $ret;
  5231. }
  5232. /**
  5233. * Return select list of groups
  5234. *
  5235. * @param string $selected Id group preselected
  5236. * @param string $htmlname Field name in form
  5237. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  5238. * @param string $exclude Array list of groups id to exclude
  5239. * @param int $disabled If select list must be disabled
  5240. * @param string $include Array list of groups id to include
  5241. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  5242. * @param int $force_entity 0 or Id of environment to force
  5243. * @return string
  5244. * @see select_dolusers
  5245. */
  5246. function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0)
  5247. {
  5248. global $conf,$user,$langs;
  5249. // Permettre l'exclusion de groupes
  5250. if (is_array($exclude)) $excludeGroups = implode("','",$exclude);
  5251. // Permettre l'inclusion de groupes
  5252. if (is_array($include)) $includeGroups = implode("','",$include);
  5253. $out='';
  5254. // On recherche les groupes
  5255. $sql = "SELECT ug.rowid, ug.nom as name";
  5256. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  5257. {
  5258. $sql.= ", e.label";
  5259. }
  5260. $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  5261. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  5262. {
  5263. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  5264. if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
  5265. else $sql.= " WHERE ug.entity IS NOT NULL";
  5266. }
  5267. else
  5268. {
  5269. $sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
  5270. }
  5271. if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  5272. if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
  5273. $sql.= " ORDER BY ug.nom ASC";
  5274. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  5275. $resql=$this->db->query($sql);
  5276. if ($resql)
  5277. {
  5278. // Enhance with select2
  5279. if ($conf->use_javascript_ajax)
  5280. {
  5281. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5282. $comboenhancement = ajax_combobox($htmlname);
  5283. $out.= $comboenhancement;
  5284. $nodatarole=($comboenhancement?' data-role="none"':'');
  5285. }
  5286. $out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$nodatarole.'>';
  5287. $num = $this->db->num_rows($resql);
  5288. $i = 0;
  5289. if ($num)
  5290. {
  5291. if ($show_empty) $out.= '<option value="-1"'.($selected==-1?' selected':'').'>&nbsp;</option>'."\n";
  5292. while ($i < $num)
  5293. {
  5294. $obj = $this->db->fetch_object($resql);
  5295. $disableline=0;
  5296. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
  5297. $out.= '<option value="'.$obj->rowid.'"';
  5298. if ($disableline) $out.= ' disabled';
  5299. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  5300. {
  5301. $out.= ' selected';
  5302. }
  5303. $out.= '>';
  5304. $out.= $obj->name;
  5305. if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode) && $conf->entity == 1)
  5306. {
  5307. $out.= " (".$obj->label.")";
  5308. }
  5309. $out.= '</option>';
  5310. $i++;
  5311. }
  5312. }
  5313. else
  5314. {
  5315. if ($show_empty) $out.= '<option value="-1"'.($selected==-1?' selected':'').'></option>'."\n";
  5316. $out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  5317. }
  5318. $out.= '</select>';
  5319. }
  5320. else
  5321. {
  5322. dol_print_error($this->db);
  5323. }
  5324. return $out;
  5325. }
  5326. /**
  5327. * Return HTML to show the search and clear seach button
  5328. *
  5329. * @param int $addcheckuncheckall Add the check all uncheck all button
  5330. * @param string $cssclass CSS class
  5331. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  5332. * @return string
  5333. */
  5334. function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
  5335. {
  5336. global $conf, $langs;
  5337. $out='';
  5338. $out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
  5339. $out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
  5340. if ($addcheckuncheckall)
  5341. {
  5342. if (! empty($conf->use_javascript_ajax)) $out.='<input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions">';
  5343. }
  5344. $out.='<script type="text/javascript">
  5345. $(document).ready(function() {
  5346. $("#checkallactions").click(function() {
  5347. if($(this).is(\':checked\')){
  5348. console.log("We check all");
  5349. $(".'.$cssclass.'").prop(\'checked\', true);
  5350. }
  5351. else
  5352. {
  5353. console.log("We uncheck all");
  5354. $(".'.$cssclass.'").prop(\'checked\', false);
  5355. }'."\n";
  5356. if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(); } else { console.log("No function initCheckForSelect found. Call won\'t done."); }';
  5357. $out.=' });
  5358. });
  5359. </script>';
  5360. return $out;
  5361. }
  5362. }