html.form.class.php 278 KB

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