html.form.class.php 385 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
  10. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  11. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  12. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  13. * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  16. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  17. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  18. * Copyright (C) 2014-2020 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018-2021 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  21. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  22. * Copyright (C) 2018 Christophe Battarel <christophe@altairis.fr>
  23. * Copyright (C) 2018 Josep Lluis Amador <joseplluis@lliuretic.cat>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. */
  38. /**
  39. * \file htdocs/core/class/html.form.class.php
  40. * \ingroup core
  41. * \brief File of class with all html predefined components
  42. */
  43. /**
  44. * Class to manage generation of HTML components
  45. * Only common components must be here.
  46. *
  47. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  48. */
  49. class Form
  50. {
  51. /**
  52. * @var DoliDB Database handler.
  53. */
  54. public $db;
  55. /**
  56. * @var string Error code (or message)
  57. */
  58. public $error = '';
  59. /**
  60. * @var string[] Array of error strings
  61. */
  62. public $errors = array();
  63. public $num;
  64. // Cache arrays
  65. public $cache_types_paiements = array();
  66. public $cache_conditions_paiements = array();
  67. public $cache_transport_mode = array();
  68. public $cache_availability = array();
  69. public $cache_demand_reason = array();
  70. public $cache_types_fees = array();
  71. public $cache_vatrates = array();
  72. /**
  73. * Constructor
  74. *
  75. * @param DoliDB $db Database handler
  76. */
  77. public function __construct($db)
  78. {
  79. $this->db = $db;
  80. }
  81. /**
  82. * Output key field for an editable field
  83. *
  84. * @param string $text Text of label or key to translate
  85. * @param string $htmlname Name of select field ('edit' prefix will be added)
  86. * @param string $preselected Value to show/edit (not used in this function)
  87. * @param object $object Object
  88. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  89. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  90. * @param string $moreparam More param to add on a href URL.
  91. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  92. * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
  93. * @param string $paramid Key of parameter for id ('id', 'socid')
  94. * @param string $help Tooltip help
  95. * @return string HTML edit field
  96. */
  97. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  98. {
  99. global $conf, $langs;
  100. $ret = '';
  101. // TODO change for compatibility
  102. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  103. if (!empty($perm)) {
  104. $tmp = explode(':', $typeofdata);
  105. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  106. if ($fieldrequired) {
  107. $ret .= '<span class="fieldrequired">';
  108. }
  109. if ($help) {
  110. $ret .= $this->textwithpicto($langs->trans($text), $help);
  111. } else {
  112. $ret .= $langs->trans($text);
  113. }
  114. if ($fieldrequired) {
  115. $ret .= '</span>';
  116. }
  117. $ret .= '</div>'."\n";
  118. } else {
  119. if ($fieldrequired) {
  120. $ret .= '<span class="fieldrequired">';
  121. }
  122. if ($help) {
  123. $ret .= $this->textwithpicto($langs->trans($text), $help);
  124. } else {
  125. $ret .= $langs->trans($text);
  126. }
  127. if ($fieldrequired) {
  128. $ret .= '</span>';
  129. }
  130. }
  131. } else {
  132. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  133. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  134. }
  135. if ($fieldrequired) {
  136. $ret .= '<span class="fieldrequired">';
  137. }
  138. if ($help) {
  139. $ret .= $this->textwithpicto($langs->trans($text), $help);
  140. } else {
  141. $ret .= $langs->trans($text);
  142. }
  143. if ($fieldrequired) {
  144. $ret .= '</span>';
  145. }
  146. if (!empty($notabletag)) {
  147. $ret .= ' ';
  148. }
  149. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  150. $ret .= '</td>';
  151. }
  152. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  153. $ret .= '<td class="right">';
  154. }
  155. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  156. $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&token='.newToken().'&'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  157. }
  158. if (!empty($notabletag) && $notabletag == 1) {
  159. $ret .= ' : ';
  160. }
  161. if (!empty($notabletag) && $notabletag == 3) {
  162. $ret .= ' ';
  163. }
  164. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  165. $ret .= '</td>';
  166. }
  167. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) {
  168. $ret .= '</tr></table>';
  169. }
  170. }
  171. return $ret;
  172. }
  173. /**
  174. * Output value of a field for an editable field
  175. *
  176. * @param string $text Text of label (not used in this function)
  177. * @param string $htmlname Name of select field
  178. * @param string $value Value to show/edit
  179. * @param object $object Object
  180. * @param boolean $perm Permission to allow button to edit parameter
  181. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  182. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value
  183. * @param object $extObject External object
  184. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  185. * @param string $moreparam More param to add on the form action href URL
  186. * @param int $notabletag Do no output table tags
  187. * @param string $formatfunc Call a specific function to output field
  188. * @param string $paramid Key of parameter for id ('id', 'socid')
  189. * @return string HTML edit field
  190. */
  191. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id')
  192. {
  193. global $conf, $langs, $db;
  194. $ret = '';
  195. // Check parameters
  196. if (empty($typeofdata)) {
  197. return 'ErrorBadParameter';
  198. }
  199. // When option to edit inline is activated
  200. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  201. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  202. } else {
  203. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  204. if ($editmode) {
  205. $ret .= "\n";
  206. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  207. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  208. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  209. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  210. if (empty($notabletag)) {
  211. $ret .= '<table class="nobordernopadding centpercent">';
  212. }
  213. if (empty($notabletag)) {
  214. $ret .= '<tr><td>';
  215. }
  216. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  217. $tmp = explode(':', $typeofdata);
  218. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  219. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  220. $tmp = explode(':', $typeofdata);
  221. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  222. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ?price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  223. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  224. $tmp = explode(':', $typeofdata);
  225. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  226. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  227. $tmp = explode(':', $typeofdata);
  228. $cols = $tmp[2];
  229. $morealt = '';
  230. if (preg_match('/%/', $cols)) {
  231. $morealt = ' style="width: '.$cols.'"';
  232. $cols = '';
  233. }
  234. $valuetoshow = ($editvalue ? $editvalue : $value);
  235. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  236. // textarea convert automatically entities chars into simple chars.
  237. // So we convert & into &amp; so a string like 'a &lt; <b>b</b><br>é<br>&lt;script&gt;alert('X');&lt;script&gt;' stay a correct html and is not converted by textarea component when wysiwig is off.
  238. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  239. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  240. $ret .= '</textarea>';
  241. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  242. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0);
  243. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  244. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0);
  245. } elseif (preg_match('/^select;/', $typeofdata)) {
  246. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  247. $arraylist = array();
  248. foreach ($arraydata as $val) {
  249. $tmp = explode(':', $val);
  250. $tmpkey = str_replace('|', ':', $tmp[0]);
  251. $arraylist[$tmpkey] = $tmp[1];
  252. }
  253. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  254. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  255. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  256. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  257. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), ($tmp[2] ? $tmp[2] : ''), ($tmp[3] ? $tmp[3] : '100'), ($tmp[1] ? $tmp[1] : 'dolibarr_notes'), 'In', ($tmp[5] ? $tmp[5] : 0), (isset($tmp[8]) ? ($tmp[8] ?true:false) : true), true, ($tmp[6] ? $tmp[6] : '20'), ($tmp[7] ? $tmp[7] : '100'));
  258. $ret .= $doleditor->Create(1);
  259. }
  260. if (empty($notabletag)) {
  261. $ret .= '</td>';
  262. }
  263. if (empty($notabletag)) {
  264. $ret .= '<td class="left">';
  265. }
  266. //else $ret.='<div class="clearboth"></div>';
  267. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  268. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  269. $ret .= '<br>'."\n";
  270. }
  271. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  272. if (empty($notabletag)) {
  273. $ret .= '</td>';
  274. }
  275. if (empty($notabletag)) {
  276. $ret .= '</tr></table>'."\n";
  277. }
  278. $ret .= '</form>'."\n";
  279. } else {
  280. if (preg_match('/^(email)/', $typeofdata)) {
  281. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  282. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  283. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  284. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  285. $tmp = explode(':', $typeofdata);
  286. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  287. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  288. $ret .= dol_htmlentitiesbr($value);
  289. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  290. $ret .= dol_string_onlythesehtmltags($value);
  291. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  292. $ret .= dol_string_onlythesehtmltags($value);
  293. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  294. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day').'</span>';
  295. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  296. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour').'</span>';
  297. } elseif (preg_match('/^select;/', $typeofdata)) {
  298. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  299. $arraylist = array();
  300. foreach ($arraydata as $val) {
  301. $tmp = explode(':', $val);
  302. $arraylist[$tmp[0]] = $tmp[1];
  303. }
  304. $ret .= $arraylist[$value];
  305. if ($htmlname == 'fk_product_type') {
  306. if ($value == 0) {
  307. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  308. } else {
  309. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  310. }
  311. }
  312. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  313. $tmpcontent = dol_htmlentitiesbr($value);
  314. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  315. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  316. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  317. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  318. }
  319. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  320. // clean data from some dangerous html
  321. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  322. } else {
  323. $ret .= dol_escape_htmltag($value);
  324. }
  325. if ($formatfunc && method_exists($object, $formatfunc)) {
  326. $ret = $object->$formatfunc($ret);
  327. }
  328. }
  329. }
  330. return $ret;
  331. }
  332. /**
  333. * Output edit in place form
  334. *
  335. * @param string $fieldname Name of the field
  336. * @param object $object Object
  337. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  338. * @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]'...)
  339. * @param string $check Same coe than $check parameter of GETPOST()
  340. * @param string $morecss More CSS
  341. * @return string HTML code for the edit of alternative language
  342. */
  343. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  344. {
  345. global $conf, $langs, $extralanguages;
  346. $result = '';
  347. // List of extra languages
  348. $arrayoflangcode = array();
  349. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  350. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  351. }
  352. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  353. if (!is_object($extralanguages)) {
  354. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  355. $extralanguages = new ExtraLanguages($this->db);
  356. }
  357. $extralanguages->fetch_name_extralanguages('societe');
  358. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  359. return ''; // No extralang field to show
  360. }
  361. $result .= '<!-- Widget for translation -->'."\n";
  362. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  363. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  364. $result .= $s;
  365. $result .= '</div>';
  366. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  367. $resultforextrlang = '';
  368. foreach ($arrayoflangcode as $langcode) {
  369. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  370. if (empty($valuetoshow)) {
  371. $object->fetchValuesForExtraLanguages();
  372. //var_dump($object->array_languages);
  373. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  374. }
  375. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  376. $resultforextrlang .= $s;
  377. // TODO Use the showInputField() method of ExtraLanguages object
  378. if ($typeofdata == 'textarea') {
  379. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  380. $resultforextrlang .= $valuetoshow;
  381. $resultforextrlang .= '</textarea>';
  382. } else {
  383. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  384. }
  385. }
  386. $result .= $resultforextrlang;
  387. $result .= '</div>';
  388. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  389. }
  390. return $result;
  391. }
  392. /**
  393. * Output edit in place form
  394. *
  395. * @param object $object Object
  396. * @param string $value Value to show/edit
  397. * @param string $htmlname DIV ID (field name)
  398. * @param int $condition Condition to edit
  399. * @param string $inputType Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:loadmethod:savemethod:buttononly')
  400. * @param string $editvalue When in edit mode, use this value as $value instead of value
  401. * @param object $extObject External object
  402. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  403. * @return string HTML edit in place
  404. */
  405. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  406. {
  407. global $conf;
  408. $out = '';
  409. // Check parameters
  410. if (preg_match('/^text/', $inputType)) {
  411. $value = dol_nl2br($value);
  412. } elseif (preg_match('/^numeric/', $inputType)) {
  413. $value = price($value);
  414. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  415. $value = dol_print_date($value, 'day');
  416. }
  417. if ($condition) {
  418. $element = false;
  419. $table_element = false;
  420. $fk_element = false;
  421. $loadmethod = false;
  422. $savemethod = false;
  423. $ext_element = false;
  424. $button_only = false;
  425. $inputOption = '';
  426. if (is_object($object)) {
  427. $element = $object->element;
  428. $table_element = $object->table_element;
  429. $fk_element = $object->id;
  430. }
  431. if (is_object($extObject)) {
  432. $ext_element = $extObject->element;
  433. }
  434. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  435. $tmp = explode(':', $inputType);
  436. $inputType = $tmp[0];
  437. if (!empty($tmp[1])) {
  438. $inputOption = $tmp[1];
  439. }
  440. if (!empty($tmp[2])) {
  441. $savemethod = $tmp[2];
  442. }
  443. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  444. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  445. $tmp = explode(':', $inputType);
  446. $inputType = $tmp[0];
  447. if (!empty($tmp[1])) {
  448. $inputOption = $tmp[1];
  449. }
  450. if (!empty($tmp[2])) {
  451. $savemethod = $tmp[2];
  452. }
  453. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  454. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  455. $tmp = explode(':', $inputType);
  456. $inputType = $tmp[0];
  457. $loadmethod = $tmp[1];
  458. if (!empty($tmp[2])) {
  459. $savemethod = $tmp[2];
  460. }
  461. if (!empty($tmp[3])) {
  462. $button_only = true;
  463. }
  464. } elseif (preg_match('/^textarea/', $inputType)) {
  465. $tmp = explode(':', $inputType);
  466. $inputType = $tmp[0];
  467. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  468. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  469. } elseif (preg_match('/^ckeditor/', $inputType)) {
  470. $tmp = explode(':', $inputType);
  471. $inputType = $tmp[0];
  472. $toolbar = $tmp[1];
  473. if (!empty($tmp[2])) {
  474. $width = $tmp[2];
  475. }
  476. if (!empty($tmp[3])) {
  477. $heigth = $tmp[3];
  478. }
  479. if (!empty($tmp[4])) {
  480. $savemethod = $tmp[4];
  481. }
  482. if (!empty($conf->fckeditor->enabled)) {
  483. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  484. } else {
  485. $inputType = 'textarea';
  486. }
  487. }
  488. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  489. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  490. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  491. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  492. if (!empty($savemethod)) {
  493. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  494. }
  495. if (!empty($ext_element)) {
  496. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  497. }
  498. if (!empty($custommsg)) {
  499. if (is_array($custommsg)) {
  500. if (!empty($custommsg['success'])) {
  501. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  502. }
  503. if (!empty($custommsg['error'])) {
  504. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  505. }
  506. } else {
  507. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  508. }
  509. }
  510. if ($inputType == 'textarea') {
  511. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  512. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  513. }
  514. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  515. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  516. } else {
  517. $out = $value;
  518. }
  519. return $out;
  520. }
  521. /**
  522. * Show a text and picto with tooltip on text or picto.
  523. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  524. *
  525. * @param string $text Text to show
  526. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  527. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  528. * @param int $direction -1=image is before, 0=no image, 1=image is after
  529. * @param string $img Html code for image (use img_xxx() function to get it)
  530. * @param string $extracss Add a CSS style to td tags
  531. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  532. * @param string $incbefore Include code before the text
  533. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  534. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  535. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  536. * @return string Code html du tooltip (texte+picto)
  537. * @see textwithpicto() Use thisfunction if you can.
  538. */
  539. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  540. {
  541. if ($incbefore) {
  542. $text = $incbefore.$text;
  543. }
  544. if (!$htmltext) {
  545. return $text;
  546. }
  547. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  548. $tag = 'td';
  549. if ($notabs == 2) {
  550. $tag = 'div';
  551. }
  552. if ($notabs == 3) {
  553. $tag = 'span';
  554. }
  555. // Sanitize tooltip
  556. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  557. $extrastyle = '';
  558. if ($direction < 0) {
  559. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  560. $extrastyle = 'padding: 0px; padding-left: 3px !important;';
  561. }
  562. if ($direction > 0) {
  563. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  564. $extrastyle = 'padding: 0px; padding-right: 3px !important;';
  565. }
  566. $classfortooltip = 'classfortooltip';
  567. $s = '';
  568. $textfordialog = '';
  569. if ($tooltiptrigger == '') {
  570. $htmltext = str_replace('"', '&quot;', $htmltext);
  571. } else {
  572. $classfortooltip = 'classfortooltiponclick';
  573. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  574. }
  575. if ($tooltipon == 2 || $tooltipon == 3) {
  576. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  577. if ($tooltiptrigger == '') {
  578. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  579. } else {
  580. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  581. }
  582. } else {
  583. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  584. }
  585. if ($tooltipon == 1 || $tooltipon == 3) {
  586. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  587. if ($tooltiptrigger == '') {
  588. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  589. } else {
  590. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  591. }
  592. } else {
  593. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  594. }
  595. if (empty($notabs)) {
  596. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  597. } elseif ($notabs == 2) {
  598. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  599. }
  600. // Define value if value is before
  601. if ($direction < 0) {
  602. $s .= '<'.$tag.$paramfortooltipimg;
  603. if ($tag == 'td') {
  604. $s .= ' class=valigntop" width="14"';
  605. }
  606. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  607. }
  608. // Use another method to help avoid having a space in value in order to use this value with jquery
  609. // Define label
  610. if ((string) $text != '') {
  611. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  612. }
  613. // Define value if value is after
  614. if ($direction > 0) {
  615. $s .= '<'.$tag.$paramfortooltipimg;
  616. if ($tag == 'td') {
  617. $s .= ' class="valignmiddle" width="14"';
  618. }
  619. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  620. }
  621. if (empty($notabs)) {
  622. $s .= '</tr></table>';
  623. } elseif ($notabs == 2) {
  624. $s .= '</div>';
  625. }
  626. return $s;
  627. }
  628. /**
  629. * Show a text with a picto and a tooltip on picto
  630. *
  631. * @param string $text Text to show
  632. * @param string $htmltext Content of tooltip
  633. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  634. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  635. * @param string $extracss Add a CSS style to td, div or span tag
  636. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  637. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  638. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key, clickable link is on image or on link if param $type='none' or on both if $type='xxxclickable')
  639. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  640. * @return string HTML code of text, picto, tooltip
  641. */
  642. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  643. {
  644. global $conf, $langs;
  645. $alt = '';
  646. if ($tooltiptrigger) {
  647. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  648. }
  649. //For backwards compatibility
  650. if ($type == '0') {
  651. $type = 'info';
  652. } elseif ($type == '1') {
  653. $type = 'help';
  654. }
  655. // If info or help with no javascript, show only text
  656. if (empty($conf->use_javascript_ajax)) {
  657. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  658. return $text;
  659. } else {
  660. $alt = $htmltext;
  661. $htmltext = '';
  662. }
  663. }
  664. // If info or help with smartphone, show only text (tooltip hover can't works)
  665. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  666. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  667. return $text;
  668. }
  669. }
  670. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  671. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  672. //{
  673. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  674. //}
  675. $img = '';
  676. if ($type == 'info') {
  677. $img = img_help(0, $alt);
  678. } elseif ($type == 'help') {
  679. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  680. } elseif ($type == 'helpclickable') {
  681. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  682. } elseif ($type == 'superadmin') {
  683. $img = img_picto($alt, 'redstar');
  684. } elseif ($type == 'admin') {
  685. $img = img_picto($alt, 'star');
  686. } elseif ($type == 'warning') {
  687. $img = img_warning($alt);
  688. } elseif ($type != 'none') {
  689. $img = img_picto($alt, $type); // $type can be an image path
  690. }
  691. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  692. }
  693. /**
  694. * Generate select HTML to choose massaction
  695. *
  696. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  697. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  698. * @param int $alwaysvisible 1=select button always visible
  699. * @param string $name Name for massaction
  700. * @param string $cssclass CSS class used to check for select
  701. * @return string|void Select list
  702. */
  703. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  704. {
  705. global $conf, $langs, $hookmanager;
  706. $disabled = 0;
  707. $ret = '<div class="centpercent center">';
  708. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  709. // 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.
  710. $parameters = array();
  711. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  712. // check if there is a mass action
  713. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  714. return;
  715. }
  716. if (empty($reshook)) {
  717. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  718. foreach ($arrayofaction as $code => $label) {
  719. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  720. }
  721. }
  722. $ret .= $hookmanager->resPrint;
  723. $ret .= '</select>';
  724. if (empty($conf->dol_optimize_smallscreen)) {
  725. $ret .= ajax_combobox('.'.$name.'select');
  726. }
  727. // 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
  728. $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.
  729. $ret .= '<input type="submit" disabled name="confirmmassaction"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display: none"').' class="button small'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  730. $ret .= '</div>';
  731. if (!empty($conf->use_javascript_ajax)) {
  732. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  733. <script>
  734. function initCheckForSelect(mode, name, cssclass) /* mode is 0 during init of page or click all, 1 when we click on 1 checkboxi, "name" refers to the class of the massaction button, "cssclass" to the class of the checkfor select boxes */
  735. {
  736. atleastoneselected=0;
  737. jQuery("."+cssclass).each(function( index ) {
  738. /* console.log( index + ": " + $( this ).text() ); */
  739. if ($(this).is(\':checked\')) atleastoneselected++;
  740. });
  741. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  742. if (atleastoneselected || '.$alwaysvisible.')
  743. {
  744. jQuery("."+name).show();
  745. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  746. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  747. }
  748. else
  749. {
  750. jQuery("."+name).hide();
  751. jQuery("."+name+"other").hide();
  752. }
  753. }
  754. jQuery(document).ready(function () {
  755. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  756. jQuery(".' . $cssclass.'").click(function() {
  757. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  758. });
  759. jQuery(".' . $name.'select").change(function() {
  760. var massaction = $( this ).val();
  761. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  762. if (massaction == "builddoc")
  763. {
  764. urlform = urlform + "#show_files";
  765. }
  766. $( this ).closest("form").attr("action", urlform);
  767. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  768. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  769. if ($(this).val() != \'0\')
  770. {
  771. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  772. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  773. jQuery(".' . $name.'"+massaction).show();
  774. }
  775. else
  776. {
  777. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  778. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  779. }
  780. });
  781. });
  782. </script>
  783. ';
  784. }
  785. return $ret;
  786. }
  787. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  788. /**
  789. * Return combo list of activated countries, into language of user
  790. *
  791. * @param string $selected Id or Code or Label of preselected country
  792. * @param string $htmlname Name of html select object
  793. * @param string $htmloption More html options on select object
  794. * @param integer $maxlength Max length for labels (0=no limit)
  795. * @param string $morecss More css class
  796. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  797. * @param int $showempty Show empty choice
  798. * @param int $disablefavorites 1=Disable favorites,
  799. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  800. * @param array $exclude_country_code Array of country code (iso2) to exclude
  801. * @param int $hideflags Hide flags
  802. * @return string HTML string with select
  803. */
  804. public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array(), $hideflags = 0)
  805. {
  806. // phpcs:enable
  807. global $conf, $langs, $mysoc;
  808. $langs->load("dict");
  809. $out = '';
  810. $countryArray = array();
  811. $favorite = array();
  812. $label = array();
  813. $atleastonefavorite = 0;
  814. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  815. $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
  816. $sql .= " WHERE active > 0";
  817. //$sql.= " ORDER BY code ASC";
  818. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  819. $resql = $this->db->query($sql);
  820. if ($resql) {
  821. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  822. $num = $this->db->num_rows($resql);
  823. $i = 0;
  824. if ($num) {
  825. while ($i < $num) {
  826. $obj = $this->db->fetch_object($resql);
  827. $countryArray[$i]['rowid'] = $obj->rowid;
  828. $countryArray[$i]['code_iso'] = $obj->code_iso;
  829. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  830. $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 : ''));
  831. $countryArray[$i]['favorite'] = $obj->favorite;
  832. $countryArray[$i]['eec'] = $obj->eec;
  833. $favorite[$i] = $obj->favorite;
  834. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  835. $i++;
  836. }
  837. if (empty($disablefavorites)) {
  838. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  839. } else {
  840. $countryArray = dol_sort_array($countryArray, 'label');
  841. }
  842. if ($showempty) {
  843. $out .= '<option value="">&nbsp;</option>'."\n";
  844. }
  845. if ($addspecialentries) { // Add dedicated entries for groups of countries
  846. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  847. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  848. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  849. if ($mysoc->isInEEC()) {
  850. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  851. }
  852. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  853. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  854. }
  855. foreach ($countryArray as $row) {
  856. //if (empty($showempty) && empty($row['rowid'])) continue;
  857. if (empty($row['rowid'])) {
  858. continue;
  859. }
  860. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  861. continue; // exclude some countries
  862. }
  863. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  864. $atleastonefavorite++;
  865. }
  866. if (empty($row['favorite']) && $atleastonefavorite) {
  867. $atleastonefavorite = 0;
  868. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  869. }
  870. $labeltoshow = '';
  871. if ($row['label']) {
  872. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  873. } else {
  874. $labeltoshow .= '&nbsp;';
  875. }
  876. if ($row['code_iso']) {
  877. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  878. if (empty($hideflags)) {
  879. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  880. $labeltoshow = $tmpflag.' '.$labeltoshow;
  881. }
  882. }
  883. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  884. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
  885. } else {
  886. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" data-html="'.dol_escape_htmltag($labeltoshow).'" data-eec="'.((int) $row['eec']).'">';
  887. }
  888. $out .= $labeltoshow;
  889. $out .= '</option>'."\n";
  890. }
  891. }
  892. $out .= '</select>';
  893. } else {
  894. dol_print_error($this->db);
  895. }
  896. // Make select dynamic
  897. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  898. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  899. return $out;
  900. }
  901. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  902. /**
  903. * Return select list of incoterms
  904. *
  905. * @param string $selected Id or Code of preselected incoterm
  906. * @param string $location_incoterms Value of input location
  907. * @param string $page Defined the form action
  908. * @param string $htmlname Name of html select object
  909. * @param string $htmloption Options html on select object
  910. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  911. * @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')))
  912. * @return string HTML string with select and input
  913. */
  914. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  915. {
  916. // phpcs:enable
  917. global $conf, $langs;
  918. $langs->load("dict");
  919. $out = '';
  920. $incotermArray = array();
  921. $sql = "SELECT rowid, code";
  922. $sql .= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  923. $sql .= " WHERE active > 0";
  924. $sql .= " ORDER BY code ASC";
  925. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  926. $resql = $this->db->query($sql);
  927. if ($resql) {
  928. if ($conf->use_javascript_ajax && !$forcecombo) {
  929. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  930. $out .= ajax_combobox($htmlname, $events);
  931. }
  932. if (!empty($page)) {
  933. $out .= '<form method="post" action="'.$page.'">';
  934. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  935. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  936. }
  937. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  938. $out .= '<option value="0">&nbsp;</option>';
  939. $num = $this->db->num_rows($resql);
  940. $i = 0;
  941. if ($num) {
  942. $foundselected = false;
  943. while ($i < $num) {
  944. $obj = $this->db->fetch_object($resql);
  945. $incotermArray[$i]['rowid'] = $obj->rowid;
  946. $incotermArray[$i]['code'] = $obj->code;
  947. $i++;
  948. }
  949. foreach ($incotermArray as $row) {
  950. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  951. $out .= '<option value="'.$row['rowid'].'" selected>';
  952. } else {
  953. $out .= '<option value="'.$row['rowid'].'">';
  954. }
  955. if ($row['code']) {
  956. $out .= $row['code'];
  957. }
  958. $out .= '</option>';
  959. }
  960. }
  961. $out .= '</select>';
  962. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  963. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  964. $moreattrib .= ' autocomplete="off"';
  965. }
  966. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  967. if (!empty($page)) {
  968. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  969. }
  970. } else {
  971. dol_print_error($this->db);
  972. }
  973. return $out;
  974. }
  975. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  976. /**
  977. * Return list of types of lines (product or service)
  978. * Example: 0=product, 1=service, 9=other (for external module)
  979. *
  980. * @param string $selected Preselected type
  981. * @param string $htmlname Name of field in html form
  982. * @param int $showempty Add an empty field
  983. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  984. * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
  985. * @return void
  986. */
  987. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  988. {
  989. // phpcs:enable
  990. global $db, $langs, $user, $conf;
  991. // If product & services are enabled or both disabled.
  992. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  993. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
  994. if (empty($hidetext)) {
  995. print $langs->trans("Type").': ';
  996. }
  997. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  998. if ($showempty) {
  999. print '<option value="-1"';
  1000. if ($selected == -1) {
  1001. print ' selected';
  1002. }
  1003. print '>&nbsp;</option>';
  1004. }
  1005. print '<option value="0"';
  1006. if (0 == $selected) {
  1007. print ' selected';
  1008. }
  1009. print '>'.$langs->trans("Product");
  1010. print '<option value="1"';
  1011. if (1 == $selected) {
  1012. print ' selected';
  1013. }
  1014. print '>'.$langs->trans("Service");
  1015. print '</select>';
  1016. print ajax_combobox('select_'.$htmlname);
  1017. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1018. }
  1019. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
  1020. print $langs->trans("Service");
  1021. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1022. }
  1023. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
  1024. print $langs->trans("Product");
  1025. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1026. }
  1027. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1028. 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
  1029. }
  1030. }
  1031. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1032. /**
  1033. * Load into cache cache_types_fees, array of types of fees
  1034. *
  1035. * @return int Nb of lines loaded, <0 if KO
  1036. */
  1037. public function load_cache_types_fees()
  1038. {
  1039. // phpcs:enable
  1040. global $langs;
  1041. $num = count($this->cache_types_fees);
  1042. if ($num > 0) {
  1043. return 0; // Cache already loaded
  1044. }
  1045. dol_syslog(__METHOD__, LOG_DEBUG);
  1046. $langs->load("trips");
  1047. $sql = "SELECT c.code, c.label";
  1048. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  1049. $sql .= " WHERE active > 0";
  1050. $resql = $this->db->query($sql);
  1051. if ($resql) {
  1052. $num = $this->db->num_rows($resql);
  1053. $i = 0;
  1054. while ($i < $num) {
  1055. $obj = $this->db->fetch_object($resql);
  1056. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1057. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1058. $this->cache_types_fees[$obj->code] = $label;
  1059. $i++;
  1060. }
  1061. asort($this->cache_types_fees);
  1062. return $num;
  1063. } else {
  1064. dol_print_error($this->db);
  1065. return -1;
  1066. }
  1067. }
  1068. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1069. /**
  1070. * Return list of types of notes
  1071. *
  1072. * @param string $selected Preselected type
  1073. * @param string $htmlname Name of field in form
  1074. * @param int $showempty Add an empty field
  1075. * @return void
  1076. */
  1077. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1078. {
  1079. // phpcs:enable
  1080. global $user, $langs;
  1081. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1082. $this->load_cache_types_fees();
  1083. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1084. if ($showempty) {
  1085. print '<option value="-1"';
  1086. if ($selected == -1) {
  1087. print ' selected';
  1088. }
  1089. print '>&nbsp;</option>';
  1090. }
  1091. foreach ($this->cache_types_fees as $key => $value) {
  1092. print '<option value="'.$key.'"';
  1093. if ($key == $selected) {
  1094. print ' selected';
  1095. }
  1096. print '>';
  1097. print $value;
  1098. print '</option>';
  1099. }
  1100. print '</select>';
  1101. if ($user->admin) {
  1102. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1103. }
  1104. }
  1105. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1106. /**
  1107. * Output html form to select a third party
  1108. *
  1109. * @param string $selected Preselected type
  1110. * @param string $htmlname Name of field in form
  1111. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>] are allowed here (example: 's.rowid <> x', 's.client IN (1,3)')
  1112. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1113. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1114. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1115. * @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')))
  1116. * @param int $limit Maximum number of elements
  1117. * @param string $morecss Add more css styles to the SELECT component
  1118. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1119. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1120. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1121. * @param array $ajaxoptions Options for ajax_autocompleter
  1122. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1123. * @param array $excludeids Exclude IDs from the select combo
  1124. * @return string HTML string with select box for thirdparty.
  1125. */
  1126. public function select_company($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $limit = 0, $morecss = 'minwidth100', $moreparam = '', $selected_input_value = '', $hidelabel = 1, $ajaxoptions = array(), $multiple = false, $excludeids = array())
  1127. {
  1128. // phpcs:enable
  1129. global $conf, $user, $langs;
  1130. $out = '';
  1131. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1132. if (is_null($ajaxoptions)) {
  1133. $ajaxoptions = array();
  1134. }
  1135. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1136. // No immediate load of all database
  1137. $placeholder = '';
  1138. if ($selected && empty($selected_input_value)) {
  1139. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1140. $societetmp = new Societe($this->db);
  1141. $societetmp->fetch($selected);
  1142. $selected_input_value = $societetmp->name;
  1143. unset($societetmp);
  1144. }
  1145. // mode 1
  1146. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '');
  1147. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1148. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1149. if (empty($hidelabel)) {
  1150. print $langs->trans("RefOrLabel").' : ';
  1151. } elseif ($hidelabel > 1) {
  1152. $placeholder = $langs->trans("RefOrLabel");
  1153. if ($hidelabel == 2) {
  1154. $out .= img_picto($langs->trans("Search"), 'search');
  1155. }
  1156. }
  1157. $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '').' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1158. if ($hidelabel == 3) {
  1159. $out .= img_picto($langs->trans("Search"), 'search');
  1160. }
  1161. } else {
  1162. // Immediate load of all database
  1163. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids);
  1164. }
  1165. return $out;
  1166. }
  1167. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1168. /**
  1169. * Output html form to select a third party.
  1170. * 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.
  1171. *
  1172. * @param string $selected Preselected type
  1173. * @param string $htmlname Name of field in form
  1174. * @param string $filter Optional filters criteras (example: 's.rowid NOT IN (x)', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1175. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1176. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1177. * @param int $forcecombo Force to use standard HTML select component without beautification
  1178. * @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')))
  1179. * @param string $filterkey Filter on key value
  1180. * @param int $outputmode 0=HTML select string, 1=Array
  1181. * @param int $limit Limit number of answers
  1182. * @param string $morecss Add more css styles to the SELECT component
  1183. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1184. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1185. * @param array $excludeids Exclude IDs from the select combo
  1186. * @return string HTML string with
  1187. */
  1188. public function select_thirdparty_list($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $filterkey = '', $outputmode = 0, $limit = 0, $morecss = 'minwidth100', $moreparam = '', $multiple = false, $excludeids = array())
  1189. {
  1190. // phpcs:enable
  1191. global $conf, $user, $langs;
  1192. $out = '';
  1193. $num = 0;
  1194. $outarray = array();
  1195. if ($selected === '') {
  1196. $selected = array();
  1197. } elseif (!is_array($selected)) {
  1198. $selected = array($selected);
  1199. }
  1200. // Clean $filter that may contains sql conditions so sql code
  1201. if (function_exists('testSqlAndScriptInject')) {
  1202. if (testSqlAndScriptInject($filter, 3) > 0) {
  1203. $filter = '';
  1204. }
  1205. }
  1206. // We search companies
  1207. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1208. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1209. $sql .= ", s.address, s.zip, s.town";
  1210. $sql .= ", dictp.code as country_code";
  1211. }
  1212. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  1213. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1214. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid = s.fk_pays";
  1215. }
  1216. if (!$user->rights->societe->client->voir && !$user->socid) {
  1217. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1218. }
  1219. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1220. if (!empty($user->socid)) {
  1221. $sql .= " AND s.rowid = ".((int) $user->socid);
  1222. }
  1223. if ($filter) {
  1224. $sql .= " AND (".$filter.")";
  1225. }
  1226. if (!$user->rights->societe->client->voir && !$user->socid) {
  1227. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1228. }
  1229. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1230. $sql .= " AND s.status <> 0";
  1231. }
  1232. if (!empty($excludeids)) {
  1233. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1234. }
  1235. // Add criteria
  1236. if ($filterkey && $filterkey != '') {
  1237. $sql .= " AND (";
  1238. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1239. // For natural search
  1240. $scrit = explode(' ', $filterkey);
  1241. $i = 0;
  1242. if (count($scrit) > 1) {
  1243. $sql .= "(";
  1244. }
  1245. foreach ($scrit as $crit) {
  1246. if ($i > 0) {
  1247. $sql .= " AND ";
  1248. }
  1249. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1250. $i++;
  1251. }
  1252. if (count($scrit) > 1) {
  1253. $sql .= ")";
  1254. }
  1255. if (!empty($conf->barcode->enabled)) {
  1256. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1257. }
  1258. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1259. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1260. $sql .= ")";
  1261. }
  1262. $sql .= $this->db->order("nom", "ASC");
  1263. $sql .= $this->db->plimit($limit, 0);
  1264. // Build output string
  1265. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1266. $resql = $this->db->query($sql);
  1267. if ($resql) {
  1268. if (!$forcecombo) {
  1269. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1270. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1271. }
  1272. // Construct $out and $outarray
  1273. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1274. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1275. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1276. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1277. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1278. if ($showempty && !is_numeric($showempty)) {
  1279. $textifempty = $langs->trans($showempty);
  1280. } else {
  1281. $textifempty .= $langs->trans("All");
  1282. }
  1283. }
  1284. if ($showempty) {
  1285. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1286. }
  1287. $num = $this->db->num_rows($resql);
  1288. $i = 0;
  1289. if ($num) {
  1290. while ($i < $num) {
  1291. $obj = $this->db->fetch_object($resql);
  1292. $label = '';
  1293. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1294. if (($obj->client) && (!empty($obj->code_client))) {
  1295. $label = $obj->code_client.' - ';
  1296. }
  1297. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1298. $label .= $obj->code_fournisseur.' - ';
  1299. }
  1300. $label .= ' '.$obj->name;
  1301. } else {
  1302. $label = $obj->name;
  1303. }
  1304. if (!empty($obj->name_alias)) {
  1305. $label .= ' ('.$obj->name_alias.')';
  1306. }
  1307. if ($showtype) {
  1308. if ($obj->client || $obj->fournisseur) {
  1309. $label .= ' (';
  1310. }
  1311. if ($obj->client == 1 || $obj->client == 3) {
  1312. $label .= $langs->trans("Customer");
  1313. }
  1314. if ($obj->client == 2 || $obj->client == 3) {
  1315. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1316. }
  1317. if ($obj->fournisseur) {
  1318. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1319. }
  1320. if ($obj->client || $obj->fournisseur) {
  1321. $label .= ')';
  1322. }
  1323. }
  1324. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1325. $label .= ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1326. if (!empty($obj->country_code)) {
  1327. $label .= ', '.$langs->trans('Country'.$obj->country_code);
  1328. }
  1329. }
  1330. if (empty($outputmode)) {
  1331. if (in_array($obj->rowid, $selected)) {
  1332. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1333. } else {
  1334. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1335. }
  1336. } else {
  1337. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1338. }
  1339. $i++;
  1340. if (($i % 10) == 0) {
  1341. $out .= "\n";
  1342. }
  1343. }
  1344. }
  1345. $out .= '</select>'."\n";
  1346. } else {
  1347. dol_print_error($this->db);
  1348. }
  1349. $this->result = array('nbofthirdparties'=>$num);
  1350. if ($outputmode) {
  1351. return $outarray;
  1352. }
  1353. return $out;
  1354. }
  1355. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1356. /**
  1357. * Return HTML combo list of absolute discounts
  1358. *
  1359. * @param string $selected Id remise fixe pre-selectionnee
  1360. * @param string $htmlname Nom champ formulaire
  1361. * @param string $filter Criteres optionnels de filtre
  1362. * @param int $socid Id of thirdparty
  1363. * @param int $maxvalue Max value for lines that can be selected
  1364. * @return int Return number of qualifed lines in list
  1365. */
  1366. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1367. {
  1368. // phpcs:enable
  1369. global $langs, $conf;
  1370. // On recherche les remises
  1371. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1372. $sql .= " re.description, re.fk_facture_source";
  1373. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  1374. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1375. $sql .= " AND re.entity = ".$conf->entity;
  1376. if ($filter) {
  1377. $sql .= " AND ".$filter;
  1378. }
  1379. $sql .= " ORDER BY re.description ASC";
  1380. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1381. $resql = $this->db->query($sql);
  1382. if ($resql) {
  1383. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1384. $num = $this->db->num_rows($resql);
  1385. $qualifiedlines = $num;
  1386. $i = 0;
  1387. if ($num) {
  1388. print '<option value="0">&nbsp;</option>';
  1389. while ($i < $num) {
  1390. $obj = $this->db->fetch_object($resql);
  1391. $desc = dol_trunc($obj->description, 40);
  1392. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1393. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1394. }
  1395. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1396. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1397. }
  1398. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1399. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1400. }
  1401. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1402. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1403. }
  1404. $selectstring = '';
  1405. if ($selected > 0 && $selected == $obj->rowid) {
  1406. $selectstring = ' selected';
  1407. }
  1408. $disabled = '';
  1409. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1410. $qualifiedlines--;
  1411. $disabled = ' disabled';
  1412. }
  1413. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1414. $tmpfac = new Facture($this->db);
  1415. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1416. $desc = $desc.' - '.$tmpfac->ref;
  1417. }
  1418. }
  1419. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1420. $i++;
  1421. }
  1422. }
  1423. print '</select>';
  1424. return $qualifiedlines;
  1425. } else {
  1426. dol_print_error($this->db);
  1427. return -1;
  1428. }
  1429. }
  1430. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1431. /**
  1432. * Return list of all contacts (for a third party or all)
  1433. *
  1434. * @param int $socid Id ot third party or 0 for all
  1435. * @param string $selected Id contact pre-selectionne
  1436. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1437. * @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
  1438. * @param string $exclude List of contacts id to exclude
  1439. * @param string $limitto Disable answers that are not id in this array list
  1440. * @param integer $showfunction Add function into label
  1441. * @param string $moreclass Add more class to class style
  1442. * @param integer $showsoc Add company into label
  1443. * @param int $forcecombo Force to use combo box
  1444. * @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')))
  1445. * @param bool $options_only Return options only (for ajax treatment)
  1446. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1447. * @param string $htmlid Html id to use instead of htmlname
  1448. * @return int <0 if KO, Nb of contact in list if OK
  1449. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1450. */
  1451. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1452. {
  1453. // phpcs:enable
  1454. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1455. return $this->num;
  1456. }
  1457. /**
  1458. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1459. * This also set the number of contacts found into $this->num
  1460. *
  1461. * @since 9.0 Add afterSelectContactOptions hook
  1462. *
  1463. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1464. * @param array|int $selected Array of ID of pre-selected contact id
  1465. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1466. * @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
  1467. * @param string $exclude List of contacts id to exclude
  1468. * @param string $limitto Disable answers that are not id in this array list
  1469. * @param integer $showfunction Add function into label
  1470. * @param string $moreclass Add more class to class style
  1471. * @param bool $options_only Return options only (for ajax treatment)
  1472. * @param integer $showsoc Add company into label
  1473. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1474. * @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')))
  1475. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1476. * @param string $htmlid Html id to use instead of htmlname
  1477. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1478. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1479. * @return int|string <0 if KO, HTML with select string if OK.
  1480. */
  1481. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1482. {
  1483. global $conf, $langs, $hookmanager, $action;
  1484. $langs->load('companies');
  1485. if (empty($htmlid)) {
  1486. $htmlid = $htmlname;
  1487. }
  1488. $num = 0;
  1489. if ($selected === '') {
  1490. $selected = array();
  1491. } elseif (!is_array($selected)) {
  1492. $selected = array($selected);
  1493. }
  1494. $out = '';
  1495. if (!is_object($hookmanager)) {
  1496. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1497. $hookmanager = new HookManager($this->db);
  1498. }
  1499. // We search third parties
  1500. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste, sp.email, sp.phone, sp.phone_perso, sp.phone_mobile, sp.town AS contact_town";
  1501. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1502. $sql .= ", s.nom as company, s.town AS company_town";
  1503. }
  1504. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
  1505. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1506. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=sp.fk_soc";
  1507. }
  1508. $sql .= " WHERE sp.entity IN (".getEntity('socpeople').")";
  1509. if ($socid > 0 || $socid == -1) {
  1510. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1511. }
  1512. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1513. $sql .= " AND sp.statut <> 0";
  1514. }
  1515. $sql .= " ORDER BY sp.lastname ASC";
  1516. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1517. $resql = $this->db->query($sql);
  1518. if ($resql) {
  1519. $num = $this->db->num_rows($resql);
  1520. if ($htmlname != 'none' && !$options_only) {
  1521. $out .= '<select class="flat'.($moreclass ? ' '.$moreclass : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1522. }
  1523. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
  1524. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1525. }
  1526. if ($showempty == 2) {
  1527. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1528. }
  1529. $i = 0;
  1530. if ($num) {
  1531. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1532. $contactstatic = new Contact($this->db);
  1533. while ($i < $num) {
  1534. $obj = $this->db->fetch_object($resql);
  1535. // Set email (or phones) and town extended infos
  1536. $extendedInfos = '';
  1537. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1538. $extendedInfos = array();
  1539. $email = trim($obj->email);
  1540. if (!empty($email)) {
  1541. $extendedInfos[] = $email;
  1542. } else {
  1543. $phone = trim($obj->phone);
  1544. $phone_perso = trim($obj->phone_perso);
  1545. $phone_mobile = trim($obj->phone_mobile);
  1546. if (!empty($phone)) {
  1547. $extendedInfos[] = $phone;
  1548. }
  1549. if (!empty($phone_perso)) {
  1550. $extendedInfos[] = $phone_perso;
  1551. }
  1552. if (!empty($phone_mobile)) {
  1553. $extendedInfos[] = $phone_mobile;
  1554. }
  1555. }
  1556. $contact_town = trim($obj->contact_town);
  1557. $company_town = trim($obj->company_town);
  1558. if (!empty($contact_town)) {
  1559. $extendedInfos[] = $contact_town;
  1560. } elseif (!empty($company_town)) {
  1561. $extendedInfos[] = $company_town;
  1562. }
  1563. $extendedInfos = implode(' - ', $extendedInfos);
  1564. if (!empty($extendedInfos)) {
  1565. $extendedInfos = ' - '.$extendedInfos;
  1566. }
  1567. }
  1568. $contactstatic->id = $obj->rowid;
  1569. $contactstatic->lastname = $obj->lastname;
  1570. $contactstatic->firstname = $obj->firstname;
  1571. if ($obj->statut == 1) {
  1572. if ($htmlname != 'none') {
  1573. $disabled = 0;
  1574. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1575. $disabled = 1;
  1576. }
  1577. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1578. $disabled = 1;
  1579. }
  1580. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1581. $out .= '<option value="'.$obj->rowid.'"';
  1582. if ($disabled) {
  1583. $out .= ' disabled';
  1584. }
  1585. $out .= ' selected>';
  1586. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1587. if ($showfunction && $obj->poste) {
  1588. $out .= ' ('.$obj->poste.')';
  1589. }
  1590. if (($showsoc > 0) && $obj->company) {
  1591. $out .= ' - ('.$obj->company.')';
  1592. }
  1593. $out .= '</option>';
  1594. } else {
  1595. $out .= '<option value="'.$obj->rowid.'"';
  1596. if ($disabled) {
  1597. $out .= ' disabled';
  1598. }
  1599. $out .= '>';
  1600. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1601. if ($showfunction && $obj->poste) {
  1602. $out .= ' ('.$obj->poste.')';
  1603. }
  1604. if (($showsoc > 0) && $obj->company) {
  1605. $out .= ' - ('.$obj->company.')';
  1606. }
  1607. $out .= '</option>';
  1608. }
  1609. } else {
  1610. if (in_array($obj->rowid, $selected)) {
  1611. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1612. if ($showfunction && $obj->poste) {
  1613. $out .= ' ('.$obj->poste.')';
  1614. }
  1615. if (($showsoc > 0) && $obj->company) {
  1616. $out .= ' - ('.$obj->company.')';
  1617. }
  1618. }
  1619. }
  1620. }
  1621. $i++;
  1622. }
  1623. } else {
  1624. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1625. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1626. $out .= $labeltoshow;
  1627. $out .= '</option>';
  1628. }
  1629. $parameters = array(
  1630. 'socid'=>$socid,
  1631. 'htmlname'=>$htmlname,
  1632. 'resql'=>$resql,
  1633. 'out'=>&$out,
  1634. 'showfunction'=>$showfunction,
  1635. 'showsoc'=>$showsoc,
  1636. );
  1637. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1638. if ($htmlname != 'none' && !$options_only) {
  1639. $out .= '</select>';
  1640. }
  1641. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1642. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1643. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1644. }
  1645. $this->num = $num;
  1646. return $out;
  1647. } else {
  1648. dol_print_error($this->db);
  1649. return -1;
  1650. }
  1651. }
  1652. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1653. /**
  1654. * Return the HTML select list of users
  1655. *
  1656. * @param string $selected Id user preselected
  1657. * @param string $htmlname Field name in form
  1658. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1659. * @param array $exclude Array list of users id to exclude
  1660. * @param int $disabled If select list must be disabled
  1661. * @param array|string $include Array list of users id to include. User '' for all users or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1662. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1663. * @param string $force_entity '0' or Ids of environment to force
  1664. * @return void
  1665. * @deprecated Use select_dolusers instead
  1666. * @see select_dolusers()
  1667. */
  1668. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1669. {
  1670. // phpcs:enable
  1671. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1672. }
  1673. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1674. /**
  1675. * Return select list of users
  1676. *
  1677. * @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)
  1678. * @param string $htmlname Field name in form
  1679. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1680. * @param array $exclude Array list of users id to exclude
  1681. * @param int $disabled If select list must be disabled
  1682. * @param array|string $include Array list of users id to include. User '' for all users or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1683. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1684. * @param string $force_entity '0' or Ids of environment to force
  1685. * @param int $maxlength Maximum length of string into list (0=no limit)
  1686. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1687. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1688. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1689. * @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.
  1690. * @param string $morecss More css
  1691. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1692. * @param int $outputmode 0=HTML select string, 1=Array
  1693. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1694. * @return string HTML select string
  1695. * @see select_dolgroups()
  1696. */
  1697. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $noactive = 0, $outputmode = 0, $multiple = false)
  1698. {
  1699. // phpcs:enable
  1700. global $conf, $user, $langs, $hookmanager;
  1701. // If no preselected user defined, we take current user
  1702. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1703. $selected = $user->id;
  1704. }
  1705. if ($selected === '') {
  1706. $selected = array();
  1707. } elseif (!is_array($selected)) {
  1708. $selected = array($selected);
  1709. }
  1710. $excludeUsers = null;
  1711. $includeUsers = null;
  1712. // Permettre l'exclusion d'utilisateurs
  1713. if (is_array($exclude)) {
  1714. $excludeUsers = implode(",", $exclude);
  1715. }
  1716. // Permettre l'inclusion d'utilisateurs
  1717. if (is_array($include)) {
  1718. $includeUsers = implode(",", $include);
  1719. } elseif ($include == 'hierarchy') {
  1720. // Build list includeUsers to have only hierarchy
  1721. $includeUsers = implode(",", $user->getAllChildIds(0));
  1722. } elseif ($include == 'hierarchyme') {
  1723. // Build list includeUsers to have only hierarchy and current user
  1724. $includeUsers = implode(",", $user->getAllChildIds(1));
  1725. }
  1726. $out = '';
  1727. $outarray = array();
  1728. // Forge request to select users
  1729. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1730. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1731. $sql .= ", e.label";
  1732. }
  1733. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  1734. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1735. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid = u.entity";
  1736. if ($force_entity) {
  1737. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1738. } else {
  1739. $sql .= " WHERE u.entity IS NOT NULL";
  1740. }
  1741. } else {
  1742. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1743. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1744. $sql .= " ON ug.fk_user = u.rowid";
  1745. $sql .= " WHERE ug.entity = ".$conf->entity;
  1746. } else {
  1747. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1748. }
  1749. }
  1750. if (!empty($user->socid)) {
  1751. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1752. }
  1753. if (is_array($exclude) && $excludeUsers) {
  1754. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1755. }
  1756. if ($includeUsers) {
  1757. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1758. }
  1759. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
  1760. $sql .= " AND u.statut <> 0";
  1761. }
  1762. if (!empty($morefilter)) {
  1763. $sql .= " ".$morefilter;
  1764. }
  1765. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1766. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1767. if (!empty($reshook)) {
  1768. $sql .= $hookmanager->resPrint;
  1769. }
  1770. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1771. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1772. } else {
  1773. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1774. }
  1775. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1776. $resql = $this->db->query($sql);
  1777. if ($resql) {
  1778. $num = $this->db->num_rows($resql);
  1779. $i = 0;
  1780. if ($num) {
  1781. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1782. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1783. if ($show_empty && !$multiple) {
  1784. $textforempty = ' ';
  1785. if (!empty($conf->use_javascript_ajax)) {
  1786. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1787. }
  1788. if (!is_numeric($show_empty)) {
  1789. $textforempty = $show_empty;
  1790. }
  1791. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1792. }
  1793. if ($show_every) {
  1794. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1795. }
  1796. $userstatic = new User($this->db);
  1797. while ($i < $num) {
  1798. $obj = $this->db->fetch_object($resql);
  1799. $userstatic->id = $obj->rowid;
  1800. $userstatic->lastname = $obj->lastname;
  1801. $userstatic->firstname = $obj->firstname;
  1802. $userstatic->photo = $obj->photo;
  1803. $userstatic->statut = $obj->status;
  1804. $userstatic->entity = $obj->entity;
  1805. $userstatic->admin = $obj->admin;
  1806. $disableline = '';
  1807. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1808. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1809. }
  1810. $labeltoshow = '';
  1811. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1812. $fullNameMode = 0;
  1813. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1814. $fullNameMode = 1; //Firstname+lastname
  1815. }
  1816. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1817. if (empty($obj->firstname) && empty($obj->lastname)) {
  1818. $labeltoshow .= $obj->login;
  1819. }
  1820. // Complete name with more info
  1821. $moreinfo = '';
  1822. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1823. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1824. }
  1825. if ($showstatus >= 0) {
  1826. if ($obj->status == 1 && $showstatus == 1) {
  1827. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1828. }
  1829. if ($obj->status == 0 && $showstatus == 1) {
  1830. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1831. }
  1832. }
  1833. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1834. if (!$obj->entity) {
  1835. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1836. } else {
  1837. if ($obj->entity != $conf->entity) {
  1838. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1839. }
  1840. }
  1841. }
  1842. $moreinfo .= ($moreinfo ? ')' : '');
  1843. if ($disableline && $disableline != '1') {
  1844. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1845. }
  1846. $labeltoshow .= $moreinfo;
  1847. $out .= '<option value="'.$obj->rowid.'"';
  1848. if ($disableline) {
  1849. $out .= ' disabled';
  1850. }
  1851. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1852. $out .= ' selected';
  1853. }
  1854. $out .= ' data-html="';
  1855. $outhtml = '';
  1856. // if (!empty($obj->photo)) {
  1857. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1858. // }
  1859. if ($showstatus >= 0 && $obj->status == 0) {
  1860. $outhtml .= '<strike class="opacitymediumxxx">';
  1861. }
  1862. $outhtml .= $labeltoshow;
  1863. if ($showstatus >= 0 && $obj->status == 0) {
  1864. $outhtml .= '</strike>';
  1865. }
  1866. $out .= dol_escape_htmltag($outhtml);
  1867. $out .= '">';
  1868. $out .= $labeltoshow;
  1869. $out .= '</option>';
  1870. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1871. $i++;
  1872. }
  1873. } else {
  1874. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1875. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1876. }
  1877. $out .= '</select>';
  1878. if ($num) {
  1879. // Enhance with select2
  1880. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1881. $out .= ajax_combobox($htmlname);
  1882. }
  1883. } else {
  1884. dol_print_error($this->db);
  1885. }
  1886. if ($outputmode) {
  1887. return $outarray;
  1888. }
  1889. return $out;
  1890. }
  1891. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1892. /**
  1893. * Return select list of users. Selected users are stored into session.
  1894. * List of users are provided into $_SESSION['assignedtouser'].
  1895. *
  1896. * @param string $action Value for $action
  1897. * @param string $htmlname Field name in form
  1898. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1899. * @param array $exclude Array list of users id to exclude
  1900. * @param int $disabled If select list must be disabled
  1901. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1902. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1903. * @param int $force_entity '0' or Ids of environment to force
  1904. * @param int $maxlength Maximum length of string into list (0=no limit)
  1905. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1906. * @param string $morefilter Add more filters into sql request
  1907. * @param int $showproperties Show properties of each attendees
  1908. * @param array $listofuserid Array with properties of each user
  1909. * @param array $listofcontactid Array with properties of each contact
  1910. * @param array $listofotherid Array with properties of each other contact
  1911. * @return string HTML select string
  1912. * @see select_dolgroups()
  1913. */
  1914. public function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array())
  1915. {
  1916. // phpcs:enable
  1917. global $conf, $user, $langs;
  1918. $userstatic = new User($this->db);
  1919. $out = '';
  1920. $assignedtouser = array();
  1921. if (!empty($_SESSION['assignedtouser'])) {
  1922. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1923. }
  1924. $nbassignetouser = count($assignedtouser);
  1925. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1926. if ($nbassignetouser) {
  1927. $out .= '<ul class="attendees">';
  1928. }
  1929. $i = 0;
  1930. $ownerid = 0;
  1931. foreach ($assignedtouser as $key => $value) {
  1932. if ($value['id'] == $ownerid) {
  1933. continue;
  1934. }
  1935. $out .= '<li>';
  1936. $userstatic->fetch($value['id']);
  1937. $out .= $userstatic->getNomUrl(-1);
  1938. if ($i == 0) {
  1939. $ownerid = $value['id'];
  1940. $out .= ' ('.$langs->trans("Owner").')';
  1941. }
  1942. if ($nbassignetouser > 1 && $action != 'view') {
  1943. $out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned reposition" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
  1944. }
  1945. // Show my availability
  1946. if ($showproperties) {
  1947. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  1948. $out .= '<div class="myavailability inline-block">';
  1949. $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span> </span><input id="transparency" class="paddingrightonly" '.($action == 'view' ? 'disabled' : '').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency'] ? ' checked' : '').'><label for="transparency">'.$langs->trans("Busy").'</label>';
  1950. $out .= '</div>';
  1951. }
  1952. }
  1953. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1954. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1955. $out .= '</li>';
  1956. $i++;
  1957. }
  1958. if ($nbassignetouser) {
  1959. $out .= '</ul>';
  1960. }
  1961. // Method with no ajax
  1962. if ($action != 'view') {
  1963. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1964. $out .= '<script type="text/javascript" language="javascript">jQuery(document).ready(function () {';
  1965. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  1966. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  1967. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  1968. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  1969. $out .= '});';
  1970. $out .= '})</script>';
  1971. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1972. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1973. $out .= '<br>';
  1974. }
  1975. return $out;
  1976. }
  1977. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1978. /**
  1979. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1980. *
  1981. * @param int $selected Preselected products
  1982. * @param string $htmlname Name of HTML select field (must be unique in page).
  1983. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1984. * @param int $limit Limit on number of returned lines
  1985. * @param int $price_level Level of price to show
  1986. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1987. * @param int $finished 2=all, 1=finished, 0=raw material
  1988. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1989. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1990. * @param array $ajaxoptions Options for ajax_autocompleter
  1991. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1992. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1993. * @param int $forcecombo Force to use combo box
  1994. * @param string $morecss Add more css on select
  1995. * @param int $hidepriceinlabel 1=Hide prices in label
  1996. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  1997. * 'warehouseopen' = count products from open warehouses,
  1998. * 'warehouseclosed' = count products from closed warehouses,
  1999. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2000. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2001. * @param string $nooutput No print, return the output into a string
  2002. * @return void|string
  2003. */
  2004. public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 0, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = null, $nooutput = 0)
  2005. {
  2006. // phpcs:enable
  2007. global $langs, $conf;
  2008. $out = '';
  2009. // check parameters
  2010. $price_level = (!empty($price_level) ? $price_level : 0);
  2011. if (is_null($ajaxoptions)) {
  2012. $ajaxoptions = array();
  2013. }
  2014. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  2015. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  2016. $filtertype = '0';
  2017. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  2018. $filtertype = '1';
  2019. }
  2020. }
  2021. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2022. $placeholder = '';
  2023. if ($selected && empty($selected_input_value)) {
  2024. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2025. $producttmpselect = new Product($this->db);
  2026. $producttmpselect->fetch($selected);
  2027. $selected_input_value = $producttmpselect->ref;
  2028. unset($producttmpselect);
  2029. }
  2030. // handle case where product or service module is disabled + no filter specified
  2031. if ($filtertype == '') {
  2032. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2033. $filtertype = 1;
  2034. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2035. $filtertype = 0;
  2036. }
  2037. }
  2038. // mode=1 means customers products
  2039. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  2040. //Price by customer
  2041. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2042. $urloption .= '&socid='.$socid;
  2043. }
  2044. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2045. if (!empty($conf->variants->enabled) && is_array($selected_combinations)) {
  2046. // Code to automatically insert with javascript the select of attributes under the select of product
  2047. // when a parent of variant has been selected.
  2048. $out .= '
  2049. <!-- script to auto show attributes select tags if a variant was selected -->
  2050. <script>
  2051. // auto show attributes fields
  2052. selected = '.json_encode($selected_combinations).';
  2053. combvalues = {};
  2054. jQuery(document).ready(function () {
  2055. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2056. if (jQuery(this).val() == \'free\') {
  2057. jQuery(\'div#attributes_box\').empty();
  2058. }
  2059. });
  2060. jQuery("input#'.$htmlname.'").change(function () {
  2061. if (!jQuery(this).val()) {
  2062. jQuery(\'div#attributes_box\').empty();
  2063. return;
  2064. }
  2065. console.log("A change has started. We get variants fields to inject html select");
  2066. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2067. id: jQuery(this).val()
  2068. }, function (data) {
  2069. jQuery(\'div#attributes_box\').empty();
  2070. jQuery.each(data, function (key, val) {
  2071. combvalues[val.id] = val.values;
  2072. var span = jQuery(document.createElement(\'div\')).css({
  2073. \'display\': \'table-row\'
  2074. });
  2075. span.append(
  2076. jQuery(document.createElement(\'div\')).text(val.label).css({
  2077. \'font-weight\': \'bold\',
  2078. \'display\': \'table-cell\'
  2079. })
  2080. );
  2081. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2082. \'margin-left\': \'15px\',
  2083. \'white-space\': \'pre\'
  2084. }).append(
  2085. jQuery(document.createElement(\'option\')).val(\'\')
  2086. );
  2087. jQuery.each(combvalues[val.id], function (key, val) {
  2088. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2089. if (selected[val.fk_product_attribute] == val.id) {
  2090. tag.attr(\'selected\', \'selected\');
  2091. }
  2092. html.append(tag);
  2093. });
  2094. span.append(html);
  2095. jQuery(\'div#attributes_box\').append(span);
  2096. });
  2097. })
  2098. });
  2099. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2100. });
  2101. </script>
  2102. ';
  2103. }
  2104. if (empty($hidelabel)) {
  2105. $out .= $langs->trans("RefOrLabel").' : ';
  2106. } elseif ($hidelabel > 1) {
  2107. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2108. if ($hidelabel == 2) {
  2109. $out .= img_picto($langs->trans("Search"), 'search');
  2110. }
  2111. }
  2112. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  2113. if ($hidelabel == 3) {
  2114. $out .= img_picto($langs->trans("Search"), 'search');
  2115. }
  2116. } else {
  2117. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus);
  2118. }
  2119. if (empty($nooutput)) {
  2120. print $out;
  2121. } else {
  2122. return $out;
  2123. }
  2124. }
  2125. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2126. /**
  2127. * Return list of products for a customer.
  2128. * Called by select_produits.
  2129. *
  2130. * @param int $selected Preselected product
  2131. * @param string $htmlname Name of select html
  2132. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2133. * @param int $limit Limit on number of returned lines
  2134. * @param int $price_level Level of price to show
  2135. * @param string $filterkey Filter on product
  2136. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2137. * @param int $finished Filter on finished field: 2=No filter
  2138. * @param int $outputmode 0=HTML select string, 1=Array
  2139. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2140. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2141. * @param int $forcecombo Force to use combo box
  2142. * @param string $morecss Add more css on select
  2143. * @param int $hidepriceinlabel 1=Hide prices in label
  2144. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2145. * 'warehouseopen' = count products from open warehouses,
  2146. * 'warehouseclosed' = count products from closed warehouses,
  2147. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2148. * @return array Array of keys for json
  2149. */
  2150. public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '')
  2151. {
  2152. // phpcs:enable
  2153. global $langs, $conf, $user, $db;
  2154. $out = '';
  2155. $outarray = array();
  2156. // Units
  2157. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2158. $langs->load('other');
  2159. }
  2160. $warehouseStatusArray = array();
  2161. if (!empty($warehouseStatus)) {
  2162. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2163. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2164. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2165. }
  2166. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2167. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2168. }
  2169. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2170. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2171. }
  2172. }
  2173. $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_country, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression";
  2174. if (count($warehouseStatusArray)) {
  2175. $selectFieldsGrouped = ", sum(".$this->db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock
  2176. } else {
  2177. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2178. }
  2179. $sql = "SELECT ";
  2180. $sql .= $selectFields.$selectFieldsGrouped;
  2181. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2182. //Product category
  2183. $sql .= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
  2184. FROM ".MAIN_DB_PREFIX."categorie_product
  2185. WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
  2186. LIMIT 1
  2187. ) AS categorie_product_id ";
  2188. }
  2189. //Price by customer
  2190. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2191. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2192. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx, pcp.ref_customer as custref';
  2193. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custref";
  2194. }
  2195. // Units
  2196. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2197. $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
  2198. $selectFields .= ', unit_long, unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units';
  2199. }
  2200. // Multilang : we add translation
  2201. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2202. $sql .= ", pl.label as label_translated";
  2203. $sql .= ", pl.description as description_translated";
  2204. $selectFields .= ", label_translated";
  2205. $selectFields .= ", description_translated";
  2206. }
  2207. // Price by quantity
  2208. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2209. $sql .= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  2210. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2211. $sql .= " AND price_level = ".((int) $price_level);
  2212. }
  2213. $sql .= " ORDER BY date_price";
  2214. $sql .= " DESC LIMIT 1) as price_rowid";
  2215. $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
  2216. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2217. $sql .= " AND price_level = ".((int) $price_level);
  2218. }
  2219. $sql .= " ORDER BY date_price";
  2220. $sql .= " DESC LIMIT 1) as price_by_qty";
  2221. $selectFields .= ", price_rowid, price_by_qty";
  2222. }
  2223. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2224. if (count($warehouseStatusArray)) {
  2225. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  2226. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2227. $sql .= ' AND e.statut IN ('.$this->db->sanitize($this->db->escape(implode(',', $warehouseStatusArray))).')'; // Return line if product is inside the selected stock. If not, an empty line will be returned so we will count 0.
  2228. }
  2229. // include search in supplier ref
  2230. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2231. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2232. }
  2233. //Price by customer
  2234. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2235. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2236. }
  2237. // Units
  2238. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2239. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  2240. }
  2241. // Multilang : we add translation
  2242. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2243. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid ";
  2244. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2245. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2246. $soc = new Societe($db);
  2247. $result = $soc->fetch($socid);
  2248. if ($result > 0 && !empty($soc->default_lang)) {
  2249. $sql .= " AND pl.lang='" . $this->db->escape($soc->default_lang) . "'";
  2250. } else {
  2251. $sql .= " AND pl.lang='".$this->db->escape($langs->getDefaultLang())."'";
  2252. }
  2253. } else {
  2254. $sql .= " AND pl.lang='".$this->db->escape($langs->getDefaultLang())."'";
  2255. }
  2256. }
  2257. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2258. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2259. }
  2260. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2261. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2262. $sql .= " AND pac.rowid IS NULL";
  2263. }
  2264. if ($finished == 0) {
  2265. $sql .= " AND p.finished = ".((int) $finished);
  2266. } elseif ($finished == 1) {
  2267. $sql .= " AND p.finished = ".((int) $finished);
  2268. if ($status >= 0) {
  2269. $sql .= " AND p.tosell = ".((int) $status);
  2270. }
  2271. } elseif ($status >= 0) {
  2272. $sql .= " AND p.tosell = ".((int) $status);
  2273. }
  2274. // Filter by product type
  2275. if (strval($filtertype) != '') {
  2276. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2277. } elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2278. $sql .= " AND p.fk_product_type = 1";
  2279. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2280. $sql .= " AND p.fk_product_type = 0";
  2281. }
  2282. // Add criteria on ref/label
  2283. if ($filterkey != '') {
  2284. $sql .= ' AND (';
  2285. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2286. // For natural search
  2287. $scrit = explode(' ', $filterkey);
  2288. $i = 0;
  2289. if (count($scrit) > 1) {
  2290. $sql .= "(";
  2291. }
  2292. foreach ($scrit as $crit) {
  2293. if ($i > 0) {
  2294. $sql .= " AND ";
  2295. }
  2296. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2297. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2298. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2299. }
  2300. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) {
  2301. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2302. }
  2303. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2304. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2305. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2306. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2307. }
  2308. }
  2309. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2310. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2311. }
  2312. $sql .= ")";
  2313. $i++;
  2314. }
  2315. if (count($scrit) > 1) {
  2316. $sql .= ")";
  2317. }
  2318. if (!empty($conf->barcode->enabled)) {
  2319. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2320. }
  2321. $sql .= ')';
  2322. }
  2323. if (count($warehouseStatusArray)) {
  2324. $sql .= " GROUP BY ".$selectFields;
  2325. }
  2326. //Sort by category
  2327. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2328. $sql .= " ORDER BY categorie_product_id ";
  2329. //ASC OR DESC order
  2330. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2331. } else {
  2332. $sql .= $this->db->order("p.ref");
  2333. }
  2334. $sql .= $this->db->plimit($limit, 0);
  2335. // Build output string
  2336. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2337. $result = $this->db->query($sql);
  2338. if ($result) {
  2339. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2340. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2341. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2342. $num = $this->db->num_rows($result);
  2343. $events = null;
  2344. if (!$forcecombo) {
  2345. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2346. $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  2347. }
  2348. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2349. $textifempty = '';
  2350. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2351. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2352. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2353. if ($showempty && !is_numeric($showempty)) {
  2354. $textifempty = $langs->trans($showempty);
  2355. } else {
  2356. $textifempty .= $langs->trans("All");
  2357. }
  2358. } else {
  2359. if ($showempty && !is_numeric($showempty)) {
  2360. $textifempty = $langs->trans($showempty);
  2361. }
  2362. }
  2363. if ($showempty) {
  2364. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2365. }
  2366. $i = 0;
  2367. while ($num && $i < $num) {
  2368. $opt = '';
  2369. $optJson = array();
  2370. $objp = $this->db->fetch_object($result);
  2371. if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1) { // Price by quantity will return many prices for the same product
  2372. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2373. $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  2374. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2375. $sql .= " ORDER BY quantity ASC";
  2376. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2377. $result2 = $this->db->query($sql);
  2378. if ($result2) {
  2379. $nb_prices = $this->db->num_rows($result2);
  2380. $j = 0;
  2381. while ($nb_prices && $j < $nb_prices) {
  2382. $objp2 = $this->db->fetch_object($result2);
  2383. $objp->price_by_qty_rowid = $objp2->rowid;
  2384. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2385. $objp->price_by_qty_quantity = $objp2->quantity;
  2386. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2387. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2388. // For backward compatibility
  2389. $objp->quantity = $objp2->quantity;
  2390. $objp->price = $objp2->price;
  2391. $objp->unitprice = $objp2->unitprice;
  2392. $objp->remise_percent = $objp2->remise_percent;
  2393. $objp->remise = $objp2->remise;
  2394. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2395. $j++;
  2396. // Add new entry
  2397. // "key" value of json key array is used by jQuery automatically as selected value
  2398. // "label" value of json key array is used by jQuery automatically as text for combo box
  2399. $out .= $opt;
  2400. array_push($outarray, $optJson);
  2401. }
  2402. }
  2403. } else {
  2404. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2405. $price_product = new Product($this->db);
  2406. $price_product->fetch($objp->rowid, '', '', 1);
  2407. $priceparser = new PriceParser($this->db);
  2408. $price_result = $priceparser->parseProduct($price_product);
  2409. if ($price_result >= 0) {
  2410. $objp->price = $price_result;
  2411. $objp->unitprice = $price_result;
  2412. //Calculate the VAT
  2413. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2414. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2415. }
  2416. }
  2417. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2418. // Add new entry
  2419. // "key" value of json key array is used by jQuery automatically as selected value
  2420. // "label" value of json key array is used by jQuery automatically as text for combo box
  2421. $out .= $opt;
  2422. array_push($outarray, $optJson);
  2423. }
  2424. $i++;
  2425. }
  2426. $out .= '</select>';
  2427. $this->db->free($result);
  2428. if (empty($outputmode)) {
  2429. return $out;
  2430. }
  2431. return $outarray;
  2432. } else {
  2433. dol_print_error($db);
  2434. }
  2435. }
  2436. /**
  2437. * constructProductListOption.
  2438. * This define value for &$opt and &$optJson.
  2439. *
  2440. * @param resource $objp Resultset of fetch
  2441. * @param string $opt Option (var used for returned value in string option format)
  2442. * @param string $optJson Option (var used for returned value in json format)
  2443. * @param int $price_level Price level
  2444. * @param string $selected Preselected value
  2445. * @param int $hidepriceinlabel Hide price in label
  2446. * @param string $filterkey Filter key to highlight
  2447. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2448. * @return void
  2449. */
  2450. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2451. {
  2452. global $langs, $conf, $user, $db;
  2453. $outkey = '';
  2454. $outval = '';
  2455. $outref = '';
  2456. $outlabel = '';
  2457. $outlabel_translated = '';
  2458. $outdesc = '';
  2459. $outdesc_translated = '';
  2460. $outbarcode = '';
  2461. $outorigin = '';
  2462. $outtype = '';
  2463. $outprice_ht = '';
  2464. $outprice_ttc = '';
  2465. $outpricebasetype = '';
  2466. $outtva_tx = '';
  2467. $outqty = 1;
  2468. $outdiscount = 0;
  2469. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2470. $label = $objp->label;
  2471. if (!empty($objp->label_translated)) {
  2472. $label = $objp->label_translated;
  2473. }
  2474. if (!empty($filterkey) && $filterkey != '') {
  2475. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2476. }
  2477. $outkey = $objp->rowid;
  2478. $outref = $objp->ref;
  2479. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2480. $outlabel = $objp->label;
  2481. $outdesc = $objp->description;
  2482. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2483. $outlabel_translated = $objp->label_translated;
  2484. $outdesc_translated = $objp->description_translated;
  2485. }
  2486. $outbarcode = $objp->barcode;
  2487. $outorigin = $objp->fk_country;
  2488. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2489. $outtype = $objp->fk_product_type;
  2490. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2491. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2492. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2493. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2494. }
  2495. // Units
  2496. $outvalUnits = '';
  2497. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2498. if (!empty($objp->unit_short)) {
  2499. $outvalUnits .= ' - '.$objp->unit_short;
  2500. }
  2501. }
  2502. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2503. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2504. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2505. $outvalUnits .= ' - '.$unitToShow;
  2506. }
  2507. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2508. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2509. $outvalUnits .= ' - '.$unitToShow;
  2510. }
  2511. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2512. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2513. $outvalUnits .= ' - '.$unitToShow;
  2514. }
  2515. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2516. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2517. $outvalUnits .= ' - '.$unitToShow;
  2518. }
  2519. }
  2520. if ($outdurationvalue && $outdurationunit) {
  2521. $da = array(
  2522. 'h' => $langs->trans('Hour'),
  2523. 'd' => $langs->trans('Day'),
  2524. 'w' => $langs->trans('Week'),
  2525. 'm' => $langs->trans('Month'),
  2526. 'y' => $langs->trans('Year')
  2527. );
  2528. if (isset($da[$outdurationunit])) {
  2529. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2530. }
  2531. }
  2532. $opt = '<option value="'.$objp->rowid.'"';
  2533. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2534. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2535. $opt .= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqup="'.$objp->price_by_qty_unitprice.'" data-pbqbase="'.$objp->price_by_qty_price_base_type.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
  2536. }
  2537. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2538. if (!empty($user->rights->stock->lire)) {
  2539. if ($objp->stock > 0) {
  2540. $opt .= ' class="product_line_stock_ok"';
  2541. } elseif ($objp->stock <= 0) {
  2542. $opt .= ' class="product_line_stock_too_low"';
  2543. }
  2544. }
  2545. }
  2546. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2547. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2548. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2549. }
  2550. $opt .= '>';
  2551. $opt .= $objp->ref;
  2552. if (! empty($objp->custref)) {
  2553. $opt.= ' (' . $objp->custref . ')';
  2554. }
  2555. if ($outbarcode) {
  2556. $opt .= ' ('.$outbarcode.')';
  2557. }
  2558. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2559. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2560. $opt .= ' ('.getCountry($outorigin, 1).')';
  2561. }
  2562. $objRef = $objp->ref;
  2563. if (! empty($objp->custref)) {
  2564. $objRef .= ' (' . $objp->custref . ')';
  2565. }
  2566. if (!empty($filterkey) && $filterkey != '') {
  2567. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2568. }
  2569. $outval .= $objRef;
  2570. if ($outbarcode) {
  2571. $outval .= ' ('.$outbarcode.')';
  2572. }
  2573. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2574. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2575. $outval .= ' ('.getCountry($outorigin, 1).')';
  2576. }
  2577. // Units
  2578. $opt .= $outvalUnits;
  2579. $outval .= $outvalUnits;
  2580. $found = 0;
  2581. // Multiprice
  2582. // If we need a particular price level (from 1 to 6)
  2583. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2584. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  2585. $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
  2586. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2587. $sql .= " AND entity IN (".getEntity('productprice').")";
  2588. $sql .= " AND price_level = ".((int) $price_level);
  2589. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2590. $sql .= " LIMIT 1";
  2591. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2592. $result2 = $this->db->query($sql);
  2593. if ($result2) {
  2594. $objp2 = $this->db->fetch_object($result2);
  2595. if ($objp2) {
  2596. $found = 1;
  2597. if ($objp2->price_base_type == 'HT') {
  2598. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2599. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2600. } else {
  2601. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2602. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2603. }
  2604. $outprice_ht = price($objp2->price);
  2605. $outprice_ttc = price($objp2->price_ttc);
  2606. $outpricebasetype = $objp2->price_base_type;
  2607. $outtva_tx = $objp2->tva_tx;
  2608. }
  2609. } else {
  2610. dol_print_error($this->db);
  2611. }
  2612. }
  2613. // Price by quantity
  2614. 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))) {
  2615. $found = 1;
  2616. $outqty = $objp->quantity;
  2617. $outdiscount = $objp->remise_percent;
  2618. if ($objp->quantity == 1) {
  2619. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2620. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2621. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2622. $outval .= $langs->transnoentities("Unit");
  2623. } else {
  2624. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2625. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2626. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2627. $outval .= $langs->transnoentities("Units");
  2628. }
  2629. $outprice_ht = price($objp->unitprice);
  2630. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2631. $outpricebasetype = $objp->price_base_type;
  2632. $outtva_tx = $objp->tva_tx;
  2633. }
  2634. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2635. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2636. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2637. }
  2638. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2639. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2640. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2641. }
  2642. // Price by customer
  2643. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2644. if (!empty($objp->idprodcustprice)) {
  2645. $found = 1;
  2646. if ($objp->custprice_base_type == 'HT') {
  2647. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2648. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2649. } else {
  2650. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2651. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2652. }
  2653. $outprice_ht = price($objp->custprice);
  2654. $outprice_ttc = price($objp->custprice_ttc);
  2655. $outpricebasetype = $objp->custprice_base_type;
  2656. $outtva_tx = $objp->custtva_tx;
  2657. }
  2658. }
  2659. // If level no defined or multiprice not found, we used the default price
  2660. if (empty($hidepriceinlabel) && !$found) {
  2661. if ($objp->price_base_type == 'HT') {
  2662. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2663. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2664. } else {
  2665. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2666. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2667. }
  2668. $outprice_ht = price($objp->price);
  2669. $outprice_ttc = price($objp->price_ttc);
  2670. $outpricebasetype = $objp->price_base_type;
  2671. $outtva_tx = $objp->tva_tx;
  2672. }
  2673. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2674. if (!empty($user->rights->stock->lire)) {
  2675. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2676. if ($objp->stock > 0) {
  2677. $outval .= ' - <span class="product_line_stock_ok">';
  2678. } elseif ($objp->stock <= 0) {
  2679. $outval .= ' - <span class="product_line_stock_too_low">';
  2680. }
  2681. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2682. $outval .= '</span>';
  2683. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2684. $langs->load("stocks");
  2685. $tmpproduct = new Product($this->db);
  2686. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2687. $tmpproduct->load_virtual_stock();
  2688. $virtualstock = $tmpproduct->stock_theorique;
  2689. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2690. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2691. if ($virtualstock > 0) {
  2692. $outval .= '<span class="product_line_stock_ok">';
  2693. } elseif ($virtualstock <= 0) {
  2694. $outval .= '<span class="product_line_stock_too_low">';
  2695. }
  2696. $outval .= $virtualstock;
  2697. $outval .= '</span>';
  2698. unset($tmpproduct);
  2699. }
  2700. }
  2701. }
  2702. $opt .= "</option>\n";
  2703. $optJson = array(
  2704. 'key'=>$outkey,
  2705. 'value'=>$outref,
  2706. 'label'=>$outval,
  2707. 'label2'=>$outlabel,
  2708. 'desc'=>$outdesc,
  2709. 'type'=>$outtype,
  2710. 'price_ht'=>price2num($outprice_ht),
  2711. 'price_ttc'=>price2num($outprice_ttc),
  2712. 'pricebasetype'=>$outpricebasetype,
  2713. 'tva_tx'=>$outtva_tx, 'qty'=>$outqty,
  2714. 'discount'=>$outdiscount,
  2715. 'duration_value'=>$outdurationvalue,
  2716. 'duration_unit'=>$outdurationunit,
  2717. 'pbq'=>$outpbq,
  2718. 'labeltrans'=>$outlabel_translated,
  2719. 'desctrans'=>$outdesc_translated,
  2720. 'ref_customer'=>$outrefcust
  2721. );
  2722. }
  2723. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2724. /**
  2725. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2726. *
  2727. * @param int $socid Id third party
  2728. * @param string $selected Preselected product
  2729. * @param string $htmlname Name of HTML Select
  2730. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2731. * @param string $filtre For a SQL filter
  2732. * @param array $ajaxoptions Options for ajax_autocompleter
  2733. * @param int $hidelabel Hide label (0=no, 1=yes)
  2734. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2735. * @param string $morecss More CSS
  2736. * @param string $placeholder Placeholder
  2737. * @return void
  2738. */
  2739. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2740. {
  2741. // phpcs:enable
  2742. global $langs, $conf;
  2743. global $price_level, $status, $finished;
  2744. if (!isset($status)) {
  2745. $status = 1;
  2746. }
  2747. $selected_input_value = '';
  2748. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2749. if ($selected > 0) {
  2750. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2751. $producttmpselect = new Product($this->db);
  2752. $producttmpselect->fetch($selected);
  2753. $selected_input_value = $producttmpselect->ref;
  2754. unset($producttmpselect);
  2755. }
  2756. // mode=2 means suppliers products
  2757. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2758. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2759. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2760. } else {
  2761. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2762. }
  2763. }
  2764. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2765. /**
  2766. * Return list of suppliers products
  2767. *
  2768. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2769. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2770. * @param string $htmlname Name of HTML select
  2771. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2772. * @param string $filtre Generic filter. Data must not come from user input.
  2773. * @param string $filterkey Filter of produdts
  2774. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2775. * @param int $outputmode 0=HTML select string, 1=Array
  2776. * @param int $limit Limit of line number
  2777. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2778. * @param string $morecss Add more CSS
  2779. * @param int $showstockinlist Show stock information (slower).
  2780. * @param string $placeholder Placeholder
  2781. * @return array Array of keys for json
  2782. */
  2783. public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '', $showstockinlist = 0, $placeholder = '')
  2784. {
  2785. // phpcs:enable
  2786. global $langs, $conf, $db, $user;
  2787. $out = '';
  2788. $outarray = array();
  2789. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2790. $langs->load('stocks');
  2791. // Units
  2792. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2793. $langs->load('other');
  2794. }
  2795. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2796. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2797. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  2798. $sql .= " pfp.supplier_reputation";
  2799. // if we use supplier description of the products
  2800. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2801. $sql .= " ,pfp.desc_fourn as description";
  2802. } else {
  2803. $sql .= " ,p.description";
  2804. }
  2805. // Units
  2806. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2807. $sql .= ", u.label as unit_long, u.short_label as unit_short, p.weight, p.weight_units, p.length, p.length_units, p.width, p.width_units, p.height, p.height_units, p.surface, p.surface_units, p.volume, p.volume_units";
  2808. }
  2809. if (!empty($conf->barcode->enabled)) {
  2810. $sql .= ", pfp.barcode";
  2811. }
  2812. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2813. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2814. if ($socid > 0) {
  2815. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2816. }
  2817. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2818. // Units
  2819. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2820. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  2821. }
  2822. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2823. if ($statut != -1) {
  2824. $sql .= " AND p.tobuy = ".((int) $statut);
  2825. }
  2826. if (strval($filtertype) != '') {
  2827. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2828. }
  2829. if (!empty($filtre)) {
  2830. $sql .= " ".$filtre;
  2831. }
  2832. // Add criteria on ref/label
  2833. if ($filterkey != '') {
  2834. $sql .= ' AND (';
  2835. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2836. // For natural search
  2837. $scrit = explode(' ', $filterkey);
  2838. $i = 0;
  2839. if (count($scrit) > 1) {
  2840. $sql .= "(";
  2841. }
  2842. foreach ($scrit as $crit) {
  2843. if ($i > 0) {
  2844. $sql .= " AND ";
  2845. }
  2846. $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)."%'";
  2847. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2848. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2849. }
  2850. $sql .= ")";
  2851. $i++;
  2852. }
  2853. if (count($scrit) > 1) {
  2854. $sql .= ")";
  2855. }
  2856. if (!empty($conf->barcode->enabled)) {
  2857. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2858. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2859. }
  2860. $sql .= ')';
  2861. }
  2862. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2863. $sql .= $this->db->plimit($limit, 0);
  2864. // Build output string
  2865. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2866. $result = $this->db->query($sql);
  2867. if ($result) {
  2868. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2869. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2870. $num = $this->db->num_rows($result);
  2871. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2872. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2873. if (!$selected) {
  2874. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2875. } else {
  2876. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  2877. }
  2878. $i = 0;
  2879. while ($i < $num) {
  2880. $objp = $this->db->fetch_object($result);
  2881. $outkey = $objp->idprodfournprice; // id in table of price
  2882. if (!$outkey && $alsoproductwithnosupplierprice) {
  2883. $outkey = 'idprod_'.$objp->rowid; // id of product
  2884. }
  2885. $outref = $objp->ref;
  2886. $outval = '';
  2887. $outbarcode = $objp->barcode;
  2888. $outqty = 1;
  2889. $outdiscount = 0;
  2890. $outtype = $objp->fk_product_type;
  2891. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2892. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2893. // Units
  2894. $outvalUnits = '';
  2895. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2896. if (!empty($objp->unit_short)) {
  2897. $outvalUnits .= ' - '.$objp->unit_short;
  2898. }
  2899. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2900. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2901. $outvalUnits .= ' - '.$unitToShow;
  2902. }
  2903. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2904. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2905. $outvalUnits .= ' - '.$unitToShow;
  2906. }
  2907. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2908. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2909. $outvalUnits .= ' - '.$unitToShow;
  2910. }
  2911. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2912. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2913. $outvalUnits .= ' - '.$unitToShow;
  2914. }
  2915. if ($outdurationvalue && $outdurationunit) {
  2916. $da = array(
  2917. 'h' => $langs->trans('Hour'),
  2918. 'd' => $langs->trans('Day'),
  2919. 'w' => $langs->trans('Week'),
  2920. 'm' => $langs->trans('Month'),
  2921. 'y' => $langs->trans('Year')
  2922. );
  2923. if (isset($da[$outdurationunit])) {
  2924. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2925. }
  2926. }
  2927. }
  2928. $objRef = $objp->ref;
  2929. if ($filterkey && $filterkey != '') {
  2930. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2931. }
  2932. $objRefFourn = $objp->ref_fourn;
  2933. if ($filterkey && $filterkey != '') {
  2934. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  2935. }
  2936. $label = $objp->label;
  2937. if ($filterkey && $filterkey != '') {
  2938. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2939. }
  2940. $optlabel = $objp->ref;
  2941. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2942. $optlabel .= ' <span class=\'opacitymedium\'>('.$objp->ref_fourn.')</span>';
  2943. }
  2944. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2945. $optlabel .= ' ('.$outbarcode.')';
  2946. }
  2947. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2948. $outvallabel = $objRef;
  2949. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2950. $outvallabel .= ' ('.$objRefFourn.')';
  2951. }
  2952. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2953. $outvallabel .= ' ('.$outbarcode.')';
  2954. }
  2955. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2956. // Units
  2957. $optlabel .= $outvalUnits;
  2958. $outvallabel .= $outvalUnits;
  2959. if (!empty($objp->idprodfournprice)) {
  2960. $outqty = $objp->quantity;
  2961. $outdiscount = $objp->remise_percent;
  2962. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2963. $prod_supplier = new ProductFournisseur($this->db);
  2964. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2965. $prod_supplier->id = $objp->fk_product;
  2966. $prod_supplier->fourn_qty = $objp->quantity;
  2967. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2968. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2969. $priceparser = new PriceParser($this->db);
  2970. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2971. if ($price_result >= 0) {
  2972. $objp->fprice = $price_result;
  2973. if ($objp->quantity >= 1) {
  2974. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  2975. }
  2976. }
  2977. }
  2978. if ($objp->quantity == 1) {
  2979. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2980. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  2981. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2982. $outvallabel .= $langs->transnoentities("Unit");
  2983. } else {
  2984. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2985. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2986. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2987. $outvallabel .= ' '.$langs->transnoentities("Units");
  2988. }
  2989. if ($objp->quantity > 1) {
  2990. $optlabel .= " (".price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2991. $outvallabel .= " (".price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2992. }
  2993. if ($objp->remise_percent >= 1) {
  2994. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2995. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2996. }
  2997. if ($objp->duration) {
  2998. $optlabel .= " - ".$objp->duration;
  2999. $outvallabel .= " - ".$objp->duration;
  3000. }
  3001. if (!$socid) {
  3002. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3003. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3004. }
  3005. if ($objp->supplier_reputation) {
  3006. //TODO dictionary
  3007. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3008. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3009. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3010. }
  3011. } else {
  3012. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3013. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3014. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3015. } else // No supplier price defined for product, even on other suppliers
  3016. {
  3017. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3018. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3019. }
  3020. }
  3021. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3022. $novirtualstock = ($showstockinlist == 2);
  3023. if (!empty($user->rights->stock->lire)) {
  3024. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3025. if ($objp->stock > 0) {
  3026. $optlabel .= ' - <span class="product_line_stock_ok">';
  3027. } elseif ($objp->stock <= 0) {
  3028. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3029. }
  3030. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3031. $optlabel .= '</span>';
  3032. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3033. $langs->load("stocks");
  3034. $tmpproduct = new Product($this->db);
  3035. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3036. $tmpproduct->load_virtual_stock();
  3037. $virtualstock = $tmpproduct->stock_theorique;
  3038. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3039. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3040. if ($virtualstock > 0) {
  3041. $optlabel .= '<span class="product_line_stock_ok">';
  3042. } elseif ($virtualstock <= 0) {
  3043. $optlabel .= '<span class="product_line_stock_too_low">';
  3044. }
  3045. $optlabel .= $virtualstock;
  3046. $optlabel .= '</span>';
  3047. unset($tmpproduct);
  3048. }
  3049. }
  3050. }
  3051. $opt = '<option value="'.$outkey.'"';
  3052. if ($selected && $selected == $objp->idprodfournprice) {
  3053. $opt .= ' selected';
  3054. }
  3055. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3056. $opt .= ' disabled';
  3057. }
  3058. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3059. $opt .= ' data-product-id="'.$objp->rowid.'" data-price-id="'.$objp->idprodfournprice.'" data-qty="'.$objp->quantity.'" data-up="'.$objp->unitprice.'" data-discount="'.$outdiscount.'"';
  3060. }
  3061. $opt .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3062. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  3063. $opt .= '>';
  3064. $opt .= $optlabel;
  3065. $outval .= $outvallabel;
  3066. $opt .= "</option>\n";
  3067. // Add new entry
  3068. // "key" value of json key array is used by jQuery automatically as selected value. Example: 'type' = product or service, 'price_ht' = unit price without tax
  3069. // "label" value of json key array is used by jQuery automatically as text for combo box
  3070. $out .= $opt;
  3071. array_push(
  3072. $outarray,
  3073. array('key'=>$outkey,
  3074. 'value'=>$outref,
  3075. 'label'=>$outval,
  3076. 'qty'=>$outqty,
  3077. 'price_ht'=>price2num($objp->unitprice, 'MT'),
  3078. 'discount'=>$outdiscount,
  3079. 'type'=>$outtype,
  3080. 'duration_value'=>$outdurationvalue,
  3081. 'duration_unit'=>$outdurationunit,
  3082. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3083. 'description'=>$objp->description
  3084. )
  3085. );
  3086. // Exemple of var_dump $outarray
  3087. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3088. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3089. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3090. //}
  3091. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3092. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3093. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3094. $i++;
  3095. }
  3096. $out .= '</select>';
  3097. $this->db->free($result);
  3098. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3099. $out .= ajax_combobox($htmlname);
  3100. if (empty($outputmode)) {
  3101. return $out;
  3102. }
  3103. return $outarray;
  3104. } else {
  3105. dol_print_error($this->db);
  3106. }
  3107. }
  3108. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3109. /**
  3110. * Return list of suppliers prices for a product
  3111. *
  3112. * @param int $productid Id of product
  3113. * @param string $htmlname Name of HTML field
  3114. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3115. * @return string
  3116. */
  3117. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3118. {
  3119. // phpcs:enable
  3120. global $langs, $conf;
  3121. $langs->load('stocks');
  3122. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3123. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3124. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3125. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  3126. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3127. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  3128. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3129. $sql .= " AND p.tobuy = 1";
  3130. $sql .= " AND s.fournisseur = 1";
  3131. $sql .= " AND p.rowid = ".((int) $productid);
  3132. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3133. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3134. $result = $this->db->query($sql);
  3135. if ($result) {
  3136. $num = $this->db->num_rows($result);
  3137. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3138. if (!$num) {
  3139. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3140. } else {
  3141. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3142. $form .= '<option value="0">&nbsp;</option>';
  3143. $i = 0;
  3144. while ($i < $num) {
  3145. $objp = $this->db->fetch_object($result);
  3146. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3147. //if there is only one supplier, preselect it
  3148. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  3149. $opt .= ' selected';
  3150. }
  3151. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3152. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3153. $prod_supplier = new ProductFournisseur($this->db);
  3154. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3155. $prod_supplier->id = $productid;
  3156. $prod_supplier->fourn_qty = $objp->quantity;
  3157. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3158. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3159. $priceparser = new PriceParser($this->db);
  3160. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3161. if ($price_result >= 0) {
  3162. $objp->fprice = $price_result;
  3163. if ($objp->quantity >= 1) {
  3164. $objp->unitprice = $objp->fprice / $objp->quantity;
  3165. }
  3166. }
  3167. }
  3168. if ($objp->quantity == 1) {
  3169. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3170. }
  3171. $opt .= $objp->quantity.' ';
  3172. if ($objp->quantity == 1) {
  3173. $opt .= $langs->trans("Unit");
  3174. } else {
  3175. $opt .= $langs->trans("Units");
  3176. }
  3177. if ($objp->quantity > 1) {
  3178. $opt .= " - ";
  3179. $opt .= price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
  3180. }
  3181. if ($objp->duration) {
  3182. $opt .= " - ".$objp->duration;
  3183. }
  3184. $opt .= "</option>\n";
  3185. $form .= $opt;
  3186. $i++;
  3187. }
  3188. }
  3189. $form .= '</select>';
  3190. $this->db->free($result);
  3191. return $form;
  3192. } else {
  3193. dol_print_error($this->db);
  3194. }
  3195. }
  3196. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3197. /**
  3198. * Return list of delivery address
  3199. *
  3200. * @param string $selected Id contact pre-selectionn
  3201. * @param int $socid Id of company
  3202. * @param string $htmlname Name of HTML field
  3203. * @param int $showempty Add an empty field
  3204. * @return integer|null
  3205. */
  3206. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3207. {
  3208. // phpcs:enable
  3209. // looking for users
  3210. $sql = "SELECT a.rowid, a.label";
  3211. $sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a";
  3212. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3213. $sql .= " ORDER BY a.label ASC";
  3214. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3215. $resql = $this->db->query($sql);
  3216. if ($resql) {
  3217. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3218. if ($showempty) {
  3219. print '<option value="0">&nbsp;</option>';
  3220. }
  3221. $num = $this->db->num_rows($resql);
  3222. $i = 0;
  3223. if ($num) {
  3224. while ($i < $num) {
  3225. $obj = $this->db->fetch_object($resql);
  3226. if ($selected && $selected == $obj->rowid) {
  3227. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3228. } else {
  3229. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3230. }
  3231. $i++;
  3232. }
  3233. }
  3234. print '</select>';
  3235. return $num;
  3236. } else {
  3237. dol_print_error($this->db);
  3238. }
  3239. }
  3240. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3241. /**
  3242. * Load into cache list of payment terms
  3243. *
  3244. * @return int Nb of lines loaded, <0 if KO
  3245. */
  3246. public function load_cache_conditions_paiements()
  3247. {
  3248. // phpcs:enable
  3249. global $langs;
  3250. $num = count($this->cache_conditions_paiements);
  3251. if ($num > 0) {
  3252. return 0; // Cache already loaded
  3253. }
  3254. dol_syslog(__METHOD__, LOG_DEBUG);
  3255. $sql = "SELECT rowid, code, libelle as label";
  3256. $sql .= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  3257. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3258. $sql .= " AND active > 0";
  3259. $sql .= " ORDER BY sortorder";
  3260. $resql = $this->db->query($sql);
  3261. if ($resql) {
  3262. $num = $this->db->num_rows($resql);
  3263. $i = 0;
  3264. while ($i < $num) {
  3265. $obj = $this->db->fetch_object($resql);
  3266. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3267. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3268. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3269. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3270. $i++;
  3271. }
  3272. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3273. return $num;
  3274. } else {
  3275. dol_print_error($this->db);
  3276. return -1;
  3277. }
  3278. }
  3279. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3280. /**
  3281. * Charge dans cache la liste des délais de livraison possibles
  3282. *
  3283. * @return int Nb of lines loaded, <0 if KO
  3284. */
  3285. public function load_cache_availability()
  3286. {
  3287. // phpcs:enable
  3288. global $langs;
  3289. $num = count($this->cache_availability);
  3290. if ($num > 0) {
  3291. return 0; // Cache already loaded
  3292. }
  3293. dol_syslog(__METHOD__, LOG_DEBUG);
  3294. $langs->load('propal');
  3295. $sql = "SELECT rowid, code, label, position";
  3296. $sql .= " FROM ".MAIN_DB_PREFIX.'c_availability';
  3297. $sql .= " WHERE active > 0";
  3298. $resql = $this->db->query($sql);
  3299. if ($resql) {
  3300. $num = $this->db->num_rows($resql);
  3301. $i = 0;
  3302. while ($i < $num) {
  3303. $obj = $this->db->fetch_object($resql);
  3304. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3305. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3306. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3307. $this->cache_availability[$obj->rowid]['label'] = $label;
  3308. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3309. $i++;
  3310. }
  3311. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3312. return $num;
  3313. } else {
  3314. dol_print_error($this->db);
  3315. return -1;
  3316. }
  3317. }
  3318. /**
  3319. * Retourne la liste des types de delais de livraison possibles
  3320. *
  3321. * @param int $selected Id du type de delais pre-selectionne
  3322. * @param string $htmlname Nom de la zone select
  3323. * @param string $filtertype To add a filter
  3324. * @param int $addempty Add empty entry
  3325. * @param string $morecss More CSS
  3326. * @return void
  3327. */
  3328. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3329. {
  3330. global $langs, $user;
  3331. $this->load_cache_availability();
  3332. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3333. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3334. if ($addempty) {
  3335. print '<option value="0">&nbsp;</option>';
  3336. }
  3337. foreach ($this->cache_availability as $id => $arrayavailability) {
  3338. if ($selected == $id) {
  3339. print '<option value="'.$id.'" selected>';
  3340. } else {
  3341. print '<option value="'.$id.'">';
  3342. }
  3343. print dol_escape_htmltag($arrayavailability['label']);
  3344. print '</option>';
  3345. }
  3346. print '</select>';
  3347. if ($user->admin) {
  3348. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3349. }
  3350. print ajax_combobox($htmlname);
  3351. }
  3352. /**
  3353. * Load into cache cache_demand_reason, array of input reasons
  3354. *
  3355. * @return int Nb of lines loaded, <0 if KO
  3356. */
  3357. public function loadCacheInputReason()
  3358. {
  3359. global $langs;
  3360. $num = count($this->cache_demand_reason);
  3361. if ($num > 0) {
  3362. return 0; // Cache already loaded
  3363. }
  3364. $sql = "SELECT rowid, code, label";
  3365. $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  3366. $sql .= " WHERE active > 0";
  3367. $resql = $this->db->query($sql);
  3368. if ($resql) {
  3369. $num = $this->db->num_rows($resql);
  3370. $i = 0;
  3371. $tmparray = array();
  3372. while ($i < $num) {
  3373. $obj = $this->db->fetch_object($resql);
  3374. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3375. $label = ($obj->label != '-' ? $obj->label : '');
  3376. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3377. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3378. }
  3379. if ($langs->trans($obj->code) != $obj->code) {
  3380. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3381. }
  3382. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3383. $tmparray[$obj->rowid]['code'] = $obj->code;
  3384. $tmparray[$obj->rowid]['label'] = $label;
  3385. $i++;
  3386. }
  3387. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3388. unset($tmparray);
  3389. return $num;
  3390. } else {
  3391. dol_print_error($this->db);
  3392. return -1;
  3393. }
  3394. }
  3395. /**
  3396. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3397. * List found into table c_input_reason loaded by loadCacheInputReason
  3398. *
  3399. * @param int $selected Id or code of type origin to select by default
  3400. * @param string $htmlname Nom de la zone select
  3401. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3402. * @param int $addempty Add an empty entry
  3403. * @param string $morecss Add more css to the HTML select component
  3404. * @param int $notooltip Do not show the tooltip for admin
  3405. * @return void
  3406. */
  3407. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3408. {
  3409. global $langs, $user;
  3410. $this->loadCacheInputReason();
  3411. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3412. if ($addempty) {
  3413. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3414. }
  3415. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3416. if ($arraydemandreason['code'] == $exclude) {
  3417. continue;
  3418. }
  3419. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3420. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3421. } else {
  3422. print '<option value="'.$arraydemandreason['id'].'">';
  3423. }
  3424. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3425. print $langs->trans($label);
  3426. print '</option>';
  3427. }
  3428. print '</select>';
  3429. if ($user->admin && empty($notooltip)) {
  3430. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3431. }
  3432. print ajax_combobox('select_'.$htmlname);
  3433. }
  3434. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3435. /**
  3436. * Charge dans cache la liste des types de paiements possibles
  3437. *
  3438. * @return int Nb of lines loaded, <0 if KO
  3439. */
  3440. public function load_cache_types_paiements()
  3441. {
  3442. // phpcs:enable
  3443. global $langs;
  3444. $num = count($this->cache_types_paiements);
  3445. if ($num > 0) {
  3446. return $num; // Cache already loaded
  3447. }
  3448. dol_syslog(__METHOD__, LOG_DEBUG);
  3449. $this->cache_types_paiements = array();
  3450. $sql = "SELECT id, code, libelle as label, type, active";
  3451. $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement";
  3452. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3453. $resql = $this->db->query($sql);
  3454. if ($resql) {
  3455. $num = $this->db->num_rows($resql);
  3456. $i = 0;
  3457. while ($i < $num) {
  3458. $obj = $this->db->fetch_object($resql);
  3459. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3460. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3461. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3462. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3463. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3464. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3465. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3466. $i++;
  3467. }
  3468. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3469. return $num;
  3470. } else {
  3471. dol_print_error($this->db);
  3472. return -1;
  3473. }
  3474. }
  3475. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3476. /**
  3477. * Return list of payment modes.
  3478. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3479. * See instead to force the default value by the caller.
  3480. *
  3481. * @param int $selected Id of payment term to preselect by default
  3482. * @param string $htmlname Nom de la zone select
  3483. * @param int $filtertype Not used
  3484. * @param int $addempty Add an empty entry
  3485. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3486. * @param string $morecss Add more CSS on select tag
  3487. * @return void
  3488. */
  3489. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
  3490. {
  3491. // phpcs:enable
  3492. global $langs, $user, $conf;
  3493. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3494. $this->load_cache_conditions_paiements();
  3495. // Set default value if not already set by caller
  3496. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3497. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3498. }
  3499. print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3500. if ($addempty) {
  3501. print '<option value="0">&nbsp;</option>';
  3502. }
  3503. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3504. if ($selected == $id) {
  3505. print '<option value="'.$id.'" selected>';
  3506. } else {
  3507. print '<option value="'.$id.'">';
  3508. }
  3509. print $arrayconditions['label'];
  3510. print '</option>';
  3511. }
  3512. print '</select>';
  3513. if ($user->admin && empty($noinfoadmin)) {
  3514. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3515. }
  3516. print ajax_combobox($htmlname);
  3517. }
  3518. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3519. /**
  3520. * Return list of payment methods
  3521. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3522. *
  3523. * @param string $selected Id or code or preselected payment mode
  3524. * @param string $htmlname Name of select field
  3525. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3526. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3527. * @param int $empty 1=can be empty, 0 otherwise
  3528. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3529. * @param int $maxlength Max length of label
  3530. * @param int $active Active or not, -1 = all
  3531. * @param string $morecss Add more CSS on select tag
  3532. * @param int $nooutput 1=Return string, do not send to output
  3533. * @return void
  3534. */
  3535. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3536. {
  3537. // phpcs:enable
  3538. global $langs, $user, $conf;
  3539. $out = '';
  3540. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3541. $filterarray = array();
  3542. if ($filtertype == 'CRDT') {
  3543. $filterarray = array(0, 2, 3);
  3544. } elseif ($filtertype == 'DBIT') {
  3545. $filterarray = array(1, 2, 3);
  3546. } elseif ($filtertype != '' && $filtertype != '-1') {
  3547. $filterarray = explode(',', $filtertype);
  3548. }
  3549. $this->load_cache_types_paiements();
  3550. // Set default value if not already set by caller
  3551. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3552. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3553. }
  3554. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3555. if ($empty) {
  3556. $out .= '<option value="">&nbsp;</option>';
  3557. }
  3558. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3559. // If not good status
  3560. if ($active >= 0 && $arraytypes['active'] != $active) {
  3561. continue;
  3562. }
  3563. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3564. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3565. continue;
  3566. }
  3567. // We discard empty line if showempty is on because an empty line has already been output.
  3568. if ($empty && empty($arraytypes['code'])) {
  3569. continue;
  3570. }
  3571. if ($format == 0) {
  3572. $out .= '<option value="'.$id.'"';
  3573. } elseif ($format == 1) {
  3574. $out .= '<option value="'.$arraytypes['code'].'"';
  3575. } elseif ($format == 2) {
  3576. $out .= '<option value="'.$arraytypes['code'].'"';
  3577. } elseif ($format == 3) {
  3578. $out .= '<option value="'.$id.'"';
  3579. }
  3580. // Print attribute selected or not
  3581. if ($format == 1 || $format == 2) {
  3582. if ($selected == $arraytypes['code']) {
  3583. $out .= ' selected';
  3584. }
  3585. } else {
  3586. if ($selected == $id) {
  3587. $out .= ' selected';
  3588. }
  3589. }
  3590. $out .= '>';
  3591. if ($format == 0) {
  3592. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3593. } elseif ($format == 1) {
  3594. $value = $arraytypes['code'];
  3595. } elseif ($format == 2) {
  3596. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3597. } elseif ($format == 3) {
  3598. $value = $arraytypes['code'];
  3599. }
  3600. $out .= $value ? $value : '&nbsp;';
  3601. $out .= '</option>';
  3602. }
  3603. $out .= '</select>';
  3604. if ($user->admin && !$noadmininfo) {
  3605. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3606. }
  3607. $out .= ajax_combobox('select'.$htmlname);
  3608. if (empty($nooutput)) {
  3609. print $out;
  3610. } else {
  3611. return $out;
  3612. }
  3613. }
  3614. /**
  3615. * Selection HT or TTC
  3616. *
  3617. * @param string $selected Id pre-selectionne
  3618. * @param string $htmlname Nom de la zone select
  3619. * @param string $addjscombo Add js combo
  3620. * @return string Code of HTML select to chose tax or not
  3621. */
  3622. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3623. {
  3624. global $langs;
  3625. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3626. $options = array(
  3627. 'HT'=>$langs->trans("HT"),
  3628. 'TTC'=>$langs->trans("TTC")
  3629. );
  3630. foreach ($options as $id => $value) {
  3631. if ($selected == $id) {
  3632. $return .= '<option value="'.$id.'" selected>'.$value;
  3633. } else {
  3634. $return .= '<option value="'.$id.'">'.$value;
  3635. }
  3636. $return .= '</option>';
  3637. }
  3638. $return .= '</select>';
  3639. if ($addjscombo) {
  3640. $return .= ajax_combobox('select_'.$htmlname);
  3641. }
  3642. return $return;
  3643. }
  3644. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3645. /**
  3646. * Load in cache list of transport mode
  3647. *
  3648. * @return int Nb of lines loaded, <0 if KO
  3649. */
  3650. public function load_cache_transport_mode()
  3651. {
  3652. // phpcs:enable
  3653. global $langs;
  3654. $num = count($this->cache_transport_mode);
  3655. if ($num > 0) {
  3656. return $num; // Cache already loaded
  3657. }
  3658. dol_syslog(__METHOD__, LOG_DEBUG);
  3659. $this->cache_transport_mode = array();
  3660. $sql = "SELECT rowid, code, label, active";
  3661. $sql .= " FROM ".MAIN_DB_PREFIX."c_transport_mode";
  3662. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3663. $resql = $this->db->query($sql);
  3664. if ($resql) {
  3665. $num = $this->db->num_rows($resql);
  3666. $i = 0;
  3667. while ($i < $num) {
  3668. $obj = $this->db->fetch_object($resql);
  3669. // If traduction exist, we use it else we take the default label
  3670. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3671. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3672. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3673. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3674. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3675. $i++;
  3676. }
  3677. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3678. return $num;
  3679. } else {
  3680. dol_print_error($this->db);
  3681. return -1;
  3682. }
  3683. }
  3684. /**
  3685. * Return list of transport mode for intracomm report
  3686. *
  3687. * @param string $selected Id of the transport mode pre-selected
  3688. * @param string $htmlname Name of the select field
  3689. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3690. * @param int $empty 1=can be empty, 0 else
  3691. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3692. * @param int $maxlength Max length of label
  3693. * @param int $active Active or not, -1 = all
  3694. * @param string $morecss Add more CSS on select tag
  3695. * @return void
  3696. */
  3697. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3698. {
  3699. global $langs, $user;
  3700. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3701. $this->load_cache_transport_mode();
  3702. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3703. if ($empty) {
  3704. print '<option value="">&nbsp;</option>';
  3705. }
  3706. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3707. // If not good status
  3708. if ($active >= 0 && $arraytypes['active'] != $active) {
  3709. continue;
  3710. }
  3711. // We discard empty line if showempty is on because an empty line has already been output.
  3712. if ($empty && empty($arraytypes['code'])) {
  3713. continue;
  3714. }
  3715. if ($format == 0) {
  3716. print '<option value="'.$id.'"';
  3717. } elseif ($format == 1) {
  3718. print '<option value="'.$arraytypes['code'].'"';
  3719. } elseif ($format == 2) {
  3720. print '<option value="'.$arraytypes['code'].'"';
  3721. } elseif ($format == 3) {
  3722. print '<option value="'.$id.'"';
  3723. }
  3724. // If text is selected, we compare with code, else with id
  3725. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  3726. print ' selected';
  3727. } elseif ($selected == $id) {
  3728. print ' selected';
  3729. }
  3730. print '>';
  3731. if ($format == 0) {
  3732. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3733. } elseif ($format == 1) {
  3734. $value = $arraytypes['code'];
  3735. } elseif ($format == 2) {
  3736. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3737. } elseif ($format == 3) {
  3738. $value = $arraytypes['code'];
  3739. }
  3740. print $value ? $value : '&nbsp;';
  3741. print '</option>';
  3742. }
  3743. print '</select>';
  3744. if ($user->admin && !$noadmininfo) {
  3745. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3746. }
  3747. }
  3748. /**
  3749. * Return a HTML select list of shipping mode
  3750. *
  3751. * @param string $selected Id shipping mode pre-selected
  3752. * @param string $htmlname Name of select zone
  3753. * @param string $filtre To filter list. This parameter must not come from input of users
  3754. * @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.
  3755. * @param string $moreattrib To add more attribute on select
  3756. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3757. * @param string $morecss More CSS
  3758. * @return void
  3759. */
  3760. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  3761. {
  3762. global $langs, $conf, $user;
  3763. $langs->load("admin");
  3764. $langs->load("deliveries");
  3765. $sql = "SELECT rowid, code, libelle as label";
  3766. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  3767. $sql .= " WHERE active > 0";
  3768. if ($filtre) {
  3769. $sql .= " AND ".$filtre;
  3770. }
  3771. $sql .= " ORDER BY libelle ASC";
  3772. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3773. $result = $this->db->query($sql);
  3774. if ($result) {
  3775. $num = $this->db->num_rows($result);
  3776. $i = 0;
  3777. if ($num) {
  3778. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3779. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3780. print '<option value="-1">&nbsp;</option>';
  3781. }
  3782. while ($i < $num) {
  3783. $obj = $this->db->fetch_object($result);
  3784. if ($selected == $obj->rowid) {
  3785. print '<option value="'.$obj->rowid.'" selected>';
  3786. } else {
  3787. print '<option value="'.$obj->rowid.'">';
  3788. }
  3789. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3790. print '</option>';
  3791. $i++;
  3792. }
  3793. print "</select>";
  3794. if ($user->admin && empty($noinfoadmin)) {
  3795. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3796. }
  3797. print ajax_combobox('select'.$htmlname);
  3798. } else {
  3799. print $langs->trans("NoShippingMethodDefined");
  3800. }
  3801. } else {
  3802. dol_print_error($this->db);
  3803. }
  3804. }
  3805. /**
  3806. * Display form to select shipping mode
  3807. *
  3808. * @param string $page Page
  3809. * @param int $selected Id of shipping mode
  3810. * @param string $htmlname Name of select html field
  3811. * @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.
  3812. * @return void
  3813. */
  3814. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3815. {
  3816. global $langs, $db;
  3817. $langs->load("deliveries");
  3818. if ($htmlname != "none") {
  3819. print '<form method="POST" action="'.$page.'">';
  3820. print '<input type="hidden" name="action" value="setshippingmethod">';
  3821. print '<input type="hidden" name="token" value="'.newToken().'">';
  3822. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3823. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3824. print '</form>';
  3825. } else {
  3826. if ($selected) {
  3827. $code = $langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3828. print $langs->trans("SendingMethod".strtoupper($code));
  3829. } else {
  3830. print "&nbsp;";
  3831. }
  3832. }
  3833. }
  3834. /**
  3835. * Creates HTML last in cycle situation invoices selector
  3836. *
  3837. * @param string $selected Preselected ID
  3838. * @param int $socid Company ID
  3839. *
  3840. * @return string HTML select
  3841. */
  3842. public function selectSituationInvoices($selected = '', $socid = 0)
  3843. {
  3844. global $langs;
  3845. $langs->load('bills');
  3846. $opt = '<option value ="" selected></option>';
  3847. $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc';
  3848. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture';
  3849. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  3850. $sql .= ' AND situation_counter >= 1';
  3851. $sql .= ' AND fk_soc = '.(int) $socid;
  3852. $sql .= ' AND type <> 2';
  3853. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  3854. $resql = $this->db->query($sql);
  3855. if ($resql && $this->db->num_rows($resql) > 0) {
  3856. // Last seen cycle
  3857. $ref = 0;
  3858. while ($obj = $this->db->fetch_object($resql)) {
  3859. //Same cycle ?
  3860. if ($obj->situation_cycle_ref != $ref) {
  3861. // Just seen this cycle
  3862. $ref = $obj->situation_cycle_ref;
  3863. //not final ?
  3864. if ($obj->situation_final != 1) {
  3865. //Not prov?
  3866. if (substr($obj->ref, 1, 4) != 'PROV') {
  3867. if ($selected == $obj->rowid) {
  3868. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  3869. } else {
  3870. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  3871. }
  3872. }
  3873. }
  3874. }
  3875. }
  3876. } else {
  3877. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  3878. }
  3879. if ($opt == '<option value ="" selected></option>') {
  3880. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  3881. }
  3882. return $opt;
  3883. }
  3884. /**
  3885. * Creates HTML units selector (code => label)
  3886. *
  3887. * @param string $selected Preselected Unit ID
  3888. * @param string $htmlname Select name
  3889. * @param int $showempty Add a nempty line
  3890. * @param string $unit_type Restrict to one given unit type
  3891. * @return string HTML select
  3892. */
  3893. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  3894. {
  3895. global $langs;
  3896. $langs->load('products');
  3897. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  3898. $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
  3899. $sql .= ' WHERE active > 0';
  3900. if (!empty($unit_type)) {
  3901. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  3902. }
  3903. $resql = $this->db->query($sql);
  3904. if ($resql && $this->db->num_rows($resql) > 0) {
  3905. if ($showempty) {
  3906. $return .= '<option value="none"></option>';
  3907. }
  3908. while ($res = $this->db->fetch_object($resql)) {
  3909. $unitLabel = $res->label;
  3910. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  3911. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  3912. }
  3913. if ($selected == $res->rowid) {
  3914. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  3915. } else {
  3916. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  3917. }
  3918. }
  3919. $return .= '</select>';
  3920. }
  3921. return $return;
  3922. }
  3923. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3924. /**
  3925. * Return a HTML select list of bank accounts
  3926. *
  3927. * @param string $selected Id account pre-selected
  3928. * @param string $htmlname Name of select zone
  3929. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  3930. * @param string $filtre To filter list. This parameter must not come from input of users
  3931. * @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.
  3932. * @param string $moreattrib To add more attribute on select
  3933. * @param int $showcurrency Show currency in label
  3934. * @param string $morecss More CSS
  3935. * @param int $nooutput 1=Return string, do not send to output
  3936. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  3937. */
  3938. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  3939. {
  3940. // phpcs:enable
  3941. global $langs, $conf;
  3942. $out = '';
  3943. $langs->load("admin");
  3944. $num = 0;
  3945. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  3946. $sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
  3947. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  3948. if ($status != 2) {
  3949. $sql .= " AND clos = ".(int) $status;
  3950. }
  3951. if ($filtre) {
  3952. $sql .= " AND ".$filtre;
  3953. }
  3954. $sql .= " ORDER BY label";
  3955. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  3956. $result = $this->db->query($sql);
  3957. if ($result) {
  3958. $num = $this->db->num_rows($result);
  3959. $i = 0;
  3960. if ($num) {
  3961. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3962. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3963. $out .= '<option value="-1">&nbsp;</option>';
  3964. }
  3965. while ($i < $num) {
  3966. $obj = $this->db->fetch_object($result);
  3967. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  3968. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  3969. } else {
  3970. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  3971. }
  3972. $out .= trim($obj->label);
  3973. if ($showcurrency) {
  3974. $out .= ' ('.$obj->currency_code.')';
  3975. }
  3976. if ($status == 2 && $obj->status == 1) {
  3977. $out .= ' ('.$langs->trans("Closed").')';
  3978. }
  3979. $out .= '</option>';
  3980. $i++;
  3981. }
  3982. $out .= "</select>";
  3983. $out .= ajax_combobox('select'.$htmlname);
  3984. } else {
  3985. if ($status == 0) {
  3986. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  3987. } else {
  3988. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  3989. }
  3990. }
  3991. } else {
  3992. dol_print_error($this->db);
  3993. }
  3994. // Output or return
  3995. if (empty($nooutput)) {
  3996. print $out;
  3997. } else {
  3998. return $out;
  3999. }
  4000. return $num;
  4001. }
  4002. /**
  4003. * Return a HTML select list of establishment
  4004. *
  4005. * @param string $selected Id establishment pre-selected
  4006. * @param string $htmlname Name of select zone
  4007. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4008. * @param string $filtre To filter list. This parameter must not come from input of users
  4009. * @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.
  4010. * @param string $moreattrib To add more attribute on select
  4011. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4012. */
  4013. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4014. {
  4015. global $langs, $conf;
  4016. $langs->load("admin");
  4017. $num = 0;
  4018. $sql = "SELECT rowid, name, fk_country, status, entity";
  4019. $sql .= " FROM ".MAIN_DB_PREFIX."establishment";
  4020. $sql .= " WHERE 1=1";
  4021. if ($status != 2) {
  4022. $sql .= " AND status = ".(int) $status;
  4023. }
  4024. if ($filtre) {
  4025. $sql .= " AND ".$filtre;
  4026. }
  4027. $sql .= " ORDER BY name";
  4028. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4029. $result = $this->db->query($sql);
  4030. if ($result) {
  4031. $num = $this->db->num_rows($result);
  4032. $i = 0;
  4033. if ($num) {
  4034. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4035. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4036. print '<option value="-1">&nbsp;</option>';
  4037. }
  4038. while ($i < $num) {
  4039. $obj = $this->db->fetch_object($result);
  4040. if ($selected == $obj->rowid) {
  4041. print '<option value="'.$obj->rowid.'" selected>';
  4042. } else {
  4043. print '<option value="'.$obj->rowid.'">';
  4044. }
  4045. print trim($obj->name);
  4046. if ($status == 2 && $obj->status == 1) {
  4047. print ' ('.$langs->trans("Closed").')';
  4048. }
  4049. print '</option>';
  4050. $i++;
  4051. }
  4052. print "</select>";
  4053. } else {
  4054. if ($status == 0) {
  4055. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4056. } else {
  4057. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4058. }
  4059. }
  4060. } else {
  4061. dol_print_error($this->db);
  4062. }
  4063. }
  4064. /**
  4065. * Display form to select bank account
  4066. *
  4067. * @param string $page Page
  4068. * @param int $selected Id of bank account
  4069. * @param string $htmlname Name of select html field
  4070. * @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.
  4071. * @return void
  4072. */
  4073. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4074. {
  4075. global $langs;
  4076. if ($htmlname != "none") {
  4077. print '<form method="POST" action="'.$page.'">';
  4078. print '<input type="hidden" name="action" value="setbankaccount">';
  4079. print '<input type="hidden" name="token" value="'.newToken().'">';
  4080. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4081. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4082. if ($nbaccountfound > 0) {
  4083. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4084. }
  4085. print '</form>';
  4086. } else {
  4087. $langs->load('banks');
  4088. if ($selected) {
  4089. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4090. $bankstatic = new Account($this->db);
  4091. $result = $bankstatic->fetch($selected);
  4092. if ($result) {
  4093. print $bankstatic->getNomUrl(1);
  4094. }
  4095. } else {
  4096. print "&nbsp;";
  4097. }
  4098. }
  4099. }
  4100. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4101. /**
  4102. * Return list of categories having choosed type
  4103. *
  4104. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4105. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4106. * @param string $htmlname HTML field name
  4107. * @param int $maxlength Maximum length for labels
  4108. * @param int|string|array $markafterid Keep only or removed all categories including the leaf $markafterid in category tree (exclude) or Keep only of category is inside the leaf starting with this id.
  4109. * $markafterid can be an :
  4110. * - int (id of category)
  4111. * - string (categories ids seprated by comma)
  4112. * - array (list of categories ids)
  4113. * @param int $outputmode 0=HTML select string, 1=Array
  4114. * @param int $include [=0] Removed or 1=Keep only
  4115. * @param string $morecss More CSS
  4116. * @return string
  4117. * @see select_categories()
  4118. */
  4119. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4120. {
  4121. // phpcs:enable
  4122. global $conf, $langs;
  4123. $langs->load("categories");
  4124. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4125. // For backward compatibility
  4126. if (is_numeric($type)) {
  4127. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4128. }
  4129. if ($type === Categorie::TYPE_BANK_LINE) {
  4130. // TODO Move this into common category feature
  4131. $cate_arbo = array();
  4132. $sql = "SELECT c.label, c.rowid";
  4133. $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  4134. $sql .= " WHERE entity = ".$conf->entity;
  4135. $sql .= " ORDER BY c.label";
  4136. $result = $this->db->query($sql);
  4137. if ($result) {
  4138. $num = $this->db->num_rows($result);
  4139. $i = 0;
  4140. while ($i < $num) {
  4141. $objp = $this->db->fetch_object($result);
  4142. if ($objp) {
  4143. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  4144. }
  4145. $i++;
  4146. }
  4147. $this->db->free($result);
  4148. } else {
  4149. dol_print_error($this->db);
  4150. }
  4151. } else {
  4152. $cat = new Categorie($this->db);
  4153. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4154. }
  4155. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4156. $outarray = array();
  4157. if (is_array($cate_arbo)) {
  4158. if (!count($cate_arbo)) {
  4159. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4160. } else {
  4161. $output .= '<option value="-1">&nbsp;</option>';
  4162. foreach ($cate_arbo as $key => $value) {
  4163. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4164. $add = 'selected ';
  4165. } else {
  4166. $add = '';
  4167. }
  4168. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  4169. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4170. }
  4171. }
  4172. }
  4173. $output .= '</select>';
  4174. $output .= "\n";
  4175. if ($outputmode) {
  4176. return $outarray;
  4177. }
  4178. return $output;
  4179. }
  4180. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4181. /**
  4182. * Show a confirmation HTML form or AJAX popup
  4183. *
  4184. * @param string $page Url of page to call if confirmation is OK
  4185. * @param string $title Title
  4186. * @param string $question Question
  4187. * @param string $action Action
  4188. * @param array $formquestion An array with forms complementary inputs
  4189. * @param string $selectedchoice "" or "no" or "yes"
  4190. * @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
  4191. * @param int $height Force height of box
  4192. * @param int $width Force width of box
  4193. * @return void
  4194. * @deprecated
  4195. * @see formconfirm()
  4196. */
  4197. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4198. {
  4199. // phpcs:enable
  4200. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4201. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4202. }
  4203. /**
  4204. * Show a confirmation HTML form or AJAX popup.
  4205. * Easiest way to use this is with useajax=1.
  4206. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4207. * just after calling this method. For example:
  4208. * print '<script type="text/javascript">'."\n";
  4209. * print 'jQuery(document).ready(function() {'."\n";
  4210. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4211. * print '});'."\n";
  4212. * print '</script>'."\n";
  4213. *
  4214. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4215. * @param string $title Title
  4216. * @param string $question Question
  4217. * @param string $action Action
  4218. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>))
  4219. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', 'other' or 'onecolumn'...
  4220. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  4221. * @param int|string $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4222. * @param int|string $height Force height of box (0 = auto)
  4223. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4224. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4225. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4226. */
  4227. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  4228. {
  4229. global $langs, $conf;
  4230. $more = '<!-- formconfirm before calling page='.dol_escape_htmltag($page).' -->';
  4231. $formconfirm = '';
  4232. $inputok = array();
  4233. $inputko = array();
  4234. // Clean parameters
  4235. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4236. if ($conf->browser->layout == 'phone') {
  4237. $width = '95%';
  4238. }
  4239. // Set height automatically if not defined
  4240. if (empty($height)) {
  4241. $height = 220;
  4242. if (is_array($formquestion) && count($formquestion) > 2) {
  4243. $height += ((count($formquestion) - 2) * 24);
  4244. }
  4245. }
  4246. if (is_array($formquestion) && !empty($formquestion)) {
  4247. // First add hidden fields and value
  4248. foreach ($formquestion as $key => $input) {
  4249. if (is_array($input) && !empty($input)) {
  4250. if ($input['type'] == 'hidden') {
  4251. $more .= '<input type="hidden" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  4252. }
  4253. }
  4254. }
  4255. // Now add questions
  4256. $moreonecolumn = '';
  4257. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4258. foreach ($formquestion as $key => $input) {
  4259. if (is_array($input) && !empty($input)) {
  4260. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4261. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4262. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4263. if ($input['type'] == 'text') {
  4264. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="text" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4265. } elseif ($input['type'] == 'password') {
  4266. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="password" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4267. } elseif ($input['type'] == 'textarea') {
  4268. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4269. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4270. $more .= $input['value'];
  4271. $more .= '</textarea>';
  4272. $more .= '</div></div>'."\n";*/
  4273. $moreonecolumn .= '<div class="margintoponly">';
  4274. $moreonecolumn .= $input['label'].'<br>';
  4275. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4276. $moreonecolumn .= $input['value'];
  4277. $moreonecolumn .= '</textarea>';
  4278. $moreonecolumn .= '</div>';
  4279. } elseif ($input['type'] == 'select') {
  4280. if (empty($morecss)) {
  4281. $morecss = 'minwidth100';
  4282. }
  4283. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4284. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4285. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4286. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4287. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4288. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4289. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4290. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4291. if (!empty($input['label'])) {
  4292. $more .= $input['label'].'</div><div class="tagtd left">';
  4293. }
  4294. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4295. $more .= '</div></div>'."\n";
  4296. } elseif ($input['type'] == 'checkbox') {
  4297. $more .= '<div class="tagtr">';
  4298. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4299. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4300. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') {
  4301. $more .= ' checked';
  4302. }
  4303. if (is_bool($input['value']) && $input['value']) {
  4304. $more .= ' checked';
  4305. }
  4306. if (isset($input['disabled'])) {
  4307. $more .= ' disabled';
  4308. }
  4309. $more .= ' /></div>';
  4310. $more .= '</div>'."\n";
  4311. } elseif ($input['type'] == 'radio') {
  4312. $i = 0;
  4313. foreach ($input['values'] as $selkey => $selval) {
  4314. $more .= '<div class="tagtr">';
  4315. if ($i == 0) {
  4316. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4317. } else {
  4318. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4319. }
  4320. $more .= '<div class="tagtd'.($i == 0 ? ' tdtop' : '').'"><input type="radio" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name'].$selkey).'" name="'.dol_escape_htmltag($input['name']).'" value="'.$selkey.'"'.$moreattr;
  4321. if ($input['disabled']) {
  4322. $more .= ' disabled';
  4323. }
  4324. if (isset($input['default']) && $input['default'] === $selkey) {
  4325. $more .= ' checked="checked"';
  4326. }
  4327. $more .= ' /> ';
  4328. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'">'.$selval.'</label>';
  4329. $more .= '</div></div>'."\n";
  4330. $i++;
  4331. }
  4332. } elseif ($input['type'] == 'date') {
  4333. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4334. $more .= '<div class="tagtd">';
  4335. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4336. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4337. $more .= '</div></div>'."\n";
  4338. $formquestion[] = array('name'=>$input['name'].'day');
  4339. $formquestion[] = array('name'=>$input['name'].'month');
  4340. $formquestion[] = array('name'=>$input['name'].'year');
  4341. $formquestion[] = array('name'=>$input['name'].'hour');
  4342. $formquestion[] = array('name'=>$input['name'].'min');
  4343. } elseif ($input['type'] == 'other') {
  4344. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4345. if (!empty($input['label'])) {
  4346. $more .= $input['label'].'</div><div class="tagtd">';
  4347. }
  4348. $more .= $input['value'];
  4349. $more .= '</div></div>'."\n";
  4350. } elseif ($input['type'] == 'onecolumn') {
  4351. $moreonecolumn .= '<div class="margintoponly">';
  4352. $moreonecolumn .= $input['value'];
  4353. $moreonecolumn .= '</div>'."\n";
  4354. } elseif ($input['type'] == 'hidden') {
  4355. // Do nothing more, already added by a previous loop
  4356. } else {
  4357. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4358. }
  4359. }
  4360. }
  4361. $more .= '</div>'."\n";
  4362. $more .= $moreonecolumn;
  4363. }
  4364. // JQUI method dialog is broken with jmobile, we use standard HTML.
  4365. // 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
  4366. // See page product/card.php for example
  4367. if (!empty($conf->dol_use_jmobile)) {
  4368. $useajax = 0;
  4369. }
  4370. if (empty($conf->use_javascript_ajax)) {
  4371. $useajax = 0;
  4372. }
  4373. if ($useajax) {
  4374. $autoOpen = true;
  4375. $dialogconfirm = 'dialog-confirm';
  4376. $button = '';
  4377. if (!is_numeric($useajax)) {
  4378. $button = $useajax;
  4379. $useajax = 1;
  4380. $autoOpen = false;
  4381. $dialogconfirm .= '-'.$button;
  4382. }
  4383. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes';
  4384. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : '');
  4385. // Add input fields into list of fields to read during submit (inputok and inputko)
  4386. if (is_array($formquestion)) {
  4387. foreach ($formquestion as $key => $input) {
  4388. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4389. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4390. if (is_array($input) && isset($input['name'])) {
  4391. if (strpos($input['name'], ',') > 0) {
  4392. $inputok = array_merge($inputok, explode(',', $input['name']));
  4393. } else {
  4394. array_push($inputok, $input['name']);
  4395. }
  4396. }
  4397. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4398. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4399. array_push($inputko, $input['name']);
  4400. }
  4401. }
  4402. }
  4403. // Show JQuery confirm box.
  4404. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4405. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4406. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4407. }
  4408. if (!empty($more)) {
  4409. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4410. }
  4411. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4412. $formconfirm .= '</div>'."\n";
  4413. $formconfirm .= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
  4414. $formconfirm .= '<script type="text/javascript">'."\n";
  4415. $formconfirm .= 'jQuery(document).ready(function() {
  4416. $(function() {
  4417. $( "#'.$dialogconfirm.'" ).dialog(
  4418. {
  4419. autoOpen: '.($autoOpen ? "true" : "false").',';
  4420. if ($newselectedchoice == 'no') {
  4421. $formconfirm .= '
  4422. open: function() {
  4423. $(this).parent().find("button.ui-button:eq(2)").focus();
  4424. },';
  4425. }
  4426. $formconfirm .= '
  4427. resizable: false,
  4428. height: "'.$height.'",
  4429. width: "'.$width.'",
  4430. modal: true,
  4431. closeOnEscape: false,
  4432. buttons: {
  4433. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  4434. var options = "&token='.urlencode(newToken()).'";
  4435. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4436. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4437. if (inputok.length>0) {
  4438. $.each(inputok, function(i, inputname) {
  4439. var more = "";
  4440. var inputvalue;
  4441. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4442. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4443. } else {
  4444. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4445. inputvalue = $("#" + inputname + more).val();
  4446. }
  4447. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4448. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4449. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4450. });
  4451. }
  4452. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  4453. if (pageyes.length > 0) { location.href = urljump; }
  4454. $(this).dialog("close");
  4455. },
  4456. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  4457. var options = "&token='.urlencode(newToken()).'";
  4458. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4459. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4460. if (inputko.length>0) {
  4461. $.each(inputko, function(i, inputname) {
  4462. var more = "";
  4463. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4464. var inputvalue = $("#" + inputname + more).val();
  4465. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4466. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4467. });
  4468. }
  4469. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  4470. //alert(urljump);
  4471. if (pageno.length > 0) { location.href = urljump; }
  4472. $(this).dialog("close");
  4473. }
  4474. }
  4475. }
  4476. );
  4477. var button = "'.$button.'";
  4478. if (button.length > 0) {
  4479. $( "#" + button ).click(function() {
  4480. $("#'.$dialogconfirm.'").dialog("open");
  4481. });
  4482. }
  4483. });
  4484. });
  4485. </script>';
  4486. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4487. } else {
  4488. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4489. if (empty($disableformtag)) {
  4490. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4491. }
  4492. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4493. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4494. $formconfirm .= '<table class="valid centpercent">'."\n";
  4495. // Line title
  4496. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4497. $formconfirm .= img_picto('', 'recent').' '.$title;
  4498. $formconfirm .= '</td></tr>'."\n";
  4499. // Line text
  4500. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4501. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4502. }
  4503. // Line form fields
  4504. if ($more) {
  4505. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4506. $formconfirm .= $more;
  4507. $formconfirm .= '</td></tr>'."\n";
  4508. }
  4509. // Line with question
  4510. $formconfirm .= '<tr class="valid">';
  4511. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4512. $formconfirm .= '<td class="valid center">';
  4513. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly');
  4514. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton" type="submit" value="'.$langs->trans("Validate").'">';
  4515. $formconfirm .= '</td>';
  4516. $formconfirm .= '</tr>'."\n";
  4517. $formconfirm .= '</table>'."\n";
  4518. if (empty($disableformtag)) {
  4519. $formconfirm .= "</form>\n";
  4520. }
  4521. $formconfirm .= '<br>';
  4522. if (empty($conf->use_javascript_ajax)) {
  4523. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4524. $formconfirm .= '<script type="text/javascript">'."\n";
  4525. $formconfirm .= '
  4526. $(document).ready(function () {
  4527. $(".confirmvalidatebutton").on("click", function() {
  4528. console.log("We click on button");
  4529. $(this).attr("disabled", "disabled");
  4530. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4531. //console.log($(this).closest("form"));
  4532. $(this).closest("form").submit();
  4533. });
  4534. });
  4535. ';
  4536. $formconfirm .= '</script>'."\n";
  4537. }
  4538. $formconfirm .= "<!-- end formconfirm -->\n";
  4539. }
  4540. return $formconfirm;
  4541. }
  4542. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4543. /**
  4544. * Show a form to select a project
  4545. *
  4546. * @param int $page Page
  4547. * @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)
  4548. * @param int $selected Id pre-selected project
  4549. * @param string $htmlname Name of select field
  4550. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4551. * @param int $maxlength Max length
  4552. * @param int $forcefocus Force focus on field (works with javascript only)
  4553. * @param int $nooutput No print is done. String is returned.
  4554. * @return string Return html content
  4555. */
  4556. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4557. {
  4558. // phpcs:enable
  4559. global $langs;
  4560. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4561. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4562. $out = '';
  4563. $formproject = new FormProjets($this->db);
  4564. $langs->load("project");
  4565. if ($htmlname != "none") {
  4566. $out .= "\n";
  4567. $out .= '<form method="post" action="'.$page.'">';
  4568. $out .= '<input type="hidden" name="action" value="classin">';
  4569. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4570. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4571. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4572. $out .= '</form>';
  4573. } else {
  4574. if ($selected) {
  4575. $projet = new Project($this->db);
  4576. $projet->fetch($selected);
  4577. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  4578. $out .= $projet->getNomUrl(0, '', 1);
  4579. } else {
  4580. $out .= "&nbsp;";
  4581. }
  4582. }
  4583. if (empty($nooutput)) {
  4584. print $out;
  4585. return '';
  4586. }
  4587. return $out;
  4588. }
  4589. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4590. /**
  4591. * Show a form to select payment conditions
  4592. *
  4593. * @param int $page Page
  4594. * @param string $selected Id condition pre-selectionne
  4595. * @param string $htmlname Name of select html field
  4596. * @param int $addempty Add empty entry
  4597. * @return void
  4598. */
  4599. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0)
  4600. {
  4601. // phpcs:enable
  4602. global $langs;
  4603. if ($htmlname != "none") {
  4604. print '<form method="post" action="'.$page.'">';
  4605. print '<input type="hidden" name="action" value="setconditions">';
  4606. print '<input type="hidden" name="token" value="'.newToken().'">';
  4607. $this->select_conditions_paiements($selected, $htmlname, -1, $addempty);
  4608. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4609. print '</form>';
  4610. } else {
  4611. if ($selected) {
  4612. $this->load_cache_conditions_paiements();
  4613. if (isset($this->cache_conditions_paiements[$selected])) {
  4614. print $this->cache_conditions_paiements[$selected]['label'];
  4615. } else {
  4616. $langs->load('errors');
  4617. print $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4618. }
  4619. } else {
  4620. print "&nbsp;";
  4621. }
  4622. }
  4623. }
  4624. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4625. /**
  4626. * Show a form to select a delivery delay
  4627. *
  4628. * @param int $page Page
  4629. * @param string $selected Id condition pre-selectionne
  4630. * @param string $htmlname Name of select html field
  4631. * @param int $addempty Ajoute entree vide
  4632. * @return void
  4633. */
  4634. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4635. {
  4636. // phpcs:enable
  4637. global $langs;
  4638. if ($htmlname != "none") {
  4639. print '<form method="post" action="'.$page.'">';
  4640. print '<input type="hidden" name="action" value="setavailability">';
  4641. print '<input type="hidden" name="token" value="'.newToken().'">';
  4642. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4643. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4644. print '</form>';
  4645. } else {
  4646. if ($selected) {
  4647. $this->load_cache_availability();
  4648. print $this->cache_availability[$selected]['label'];
  4649. } else {
  4650. print "&nbsp;";
  4651. }
  4652. }
  4653. }
  4654. /**
  4655. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4656. * List found into table c_input_reason loaded by loadCacheInputReason
  4657. *
  4658. * @param string $page Page
  4659. * @param string $selected Id condition pre-selectionne
  4660. * @param string $htmlname Name of select html field
  4661. * @param int $addempty Add empty entry
  4662. * @return void
  4663. */
  4664. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4665. {
  4666. global $langs;
  4667. if ($htmlname != "none") {
  4668. print '<form method="post" action="'.$page.'">';
  4669. print '<input type="hidden" name="action" value="setdemandreason">';
  4670. print '<input type="hidden" name="token" value="'.newToken().'">';
  4671. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4672. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4673. print '</form>';
  4674. } else {
  4675. if ($selected) {
  4676. $this->loadCacheInputReason();
  4677. foreach ($this->cache_demand_reason as $key => $val) {
  4678. if ($val['id'] == $selected) {
  4679. print $val['label'];
  4680. break;
  4681. }
  4682. }
  4683. } else {
  4684. print "&nbsp;";
  4685. }
  4686. }
  4687. }
  4688. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4689. /**
  4690. * Show a form + html select a date
  4691. *
  4692. * @param string $page Page
  4693. * @param string $selected Date preselected
  4694. * @param string $htmlname Html name of date input fields or 'none'
  4695. * @param int $displayhour Display hour selector
  4696. * @param int $displaymin Display minutes selector
  4697. * @param int $nooutput 1=No print output, return string
  4698. * @return string
  4699. * @see selectDate()
  4700. */
  4701. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0)
  4702. {
  4703. // phpcs:enable
  4704. global $langs;
  4705. $ret = '';
  4706. if ($htmlname != "none") {
  4707. $ret .= '<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  4708. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4709. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4710. $ret .= '<table class="nobordernopadding">';
  4711. $ret .= '<tr><td>';
  4712. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4713. $ret .= '</td>';
  4714. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4715. $ret .= '</tr></table></form>';
  4716. } else {
  4717. if ($displayhour) {
  4718. $ret .= dol_print_date($selected, 'dayhour');
  4719. } else {
  4720. $ret .= dol_print_date($selected, 'day');
  4721. }
  4722. }
  4723. if (empty($nooutput)) {
  4724. print $ret;
  4725. }
  4726. return $ret;
  4727. }
  4728. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4729. /**
  4730. * Show a select form to choose a user
  4731. *
  4732. * @param string $page Page
  4733. * @param string $selected Id of user preselected
  4734. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4735. * @param array $exclude List of users id to exclude
  4736. * @param array $include List of users id to include
  4737. * @return void
  4738. */
  4739. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4740. {
  4741. // phpcs:enable
  4742. global $langs;
  4743. if ($htmlname != "none") {
  4744. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4745. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4746. print '<input type="hidden" name="token" value="'.newToken().'">';
  4747. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4748. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4749. print '</form>';
  4750. } else {
  4751. if ($selected) {
  4752. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4753. $theuser = new User($this->db);
  4754. $theuser->fetch($selected);
  4755. print $theuser->getNomUrl(1);
  4756. } else {
  4757. print "&nbsp;";
  4758. }
  4759. }
  4760. }
  4761. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4762. /**
  4763. * Show form with payment mode
  4764. *
  4765. * @param string $page Page
  4766. * @param int $selected Id mode pre-selectionne
  4767. * @param string $htmlname Name of select html field
  4768. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  4769. * @param int $active Active or not, -1 = all
  4770. * @param int $addempty 1=Add empty entry
  4771. * @return void
  4772. */
  4773. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0)
  4774. {
  4775. // phpcs:enable
  4776. global $langs;
  4777. if ($htmlname != "none") {
  4778. print '<form method="POST" action="'.$page.'">';
  4779. print '<input type="hidden" name="action" value="setmode">';
  4780. print '<input type="hidden" name="token" value="'.newToken().'">';
  4781. $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active);
  4782. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4783. print '</form>';
  4784. } else {
  4785. if ($selected) {
  4786. $this->load_cache_types_paiements();
  4787. print $this->cache_types_paiements[$selected]['label'];
  4788. } else {
  4789. print "&nbsp;";
  4790. }
  4791. }
  4792. }
  4793. /**
  4794. * Show form with transport mode
  4795. *
  4796. * @param string $page Page
  4797. * @param int $selected Id mode pre-select
  4798. * @param string $htmlname Name of select html field
  4799. * @param int $active Active or not, -1 = all
  4800. * @param int $addempty 1=Add empty entry
  4801. * @return void
  4802. */
  4803. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  4804. {
  4805. global $langs;
  4806. if ($htmlname != "none") {
  4807. print '<form method="POST" action="'.$page.'">';
  4808. print '<input type="hidden" name="action" value="settransportmode">';
  4809. print '<input type="hidden" name="token" value="'.newToken().'">';
  4810. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  4811. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4812. print '</form>';
  4813. } else {
  4814. if ($selected) {
  4815. $this->load_cache_transport_mode();
  4816. print $this->cache_transport_mode[$selected]['label'];
  4817. } else {
  4818. print "&nbsp;";
  4819. }
  4820. }
  4821. }
  4822. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4823. /**
  4824. * Show form with multicurrency code
  4825. *
  4826. * @param string $page Page
  4827. * @param string $selected code pre-selectionne
  4828. * @param string $htmlname Name of select html field
  4829. * @return void
  4830. */
  4831. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  4832. {
  4833. // phpcs:enable
  4834. global $langs;
  4835. if ($htmlname != "none") {
  4836. print '<form method="POST" action="'.$page.'">';
  4837. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  4838. print '<input type="hidden" name="token" value="'.newToken().'">';
  4839. print $this->selectMultiCurrency($selected, $htmlname, 0);
  4840. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4841. print '</form>';
  4842. } else {
  4843. dol_include_once('/core/lib/company.lib.php');
  4844. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  4845. }
  4846. }
  4847. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4848. /**
  4849. * Show form with multicurrency rate
  4850. *
  4851. * @param string $page Page
  4852. * @param double $rate Current rate
  4853. * @param string $htmlname Name of select html field
  4854. * @param string $currency Currency code to explain the rate
  4855. * @return void
  4856. */
  4857. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  4858. {
  4859. // phpcs:enable
  4860. global $langs, $mysoc, $conf;
  4861. if ($htmlname != "none") {
  4862. print '<form method="POST" action="'.$page.'">';
  4863. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  4864. print '<input type="hidden" name="token" value="'.newToken().'">';
  4865. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  4866. print '<select name="calculation_mode">';
  4867. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  4868. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  4869. print '</select> ';
  4870. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4871. print '</form>';
  4872. } else {
  4873. if (!empty($rate)) {
  4874. print price($rate, 1, $langs, 1, 0);
  4875. if ($currency && $rate != 1) {
  4876. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  4877. }
  4878. } else {
  4879. print 1;
  4880. }
  4881. }
  4882. }
  4883. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4884. /**
  4885. * Show a select box with available absolute discounts
  4886. *
  4887. * @param string $page Page URL where form is shown
  4888. * @param int $selected Value pre-selected
  4889. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  4890. * @param int $socid Third party id
  4891. * @param float $amount Total amount available
  4892. * @param string $filter SQL filter on discounts
  4893. * @param int $maxvalue Max value for lines that can be selected
  4894. * @param string $more More string to add
  4895. * @param int $hidelist 1=Hide list
  4896. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  4897. * @return void
  4898. */
  4899. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  4900. {
  4901. // phpcs:enable
  4902. global $conf, $langs;
  4903. if ($htmlname != "none") {
  4904. print '<form method="post" action="'.$page.'">';
  4905. print '<input type="hidden" name="action" value="setabsolutediscount">';
  4906. print '<input type="hidden" name="token" value="'.newToken().'">';
  4907. print '<div class="inline-block">';
  4908. if (!empty($discount_type)) {
  4909. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  4910. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  4911. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4912. } else {
  4913. $translationKey = 'HasCreditNoteFromSupplier';
  4914. }
  4915. } else {
  4916. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  4917. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  4918. } else {
  4919. $translationKey = 'HasCreditNoteFromSupplier';
  4920. }
  4921. }
  4922. } else {
  4923. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  4924. if (!$filter || $filter == "fk_facture_source IS NULL") {
  4925. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4926. } else {
  4927. $translationKey = 'CompanyHasCreditNote';
  4928. }
  4929. } else {
  4930. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  4931. $translationKey = 'CompanyHasAbsoluteDiscount';
  4932. } else {
  4933. $translationKey = 'CompanyHasCreditNote';
  4934. }
  4935. }
  4936. }
  4937. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  4938. if (empty($hidelist)) {
  4939. print ' ';
  4940. }
  4941. print '</div>';
  4942. if (empty($hidelist)) {
  4943. print '<div class="inline-block" style="padding-right: 10px">';
  4944. $newfilter = 'discount_type='.intval($discount_type);
  4945. if (!empty($discount_type)) {
  4946. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  4947. } else {
  4948. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  4949. }
  4950. if ($filter) {
  4951. $newfilter .= ' AND ('.$filter.')';
  4952. }
  4953. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  4954. if ($nbqualifiedlines > 0) {
  4955. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  4956. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  4957. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4958. }
  4959. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  4960. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4961. }
  4962. print '>';
  4963. }
  4964. print '</div>';
  4965. }
  4966. if ($more) {
  4967. print '<div class="inline-block">';
  4968. print $more;
  4969. print '</div>';
  4970. }
  4971. print '</form>';
  4972. } else {
  4973. if ($selected) {
  4974. print $selected;
  4975. } else {
  4976. print "0";
  4977. }
  4978. }
  4979. }
  4980. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4981. /**
  4982. * Show forms to select a contact
  4983. *
  4984. * @param string $page Page
  4985. * @param Societe $societe Filter on third party
  4986. * @param int $selected Id contact pre-selectionne
  4987. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  4988. * @return void
  4989. */
  4990. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  4991. {
  4992. // phpcs:enable
  4993. global $langs, $conf;
  4994. if ($htmlname != "none") {
  4995. print '<form method="post" action="'.$page.'">';
  4996. print '<input type="hidden" name="action" value="set_contact">';
  4997. print '<input type="hidden" name="token" value="'.newToken().'">';
  4998. print '<table class="nobordernopadding">';
  4999. print '<tr><td>';
  5000. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5001. $num = $this->num;
  5002. if ($num == 0) {
  5003. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5004. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5005. }
  5006. print '</td>';
  5007. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5008. print '</tr></table></form>';
  5009. } else {
  5010. if ($selected) {
  5011. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5012. $contact = new Contact($this->db);
  5013. $contact->fetch($selected);
  5014. print $contact->getFullName($langs);
  5015. } else {
  5016. print "&nbsp;";
  5017. }
  5018. }
  5019. }
  5020. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5021. /**
  5022. * Output html select to select thirdparty
  5023. *
  5024. * @param string $page Page
  5025. * @param string $selected Id preselected
  5026. * @param string $htmlname Name of HTML select
  5027. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5028. * @param int $showempty Add an empty field
  5029. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5030. * @param int $forcecombo Force to use combo box
  5031. * @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')))
  5032. * @param int $nooutput No print output. Return it only.
  5033. * @param array $excludeids Exclude IDs from the select combo
  5034. * @return void|string
  5035. */
  5036. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array())
  5037. {
  5038. // phpcs:enable
  5039. global $langs;
  5040. $out = '';
  5041. if ($htmlname != "none") {
  5042. $out .= '<form method="post" action="'.$page.'">';
  5043. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5044. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5045. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5046. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5047. $out .= '</form>';
  5048. } else {
  5049. if ($selected) {
  5050. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5051. $soc = new Societe($this->db);
  5052. $soc->fetch($selected);
  5053. $out .= $soc->getNomUrl($langs);
  5054. } else {
  5055. $out .= "&nbsp;";
  5056. }
  5057. }
  5058. if ($nooutput) {
  5059. return $out;
  5060. } else {
  5061. print $out;
  5062. }
  5063. }
  5064. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5065. /**
  5066. * Retourne la liste des devises, dans la langue de l'utilisateur
  5067. *
  5068. * @param string $selected preselected currency code
  5069. * @param string $htmlname name of HTML select list
  5070. * @deprecated
  5071. * @return void
  5072. */
  5073. public function select_currency($selected = '', $htmlname = 'currency_id')
  5074. {
  5075. // phpcs:enable
  5076. print $this->selectCurrency($selected, $htmlname);
  5077. }
  5078. /**
  5079. * Retourne la liste des devises, dans la langue de l'utilisateur
  5080. *
  5081. * @param string $selected preselected currency code
  5082. * @param string $htmlname name of HTML select list
  5083. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5084. * @return string
  5085. */
  5086. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  5087. {
  5088. global $conf, $langs, $user;
  5089. $langs->loadCacheCurrencies('');
  5090. $out = '';
  5091. if ($selected == 'euro' || $selected == 'euros') {
  5092. $selected = 'EUR'; // Pour compatibilite
  5093. }
  5094. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5095. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5096. $labeltoshow = $currency['label'];
  5097. if ($mode == 1) {
  5098. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5099. } else {
  5100. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5101. }
  5102. if ($selected && $selected == $code_iso) {
  5103. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5104. } else {
  5105. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5106. }
  5107. $out .= $labeltoshow;
  5108. $out .= '</option>';
  5109. }
  5110. $out .= '</select>';
  5111. if ($user->admin) {
  5112. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5113. }
  5114. // Make select dynamic
  5115. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5116. $out .= ajax_combobox($htmlname);
  5117. return $out;
  5118. }
  5119. /**
  5120. * Return array of currencies in user language
  5121. *
  5122. * @param string $selected preselected currency code
  5123. * @param string $htmlname name of HTML select list
  5124. * @param integer $useempty 1=Add empty line
  5125. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5126. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available. true = we are in currency_rate update , we don't want to see conf->currency in select
  5127. * @return string
  5128. */
  5129. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false)
  5130. {
  5131. global $db, $conf, $langs, $user;
  5132. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5133. $TCurrency = array();
  5134. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  5135. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5136. if ($filter) {
  5137. $sql .= " AND ".$filter;
  5138. }
  5139. $resql = $this->db->query($sql);
  5140. if ($resql) {
  5141. while ($obj = $this->db->fetch_object($resql)) {
  5142. $TCurrency[$obj->code] = $obj->code;
  5143. }
  5144. }
  5145. $out = '';
  5146. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  5147. if ($useempty) {
  5148. $out .= '<option value="">&nbsp;</option>';
  5149. }
  5150. // If company current currency not in table, we add it into list. Should always be available.
  5151. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5152. $TCurrency[$conf->currency] = $conf->currency;
  5153. }
  5154. if (count($TCurrency) > 0) {
  5155. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5156. if (isset($TCurrency[$code_iso])) {
  5157. if (!empty($selected) && $selected == $code_iso) {
  5158. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5159. } else {
  5160. $out .= '<option value="'.$code_iso.'">';
  5161. }
  5162. $out .= $currency['label'];
  5163. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5164. $out .= '</option>';
  5165. }
  5166. }
  5167. }
  5168. $out .= '</select>';
  5169. // Make select dynamic
  5170. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5171. $out .= ajax_combobox($htmlname);
  5172. return $out;
  5173. }
  5174. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5175. /**
  5176. * Load into the cache vat rates of a country
  5177. *
  5178. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5179. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5180. */
  5181. public function load_cache_vatrates($country_code)
  5182. {
  5183. // phpcs:enable
  5184. global $langs;
  5185. $num = count($this->cache_vatrates);
  5186. if ($num > 0) {
  5187. return $num; // Cache already loaded
  5188. }
  5189. dol_syslog(__METHOD__, LOG_DEBUG);
  5190. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5191. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5192. $sql .= " WHERE t.fk_pays = c.rowid";
  5193. $sql .= " AND t.active > 0";
  5194. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5195. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5196. $resql = $this->db->query($sql);
  5197. if ($resql) {
  5198. $num = $this->db->num_rows($resql);
  5199. if ($num) {
  5200. for ($i = 0; $i < $num; $i++) {
  5201. $obj = $this->db->fetch_object($resql);
  5202. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5203. $this->cache_vatrates[$i]['code'] = $obj->code;
  5204. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5205. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5206. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5207. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5208. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5209. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5210. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5211. $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
  5212. $positiverates = '';
  5213. if ($obj->taux) {
  5214. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5215. }
  5216. if ($obj->localtax1) {
  5217. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5218. }
  5219. if ($obj->localtax2) {
  5220. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5221. }
  5222. if (empty($positiverates)) {
  5223. $positiverates = '0';
  5224. }
  5225. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5226. }
  5227. return $num;
  5228. } else {
  5229. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</font>';
  5230. return -1;
  5231. }
  5232. } else {
  5233. $this->error = '<font class="error">'.$this->db->error().'</font>';
  5234. return -2;
  5235. }
  5236. }
  5237. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5238. /**
  5239. * Output an HTML select vat rate.
  5240. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5241. *
  5242. * @param string $htmlname Name of HTML select field
  5243. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5244. * @param Societe $societe_vendeuse Thirdparty seller
  5245. * @param Societe $societe_acheteuse Thirdparty buyer
  5246. * @param int $idprod Id product. O if unknown of NA.
  5247. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5248. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5249. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5250. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5251. * 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.
  5252. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5253. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5254. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5255. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5256. * @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
  5257. * @return string
  5258. */
  5259. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5260. {
  5261. // phpcs:enable
  5262. global $langs, $conf, $mysoc;
  5263. $langs->load('errors');
  5264. $return = '';
  5265. // Define defaultnpr, defaultttx and defaultcode
  5266. $defaultnpr = ($info_bits & 0x01);
  5267. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5268. $defaulttx = str_replace('*', '', $selectedrate);
  5269. $defaultcode = '';
  5270. $reg = array();
  5271. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5272. $defaultcode = $reg[1];
  5273. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5274. }
  5275. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5276. // Check parameters
  5277. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5278. if ($societe_vendeuse->id == $mysoc->id) {
  5279. $return .= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</font>';
  5280. } else {
  5281. $return .= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</font>';
  5282. }
  5283. return $return;
  5284. }
  5285. //var_dump($societe_acheteuse);
  5286. //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";
  5287. //exit;
  5288. // Define list of countries to use to search VAT rates to show
  5289. // First we defined code_country to use to find list
  5290. if (is_object($societe_vendeuse)) {
  5291. $code_country = "'".$societe_vendeuse->country_code."'";
  5292. } else {
  5293. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5294. }
  5295. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5296. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5297. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5298. // We also add the buyer
  5299. if (is_numeric($type)) {
  5300. if ($type == 1) { // We know product is a service
  5301. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5302. }
  5303. } elseif (!$idprod) { // We don't know type of product
  5304. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5305. } else {
  5306. $prodstatic = new Product($this->db);
  5307. $prodstatic->fetch($idprod);
  5308. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5309. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5310. }
  5311. }
  5312. }
  5313. }
  5314. // Now we get list
  5315. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5316. if ($num > 0) {
  5317. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5318. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5319. $tmpthirdparty = new Societe($this->db);
  5320. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5321. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5322. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5323. $defaultcode = $reg[1];
  5324. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5325. }
  5326. if (empty($defaulttx)) {
  5327. $defaultnpr = 0;
  5328. }
  5329. }
  5330. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  5331. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  5332. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5333. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5334. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5335. } else {
  5336. $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  5337. }
  5338. }
  5339. // Disabled if seller is not subject to VAT
  5340. $disabled = false;
  5341. $title = '';
  5342. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5343. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5344. // of using supplier invoices (this is a very bad idea !)
  5345. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5346. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  5347. $disabled = true;
  5348. }
  5349. }
  5350. if (!$options_only) {
  5351. $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5352. }
  5353. $selectedfound = false;
  5354. foreach ($this->cache_vatrates as $rate) {
  5355. // Keep only 0 if seller is not subject to VAT
  5356. if ($disabled && $rate['txtva'] != 0) {
  5357. continue;
  5358. }
  5359. // Define key to use into select list
  5360. $key = $rate['txtva'];
  5361. $key .= $rate['nprtva'] ? '*' : '';
  5362. if ($mode > 0 && $rate['code']) {
  5363. $key .= ' ('.$rate['code'].')';
  5364. }
  5365. if ($mode < 0) {
  5366. $key = $rate['rowid'];
  5367. }
  5368. $return .= '<option value="'.$key.'"';
  5369. if (!$selectedfound) {
  5370. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5371. if ($defaultcode == $rate['code']) {
  5372. $return .= ' selected';
  5373. $selectedfound = true;
  5374. }
  5375. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5376. $return .= ' selected';
  5377. $selectedfound = true;
  5378. }
  5379. }
  5380. $return .= '>';
  5381. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  5382. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5383. $return .= $rate['labelpositiverates'];
  5384. } else {
  5385. $return .= vatrate($rate['label']);
  5386. }
  5387. //$return.=($rate['code']?' '.$rate['code']:'');
  5388. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5389. $return .= '</option>';
  5390. }
  5391. if (!$options_only) {
  5392. $return .= '</select>';
  5393. }
  5394. } else {
  5395. $return .= $this->error;
  5396. }
  5397. $this->num = $num;
  5398. return $return;
  5399. }
  5400. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5401. /**
  5402. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5403. * Fields are preselected with :
  5404. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5405. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5406. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5407. *
  5408. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5409. * @param string $prefix Prefix for fields name
  5410. * @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
  5411. * @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
  5412. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5413. * @param string $form_name Not used
  5414. * @param int $d 1=Show days, month, years
  5415. * @param int $addnowlink Add a link "Now"
  5416. * @param int $nooutput Do not output html string but return it
  5417. * @param int $disabled Disable input fields
  5418. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5419. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5420. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5421. * @return string|void Nothing or string if nooutput is 1
  5422. * @deprecated
  5423. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5424. */
  5425. public function select_date($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $nooutput = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '')
  5426. {
  5427. // phpcs:enable
  5428. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5429. if (!empty($nooutput)) {
  5430. return $retstring;
  5431. }
  5432. print $retstring;
  5433. return;
  5434. }
  5435. /**
  5436. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5437. * Fields are preselected with :
  5438. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5439. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5440. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5441. *
  5442. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5443. * @param integer $set_time_end Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5444. * @param string $prefix Prefix for fields name
  5445. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5446. * @return string Html for selectDate
  5447. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5448. */
  5449. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0)
  5450. {
  5451. global $langs;
  5452. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5453. $ret .= '<br>';
  5454. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5455. return $ret;
  5456. }
  5457. /**
  5458. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5459. * Fields are preselected with :
  5460. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5461. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5462. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5463. *
  5464. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5465. * @param string $prefix Prefix for fields name
  5466. * @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
  5467. * @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
  5468. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5469. * @param string $form_name Not used
  5470. * @param int $d 1=Show days, month, years
  5471. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5472. * @param int $disabled Disable input fields
  5473. * @param int $fullday When a checkbox with id #fullday is checked, hours are set with 00:00 (if value if 'fulldaystart') or 23:59 (if value is 'fulldayend')
  5474. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5475. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5476. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5477. * @param int $stepminutes Specify step for minutes between 1 and 30
  5478. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5479. * @param string $placeholder Placeholder
  5480. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5481. * @return string Html for selectDate
  5482. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5483. */
  5484. public function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '', $openinghours = '', $stepminutes = 1, $labeladddateof = '', $placeholder = '', $gm = 'auto')
  5485. {
  5486. global $conf, $langs;
  5487. if ($gm === 'auto') {
  5488. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5489. }
  5490. $retstring = '';
  5491. if ($prefix == '') {
  5492. $prefix = 're';
  5493. }
  5494. if ($h == '') {
  5495. $h = 0;
  5496. }
  5497. if ($m == '') {
  5498. $m = 0;
  5499. }
  5500. $emptydate = 0;
  5501. $emptyhours = 0;
  5502. if ($stepminutes <= 0 || $stepminutes > 30) {
  5503. $stepminutes = 1;
  5504. }
  5505. if ($empty == 1) {
  5506. $emptydate = 1;
  5507. $emptyhours = 1;
  5508. }
  5509. if ($empty == 2) {
  5510. $emptydate = 0;
  5511. $emptyhours = 1;
  5512. }
  5513. $orig_set_time = $set_time;
  5514. if ($set_time === '' && $emptydate == 0) {
  5515. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5516. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5517. $set_time = dol_now($gm);
  5518. } else {
  5519. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5520. }
  5521. }
  5522. // Analysis of the pre-selection date
  5523. $reg = array();
  5524. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5525. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5526. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5527. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5528. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5529. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5530. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5531. } elseif (strval($set_time) != '' && $set_time != -1) {
  5532. // set_time est un timestamps (0 possible)
  5533. $syear = dol_print_date($set_time, "%Y", $gm);
  5534. $smonth = dol_print_date($set_time, "%m", $gm);
  5535. $sday = dol_print_date($set_time, "%d", $gm);
  5536. if ($orig_set_time != '') {
  5537. $shour = dol_print_date($set_time, "%H", $gm);
  5538. $smin = dol_print_date($set_time, "%M", $gm);
  5539. $ssec = dol_print_date($set_time, "%S", $gm);
  5540. } else {
  5541. $shour = '';
  5542. $smin = '';
  5543. $ssec = '';
  5544. }
  5545. } else {
  5546. // Date est '' ou vaut -1
  5547. $syear = '';
  5548. $smonth = '';
  5549. $sday = '';
  5550. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5551. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5552. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5553. }
  5554. if ($h == 3) {
  5555. $shour = '';
  5556. }
  5557. if ($m == 3) {
  5558. $smin = '';
  5559. }
  5560. $nowgmt = dol_now('gmt');
  5561. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5562. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5563. $usecalendar = 'combo';
  5564. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5565. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5566. }
  5567. if ($d) {
  5568. // Show date with popup
  5569. if ($usecalendar != 'combo') {
  5570. $formated_date = '';
  5571. //print "e".$set_time." t ".$conf->format_date_short;
  5572. if (strval($set_time) != '' && $set_time != -1) {
  5573. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5574. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5575. }
  5576. // Calendrier popup version eldy
  5577. if ($usecalendar == "eldy") {
  5578. // Input area to enter date manually
  5579. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5580. $retstring .= ($disabled ? ' disabled' : '');
  5581. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5582. $retstring .= '>';
  5583. // Icon calendar
  5584. $retstringbuttom = '';
  5585. if (!$disabled) {
  5586. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5587. $base = DOL_URL_ROOT.'/core/';
  5588. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5589. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5590. } else {
  5591. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5592. }
  5593. $retstring = $retstringbuttom.$retstring;
  5594. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5595. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5596. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5597. } elseif ($usecalendar == 'jquery') {
  5598. if (!$disabled) {
  5599. // Output javascript for datepicker
  5600. $retstring .= "<script type='text/javascript'>";
  5601. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5602. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5603. autoclose: true,
  5604. todayHighlight: true,";
  5605. if (!empty($conf->dol_use_jmobile)) {
  5606. $retstring .= "
  5607. beforeShow: function (input, datePicker) {
  5608. input.disabled = true;
  5609. },
  5610. onClose: function (dateText, datePicker) {
  5611. this.disabled = false;
  5612. },
  5613. ";
  5614. }
  5615. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5616. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  5617. $retstring .= "
  5618. showOn: 'button', /* both has problem with autocompletion */
  5619. buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
  5620. buttonImageOnly: true";
  5621. }
  5622. $retstring .= "
  5623. }) });";
  5624. $retstring .= "</script>";
  5625. }
  5626. // Zone de saisie manuelle de la date
  5627. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  5628. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5629. $retstring .= ($disabled ? ' disabled' : '');
  5630. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  5631. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5632. $retstring .= '>';
  5633. // Icone calendrier
  5634. if (!$disabled) {
  5635. /* Not required. Managed by option buttonImage of jquery
  5636. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5637. $retstring.="<script type='text/javascript'>";
  5638. $retstring.="jQuery(document).ready(function() {";
  5639. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5640. $retstring.=" jQuery('#".$prefix."').focus();";
  5641. $retstring.=' });';
  5642. $retstring.='});';
  5643. $retstring.="</script>";*/
  5644. } else {
  5645. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5646. $retsring = $retstringbutton.$retstring;
  5647. }
  5648. $retstring .= '</div>';
  5649. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5650. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5651. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5652. } else {
  5653. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5654. }
  5655. } else {
  5656. // Show date with combo selects
  5657. // Day
  5658. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5659. if ($emptydate || $set_time == -1) {
  5660. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5661. }
  5662. for ($day = 1; $day <= 31; $day++) {
  5663. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5664. }
  5665. $retstring .= "</select>";
  5666. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5667. if ($emptydate || $set_time == -1) {
  5668. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5669. }
  5670. // Month
  5671. for ($month = 1; $month <= 12; $month++) {
  5672. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5673. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5674. $retstring .= "</option>";
  5675. }
  5676. $retstring .= "</select>";
  5677. // Year
  5678. if ($emptydate || $set_time == -1) {
  5679. $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.'">';
  5680. } else {
  5681. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5682. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  5683. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5684. }
  5685. $retstring .= "</select>\n";
  5686. }
  5687. }
  5688. }
  5689. if ($d && $h) {
  5690. $retstring .= ($h == 2 ? '<br>' : ' ');
  5691. $retstring .= '<span class="nowraponall">';
  5692. }
  5693. if ($h) {
  5694. $hourstart = 0;
  5695. $hourend = 24;
  5696. if ($openinghours != '') {
  5697. $openinghours = explode(',', $openinghours);
  5698. $hourstart = $openinghours[0];
  5699. $hourend = $openinghours[1];
  5700. if ($hourend < $hourstart) {
  5701. $hourend = $hourstart;
  5702. }
  5703. }
  5704. // Show hour
  5705. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5706. if ($emptyhours) {
  5707. $retstring .= '<option value="-1">&nbsp;</option>';
  5708. }
  5709. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  5710. if (strlen($hour) < 2) {
  5711. $hour = "0".$hour;
  5712. }
  5713. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5714. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5715. $retstring .= '</option>';
  5716. }
  5717. $retstring .= '</select>';
  5718. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5719. if ($m) {
  5720. $retstring .= ":";
  5721. }
  5722. }
  5723. if ($m) {
  5724. // Show minutes
  5725. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  5726. if ($emptyhours) {
  5727. $retstring .= '<option value="-1">&nbsp;</option>';
  5728. }
  5729. for ($min = 0; $min < 60; $min += $stepminutes) {
  5730. if (strlen($min) < 2) {
  5731. $min = "0".$min;
  5732. }
  5733. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  5734. }
  5735. $retstring .= '</select>';
  5736. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  5737. }
  5738. if ($d && $h) {
  5739. $retstring .= '</span>';
  5740. }
  5741. // Add a "Now" link
  5742. if ($conf->use_javascript_ajax && $addnowlink) {
  5743. // Script which will be inserted in the onClick of the "Now" link
  5744. $reset_scripts = "";
  5745. if ($addnowlink == 2) { // local computer time
  5746. // pad add leading 0 on numbers
  5747. $reset_scripts .= "Number.prototype.pad = function(size) {
  5748. var s = String(this);
  5749. while (s.length < (size || 2)) {s = '0' + s;}
  5750. return s;
  5751. };
  5752. var d = new Date();";
  5753. }
  5754. // Generate the date part, depending on the use or not of the javascript calendar
  5755. if ($addnowlink == 1) { // server time expressed in user time setup
  5756. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5757. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5758. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5759. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5760. } elseif ($addnowlink == 2) {
  5761. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5762. * This break application for foreign languages.
  5763. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5764. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5765. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5766. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5767. */
  5768. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  5769. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5770. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5771. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5772. }
  5773. /*if ($usecalendar == "eldy")
  5774. {
  5775. $base=DOL_URL_ROOT.'/core/';
  5776. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5777. }
  5778. else
  5779. {
  5780. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5781. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5782. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5783. }*/
  5784. // Update the hour part
  5785. if ($h) {
  5786. if ($fullday) {
  5787. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5788. }
  5789. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5790. if ($addnowlink == 1) {
  5791. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5792. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5793. } elseif ($addnowlink == 2) {
  5794. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5795. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5796. }
  5797. if ($fullday) {
  5798. $reset_scripts .= ' } ';
  5799. }
  5800. }
  5801. // Update the minute part
  5802. if ($m) {
  5803. if ($fullday) {
  5804. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5805. }
  5806. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  5807. if ($addnowlink == 1) {
  5808. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  5809. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5810. } elseif ($addnowlink == 2) {
  5811. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  5812. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5813. }
  5814. if ($fullday) {
  5815. $reset_scripts .= ' } ';
  5816. }
  5817. }
  5818. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5819. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  5820. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  5821. $retstring .= $langs->trans("Now");
  5822. $retstring .= '</button> ';
  5823. }
  5824. }
  5825. // Add a "Plus one hour" link
  5826. if ($conf->use_javascript_ajax && $addplusone) {
  5827. // Script which will be inserted in the onClick of the "Add plusone" link
  5828. $reset_scripts = "";
  5829. // Generate the date part, depending on the use or not of the javascript calendar
  5830. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  5831. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  5832. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  5833. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  5834. // Update the hour part
  5835. if ($h) {
  5836. if ($fullday) {
  5837. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5838. }
  5839. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  5840. if ($fullday) {
  5841. $reset_scripts .= ' } ';
  5842. }
  5843. }
  5844. // Update the minute part
  5845. if ($m) {
  5846. if ($fullday) {
  5847. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5848. }
  5849. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  5850. if ($fullday) {
  5851. $reset_scripts .= ' } ';
  5852. }
  5853. }
  5854. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5855. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  5856. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  5857. $retstring .= $langs->trans("DateStartPlusOne");
  5858. $retstring .= '</button> ';
  5859. }
  5860. }
  5861. // Add a link to set data
  5862. if ($conf->use_javascript_ajax && $adddateof) {
  5863. $tmparray = dol_getdate($adddateof);
  5864. if (empty($labeladddateof)) {
  5865. $labeladddateof = $langs->trans("DateInvoice");
  5866. }
  5867. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="console.log(\'Click on now link\'); jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  5868. }
  5869. return $retstring;
  5870. }
  5871. /**
  5872. * selectTypeDuration
  5873. *
  5874. * @param string $prefix Prefix
  5875. * @param string $selected Selected duration type
  5876. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  5877. * @return string HTML select string
  5878. */
  5879. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  5880. {
  5881. global $langs;
  5882. $TDurationTypes = array(
  5883. 'y'=>$langs->trans('Years'),
  5884. 'm'=>$langs->trans('Month'),
  5885. 'w'=>$langs->trans('Weeks'),
  5886. 'd'=>$langs->trans('Days'),
  5887. 'h'=>$langs->trans('Hours'),
  5888. 'i'=>$langs->trans('Minutes')
  5889. );
  5890. // Removed undesired duration types
  5891. foreach ($excludetypes as $value) {
  5892. unset($TDurationTypes[$value]);
  5893. }
  5894. $retstring = '<select class="flat" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  5895. foreach ($TDurationTypes as $key => $typeduration) {
  5896. $retstring .= '<option value="'.$key.'"';
  5897. if ($key == $selected) {
  5898. $retstring .= " selected";
  5899. }
  5900. $retstring .= ">".$typeduration."</option>";
  5901. }
  5902. $retstring .= "</select>";
  5903. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  5904. return $retstring;
  5905. }
  5906. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5907. /**
  5908. * Function to show a form to select a duration on a page
  5909. *
  5910. * @param string $prefix Prefix for input fields
  5911. * @param int $iSecond Default preselected duration (number of seconds or '')
  5912. * @param int $disabled Disable the combo box
  5913. * @param string $typehour If 'select' then input hour and input min is a combo,
  5914. * If 'text' input hour is in text and input min is a text,
  5915. * If 'textselect' input hour is in text and input min is a combo
  5916. * @param integer $minunderhours If 1, show minutes selection under the hours
  5917. * @param int $nooutput Do not output html string but return it
  5918. * @return string|void
  5919. */
  5920. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  5921. {
  5922. // phpcs:enable
  5923. global $langs;
  5924. $retstring = '';
  5925. $hourSelected = 0;
  5926. $minSelected = 0;
  5927. // Hours
  5928. if ($iSecond != '') {
  5929. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5930. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  5931. $minSelected = convertSecondToTime($iSecond, 'min');
  5932. }
  5933. if ($typehour == 'select') {
  5934. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  5935. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  5936. $retstring .= '<option value="'.$hour.'"';
  5937. if ($hourSelected == $hour) {
  5938. $retstring .= " selected";
  5939. }
  5940. $retstring .= ">".$hour."</option>";
  5941. }
  5942. $retstring .= "</select>";
  5943. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  5944. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  5945. } else {
  5946. return 'BadValueForParameterTypeHour';
  5947. }
  5948. if ($typehour != 'text') {
  5949. $retstring .= ' '.$langs->trans('HourShort');
  5950. } else {
  5951. $retstring .= '<span class="hideonsmartphone">:</span>';
  5952. }
  5953. // Minutes
  5954. if ($minunderhours) {
  5955. $retstring .= '<br>';
  5956. } else {
  5957. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  5958. }
  5959. if ($typehour == 'select' || $typehour == 'textselect') {
  5960. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  5961. for ($min = 0; $min <= 55; $min = $min + 5) {
  5962. $retstring .= '<option value="'.$min.'"';
  5963. if ($minSelected == $min) {
  5964. $retstring .= ' selected';
  5965. }
  5966. $retstring .= '>'.$min.'</option>';
  5967. }
  5968. $retstring .= "</select>";
  5969. } elseif ($typehour == 'text') {
  5970. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  5971. }
  5972. if ($typehour != 'text') {
  5973. $retstring .= ' '.$langs->trans('MinuteShort');
  5974. }
  5975. //$retstring.="&nbsp;";
  5976. if (!empty($nooutput)) {
  5977. return $retstring;
  5978. }
  5979. print $retstring;
  5980. return;
  5981. }
  5982. /**
  5983. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  5984. *
  5985. * @param int $selected Preselected tickets
  5986. * @param string $htmlname Name of HTML select field (must be unique in page).
  5987. * @param string $filtertype To add a filter
  5988. * @param int $limit Limit on number of returned lines
  5989. * @param int $status Ticket status
  5990. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  5991. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  5992. * @param array $ajaxoptions Options for ajax_autocompleter
  5993. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  5994. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  5995. * @param int $forcecombo Force to use combo box
  5996. * @param string $morecss Add more css on select
  5997. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  5998. * @param string $nooutput No print, return the output into a string
  5999. * @return void|string
  6000. */
  6001. public function selectTickets($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6002. {
  6003. global $langs, $conf;
  6004. $out = '';
  6005. // check parameters
  6006. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6007. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6008. $placeholder = '';
  6009. if ($selected && empty($selected_input_value)) {
  6010. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6011. $tickettmpselect = new Ticket($this->db);
  6012. $tickettmpselect->fetch($selected);
  6013. $selected_input_value = $tickettmpselect->ref;
  6014. unset($tickettmpselect);
  6015. }
  6016. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6017. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6018. elseif ($hidelabel > 1) {
  6019. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6020. if ($hidelabel == 2) {
  6021. $out .= img_picto($langs->trans("Search"), 'search');
  6022. }
  6023. }
  6024. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6025. if ($hidelabel == 3) {
  6026. $out .= img_picto($langs->trans("Search"), 'search');
  6027. }
  6028. } else {
  6029. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6030. }
  6031. if (empty($nooutput)) print $out;
  6032. else return $out;
  6033. }
  6034. /**
  6035. * Return list of tickets.
  6036. * Called by selectTickets.
  6037. *
  6038. * @param int $selected Preselected ticket
  6039. * @param string $htmlname Name of select html
  6040. * @param string $filtertype Filter on ticket type
  6041. * @param int $limit Limit on number of returned lines
  6042. * @param string $filterkey Filter on ticket ref or subject
  6043. * @param int $status Ticket status
  6044. * @param int $outputmode 0=HTML select string, 1=Array
  6045. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6046. * @param int $forcecombo Force to use combo box
  6047. * @param string $morecss Add more css on select
  6048. * @return array Array of keys for json
  6049. */
  6050. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6051. {
  6052. global $langs, $conf, $user, $db;
  6053. $out = '';
  6054. $outarray = array();
  6055. $selectFields = " p.rowid, p.ref, p.message";
  6056. $sql = "SELECT ";
  6057. $sql .= $selectFields;
  6058. $sql .= " FROM ".MAIN_DB_PREFIX."ticket as p";
  6059. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6060. // Add criteria on ref/label
  6061. if ($filterkey != '') {
  6062. $sql .= ' AND (';
  6063. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6064. // For natural search
  6065. $scrit = explode(' ', $filterkey);
  6066. $i = 0;
  6067. if (count($scrit) > 1) $sql .= "(";
  6068. foreach ($scrit as $crit) {
  6069. if ($i > 0) $sql .= " AND ";
  6070. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6071. $sql .= ")";
  6072. $i++;
  6073. }
  6074. if (count($scrit) > 1) $sql .= ")";
  6075. $sql .= ')';
  6076. }
  6077. $sql .= $this->db->plimit($limit, 0);
  6078. // Build output string
  6079. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6080. $result = $this->db->query($sql);
  6081. if ($result) {
  6082. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6083. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6084. $num = $this->db->num_rows($result);
  6085. $events = null;
  6086. if (!$forcecombo) {
  6087. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6088. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6089. }
  6090. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6091. $textifempty = '';
  6092. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6093. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6094. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6095. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6096. else $textifempty .= $langs->trans("All");
  6097. } else {
  6098. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6099. }
  6100. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6101. $i = 0;
  6102. while ($num && $i < $num) {
  6103. $opt = '';
  6104. $optJson = array();
  6105. $objp = $this->db->fetch_object($result);
  6106. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6107. // Add new entry
  6108. // "key" value of json key array is used by jQuery automatically as selected value
  6109. // "label" value of json key array is used by jQuery automatically as text for combo box
  6110. $out .= $opt;
  6111. array_push($outarray, $optJson);
  6112. $i++;
  6113. }
  6114. $out .= '</select>';
  6115. $this->db->free($result);
  6116. if (empty($outputmode)) return $out;
  6117. return $outarray;
  6118. } else {
  6119. dol_print_error($db);
  6120. }
  6121. }
  6122. /**
  6123. * constructTicketListOption.
  6124. * This define value for &$opt and &$optJson.
  6125. *
  6126. * @param resource $objp Result set of fetch
  6127. * @param string $opt Option (var used for returned value in string option format)
  6128. * @param string $optJson Option (var used for returned value in json format)
  6129. * @param string $selected Preselected value
  6130. * @param string $filterkey Filter key to highlight
  6131. * @return void
  6132. */
  6133. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6134. {
  6135. global $langs, $conf, $user, $db;
  6136. $outkey = '';
  6137. $outval = '';
  6138. $outref = '';
  6139. $outlabel = '';
  6140. $outtype = '';
  6141. $label = $objp->label;
  6142. $outkey = $objp->rowid;
  6143. $outref = $objp->ref;
  6144. $outlabel = $objp->label;
  6145. $outtype = $objp->fk_product_type;
  6146. $opt = '<option value="'.$objp->rowid.'"';
  6147. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6148. $opt .= '>';
  6149. $opt .= $objp->ref;
  6150. $objRef = $objp->ref;
  6151. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6152. $outval .= $objRef;
  6153. $opt .= "</option>\n";
  6154. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtypem);
  6155. }
  6156. /**
  6157. * Generic method to select a component from a combo list.
  6158. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6159. * This is the generic method that will replace all specific existing methods.
  6160. *
  6161. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6162. * @param string $htmlname Name of HTML select component
  6163. * @param int $preselectedvalue Preselected value (ID of element)
  6164. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6165. * @param string $searchkey Search criteria
  6166. * @param string $placeholder Place holder
  6167. * @param string $morecss More CSS
  6168. * @param string $moreparams More params provided to ajax call
  6169. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6170. * @param int $disabled 1=Html component is disabled
  6171. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6172. * @return string Return HTML string
  6173. * @see selectForFormsList() select_thirdparty_list()
  6174. */
  6175. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6176. {
  6177. global $conf, $user;
  6178. $objecttmp = null;
  6179. $InfoFieldList = explode(":", $objectdesc);
  6180. $classname = $InfoFieldList[0];
  6181. $classpath = $InfoFieldList[1];
  6182. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6183. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6184. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6185. if (!empty($classpath)) {
  6186. dol_include_once($classpath);
  6187. if ($classname && class_exists($classname)) {
  6188. $objecttmp = new $classname($this->db);
  6189. // Make some replacement
  6190. $sharedentities = getEntity(strtolower($classname));
  6191. $objecttmp->filter = str_replace(
  6192. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6193. array($conf->entity, $sharedentities, $user->id),
  6194. $filter
  6195. );
  6196. }
  6197. }
  6198. if (!is_object($objecttmp)) {
  6199. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  6200. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6201. }
  6202. //var_dump($objecttmp->filter);
  6203. $prefixforautocompletemode = $objecttmp->element;
  6204. if ($prefixforautocompletemode == 'societe') {
  6205. $prefixforautocompletemode = 'company';
  6206. }
  6207. if ($prefixforautocompletemode == 'product') {
  6208. $prefixforautocompletemode = 'produit';
  6209. }
  6210. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6211. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  6212. $out = '';
  6213. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6214. // No immediate load of all database
  6215. $placeholder = '';
  6216. if ($preselectedvalue && empty($selected_input_value)) {
  6217. $objecttmp->fetch($preselectedvalue);
  6218. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6219. //unset($objecttmp);
  6220. }
  6221. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6222. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6223. // No immediate load of all database
  6224. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($objecttmp->filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6225. // Activate the auto complete using ajax call.
  6226. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6227. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6228. $out .= '<input type="text" class="'.$morecss.'"'.($disabled ? ' disabled="disabled"' : '').' name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '') .' />';
  6229. } else {
  6230. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  6231. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield);
  6232. }
  6233. return $out;
  6234. }
  6235. /**
  6236. * Function to forge a SQL criteria
  6237. *
  6238. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  6239. * @return string Forged criteria. Example: "t.field like 'abc%'"
  6240. */
  6241. protected static function forgeCriteriaCallback($matches)
  6242. {
  6243. global $db;
  6244. //dol_syslog("Convert matches ".$matches[1]);
  6245. if (empty($matches[1])) {
  6246. return '';
  6247. }
  6248. $tmp = explode(':', $matches[1]);
  6249. if (count($tmp) < 3) {
  6250. return '';
  6251. }
  6252. $tmpescaped = $tmp[2];
  6253. $regbis = array();
  6254. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  6255. $tmpescaped = "'".$db->escape($regbis[1])."'";
  6256. } else {
  6257. $tmpescaped = $db->escape($tmpescaped);
  6258. }
  6259. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  6260. }
  6261. /**
  6262. * Output html form to select an object.
  6263. * Note, this function is called by selectForForms or by ajax selectobject.php
  6264. *
  6265. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6266. * @param string $htmlname Name of HTML select component
  6267. * @param int $preselectedvalue Preselected value (ID of element)
  6268. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6269. * @param string $searchkey Search value
  6270. * @param string $placeholder Place holder
  6271. * @param string $morecss More CSS
  6272. * @param string $moreparams More params provided to ajax call
  6273. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6274. * @param int $outputmode 0=HTML select string, 1=Array
  6275. * @param int $disabled 1=Html component is disabled
  6276. * @param string $sortfield Sort field
  6277. * @return string|array Return HTML string
  6278. * @see selectForForms()
  6279. */
  6280. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '')
  6281. {
  6282. global $conf, $langs, $user, $hookmanager;
  6283. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  6284. $prefixforautocompletemode = $objecttmp->element;
  6285. if ($prefixforautocompletemode == 'societe') {
  6286. $prefixforautocompletemode = 'company';
  6287. }
  6288. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6289. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  6290. $tmpfieldstoshow = '';
  6291. foreach ($objecttmp->fields as $key => $val) {
  6292. if (!dol_eval($val['enabled'], 1, 1)) {
  6293. continue;
  6294. }
  6295. if (!empty($val['showoncombobox'])) {
  6296. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  6297. }
  6298. }
  6299. if ($tmpfieldstoshow) {
  6300. $fieldstoshow = $tmpfieldstoshow;
  6301. }
  6302. } else {
  6303. // For backward compatibility
  6304. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  6305. }
  6306. if (empty($fieldstoshow)) {
  6307. if (isset($objecttmp->fields['ref'])) {
  6308. $fieldstoshow = 't.ref';
  6309. } else {
  6310. $langs->load("errors");
  6311. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  6312. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  6313. }
  6314. }
  6315. $out = '';
  6316. $outarray = array();
  6317. $num = 0;
  6318. // Search data
  6319. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX.$objecttmp->table_element." as t";
  6320. if (isset($objecttmp->ismultientitymanaged)) {
  6321. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6322. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  6323. $sql .= " INNER JOIN ".MAIN_DB_PREFIX.$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  6324. }
  6325. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6326. if (!$user->rights->societe->client->voir && !$user->socid) {
  6327. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  6328. }
  6329. }
  6330. }
  6331. // Add where from hooks
  6332. $parameters = array();
  6333. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  6334. if (!empty($hookmanager->resPrint)) {
  6335. $sql .= $hookmanager->resPrint;
  6336. } else {
  6337. $sql .= " WHERE 1=1";
  6338. if (isset($objecttmp->ismultientitymanaged)) {
  6339. if ($objecttmp->ismultientitymanaged == 1) {
  6340. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  6341. }
  6342. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6343. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  6344. }
  6345. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  6346. if ($objecttmp->element == 'societe') {
  6347. $sql .= " AND t.rowid = ".((int) $user->socid);
  6348. } else {
  6349. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  6350. }
  6351. }
  6352. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6353. if (!$user->rights->societe->client->voir && !$user->socid) {
  6354. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  6355. }
  6356. }
  6357. }
  6358. if ($searchkey != '') {
  6359. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  6360. }
  6361. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  6362. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  6363. {
  6364. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  6365. }*/
  6366. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  6367. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  6368. }
  6369. }
  6370. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  6371. //$sql.=$this->db->plimit($limit, 0);
  6372. //print $sql;
  6373. // Build output string
  6374. $resql = $this->db->query($sql);
  6375. if ($resql) {
  6376. // Construct $out and $outarray
  6377. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  6378. // 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
  6379. $textifempty = '&nbsp;';
  6380. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6381. if (!empty($conf->global->$confkeyforautocompletemode)) {
  6382. if ($showempty && !is_numeric($showempty)) {
  6383. $textifempty = $langs->trans($showempty);
  6384. } else {
  6385. $textifempty .= $langs->trans("All");
  6386. }
  6387. }
  6388. if ($showempty) {
  6389. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  6390. }
  6391. $num = $this->db->num_rows($resql);
  6392. $i = 0;
  6393. if ($num) {
  6394. while ($i < $num) {
  6395. $obj = $this->db->fetch_object($resql);
  6396. $label = '';
  6397. $tmparray = explode(',', $fieldstoshow);
  6398. $oldvalueforshowoncombobox = 0;
  6399. foreach ($tmparray as $key => $val) {
  6400. $val = preg_replace('/t\./', '', $val);
  6401. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  6402. $label .= $obj->$val;
  6403. $oldvalueforshowoncombobox = $objecttmp->fields[$val]['showoncombobox'];
  6404. }
  6405. if (empty($outputmode)) {
  6406. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  6407. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  6408. } else {
  6409. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  6410. }
  6411. } else {
  6412. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  6413. }
  6414. $i++;
  6415. if (($i % 10) == 0) {
  6416. $out .= "\n";
  6417. }
  6418. }
  6419. }
  6420. $out .= '</select>'."\n";
  6421. if (!$forcecombo) {
  6422. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6423. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  6424. }
  6425. } else {
  6426. dol_print_error($this->db);
  6427. }
  6428. $this->result = array('nbofelement'=>$num);
  6429. if ($outputmode) {
  6430. return $outarray;
  6431. }
  6432. return $out;
  6433. }
  6434. /**
  6435. * Return a HTML select string, built from an array of key+value.
  6436. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  6437. *
  6438. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  6439. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  6440. * @param string|string[] $id Preselected key or preselected keys for multiselect
  6441. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (If 1: key is -1 and value is '' or '&nbsp;', If placeholder string: key is -1 and value is the string), <0 to add an empty value with key that is this value.
  6442. * @param int $key_in_label 1 to show key into label with format "[key] value"
  6443. * @param int $value_as_key 1 to use value as key
  6444. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  6445. * @param int $translate 1=Translate and encode value
  6446. * @param int $maxlen Length maximum for labels
  6447. * @param int $disabled Html select box is disabled
  6448. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  6449. * @param string $morecss Add more class to css styles
  6450. * @param int $addjscombo Add js combo
  6451. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  6452. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  6453. * @param int $nohtmlescape No html escaping.
  6454. * @return string HTML select string.
  6455. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  6456. */
  6457. public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  6458. {
  6459. global $conf, $langs;
  6460. // Do we want a multiselect ?
  6461. //$jsbeautify = 0;
  6462. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  6463. $jsbeautify = 1;
  6464. if ($value_as_key) {
  6465. $array = array_combine($array, $array);
  6466. }
  6467. $out = '';
  6468. if ($addjscombo < 0) {
  6469. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6470. $addjscombo = 1;
  6471. } else {
  6472. $addjscombo = 0;
  6473. }
  6474. }
  6475. // Add code for jquery to use multiselect
  6476. if ($addjscombo && $jsbeautify) {
  6477. // Enhance with select2
  6478. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6479. $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', $show_empty < 0 ? (string) $show_empty : '-1');
  6480. }
  6481. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  6482. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  6483. $out .= '>';
  6484. if ($show_empty) {
  6485. $textforempty = ' ';
  6486. if (!empty($conf->use_javascript_ajax)) {
  6487. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  6488. }
  6489. if (!is_numeric($show_empty)) {
  6490. $textforempty = $show_empty;
  6491. }
  6492. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  6493. }
  6494. if (is_array($array)) {
  6495. // Translate
  6496. if ($translate) {
  6497. foreach ($array as $key => $value) {
  6498. if (!is_array($value)) {
  6499. $array[$key] = $langs->trans($value);
  6500. } else {
  6501. $array[$key]['label'] = $langs->trans($value['label']);
  6502. }
  6503. }
  6504. }
  6505. // Sort
  6506. if ($sort == 'ASC') {
  6507. asort($array);
  6508. } elseif ($sort == 'DESC') {
  6509. arsort($array);
  6510. }
  6511. foreach ($array as $key => $tmpvalue) {
  6512. if (is_array($tmpvalue)) {
  6513. $value = $tmpvalue['label'];
  6514. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  6515. $style = empty($tmpvalue['css']) ? ' class="'.$tmpvalue['css'].'"' : '';
  6516. } else {
  6517. $value = $tmpvalue;
  6518. $disabled = '';
  6519. $style = '';
  6520. }
  6521. if (!empty($disablebademail)) {
  6522. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  6523. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  6524. $disabled = ' disabled';
  6525. $style = ' class="warning"';
  6526. }
  6527. }
  6528. if ($key_in_label) {
  6529. if (empty($nohtmlescape)) {
  6530. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  6531. } else {
  6532. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  6533. }
  6534. } else {
  6535. if (empty($nohtmlescape)) {
  6536. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  6537. } else {
  6538. $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  6539. }
  6540. if ($value == '' || $value == '-') {
  6541. $selectOptionValue = '&nbsp;';
  6542. }
  6543. }
  6544. $out .= '<option value="'.$key.'"';
  6545. $out .= $style.$disabled;
  6546. if (is_array($id)) {
  6547. if (in_array($key, $id) && !$disabled) {
  6548. $out .= ' selected'; // To preselect a value
  6549. }
  6550. } else {
  6551. $id = (string) $id; // if $id = 0, then $id = '0'
  6552. if ($id != '' && $id == $key && !$disabled) {
  6553. $out .= ' selected'; // To preselect a value
  6554. }
  6555. }
  6556. if ($nohtmlescape) {
  6557. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  6558. }
  6559. if (is_array($tmpvalue)) {
  6560. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  6561. if (preg_match('/^data-/', $keyforvalue)) {
  6562. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  6563. }
  6564. }
  6565. }
  6566. $out .= '>';
  6567. //var_dump($selectOptionValue);
  6568. $out .= $selectOptionValue;
  6569. $out .= "</option>\n";
  6570. }
  6571. }
  6572. $out .= "</select>";
  6573. return $out;
  6574. }
  6575. /**
  6576. * 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.
  6577. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  6578. *
  6579. * @param string $htmlname Name of html select area
  6580. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  6581. * @param string $id Preselected key
  6582. * @param string $moreparam Add more parameters onto the select tag
  6583. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  6584. * @param int $disabled Html select box is disabled
  6585. * @param int $minimumInputLength Minimum Input Length
  6586. * @param string $morecss Add more class to css styles
  6587. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  6588. * @param string $placeholder String to use as placeholder
  6589. * @param integer $acceptdelayedhtml 1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
  6590. * @return string HTML select string
  6591. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  6592. */
  6593. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  6594. {
  6595. global $conf, $langs;
  6596. global $delayedhtmlcontent; // Will be used later outside of this function
  6597. // TODO Use an internal dolibarr component instead of select2
  6598. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  6599. return '';
  6600. }
  6601. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  6602. $outdelayed = '';
  6603. if (!empty($conf->use_javascript_ajax)) {
  6604. $tmpplugin = 'select2';
  6605. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  6606. <script>
  6607. $(document).ready(function () {
  6608. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  6609. $(".'.$htmlname.'").select2({
  6610. ajax: {
  6611. dir: "ltr",
  6612. url: "'.$url.'",
  6613. dataType: \'json\',
  6614. delay: 250,
  6615. data: function (params) {
  6616. return {
  6617. q: params.term, // search term
  6618. page: params.page
  6619. };
  6620. },
  6621. processResults: function (data) {
  6622. // parse the results into the format expected by Select2.
  6623. // since we are using custom formatting functions we do not need to alter the remote JSON data
  6624. //console.log(data);
  6625. saveRemoteData = data;
  6626. /* format json result for select2 */
  6627. result = []
  6628. $.each( data, function( key, value ) {
  6629. result.push({id: key, text: value.text});
  6630. });
  6631. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  6632. //console.log(result);
  6633. return {results: result, more: false}
  6634. },
  6635. cache: true
  6636. },
  6637. language: select2arrayoflanguage,
  6638. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  6639. placeholder: "'.dol_escape_js($placeholder).'",
  6640. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  6641. minimumInputLength: '.$minimumInputLength.',
  6642. formatResult: function(result, container, query, escapeMarkup) {
  6643. return escapeMarkup(result.text);
  6644. },
  6645. });
  6646. '.($callurlonselect ? '
  6647. /* Code to execute a GET when we select a value */
  6648. $(".'.$htmlname.'").change(function() {
  6649. var selected = $(".'.$htmlname.'").val();
  6650. console.log("We select in selectArrayAjax the entry "+selected)
  6651. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  6652. $.each( saveRemoteData, function( key, value ) {
  6653. if (key == selected)
  6654. {
  6655. console.log("selectArrayAjax - Do a redirect to "+value.url)
  6656. location.assign(value.url);
  6657. }
  6658. });
  6659. });' : '').'
  6660. });
  6661. </script>';
  6662. }
  6663. if ($acceptdelayedhtml) {
  6664. $delayedhtmlcontent .= $outdelayed;
  6665. } else {
  6666. $out .= $outdelayed;
  6667. }
  6668. return $out;
  6669. }
  6670. /**
  6671. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  6672. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  6673. *
  6674. * @param string $htmlname Name of html select area
  6675. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  6676. * @param string $id Preselected key
  6677. * @param string $moreparam Add more parameters onto the select tag
  6678. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  6679. * @param int $disabled Html select box is disabled
  6680. * @param int $minimumInputLength Minimum Input Length
  6681. * @param string $morecss Add more class to css styles
  6682. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  6683. * @param string $placeholder String to use as placeholder
  6684. * @param integer $acceptdelayedhtml 1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
  6685. * @return string HTML select string
  6686. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  6687. */
  6688. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  6689. {
  6690. global $conf, $langs;
  6691. global $delayedhtmlcontent; // Will be used later outside of this function
  6692. // TODO Use an internal dolibarr component instead of select2
  6693. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  6694. return '';
  6695. }
  6696. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  6697. $formattedarrayresult = array();
  6698. foreach ($array as $key => $value) {
  6699. $o = new stdClass();
  6700. $o->id = $key;
  6701. $o->text = $value['text'];
  6702. $o->url = $value['url'];
  6703. $formattedarrayresult[] = $o;
  6704. }
  6705. $outdelayed = '';
  6706. if (!empty($conf->use_javascript_ajax)) {
  6707. $tmpplugin = 'select2';
  6708. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  6709. <script>
  6710. $(document).ready(function () {
  6711. var data = '.json_encode($formattedarrayresult).';
  6712. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  6713. $(".'.$htmlname.'").select2({
  6714. data: data,
  6715. language: select2arrayoflanguage,
  6716. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  6717. placeholder: "'.dol_escape_js($placeholder).'",
  6718. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  6719. minimumInputLength: '.$minimumInputLength.',
  6720. formatResult: function(result, container, query, escapeMarkup) {
  6721. return escapeMarkup(result.text);
  6722. },
  6723. matcher: function (params, data) {
  6724. if(! data.id) return null;';
  6725. if ($callurlonselect) {
  6726. $outdelayed .= '
  6727. var urlBase = data.url;
  6728. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  6729. /* console.log("params.term="+params.term); */
  6730. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  6731. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  6732. }
  6733. if (!$disableFiltering) {
  6734. $outdelayed .= '
  6735. if(data.text.match(new RegExp(params.term))) {
  6736. return data;
  6737. }
  6738. return null;';
  6739. } else {
  6740. $outdelayed .= '
  6741. return data;';
  6742. }
  6743. $outdelayed .= '
  6744. }
  6745. });
  6746. '.($callurlonselect ? '
  6747. /* Code to execute a GET when we select a value */
  6748. $(".'.$htmlname.'").change(function() {
  6749. var selected = $(".'.$htmlname.'").val();
  6750. console.log("We select "+selected)
  6751. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  6752. $.each( saveRemoteData, function( key, value ) {
  6753. if (key == selected)
  6754. {
  6755. console.log("selectArrayFilter - Do a redirect to "+value.url)
  6756. location.assign(value.url);
  6757. }
  6758. });
  6759. });' : '').'
  6760. });
  6761. </script>';
  6762. }
  6763. if ($acceptdelayedhtml) {
  6764. $delayedhtmlcontent .= $outdelayed;
  6765. } else {
  6766. $out .= $outdelayed;
  6767. }
  6768. return $out;
  6769. }
  6770. /**
  6771. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  6772. *
  6773. * @param string $htmlname Name of select
  6774. * @param array $array Array with key+value
  6775. * @param array $selected Array with key+value preselected
  6776. * @param int $key_in_label 1 to show key like in "[key] value"
  6777. * @param int $value_as_key 1 to use value as key
  6778. * @param string $morecss Add more css style
  6779. * @param int $translate Translate and encode value
  6780. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  6781. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  6782. * @param string $elemtype Type of element we show ('category', ...). Will execute a formating function on it. To use in readonly mode if js component support HTML formatting.
  6783. * @param string $placeholder String to use as placeholder
  6784. * @param int $addjscombo Add js combo
  6785. * @return string HTML multiselect string
  6786. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  6787. */
  6788. public static function multiselectarray($htmlname, $array, $selected = array(), $key_in_label = 0, $value_as_key = 0, $morecss = '', $translate = 0, $width = 0, $moreattrib = '', $elemtype = '', $placeholder = '', $addjscombo = -1)
  6789. {
  6790. global $conf, $langs;
  6791. $out = '';
  6792. if ($addjscombo < 0) {
  6793. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6794. $addjscombo = 1;
  6795. } else {
  6796. $addjscombo = 0;
  6797. }
  6798. }
  6799. // Add code for jquery to use multiselect
  6800. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  6801. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  6802. $out .= "\n".'<script>'."\n";
  6803. if ($addjscombo == 1) {
  6804. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  6805. $out .= 'function formatResult(record) {'."\n";
  6806. if ($elemtype == 'category') {
  6807. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  6808. } else {
  6809. $out .= 'return record.text;';
  6810. }
  6811. $out .= '};'."\n";
  6812. $out .= 'function formatSelection(record) {'."\n";
  6813. if ($elemtype == 'category') {
  6814. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  6815. } else {
  6816. $out .= 'return record.text;';
  6817. }
  6818. $out .= '};'."\n";
  6819. $out .= '$(document).ready(function () {
  6820. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  6821. dir: \'ltr\',
  6822. // Specify format function for dropdown item
  6823. formatResult: formatResult,
  6824. templateResult: formatResult, /* For 4.0 */
  6825. // Specify format function for selected item
  6826. formatSelection: formatSelection,
  6827. templateSelection: formatSelection /* For 4.0 */
  6828. });
  6829. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  6830. the size only if component is not hidden by default on load */
  6831. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  6832. });'."\n";
  6833. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  6834. // Add other js lib
  6835. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  6836. // ...
  6837. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  6838. $out .= '$(document).ready(function () {
  6839. $(\'#'.$htmlname.'\').multiSelect({
  6840. containerHTML: \'<div class="multi-select-container">\',
  6841. menuHTML: \'<div class="multi-select-menu">\',
  6842. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  6843. menuItemHTML: \'<label class="multi-select-menuitem">\',
  6844. activeClass: \'multi-select-container--open\',
  6845. noneText: \''.$placeholder.'\'
  6846. });
  6847. })';
  6848. }
  6849. $out .= '</script>';
  6850. }
  6851. // Try also magic suggest
  6852. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  6853. if (is_array($array) && !empty($array)) {
  6854. if ($value_as_key) {
  6855. $array = array_combine($array, $array);
  6856. }
  6857. if (!empty($array)) {
  6858. foreach ($array as $key => $value) {
  6859. $newval = ($translate ? $langs->trans($value) : $value);
  6860. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  6861. $out .= '<option value="'.$key.'"';
  6862. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != '')) {
  6863. $out .= ' selected';
  6864. }
  6865. $out .= ' data-html="'.dol_escape_htmltag($newval).'"';
  6866. $out .= '>';
  6867. $out .= dol_htmlentitiesbr($newval);
  6868. $out .= '</option>'."\n";
  6869. }
  6870. }
  6871. }
  6872. $out .= '</select>'."\n";
  6873. return $out;
  6874. }
  6875. /**
  6876. * Show a multiselect dropbox from an array. If a saved selection of fields exists for user (into $user->conf->MAIN_SELECTEDFIELDS_contextofpage), we use this one instead of default.
  6877. *
  6878. * @param string $htmlname Name of HTML field
  6879. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  6880. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  6881. * @return string HTML multiselect string
  6882. * @see selectarray()
  6883. */
  6884. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  6885. {
  6886. global $conf, $langs, $user, $extrafields;
  6887. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6888. return '';
  6889. }
  6890. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  6891. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  6892. $tmparray = explode(',', $user->conf->$tmpvar);
  6893. foreach ($array as $key => $val) {
  6894. //var_dump($key);
  6895. //var_dump($tmparray);
  6896. if (in_array($key, $tmparray)) {
  6897. $array[$key]['checked'] = 1;
  6898. } else {
  6899. $array[$key]['checked'] = 0;
  6900. }
  6901. }
  6902. } else { // There is no list of fields already customized for user
  6903. foreach ($array as $key => $val) {
  6904. if ($array[$key]['checked'] < 0) {
  6905. $array[$key]['checked'] = 0;
  6906. }
  6907. }
  6908. }
  6909. $listoffieldsforselection = '';
  6910. $listcheckedstring = '';
  6911. foreach ($array as $key => $val) {
  6912. /* var_dump($val);
  6913. var_dump(array_key_exists('enabled', $val));
  6914. var_dump(!$val['enabled']);*/
  6915. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  6916. unset($array[$key]); // We don't want this field
  6917. continue;
  6918. }
  6919. if (!empty($val['type']) && $val['type'] == 'separate') {
  6920. // Field remains in array but we don't add it into $listoffieldsforselection
  6921. //$listoffieldsforselection .= '<li>-----</li>';
  6922. continue;
  6923. }
  6924. if ($val['label']) {
  6925. if (!empty($val['langfile']) && is_object($langs)) {
  6926. $langs->load($val['langfile']);
  6927. }
  6928. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  6929. $listoffieldsforselection .= '<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.((empty($val['checked']) && $val['checked'] != '-1') ? '' : ' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
  6930. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  6931. }
  6932. }
  6933. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  6934. <dl class="dropdown">
  6935. <dt>
  6936. <a href="#'.$htmlname.'">
  6937. '.img_picto('', 'list').'
  6938. </a>
  6939. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  6940. </dt>
  6941. <dd class="dropdowndd">
  6942. <div class="multiselectcheckbox'.$htmlname.'">
  6943. <ul class="ul'.$htmlname.'">
  6944. '.$listoffieldsforselection.'
  6945. </ul>
  6946. </div>
  6947. </dd>
  6948. </dl>
  6949. <script type="text/javascript">
  6950. jQuery(document).ready(function () {
  6951. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  6952. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  6953. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  6954. var title = $(this).val() + ",";
  6955. if ($(this).is(\':checked\')) {
  6956. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  6957. }
  6958. else {
  6959. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  6960. }
  6961. // Now, we submit page
  6962. //$(this).parents(\'form:first\').submit();
  6963. });
  6964. });
  6965. </script>
  6966. ';
  6967. return $out;
  6968. }
  6969. /**
  6970. * Render list of categories linked to object with id $id and type $type
  6971. *
  6972. * @param int $id Id of object
  6973. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  6974. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  6975. * @param int $nolink 1=Do not add html links
  6976. * @return string String with categories
  6977. */
  6978. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  6979. {
  6980. global $db;
  6981. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  6982. $cat = new Categorie($db);
  6983. $categories = $cat->containing($id, $type);
  6984. if ($rendermode == 1) {
  6985. $toprint = array();
  6986. foreach ($categories as $c) {
  6987. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  6988. foreach ($ways as $way) {
  6989. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  6990. }
  6991. }
  6992. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  6993. }
  6994. if ($rendermode == 0) {
  6995. $arrayselected = array();
  6996. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  6997. foreach ($categories as $c) {
  6998. $arrayselected[] = $c->id;
  6999. }
  7000. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7001. }
  7002. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7003. }
  7004. /**
  7005. * Show linked object block.
  7006. *
  7007. * @param CommonObject $object Object we want to show links to
  7008. * @param string $morehtmlright More html to show on right of title
  7009. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7010. * @return int <0 if KO, >=0 if OK
  7011. */
  7012. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  7013. {
  7014. global $conf, $langs, $hookmanager;
  7015. global $bc, $action;
  7016. $object->fetchObjectLinked();
  7017. // Bypass the default method
  7018. $hookmanager->initHooks(array('commonobject'));
  7019. $parameters = array(
  7020. 'morehtmlright' => $morehtmlright,
  7021. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7022. );
  7023. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7024. if (empty($reshook)) {
  7025. $nbofdifferenttypes = count($object->linkedObjects);
  7026. print '<!-- showLinkedObjectBlock -->';
  7027. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7028. print '<div class="div-table-responsive-no-min">';
  7029. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7030. print '<tr class="liste_titre">';
  7031. print '<td>'.$langs->trans("Type").'</td>';
  7032. print '<td>'.$langs->trans("Ref").'</td>';
  7033. print '<td class="center"></td>';
  7034. print '<td class="center">'.$langs->trans("Date").'</td>';
  7035. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7036. print '<td class="right">'.$langs->trans("Status").'</td>';
  7037. print '<td></td>';
  7038. print '</tr>';
  7039. $nboftypesoutput = 0;
  7040. foreach ($object->linkedObjects as $objecttype => $objects) {
  7041. $tplpath = $element = $subelement = $objecttype;
  7042. // to display inport button on tpl
  7043. $showImportButton = false;
  7044. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7045. $showImportButton = true;
  7046. }
  7047. $regs = array();
  7048. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7049. $element = $regs[1];
  7050. $subelement = $regs[2];
  7051. $tplpath = $element.'/'.$subelement;
  7052. }
  7053. $tplname = 'linkedobjectblock';
  7054. // To work with non standard path
  7055. if ($objecttype == 'facture') {
  7056. $tplpath = 'compta/'.$element;
  7057. if (empty($conf->facture->enabled)) {
  7058. continue; // Do not show if module disabled
  7059. }
  7060. } elseif ($objecttype == 'facturerec') {
  7061. $tplpath = 'compta/facture';
  7062. $tplname = 'linkedobjectblockForRec';
  7063. if (empty($conf->facture->enabled)) {
  7064. continue; // Do not show if module disabled
  7065. }
  7066. } elseif ($objecttype == 'propal') {
  7067. $tplpath = 'comm/'.$element;
  7068. if (empty($conf->propal->enabled)) {
  7069. continue; // Do not show if module disabled
  7070. }
  7071. } elseif ($objecttype == 'supplier_proposal') {
  7072. if (empty($conf->supplier_proposal->enabled)) {
  7073. continue; // Do not show if module disabled
  7074. }
  7075. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  7076. $tplpath = 'expedition';
  7077. if (empty($conf->expedition->enabled)) {
  7078. continue; // Do not show if module disabled
  7079. }
  7080. } elseif ($objecttype == 'reception') {
  7081. $tplpath = 'reception';
  7082. if (empty($conf->reception->enabled)) {
  7083. continue; // Do not show if module disabled
  7084. }
  7085. } elseif ($objecttype == 'delivery') {
  7086. $tplpath = 'delivery';
  7087. if (empty($conf->expedition->enabled)) {
  7088. continue; // Do not show if module disabled
  7089. }
  7090. } elseif ($objecttype == 'mo') {
  7091. $tplpath = 'mrp/mo';
  7092. if (empty($conf->mrp->enabled)) {
  7093. continue; // Do not show if module disabled
  7094. }
  7095. } elseif ($objecttype == 'ficheinter') {
  7096. $tplpath = 'fichinter';
  7097. if (empty($conf->ficheinter->enabled)) {
  7098. continue; // Do not show if module disabled
  7099. }
  7100. } elseif ($objecttype == 'invoice_supplier') {
  7101. $tplpath = 'fourn/facture';
  7102. } elseif ($objecttype == 'order_supplier') {
  7103. $tplpath = 'fourn/commande';
  7104. } elseif ($objecttype == 'expensereport') {
  7105. $tplpath = 'expensereport';
  7106. } elseif ($objecttype == 'subscription') {
  7107. $tplpath = 'adherents';
  7108. } elseif ($objecttype == 'conferenceorbooth') {
  7109. $tplpath = 'eventorganization';
  7110. } elseif ($objecttype == 'conferenceorboothattendee') {
  7111. $tplpath = 'eventorganization';
  7112. } elseif ($objecttype == 'mo') {
  7113. $tplpath = 'mrp';
  7114. if (empty($conf->mrp->enabled)) {
  7115. continue; // Do not show if module disabled
  7116. }
  7117. }
  7118. global $linkedObjectBlock;
  7119. $linkedObjectBlock = $objects;
  7120. // Output template part (modules that overwrite templates must declare this into descriptor)
  7121. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7122. foreach ($dirtpls as $reldir) {
  7123. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7124. global $noMoreLinkedObjectBlockAfter;
  7125. $noMoreLinkedObjectBlockAfter = 1;
  7126. }
  7127. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7128. if ($res) {
  7129. $nboftypesoutput++;
  7130. break;
  7131. }
  7132. }
  7133. }
  7134. if (!$nboftypesoutput) {
  7135. print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
  7136. }
  7137. print '</table>';
  7138. if (!empty($compatibleImportElementsList)) {
  7139. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  7140. }
  7141. print '</div>';
  7142. return $nbofdifferenttypes;
  7143. }
  7144. }
  7145. /**
  7146. * Show block with links to link to other objects.
  7147. *
  7148. * @param CommonObject $object Object we want to show links to
  7149. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7150. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7151. * @return string <0 if KO, >0 if OK
  7152. */
  7153. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7154. {
  7155. global $conf, $langs, $hookmanager;
  7156. global $bc, $action;
  7157. $linktoelem = '';
  7158. $linktoelemlist = '';
  7159. $listofidcompanytoscan = '';
  7160. if (!is_object($object->thirdparty)) {
  7161. $object->fetch_thirdparty();
  7162. }
  7163. $possiblelinks = array();
  7164. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7165. $listofidcompanytoscan = $object->thirdparty->id;
  7166. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7167. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7168. }
  7169. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7170. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7171. $tmpproject = new Project($this->db);
  7172. $tmpproject->fetch($object->fk_project);
  7173. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7174. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7175. }
  7176. unset($tmpproject);
  7177. }
  7178. $possiblelinks = array(
  7179. '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 (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('propal').')'),
  7180. '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 (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('commande').')'),
  7181. 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_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 (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'),
  7182. 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('invoice').')'),
  7183. 'contrat'=>array(
  7184. 'enabled'=>$conf->contrat->enabled,
  7185. 'perms'=>1,
  7186. 'label'=>'LinkToContract',
  7187. 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_customer as ref_client, t.ref_supplier, SUM(td.total_ht) as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t, ".MAIN_DB_PREFIX."contratdet as td WHERE t.fk_soc = s.rowid AND td.fk_contrat = t.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('contract').') GROUP BY s.rowid, s.nom, s.client, t.rowid, t.ref, t.ref_customer, t.ref_supplier'
  7188. ),
  7189. '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 (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('intervention').')'),
  7190. '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 (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('supplier_proposal').')'),
  7191. '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 (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
  7192. '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 (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('facture_fourn').')'),
  7193. 'ticket'=>array('enabled'=>$conf->ticket->enabled, 'perms'=>1, 'label'=>'LinkToTicket', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('ticket').')'),
  7194. 'mo'=>array('enabled'=>$conf->mrp->enabled, 'perms'=>1, 'label'=>'LinkToMO', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM ".MAIN_DB_PREFIX."societe as s INNER JOIN ".MAIN_DB_PREFIX."mrp_mo as t ON t.fk_soc = s.rowid WHERE t.fk_soc IN (".$this->db->sanitize($listofidcompanytoscan).') AND t.entity IN ('.getEntity('mo').')')
  7195. );
  7196. }
  7197. // Can complete the possiblelink array
  7198. $hookmanager->initHooks(array('commonobject'));
  7199. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan);
  7200. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7201. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7202. }
  7203. if (empty($reshook)) {
  7204. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7205. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  7206. }
  7207. } elseif ($reshook > 0) {
  7208. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7209. $possiblelinks = $hookmanager->resArray;
  7210. }
  7211. }
  7212. foreach ($possiblelinks as $key => $possiblelink) {
  7213. $num = 0;
  7214. if (empty($possiblelink['enabled'])) {
  7215. continue;
  7216. }
  7217. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  7218. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  7219. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7220. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  7221. print '<input type="hidden" name="id" value="' . $object->id . '">';
  7222. print '<input type="hidden" name="action" value="addlinkbyref">';
  7223. print '<input type="hidden" name="addlink" value="' . $key . '">';
  7224. print '<table class="noborder">';
  7225. print '<tr>';
  7226. print '<td>' . $langs->trans("Ref") . '</td>';
  7227. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;<input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  7228. print '</tr>';
  7229. print '</table>';
  7230. print '</form>';
  7231. }
  7232. $sql = $possiblelink['sql'];
  7233. $resqllist = $this->db->query($sql);
  7234. if ($resqllist) {
  7235. $num = $this->db->num_rows($resqllist);
  7236. $i = 0;
  7237. print '<br>';
  7238. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  7239. print '<input type="hidden" name="action" value="addlink">';
  7240. print '<input type="hidden" name="token" value="'.newToken().'">';
  7241. print '<input type="hidden" name="id" value="'.$object->id.'">';
  7242. print '<input type="hidden" name="addlink" value="'.$key.'">';
  7243. print '<table class="noborder">';
  7244. print '<tr class="liste_titre">';
  7245. print '<td class="nowrap"></td>';
  7246. print '<td class="center">'.$langs->trans("Ref").'</td>';
  7247. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  7248. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7249. print '<td class="left">'.$langs->trans("Company").'</td>';
  7250. print '</tr>';
  7251. while ($i < $num) {
  7252. $objp = $this->db->fetch_object($resqllist);
  7253. print '<tr class="oddeven">';
  7254. print '<td class="left">';
  7255. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  7256. print '</td>';
  7257. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  7258. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  7259. print '<td class="right">';
  7260. if ($possiblelink['label'] == 'LinkToContract') {
  7261. $form = new Form($this->db);
  7262. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  7263. }
  7264. print '<span class="amount">'.price($objp->total_ht).'</span>';
  7265. print '</td>';
  7266. print '<td>'.$objp->name.'</td>';
  7267. print '</tr>';
  7268. $i++;
  7269. }
  7270. print '</table>';
  7271. print '<div class="center">';
  7272. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  7273. if (empty($conf->use_javascript_ajax)) {
  7274. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7275. } else {
  7276. print '<input type="submit"; onclick="javascript:jQuery(\'#'.$key.'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7277. }
  7278. print '</form>';
  7279. $this->db->free($resqllist);
  7280. } else {
  7281. dol_print_error($this->db);
  7282. }
  7283. print '</div>';
  7284. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  7285. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7286. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  7287. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  7288. } else {
  7289. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  7290. }
  7291. }
  7292. }
  7293. if ($linktoelemlist) {
  7294. $linktoelem = '
  7295. <dl class="dropdown" id="linktoobjectname">
  7296. ';
  7297. if (!empty($conf->use_javascript_ajax)) {
  7298. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  7299. }
  7300. $linktoelem .= '<dd>
  7301. <div class="multiselectlinkto">
  7302. <ul class="ulselectedfields">'.$linktoelemlist.'
  7303. </ul>
  7304. </div>
  7305. </dd>
  7306. </dl>';
  7307. } else {
  7308. $linktoelem = '';
  7309. }
  7310. if (!empty($conf->use_javascript_ajax)) {
  7311. print '<!-- Add js to show linkto box -->
  7312. <script>
  7313. jQuery(document).ready(function() {
  7314. jQuery(".linkto").click(function() {
  7315. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  7316. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  7317. });
  7318. });
  7319. </script>
  7320. ';
  7321. }
  7322. return $linktoelem;
  7323. }
  7324. /**
  7325. * Return an html string with a select combo box to choose yes or no
  7326. *
  7327. * @param string $htmlname Name of html select field
  7328. * @param string $value Pre-selected value
  7329. * @param int $option 0 return yes/no, 1 return 1/0
  7330. * @param bool $disabled true or false
  7331. * @param int $useempty 1=Add empty line
  7332. * @param int $addjscombo 1=Add js beautifier on combo box
  7333. * @param string $morecss More CSS
  7334. * @return string See option
  7335. */
  7336. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '')
  7337. {
  7338. global $langs;
  7339. $yes = "yes";
  7340. $no = "no";
  7341. if ($option) {
  7342. $yes = "1";
  7343. $no = "0";
  7344. }
  7345. $disabled = ($disabled ? ' disabled' : '');
  7346. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  7347. if ($useempty) {
  7348. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  7349. }
  7350. if (("$value" == 'yes') || ($value == 1)) {
  7351. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  7352. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  7353. } else {
  7354. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  7355. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  7356. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  7357. }
  7358. $resultyesno .= '</select>'."\n";
  7359. if ($addjscombo) {
  7360. $resultyesno .= ajax_combobox($htmlname);
  7361. }
  7362. return $resultyesno;
  7363. }
  7364. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7365. /**
  7366. * Return list of export templates
  7367. *
  7368. * @param string $selected Id modele pre-selectionne
  7369. * @param string $htmlname Name of HTML select
  7370. * @param string $type Type of searched templates
  7371. * @param int $useempty Affiche valeur vide dans liste
  7372. * @return void
  7373. */
  7374. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  7375. {
  7376. // phpcs:enable
  7377. $sql = "SELECT rowid, label";
  7378. $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
  7379. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  7380. $sql .= " ORDER BY rowid";
  7381. $result = $this->db->query($sql);
  7382. if ($result) {
  7383. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  7384. if ($useempty) {
  7385. print '<option value="-1">&nbsp;</option>';
  7386. }
  7387. $num = $this->db->num_rows($result);
  7388. $i = 0;
  7389. while ($i < $num) {
  7390. $obj = $this->db->fetch_object($result);
  7391. if ($selected == $obj->rowid) {
  7392. print '<option value="'.$obj->rowid.'" selected>';
  7393. } else {
  7394. print '<option value="'.$obj->rowid.'">';
  7395. }
  7396. print $obj->label;
  7397. print '</option>';
  7398. $i++;
  7399. }
  7400. print "</select>";
  7401. } else {
  7402. dol_print_error($this->db);
  7403. }
  7404. }
  7405. /**
  7406. * Return a HTML area with the reference of object and a navigation bar for a business object
  7407. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  7408. *
  7409. * @param object $object Object to show.
  7410. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  7411. * @param string $morehtml More html content to output just before the nav bar.
  7412. * @param int $shownav Show Condition (navigation is shown if value is 1).
  7413. * @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.
  7414. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  7415. * @param string $morehtmlref More html to show after ref.
  7416. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  7417. * @param int $nodbprefix Do not include DB prefix to forge table name.
  7418. * @param string $morehtmlleft More html code to show before ref.
  7419. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  7420. * @param string $morehtmlright More html code to show after ref.
  7421. * @return string Portion HTML with ref + navigation buttons
  7422. */
  7423. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  7424. {
  7425. global $langs, $conf, $hookmanager, $extralanguages;
  7426. $ret = '';
  7427. if (empty($fieldid)) {
  7428. $fieldid = 'rowid';
  7429. }
  7430. if (empty($fieldref)) {
  7431. $fieldref = 'ref';
  7432. }
  7433. // Preparing gender's display if there is one
  7434. $addgendertxt = '';
  7435. if (!empty($object->gender)) {
  7436. $addgendertxt = ' ';
  7437. switch ($object->gender) {
  7438. case 'man':
  7439. $addgendertxt .= '<i class="fas fa-mars"></i>';
  7440. break;
  7441. case 'woman':
  7442. $addgendertxt .= '<i class="fas fa-venus"></i>';
  7443. break;
  7444. case 'other':
  7445. $addgendertxt .= '<i class="fas fa-genderless"></i>';
  7446. break;
  7447. }
  7448. }
  7449. // Add where from hooks
  7450. if (is_object($hookmanager)) {
  7451. $parameters = array();
  7452. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  7453. $object->next_prev_filter .= $hookmanager->resPrint;
  7454. }
  7455. $previous_ref = $next_ref = '';
  7456. if ($shownav) {
  7457. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  7458. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  7459. $navurl = $_SERVER["PHP_SELF"];
  7460. // Special case for project/task page
  7461. if ($paramid == 'project_ref') {
  7462. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  7463. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  7464. $paramid = 'ref';
  7465. }
  7466. }
  7467. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  7468. // accesskey is for Mac: CTRL + key for all browsers
  7469. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  7470. if ($conf->browser->name == 'chrome') {
  7471. $stringforfirstkey .= ' ALT +';
  7472. } elseif ($conf->browser->name == 'firefox') {
  7473. $stringforfirstkey .= ' ALT + SHIFT +';
  7474. } else {
  7475. $stringforfirstkey .= ' CTL +';
  7476. }
  7477. $previous_ref = $object->ref_previous ? '<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
  7478. $next_ref = $object->ref_next ? '<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
  7479. }
  7480. //print "xx".$previous_ref."x".$next_ref;
  7481. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  7482. // Right part of banner
  7483. if ($morehtmlright) {
  7484. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  7485. }
  7486. if ($previous_ref || $next_ref || $morehtml) {
  7487. $ret .= '<div class="pagination paginationref"><ul class="right">';
  7488. }
  7489. if ($morehtml) {
  7490. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  7491. }
  7492. if ($shownav && ($previous_ref || $next_ref)) {
  7493. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  7494. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  7495. }
  7496. if ($previous_ref || $next_ref || $morehtml) {
  7497. $ret .= '</ul></div>';
  7498. }
  7499. $parameters = array();
  7500. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  7501. if (empty($reshook)) {
  7502. $morehtmlstatus .= $hookmanager->resPrint;
  7503. } else {
  7504. $morehtmlstatus = $hookmanager->resPrint;
  7505. }
  7506. if ($morehtmlstatus) {
  7507. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  7508. }
  7509. $parameters = array();
  7510. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  7511. if (empty($reshook)) {
  7512. $morehtmlref .= $hookmanager->resPrint;
  7513. } elseif ($reshook > 0) {
  7514. $morehtmlref = $hookmanager->resPrint;
  7515. }
  7516. // Left part of banner
  7517. if ($morehtmlleft) {
  7518. if ($conf->browser->layout == 'phone') {
  7519. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  7520. } else {
  7521. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  7522. }
  7523. }
  7524. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  7525. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  7526. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  7527. if ($object->element == 'societe') {
  7528. $ret .= dol_htmlentities($object->name);
  7529. // List of extra languages
  7530. $arrayoflangcode = array();
  7531. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  7532. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  7533. }
  7534. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  7535. if (!is_object($extralanguages)) {
  7536. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  7537. $extralanguages = new ExtraLanguages($this->db);
  7538. }
  7539. $extralanguages->fetch_name_extralanguages('societe');
  7540. if (!empty($extralanguages->attributes['societe']['name'])) {
  7541. $object->fetchValuesForExtraLanguages();
  7542. $htmltext = '';
  7543. // If there is extra languages
  7544. foreach ($arrayoflangcode as $extralangcode) {
  7545. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  7546. if ($object->array_languages['name'][$extralangcode]) {
  7547. $htmltext .= $object->array_languages['name'][$extralangcode];
  7548. } else {
  7549. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  7550. }
  7551. }
  7552. $ret .= '<!-- Show translations of name -->'."\n";
  7553. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  7554. }
  7555. }
  7556. } elseif ($object->element == 'member') {
  7557. $ret .= $object->ref.'<br>';
  7558. $fullname = $object->getFullName($langs);
  7559. if ($object->morphy == 'mor' && $object->societe) {
  7560. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  7561. } else {
  7562. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  7563. }
  7564. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  7565. $ret .= dol_htmlentities($object->getFullName($langs)).$addgendertxt;
  7566. } elseif (in_array($object->element, array('action', 'agenda'))) {
  7567. $ret .= $object->ref.'<br>'.$object->label;
  7568. } elseif (in_array($object->element, array('adherent_type'))) {
  7569. $ret .= $object->label;
  7570. } elseif ($object->element == 'ecm_directories') {
  7571. $ret .= '';
  7572. } elseif ($fieldref != 'none') {
  7573. $ret .= dol_htmlentities($object->$fieldref);
  7574. }
  7575. if ($morehtmlref) {
  7576. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  7577. if (substr($morehtmlref, 0, 4) != '<div') {
  7578. $ret .= ' ';
  7579. }
  7580. $ret .= $morehtmlref;
  7581. }
  7582. $ret .= '</div>';
  7583. $ret .= '</div><!-- End banner content -->';
  7584. return $ret;
  7585. }
  7586. /**
  7587. * Return HTML code to output a barcode
  7588. *
  7589. * @param Object $object Object containing data to retrieve file name
  7590. * @param int $width Width of photo
  7591. * @param string $morecss More CSS on img of barcode
  7592. * @return string HTML code to output barcode
  7593. */
  7594. public function showbarcode(&$object, $width = 100, $morecss = '')
  7595. {
  7596. global $conf;
  7597. //Check if barcode is filled in the card
  7598. if (empty($object->barcode)) {
  7599. return '';
  7600. }
  7601. // Complete object if not complete
  7602. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  7603. $result = $object->fetch_barcode();
  7604. //Check if fetch_barcode() failed
  7605. if ($result < 1) {
  7606. return '<!-- ErrorFetchBarcode -->';
  7607. }
  7608. }
  7609. // Barcode image
  7610. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  7611. $out = '<!-- url barcode = '.$url.' -->';
  7612. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  7613. return $out;
  7614. }
  7615. /**
  7616. * Return HTML code to output a photo
  7617. *
  7618. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  7619. * @param object $object Object containing data to retrieve file name
  7620. * @param int $width Width of photo
  7621. * @param int $height Height of photo (auto if 0)
  7622. * @param int $caneditfield Add edit fields
  7623. * @param string $cssclass CSS name to use on img for photo
  7624. * @param string $imagesize 'mini', 'small' or '' (original)
  7625. * @param int $addlinktofullsize Add link to fullsize image
  7626. * @param int $cache 1=Accept to use image in cache
  7627. * @param string $forcecapture '', 'user' or 'environment'. Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if ''.
  7628. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  7629. * @return string HTML code to output photo
  7630. */
  7631. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  7632. {
  7633. global $conf, $langs;
  7634. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  7635. $id = (!empty($object->id) ? $object->id : $object->rowid);
  7636. $ret = '';
  7637. $dir = '';
  7638. $file = '';
  7639. $originalfile = '';
  7640. $altfile = '';
  7641. $email = '';
  7642. $capture = '';
  7643. if ($modulepart == 'societe') {
  7644. $dir = $conf->societe->multidir_output[$entity];
  7645. if (!empty($object->logo)) {
  7646. if (dolIsAllowedForPreview($object->logo)) {
  7647. if ((string) $imagesize == 'mini') {
  7648. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  7649. } elseif ((string) $imagesize == 'small') {
  7650. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  7651. } else {
  7652. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  7653. }
  7654. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  7655. }
  7656. }
  7657. $email = $object->email;
  7658. } elseif ($modulepart == 'contact') {
  7659. $dir = $conf->societe->multidir_output[$entity].'/contact';
  7660. if (!empty($object->photo)) {
  7661. if (dolIsAllowedForPreview($object->photo)) {
  7662. if ((string) $imagesize == 'mini') {
  7663. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  7664. } elseif ((string) $imagesize == 'small') {
  7665. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  7666. } else {
  7667. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  7668. }
  7669. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  7670. }
  7671. }
  7672. $email = $object->email;
  7673. $capture = 'user';
  7674. } elseif ($modulepart == 'userphoto') {
  7675. $dir = $conf->user->dir_output;
  7676. if (!empty($object->photo)) {
  7677. if (dolIsAllowedForPreview($object->photo)) {
  7678. if ((string) $imagesize == 'mini') {
  7679. $file = get_exdir(0, 0, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_mini');
  7680. } elseif ((string) $imagesize == 'small') {
  7681. $file = get_exdir(0, 0, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_small');
  7682. } else {
  7683. $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->photo;
  7684. }
  7685. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').$object->photo;
  7686. }
  7687. }
  7688. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  7689. $altfile = $object->id.".jpg"; // For backward compatibility
  7690. }
  7691. $email = $object->email;
  7692. $capture = 'user';
  7693. } elseif ($modulepart == 'memberphoto') {
  7694. $dir = $conf->adherent->dir_output;
  7695. if (!empty($object->photo)) {
  7696. if (dolIsAllowedForPreview($object->photo)) {
  7697. if ((string) $imagesize == 'mini') {
  7698. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  7699. } elseif ((string) $imagesize == 'small') {
  7700. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  7701. } else {
  7702. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  7703. }
  7704. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  7705. }
  7706. }
  7707. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  7708. $altfile = $object->id.".jpg"; // For backward compatibility
  7709. }
  7710. $email = $object->email;
  7711. $capture = 'user';
  7712. } else {
  7713. // Generic case to show photos
  7714. $dir = $conf->$modulepart->dir_output;
  7715. if (!empty($object->photo)) {
  7716. if (dolIsAllowedForPreview($object->photo)) {
  7717. if ((string) $imagesize == 'mini') {
  7718. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  7719. } elseif ((string) $imagesize == 'small') {
  7720. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  7721. } else {
  7722. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  7723. }
  7724. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  7725. }
  7726. }
  7727. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  7728. $altfile = $object->id.".jpg"; // For backward compatibility
  7729. }
  7730. $email = $object->email;
  7731. }
  7732. if ($forcecapture) {
  7733. $capture = $forcecapture;
  7734. }
  7735. if ($dir) {
  7736. if ($file && file_exists($dir."/".$file)) {
  7737. if ($addlinktofullsize) {
  7738. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  7739. if ($urladvanced) {
  7740. $ret .= '<a href="'.$urladvanced.'">';
  7741. } else {
  7742. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  7743. }
  7744. }
  7745. $ret .= '<img alt="Photo" class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').' photologo'.(preg_replace('/[^a-z]/i', '_', $file)).'" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
  7746. if ($addlinktofullsize) {
  7747. $ret .= '</a>';
  7748. }
  7749. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  7750. if ($addlinktofullsize) {
  7751. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  7752. if ($urladvanced) {
  7753. $ret .= '<a href="'.$urladvanced.'">';
  7754. } else {
  7755. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  7756. }
  7757. }
  7758. $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.'">';
  7759. if ($addlinktofullsize) {
  7760. $ret .= '</a>';
  7761. }
  7762. } else {
  7763. $nophoto = '/public/theme/common/nophoto.png';
  7764. $defaultimg = 'identicon'; // For gravatar
  7765. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  7766. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  7767. $nophoto = 'company';
  7768. } else {
  7769. $nophoto = '/public/theme/common/user_anonymous.png';
  7770. if (!empty($object->gender) && $object->gender == 'man') {
  7771. $nophoto = '/public/theme/common/user_man.png';
  7772. }
  7773. if (!empty($object->gender) && $object->gender == 'woman') {
  7774. $nophoto = '/public/theme/common/user_woman.png';
  7775. }
  7776. }
  7777. }
  7778. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  7779. // see https://gravatar.com/site/implement/images/php/
  7780. $ret .= '<!-- Put link to gravatar -->';
  7781. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="https://www.gravatar.com/avatar/'.md5(strtolower(trim($email))).'?s='.$width.'&d='.$defaultimg.'">'; // gravatar need md5 hash
  7782. } else {
  7783. if ($nophoto == 'company') {
  7784. $ret .= '<div class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'">'.img_picto('', 'company').'</div>';
  7785. } else {
  7786. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  7787. }
  7788. }
  7789. }
  7790. if ($caneditfield) {
  7791. if ($object->photo) {
  7792. $ret .= "<br>\n";
  7793. }
  7794. $ret .= '<table class="nobordernopadding centpercent">';
  7795. if ($object->photo) {
  7796. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  7797. }
  7798. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  7799. $ret .= '</table>';
  7800. }
  7801. } else {
  7802. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  7803. }
  7804. return $ret;
  7805. }
  7806. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  7807. /**
  7808. * Return select list of groups
  7809. *
  7810. * @param string $selected Id group preselected
  7811. * @param string $htmlname Field name in form
  7812. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  7813. * @param string $exclude Array list of groups id to exclude
  7814. * @param int $disabled If select list must be disabled
  7815. * @param string $include Array list of groups id to include
  7816. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  7817. * @param string $force_entity '0' or Ids of environment to force
  7818. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  7819. * @param string $morecss More css to add to html component
  7820. * @return string
  7821. * @see select_dolusers()
  7822. */
  7823. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  7824. {
  7825. // phpcs:enable
  7826. global $conf, $user, $langs;
  7827. // Permettre l'exclusion de groupes
  7828. if (is_array($exclude)) {
  7829. $excludeGroups = implode(",", $exclude);
  7830. }
  7831. // Permettre l'inclusion de groupes
  7832. if (is_array($include)) {
  7833. $includeGroups = implode(",", $include);
  7834. }
  7835. if (!is_array($selected)) {
  7836. $selected = array($selected);
  7837. }
  7838. $out = '';
  7839. // On recherche les groupes
  7840. $sql = "SELECT ug.rowid, ug.nom as name";
  7841. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  7842. $sql .= ", e.label";
  7843. }
  7844. $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  7845. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  7846. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  7847. if ($force_entity) {
  7848. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  7849. } else {
  7850. $sql .= " WHERE ug.entity IS NOT NULL";
  7851. }
  7852. } else {
  7853. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  7854. }
  7855. if (is_array($exclude) && $excludeGroups) {
  7856. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  7857. }
  7858. if (is_array($include) && $includeGroups) {
  7859. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  7860. }
  7861. $sql .= " ORDER BY ug.nom ASC";
  7862. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  7863. $resql = $this->db->query($sql);
  7864. if ($resql) {
  7865. // Enhance with select2
  7866. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7867. $out .= ajax_combobox($htmlname);
  7868. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  7869. $num = $this->db->num_rows($resql);
  7870. $i = 0;
  7871. if ($num) {
  7872. if ($show_empty && !$multiple) {
  7873. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  7874. }
  7875. while ($i < $num) {
  7876. $obj = $this->db->fetch_object($resql);
  7877. $disableline = 0;
  7878. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  7879. $disableline = 1;
  7880. }
  7881. $out .= '<option value="'.$obj->rowid.'"';
  7882. if ($disableline) {
  7883. $out .= ' disabled';
  7884. }
  7885. if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (!is_object($selected[0]) && in_array($obj->rowid, $selected))) {
  7886. $out .= ' selected';
  7887. }
  7888. $out .= '>';
  7889. $out .= $obj->name;
  7890. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  7891. $out .= " (".$obj->label.")";
  7892. }
  7893. $out .= '</option>';
  7894. $i++;
  7895. }
  7896. } else {
  7897. if ($show_empty) {
  7898. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  7899. }
  7900. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  7901. }
  7902. $out .= '</select>';
  7903. } else {
  7904. dol_print_error($this->db);
  7905. }
  7906. return $out;
  7907. }
  7908. /**
  7909. * Return HTML to show the search and clear seach button
  7910. *
  7911. * @return string
  7912. */
  7913. public function showFilterButtons()
  7914. {
  7915. $out = '<div class="nowraponall">';
  7916. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  7917. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  7918. $out .= '</div>';
  7919. return $out;
  7920. }
  7921. /**
  7922. * Return HTML to show the search and clear search button
  7923. *
  7924. * @param string $cssclass CSS class
  7925. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  7926. * @param string $massactionname Mass action button name that will launch an action on the selected items
  7927. * @return string
  7928. */
  7929. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  7930. {
  7931. global $conf, $langs;
  7932. $out = '';
  7933. if (!empty($conf->use_javascript_ajax)) {
  7934. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  7935. }
  7936. $out .= '<script>
  7937. $(document).ready(function() {
  7938. $("#' . $cssclass.'s").click(function() {
  7939. if($(this).is(\':checked\')){
  7940. console.log("We check all '.$cssclass.' and trigger the change method");
  7941. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  7942. }
  7943. else
  7944. {
  7945. console.log("We uncheck all");
  7946. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  7947. }'."\n";
  7948. if ($calljsfunction) {
  7949. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  7950. }
  7951. $out .= ' });
  7952. $(".' . $cssclass.'").change(function() {
  7953. $(this).closest("tr").toggleClass("highlight", this.checked);
  7954. });
  7955. });
  7956. </script>';
  7957. return $out;
  7958. }
  7959. /**
  7960. * Return HTML to show the search and clear seach button
  7961. *
  7962. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  7963. * @param string $cssclass CSS class
  7964. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  7965. * @param string $massactionname Mass action name
  7966. * @return string
  7967. */
  7968. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  7969. {
  7970. $out = $this->showFilterButtons();
  7971. if ($addcheckuncheckall) {
  7972. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  7973. }
  7974. return $out;
  7975. }
  7976. /**
  7977. * Return HTML to show the select of expense categories
  7978. *
  7979. * @param string $selected preselected category
  7980. * @param string $htmlname name of HTML select list
  7981. * @param integer $useempty 1=Add empty line
  7982. * @param array $excludeid id to exclude
  7983. * @param string $target htmlname of target select to bind event
  7984. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  7985. * @param array $params param to give
  7986. * @param int $info_admin Show the tooltip help picto to setup list
  7987. * @return string
  7988. */
  7989. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  7990. {
  7991. global $db, $langs, $user;
  7992. $out = '';
  7993. $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
  7994. $sql .= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
  7995. if (!empty($excludeid)) {
  7996. $sql .= ' AND rowid NOT IN ('.$this->db->sanitize(implode(',', $excludeid)).')';
  7997. }
  7998. $sql .= ' ORDER BY label';
  7999. $resql = $db->query($sql);
  8000. if ($resql) {
  8001. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8002. if ($useempty) {
  8003. $out .= '<option value="0">&nbsp;</option>';
  8004. }
  8005. while ($obj = $db->fetch_object($resql)) {
  8006. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8007. }
  8008. $out .= '</select>';
  8009. $out .= ajax_combobox('select_'.$htmlname);
  8010. if (!empty($htmlname) && $user->admin && $info_admin) {
  8011. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8012. }
  8013. if (!empty($target)) {
  8014. $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8015. $resql = $db->query($sql);
  8016. if ($resql) {
  8017. if ($db->num_rows($resql) > 0) {
  8018. $obj = $db->fetch_object($resql);
  8019. $out .= '<script>
  8020. $(function() {
  8021. $("select[name='.$target.']").on("change", function() {
  8022. var current_val = $(this).val();
  8023. if (current_val == '.$obj->id.') {';
  8024. if (!empty($default_selected) || !empty($selected)) {
  8025. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8026. }
  8027. $out .= '
  8028. $("select[name='.$htmlname.']").change();
  8029. }
  8030. });
  8031. $("select[name='.$htmlname.']").change(function() {
  8032. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8033. // get price of kilometer to fill the unit price
  8034. $.ajax({
  8035. method: "POST",
  8036. dataType: "json",
  8037. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8038. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.$params).'",
  8039. }).done(function( data, textStatus, jqXHR ) {
  8040. console.log(data);
  8041. if (typeof data.up != "undefined") {
  8042. $("input[name=value_unit]").val(data.up);
  8043. $("select[name='.$htmlname.']").attr("title", data.title);
  8044. } else {
  8045. $("input[name=value_unit]").val("");
  8046. $("select[name='.$htmlname.']").attr("title", "");
  8047. }
  8048. });
  8049. }
  8050. });
  8051. });
  8052. </script>';
  8053. }
  8054. }
  8055. }
  8056. } else {
  8057. dol_print_error($db);
  8058. }
  8059. return $out;
  8060. }
  8061. /**
  8062. * Return HTML to show the select ranges of expense range
  8063. *
  8064. * @param string $selected preselected category
  8065. * @param string $htmlname name of HTML select list
  8066. * @param integer $useempty 1=Add empty line
  8067. * @return string
  8068. */
  8069. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8070. {
  8071. global $db, $conf, $langs;
  8072. $out = '';
  8073. $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
  8074. $sql .= ' WHERE entity = '.$conf->entity.' AND active = 1';
  8075. $resql = $db->query($sql);
  8076. if ($resql) {
  8077. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8078. if ($useempty) {
  8079. $out .= '<option value="0"></option>';
  8080. }
  8081. while ($obj = $db->fetch_object($resql)) {
  8082. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8083. }
  8084. $out .= '</select>';
  8085. } else {
  8086. dol_print_error($db);
  8087. }
  8088. return $out;
  8089. }
  8090. /**
  8091. * Return HTML to show a select of expense
  8092. *
  8093. * @param string $selected preselected category
  8094. * @param string $htmlname name of HTML select list
  8095. * @param integer $useempty 1=Add empty choice
  8096. * @param integer $allchoice 1=Add all choice
  8097. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8098. * @return string
  8099. */
  8100. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8101. {
  8102. global $db, $langs;
  8103. $out = '';
  8104. $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
  8105. $sql .= ' WHERE active = 1';
  8106. $resql = $db->query($sql);
  8107. if ($resql) {
  8108. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8109. if ($useempty) {
  8110. $out .= '<option value="0"></option>';
  8111. }
  8112. if ($allchoice) {
  8113. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8114. }
  8115. $field = 'code';
  8116. if ($useid) {
  8117. $field = 'id';
  8118. }
  8119. while ($obj = $db->fetch_object($resql)) {
  8120. $key = $langs->trans($obj->code);
  8121. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8122. }
  8123. $out .= '</select>';
  8124. } else {
  8125. dol_print_error($db);
  8126. }
  8127. return $out;
  8128. }
  8129. /**
  8130. * Output a combo list with invoices qualified for a third party
  8131. *
  8132. * @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)
  8133. * @param int $selected Id invoice preselected
  8134. * @param string $htmlname Name of HTML select
  8135. * @param int $maxlength Maximum length of label
  8136. * @param int $option_only Return only html options lines without the select tag
  8137. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8138. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8139. * @param int $forcefocus Force focus on field (works with javascript only)
  8140. * @param int $disabled Disabled
  8141. * @param string $morecss More css added to the select component
  8142. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8143. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8144. * @param User $usertofilter User object to use for filtering
  8145. * @return int Nbr of project if OK, <0 if KO
  8146. */
  8147. public function selectInvoice($socid = -1, $selected = '', $htmlname = 'invoiceid', $maxlength = 24, $option_only = 0, $show_empty = '1', $discard_closed = 0, $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500', $projectsListId = '', $showproject = 'all', $usertofilter = null)
  8148. {
  8149. global $user, $conf, $langs;
  8150. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8151. if (is_null($usertofilter)) {
  8152. $usertofilter = $user;
  8153. }
  8154. $out = '';
  8155. $hideunselectables = false;
  8156. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8157. $hideunselectables = true;
  8158. }
  8159. if (empty($projectsListId)) {
  8160. if (empty($usertofilter->rights->projet->all->lire)) {
  8161. $projectstatic = new Project($this->db);
  8162. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8163. }
  8164. }
  8165. // Search all projects
  8166. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8167. p.title, p.fk_soc, p.fk_statut, p.public,";
  8168. $sql .= ' s.nom as name';
  8169. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p';
  8170. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
  8171. $sql .= ' '.MAIN_DB_PREFIX.'facture as f';
  8172. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  8173. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  8174. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  8175. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  8176. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  8177. $sql .= " ORDER BY p.ref, f.ref ASC";
  8178. $resql = $this->db->query($sql);
  8179. if ($resql) {
  8180. // Use select2 selector
  8181. if (!empty($conf->use_javascript_ajax)) {
  8182. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8183. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8184. $out .= $comboenhancement;
  8185. $morecss = 'minwidth200imp maxwidth500';
  8186. }
  8187. if (empty($option_only)) {
  8188. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  8189. }
  8190. if (!empty($show_empty)) {
  8191. $out .= '<option value="0" class="optiongrey">';
  8192. if (!is_numeric($show_empty)) {
  8193. $out .= $show_empty;
  8194. } else {
  8195. $out .= '&nbsp;';
  8196. }
  8197. $out .= '</option>';
  8198. }
  8199. $num = $this->db->num_rows($resql);
  8200. $i = 0;
  8201. if ($num) {
  8202. while ($i < $num) {
  8203. $obj = $this->db->fetch_object($resql);
  8204. // If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
  8205. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  8206. // Do nothing
  8207. } else {
  8208. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  8209. $i++;
  8210. continue;
  8211. }
  8212. $labeltoshow = '';
  8213. if ($showproject == 'all') {
  8214. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  8215. if ($obj->name) {
  8216. $labeltoshow .= ' - '.$obj->name; // Soc name
  8217. }
  8218. $disabled = 0;
  8219. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  8220. $disabled = 1;
  8221. $labeltoshow .= ' - '.$langs->trans("Draft");
  8222. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  8223. if ($discard_closed == 2) {
  8224. $disabled = 1;
  8225. }
  8226. $labeltoshow .= ' - '.$langs->trans("Closed");
  8227. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  8228. $disabled = 1;
  8229. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  8230. }
  8231. }
  8232. if (!empty($selected) && $selected == $obj->rowid) {
  8233. $out .= '<option value="'.$obj->rowid.'" selected';
  8234. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8235. $out .= '>'.$labeltoshow.'</option>';
  8236. } else {
  8237. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8238. $resultat = '';
  8239. } else {
  8240. $resultat = '<option value="'.$obj->rowid.'"';
  8241. if ($disabled) {
  8242. $resultat .= ' disabled';
  8243. }
  8244. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  8245. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  8246. $resultat .= '>';
  8247. $resultat .= $labeltoshow;
  8248. $resultat .= '</option>';
  8249. }
  8250. $out .= $resultat;
  8251. }
  8252. }
  8253. $i++;
  8254. }
  8255. }
  8256. if (empty($option_only)) {
  8257. $out .= '</select>';
  8258. }
  8259. print $out;
  8260. $this->db->free($resql);
  8261. return $num;
  8262. } else {
  8263. dol_print_error($this->db);
  8264. return -1;
  8265. }
  8266. }
  8267. /**
  8268. * Output the component to make advanced search criteries
  8269. *
  8270. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  8271. * @param array $search_component_params Array of selected search criterias
  8272. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  8273. * @return string HTML component for advanced search
  8274. */
  8275. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array())
  8276. {
  8277. global $langs;
  8278. $ret = '';
  8279. $ret .= '<div class="nowrap centpercent">';
  8280. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8281. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor paddingright">';
  8282. $ret .= '<span class="fas fa-filter linkobject boxfilter" title="Filter" id="idsubimgproductdistribution"></span>';
  8283. $ret .= $langs->trans("Filters");
  8284. $ret .= '</a>';
  8285. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8286. $ret .= '<div name="search_component_params" class="search_component_params inline-block minwidth500 maxwidth300onsmartphone valignmiddle">';
  8287. $texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  8288. $ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  8289. $ret .= '</div>';
  8290. $ret .= '<input type="hidden" name="search_component_params_hidden" class="search_component_params_hidden" value="'.GETPOST("search_component_params_hidden").'">';
  8291. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  8292. foreach ($arrayofcriterias as $criterias) {
  8293. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  8294. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  8295. continue;
  8296. }
  8297. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  8298. continue;
  8299. }
  8300. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  8301. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  8302. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  8303. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  8304. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  8305. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  8306. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  8307. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  8308. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  8309. } else {
  8310. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  8311. }
  8312. }
  8313. }
  8314. $ret .= '</div>';
  8315. return $ret;
  8316. }
  8317. /**
  8318. * selectModelMail
  8319. *
  8320. * @param string $prefix Prefix
  8321. * @param string $modelType Model type
  8322. * @param int $default 1=Show also Default mail template
  8323. * @param int $addjscombo Add js combobox
  8324. * @return string HTML select string
  8325. */
  8326. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  8327. {
  8328. global $langs, $db, $user;
  8329. $retstring = '';
  8330. $TModels = array();
  8331. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  8332. $formmail = new FormMail($db);
  8333. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  8334. if ($default) {
  8335. $TModels[0] = $langs->trans('DefaultMailModel');
  8336. }
  8337. if ($result > 0) {
  8338. foreach ($formmail->lines_model as $model) {
  8339. $TModels[$model->id] = $model->label;
  8340. }
  8341. }
  8342. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  8343. foreach ($TModels as $id_model => $label_model) {
  8344. $retstring .= '<option value="'.$id_model.'"';
  8345. $retstring .= ">".$label_model."</option>";
  8346. }
  8347. $retstring .= "</select>";
  8348. if ($addjscombo) {
  8349. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  8350. }
  8351. return $retstring;
  8352. }
  8353. /**
  8354. * Output the buttons to submit a creation/edit form
  8355. *
  8356. * @param string $save_label Alternative label for save button
  8357. * @param string $cancel_label Alternative label for cancel button
  8358. * @param array $morefields Add additional buttons between save and cancel
  8359. * @param bool $withoutdiv Option to remove enclosing centered div
  8360. * @return string Html code with the buttons
  8361. */
  8362. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morefields = array(), $withoutdiv = 0)
  8363. {
  8364. global $langs;
  8365. $buttons = array();
  8366. $save = array(
  8367. 'name' => 'save',
  8368. 'label_key' => $save_label,
  8369. );
  8370. if ($save_label == 'Create' || $save_label == 'Add' ) {
  8371. $save['name'] = 'add';
  8372. } elseif ($save_label == 'Modify') {
  8373. $save['name'] = 'edit';
  8374. }
  8375. $cancel = array(
  8376. 'name' => 'cancel',
  8377. 'label_key' => 'Cancel',
  8378. );
  8379. !empty($save_label) ? $buttons[] = $save : '';
  8380. if (!empty($morefields)) {
  8381. $buttons[] = $morefields;
  8382. }
  8383. !empty($cancel_label) ? $buttons[] = $cancel : '';
  8384. $retstring = $withoutdiv ? '': '<div class="center">';
  8385. foreach ($buttons as $button) {
  8386. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  8387. $retstring .= '<input type="submit" class="button button-'.$button['name'].' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  8388. }
  8389. $retstring .= $withoutdiv ? '': '</div>';
  8390. return $retstring;
  8391. }
  8392. }