html.form.class.php 461 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997
  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-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018-2022 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  21. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  22. * Copyright (C) 2018 Christophe Battarel <christophe@altairis.fr>
  23. * Copyright (C) 2018 Josep Lluis Amador <joseplluis@lliuretic.cat>
  24. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  25. * Copyright (C) 2023 Nick Fragoulis
  26. *
  27. * This program is free software; you can redistribute it and/or modify
  28. * it under the terms of the GNU General Public License as published by
  29. * the Free Software Foundation; either version 3 of the License, or
  30. * (at your option) any later version.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU General Public License
  38. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  39. */
  40. /**
  41. * \file htdocs/core/class/html.form.class.php
  42. * \ingroup core
  43. * \brief File of class with all html predefined components
  44. */
  45. /**
  46. * Class to manage generation of HTML components
  47. * Only common components must be here.
  48. *
  49. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  50. */
  51. class Form
  52. {
  53. /**
  54. * @var DoliDB Database handler.
  55. */
  56. public $db;
  57. /**
  58. * @var string Error code (or message)
  59. */
  60. public $error = '';
  61. /**
  62. * @var string[] Array of error strings
  63. */
  64. public $errors = array();
  65. // Some properties used to return data by some methods
  66. public $result;
  67. public $num;
  68. // Cache arrays
  69. public $cache_types_paiements = array();
  70. public $cache_conditions_paiements = array();
  71. public $cache_transport_mode = array();
  72. public $cache_availability = array();
  73. public $cache_demand_reason = array();
  74. public $cache_types_fees = array();
  75. public $cache_vatrates = array();
  76. public $cache_invoice_subtype = array();
  77. /**
  78. * Constructor
  79. *
  80. * @param DoliDB $db Database handler
  81. */
  82. public function __construct($db)
  83. {
  84. $this->db = $db;
  85. }
  86. /**
  87. * Output key field for an editable field
  88. *
  89. * @param string $text Text of label or key to translate
  90. * @param string $htmlname Name of select field ('edit' prefix will be added)
  91. * @param string $preselected Value to show/edit (not used in this function)
  92. * @param object $object Object (on the page we show)
  93. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  94. * @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 'datehourpicker' 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  95. * @param string $moreparam More param to add on a href URL.
  96. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  97. * @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 ' '
  98. * @param string $paramid Key of parameter for id ('id', 'socid')
  99. * @param string $help Tooltip help
  100. * @return string HTML edit field
  101. */
  102. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  103. {
  104. global $conf, $langs;
  105. $ret = '';
  106. // TODO change for compatibility
  107. if (getDolGlobalString('MAIN_USE_JQUERY_JEDITABLE') && !preg_match('/^select;/', $typeofdata)) {
  108. if (!empty($perm)) {
  109. $tmp = explode(':', $typeofdata);
  110. $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
  111. if ($fieldrequired) {
  112. $ret .= '<span class="fieldrequired">';
  113. }
  114. if ($help) {
  115. $ret .= $this->textwithpicto($langs->trans($text), $help);
  116. } else {
  117. $ret .= $langs->trans($text);
  118. }
  119. if ($fieldrequired) {
  120. $ret .= '</span>';
  121. }
  122. $ret .= '</div>' . "\n";
  123. } else {
  124. if ($fieldrequired) {
  125. $ret .= '<span class="fieldrequired">';
  126. }
  127. if ($help) {
  128. $ret .= $this->textwithpicto($langs->trans($text), $help);
  129. } else {
  130. $ret .= $langs->trans($text);
  131. }
  132. if ($fieldrequired) {
  133. $ret .= '</span>';
  134. }
  135. }
  136. } else {
  137. if (empty($notabletag) && $perm) {
  138. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  139. }
  140. if ($fieldrequired) {
  141. $ret .= '<span class="fieldrequired">';
  142. }
  143. if ($help) {
  144. $ret .= $this->textwithpicto($langs->trans($text), $help);
  145. } else {
  146. $ret .= $langs->trans($text);
  147. }
  148. if ($fieldrequired) {
  149. $ret .= '</span>';
  150. }
  151. if (!empty($notabletag)) {
  152. $ret .= ' ';
  153. }
  154. if (empty($notabletag) && $perm) {
  155. $ret .= '</td>';
  156. }
  157. if (empty($notabletag) && $perm) {
  158. $ret .= '<td class="right">';
  159. }
  160. if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
  161. $ret .= '<a class="editfielda reposition" href="' . $_SERVER["PHP_SELF"] . '?action=edit' . $htmlname . '&token=' . newToken() . '&' . $paramid . '=' . $object->id . $moreparam . '">' . img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)) . '</a>';
  162. }
  163. if (!empty($notabletag) && $notabletag == 1) {
  164. if ($text) {
  165. $ret .= ' : ';
  166. } else {
  167. $ret .= ' ';
  168. }
  169. }
  170. if (!empty($notabletag) && $notabletag == 3) {
  171. $ret .= ' ';
  172. }
  173. if (empty($notabletag) && $perm) {
  174. $ret .= '</td>';
  175. }
  176. if (empty($notabletag) && $perm) {
  177. $ret .= '</tr></table>';
  178. }
  179. }
  180. return $ret;
  181. }
  182. /**
  183. * Output value of a field for an editable field
  184. *
  185. * @param string $text Text of label (not used in this function)
  186. * @param string $htmlname Name of select field
  187. * @param string $value Value to show/edit
  188. * @param object $object Object (that we want to show)
  189. * @param boolean $perm Permission to allow button to edit parameter
  190. * @param string $typeofdata Type of data ('string' by default, 'checkbox', 'email', 'phone', 'amount:99', 'numeric:99',
  191. * 'text' or 'textarea:rows:cols%', 'safehtmlstring', 'restricthtml',
  192. * 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datehourpicker', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  193. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of numeric value, or a select combo). Use '' to use same than $value
  194. * @param object $extObject External object ???
  195. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  196. * @param string $moreparam More param to add on the form on action href URL parameter
  197. * @param int $notabletag Do no output table tags
  198. * @param string $formatfunc Call a specific method of $object->$formatfunc to output field in view mode (For example: 'dol_print_email')
  199. * @param string $paramid Key of parameter for id ('id', 'socid')
  200. * @param string $gm 'auto' or 'tzuser' or 'tzuserrel' or 'tzserver' (when $typeofdata is a date)
  201. * @param array $moreoptions Array with more options. For example array('addnowlink'=>1), array('valuealreadyhtmlescaped'=>1)
  202. * @param string $editaction [=''] use GETPOST default action or set action to edit mode
  203. * @return string HTML edit field
  204. */
  205. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 1, $formatfunc = '', $paramid = 'id', $gm = 'auto', $moreoptions = array(), $editaction = '')
  206. {
  207. global $conf, $langs;
  208. $ret = '';
  209. // Check parameters
  210. if (empty($typeofdata)) {
  211. return 'ErrorBadParameter typeofdata is empty';
  212. }
  213. // Clean paramater $typeofdata
  214. if ($typeofdata == 'datetime') {
  215. $typeofdata = 'dayhour';
  216. }
  217. $reg = array();
  218. if (preg_match('/^(\w+)\((\d+)\)$/', $typeofdata, $reg)) {
  219. if ($reg[1] == 'varchar') {
  220. $typeofdata = 'string';
  221. } elseif ($reg[1] == 'int') {
  222. $typeofdata = 'numeric';
  223. } else {
  224. return 'ErrorBadParameter ' . $typeofdata;
  225. }
  226. }
  227. // When option to edit inline is activated
  228. if (getDolGlobalString('MAIN_USE_JQUERY_JEDITABLE') && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  229. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  230. } else {
  231. if ($editaction == '') {
  232. $editaction = GETPOST('action', 'aZ09');
  233. }
  234. $editmode = ($editaction == 'edit' . $htmlname);
  235. if ($editmode) { // edit mode
  236. $ret .= "\n";
  237. $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
  238. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  239. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  240. $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
  241. if (empty($notabletag)) {
  242. $ret .= '<table class="nobordernopadding centpercent">';
  243. }
  244. if (empty($notabletag)) {
  245. $ret .= '<tr><td>';
  246. }
  247. if (preg_match('/^(string|safehtmlstring|email|phone|url)/', $typeofdata)) {
  248. $tmp = explode(':', $typeofdata);
  249. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  250. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  251. $tmp = explode(':', $typeofdata);
  252. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  253. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $valuetoshow . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  254. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  255. $tmp = explode(':', $typeofdata);
  256. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  257. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  258. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  259. $tmp = explode(':', $typeofdata);
  260. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($value ? $value : 'on') . '"' . ($value ? ' checked' : '') . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
  261. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  262. $tmp = explode(':', $typeofdata);
  263. $cols = (empty($tmp[2]) ? '' : $tmp[2]);
  264. $morealt = '';
  265. if (preg_match('/%/', $cols)) {
  266. $morealt = ' style="width: ' . $cols . '"';
  267. $cols = '';
  268. }
  269. $valuetoshow = ($editvalue ? $editvalue : $value);
  270. $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . (empty($tmp[1]) ? '20' : $tmp[1]) . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '" autofocus>';
  271. // textarea convert automatically entities chars into simple chars.
  272. // 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.
  273. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  274. $ret .= dol_htmlwithnojs(dol_string_neverthesehtmltags($valuetoshow, array('textarea')));
  275. $ret .= '</textarea>';
  276. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  277. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  278. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  279. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  280. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  281. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  282. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  283. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  284. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  285. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  286. } elseif (preg_match('/^select;/', $typeofdata)) {
  287. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  288. $arraylist = array();
  289. foreach ($arraydata as $val) {
  290. $tmp = explode(':', $val);
  291. $tmpkey = str_replace('|', ':', $tmp[0]);
  292. $arraylist[$tmpkey] = $tmp[1];
  293. }
  294. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  295. } elseif (preg_match('/^link/', $typeofdata)) {
  296. // TODO Not yet implemented. See code for extrafields
  297. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  298. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  299. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  300. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), (empty($tmp[2]) ? '' : $tmp[2]), (empty($tmp[3]) ? '100' : $tmp[3]), (empty($tmp[1]) ? 'dolibarr_notes' : $tmp[1]), 'In', (empty($tmp[5]) ? 0 : $tmp[5]), (isset($tmp[8]) ? ($tmp[8] ? true : false) : true), true, (empty($tmp[6]) ? '20' : $tmp[6]), (empty($tmp[7]) ? '100' : $tmp[7]));
  301. $ret .= $doleditor->Create(1);
  302. } elseif ($typeofdata == 'asis') {
  303. $ret .= ($editvalue ? $editvalue : $value);
  304. }
  305. if (empty($notabletag)) {
  306. $ret .= '</td>';
  307. }
  308. // Button save-cancel
  309. if (empty($notabletag)) {
  310. $ret .= '<td>';
  311. }
  312. //else $ret.='<div class="clearboth"></div>';
  313. $ret .= '<input type="submit" class="smallpaddingimp button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Modify") . '">';
  314. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  315. $ret .= '<br>' . "\n";
  316. }
  317. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
  318. if (empty($notabletag)) {
  319. $ret .= '</td>';
  320. }
  321. if (empty($notabletag)) {
  322. $ret .= '</tr></table>' . "\n";
  323. }
  324. $ret .= '</form>' . "\n";
  325. } else { // view mode
  326. if (preg_match('/^email/', $typeofdata)) {
  327. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  328. } elseif (preg_match('/^phone/', $typeofdata)) {
  329. $ret .= dol_print_phone($value, '_blank', 32, 1);
  330. } elseif (preg_match('/^url/', $typeofdata)) {
  331. $ret .= dol_print_url($value, '_blank', 32, 1);
  332. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  333. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  334. } elseif (preg_match('/^checkbox/', $typeofdata)) {
  335. $tmp = explode(':', $typeofdata);
  336. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($value ? ' checked' : '') . ($tmp[1] ? $tmp[1] : '') . '/>';
  337. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  338. $ret .= dol_htmlwithnojs(dol_string_onlythesehtmltags(dol_htmlentitiesbr($value), 1, 1, 1));
  339. } elseif (preg_match('/^(safehtmlstring|restricthtml)/', $typeofdata)) { // 'restricthtml' is not an allowed type for editfieldval. Value is 'safehtmlstring'
  340. $ret .= dol_htmlwithnojs(dol_string_onlythesehtmltags($value));
  341. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  342. $ret .= '<span class="valuedate">' . dol_print_date($value, 'day', $gm) . '</span>';
  343. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  344. $ret .= '<span class="valuedate">' . dol_print_date($value, 'dayhour', $gm) . '</span>';
  345. } elseif (preg_match('/^select;/', $typeofdata)) {
  346. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  347. $arraylist = array();
  348. foreach ($arraydata as $val) {
  349. $tmp = explode(':', $val);
  350. $arraylist[$tmp[0]] = $tmp[1];
  351. }
  352. $ret .= $arraylist[$value];
  353. if ($htmlname == 'fk_product_type') {
  354. if ($value == 0) {
  355. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  356. } else {
  357. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  358. }
  359. }
  360. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  361. $tmpcontent = dol_htmlentitiesbr($value);
  362. if (getDolGlobalString('MAIN_DISABLE_NOTES_TAB')) {
  363. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  364. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  365. $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  366. }
  367. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  368. // clean data from some dangerous html
  369. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  370. } else {
  371. if (empty($moreoptions['valuealreadyhtmlescaped'])) {
  372. $ret .= dol_escape_htmltag($value);
  373. } else {
  374. $ret .= $value; // $value must be already html escaped.
  375. }
  376. }
  377. // Custom format if parameter $formatfunc has been provided
  378. if ($formatfunc && method_exists($object, $formatfunc)) {
  379. $ret = $object->$formatfunc($ret);
  380. }
  381. }
  382. }
  383. return $ret;
  384. }
  385. /**
  386. * Output edit in place form
  387. *
  388. * @param string $fieldname Name of the field
  389. * @param object $object Object
  390. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  391. * @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]'...)
  392. * @param string $check Same coe than $check parameter of GETPOST()
  393. * @param string $morecss More CSS
  394. * @return string HTML code for the edit of alternative language
  395. */
  396. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  397. {
  398. global $conf, $langs, $extralanguages;
  399. $result = '';
  400. // List of extra languages
  401. $arrayoflangcode = array();
  402. if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
  403. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  404. }
  405. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  406. if (!is_object($extralanguages)) {
  407. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  408. $extralanguages = new ExtraLanguages($this->db);
  409. }
  410. $extralanguages->fetch_name_extralanguages('societe');
  411. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  412. return ''; // No extralang field to show
  413. }
  414. $result .= '<!-- Widget for translation -->' . "\n";
  415. $result .= '<div class="inline-block paddingleft image-' . $object->element . '-' . $fieldname . '">';
  416. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  417. $result .= $s;
  418. $result .= '</div>';
  419. $result .= '<div class="inline-block hidden field-' . $object->element . '-' . $fieldname . '">';
  420. $resultforextrlang = '';
  421. foreach ($arrayoflangcode as $langcode) {
  422. $valuetoshow = GETPOSTISSET('field-' . $object->element . "-" . $fieldname . "-" . $langcode) ? GETPOST('field-' . $object->element . '-' . $fieldname . "-" . $langcode, $check) : '';
  423. if (empty($valuetoshow)) {
  424. $object->fetchValuesForExtraLanguages();
  425. //var_dump($object->array_languages);
  426. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  427. }
  428. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  429. $resultforextrlang .= $s;
  430. // TODO Use the showInputField() method of ExtraLanguages object
  431. if ($typeofdata == 'textarea') {
  432. $resultforextrlang .= '<textarea name="field-' . $object->element . "-" . $fieldname . "-" . $langcode . '" id="' . $fieldname . "-" . $langcode . '" class="' . $morecss . '" rows="' . ROWS_2 . '" wrap="soft">';
  433. $resultforextrlang .= $valuetoshow;
  434. $resultforextrlang .= '</textarea>';
  435. } else {
  436. $resultforextrlang .= '<input type="text" class="inputfieldforlang ' . ($morecss ? ' ' . $morecss : '') . '" name="field-' . $object->element . '-' . $fieldname . '-' . $langcode . '" value="' . $valuetoshow . '">';
  437. }
  438. }
  439. $result .= $resultforextrlang;
  440. $result .= '</div>';
  441. $result .= '<script nonce="' . getNonce() . '">$(".image-' . $object->element . '-' . $fieldname . '").click(function() { console.log("Toggle lang widget"); jQuery(".field-' . $object->element . '-' . $fieldname . '").toggle(); });</script>';
  442. }
  443. return $result;
  444. }
  445. /**
  446. * Output edit in place form
  447. *
  448. * @param object $object Object
  449. * @param string $value Value to show/edit
  450. * @param string $htmlname DIV ID (field name)
  451. * @param int $condition Condition to edit
  452. * @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')
  453. * @param string $editvalue When in edit mode, use this value as $value instead of value
  454. * @param object $extObject External object
  455. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  456. * @return string HTML edit in place
  457. */
  458. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  459. {
  460. global $conf;
  461. $out = '';
  462. // Check parameters
  463. if (preg_match('/^text/', $inputType)) {
  464. $value = dol_nl2br($value);
  465. } elseif (preg_match('/^numeric/', $inputType)) {
  466. $value = price($value);
  467. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  468. $value = dol_print_date($value, 'day');
  469. }
  470. if ($condition) {
  471. $element = false;
  472. $table_element = false;
  473. $fk_element = false;
  474. $loadmethod = false;
  475. $savemethod = false;
  476. $ext_element = false;
  477. $button_only = false;
  478. $inputOption = '';
  479. $rows = '';
  480. $cols = '';
  481. if (is_object($object)) {
  482. $element = $object->element;
  483. $table_element = $object->table_element;
  484. $fk_element = $object->id;
  485. }
  486. if (is_object($extObject)) {
  487. $ext_element = $extObject->element;
  488. }
  489. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  490. $tmp = explode(':', $inputType);
  491. $inputType = $tmp[0];
  492. if (!empty($tmp[1])) {
  493. $inputOption = $tmp[1];
  494. }
  495. if (!empty($tmp[2])) {
  496. $savemethod = $tmp[2];
  497. }
  498. $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
  499. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  500. $tmp = explode(':', $inputType);
  501. $inputType = $tmp[0];
  502. if (!empty($tmp[1])) {
  503. $inputOption = $tmp[1];
  504. }
  505. if (!empty($tmp[2])) {
  506. $savemethod = $tmp[2];
  507. }
  508. $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
  509. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  510. $tmp = explode(':', $inputType);
  511. $inputType = $tmp[0];
  512. $loadmethod = $tmp[1];
  513. if (!empty($tmp[2])) {
  514. $savemethod = $tmp[2];
  515. }
  516. if (!empty($tmp[3])) {
  517. $button_only = true;
  518. }
  519. } elseif (preg_match('/^textarea/', $inputType)) {
  520. $tmp = explode(':', $inputType);
  521. $inputType = $tmp[0];
  522. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  523. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  524. } elseif (preg_match('/^ckeditor/', $inputType)) {
  525. $tmp = explode(':', $inputType);
  526. $inputType = $tmp[0];
  527. $toolbar = $tmp[1];
  528. if (!empty($tmp[2])) {
  529. $width = $tmp[2];
  530. }
  531. if (!empty($tmp[3])) {
  532. $heigth = $tmp[3];
  533. }
  534. if (!empty($tmp[4])) {
  535. $savemethod = $tmp[4];
  536. }
  537. if (isModEnabled('fckeditor')) {
  538. $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
  539. } else {
  540. $inputType = 'textarea';
  541. }
  542. }
  543. $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
  544. $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
  545. $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
  546. $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
  547. if (!empty($savemethod)) {
  548. $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
  549. }
  550. if (!empty($ext_element)) {
  551. $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
  552. }
  553. if (!empty($custommsg)) {
  554. if (is_array($custommsg)) {
  555. if (!empty($custommsg['success'])) {
  556. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
  557. }
  558. if (!empty($custommsg['error'])) {
  559. $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
  560. }
  561. } else {
  562. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
  563. }
  564. }
  565. if ($inputType == 'textarea') {
  566. $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
  567. $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
  568. }
  569. $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
  570. $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
  571. } else {
  572. $out = $value;
  573. }
  574. return $out;
  575. }
  576. /**
  577. * Show a text and picto with tooltip on text or picto.
  578. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  579. *
  580. * @param string $text Text to show
  581. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  582. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  583. * @param int $direction -1=image is before, 0=no image, 1=image is after
  584. * @param string $img Html code for image (use img_xxx() function to get it)
  585. * @param string $extracss Add a CSS style to td tags
  586. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  587. * @param string $incbefore Include code before the text
  588. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  589. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  590. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  591. * @return string Code html du tooltip (texte+picto)
  592. * @see textwithpicto() Use textwithpicto() instead of textwithtooltip if you can.
  593. */
  594. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  595. {
  596. if ($incbefore) {
  597. $text = $incbefore . $text;
  598. }
  599. if (!$htmltext) {
  600. return $text;
  601. }
  602. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  603. $tag = 'td';
  604. if ($notabs == 2) {
  605. $tag = 'div';
  606. }
  607. if ($notabs == 3) {
  608. $tag = 'span';
  609. }
  610. // Sanitize tooltip
  611. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  612. $extrastyle = '';
  613. if ($direction < 0) {
  614. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  615. $extrastyle = 'padding: 0px; padding-left: 3px;';
  616. }
  617. if ($direction > 0) {
  618. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  619. $extrastyle = 'padding: 0px; padding-right: 3px;';
  620. }
  621. $classfortooltip = 'classfortooltip';
  622. $s = '';
  623. $textfordialog = '';
  624. if ($tooltiptrigger == '') {
  625. $htmltext = str_replace('"', '&quot;', $htmltext);
  626. } else {
  627. $classfortooltip = 'classfortooltiponclick';
  628. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext">' . $htmltext . '</div>';
  629. }
  630. if ($tooltipon == 2 || $tooltipon == 3) {
  631. $paramfortooltipimg = ' class="' . $classfortooltip . ($notabs != 3 ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
  632. if ($tooltiptrigger == '') {
  633. $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on img tag to store tooltip
  634. } else {
  635. $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
  636. }
  637. } else {
  638. $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  639. }
  640. if ($tooltipon == 1 || $tooltipon == 3) {
  641. $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ' inline-block' . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
  642. if ($tooltiptrigger == '') {
  643. $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on td tag to store tooltip
  644. } else {
  645. $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
  646. }
  647. } else {
  648. $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  649. }
  650. if (empty($notabs)) {
  651. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  652. } elseif ($notabs == 2) {
  653. $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
  654. }
  655. // Define value if value is before
  656. if ($direction < 0) {
  657. $s .= '<' . $tag . $paramfortooltipimg;
  658. if ($tag == 'td') {
  659. $s .= ' class="valigntop" width="14"';
  660. }
  661. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  662. }
  663. // Use another method to help avoid having a space in value in order to use this value with jquery
  664. // Define label
  665. if ((string) $text != '') {
  666. $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
  667. }
  668. // Define value if value is after
  669. if ($direction > 0) {
  670. $s .= '<' . $tag . $paramfortooltipimg;
  671. if ($tag == 'td') {
  672. $s .= ' class="valignmiddle" width="14"';
  673. }
  674. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  675. }
  676. if (empty($notabs)) {
  677. $s .= '</tr></table>';
  678. } elseif ($notabs == 2) {
  679. $s .= '</div>';
  680. }
  681. return $s;
  682. }
  683. /**
  684. * Show a text with a picto and a tooltip on picto
  685. *
  686. * @param string $text Text to show
  687. * @param string $htmltext Content of tooltip
  688. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  689. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  690. * @param string $extracss Add a CSS style to td, div or span tag
  691. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  692. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  693. * @param string $tooltiptrigger ''=Tooltip on hover and hidden on smartphone, 'abconsmartphone'=Tooltip on hover and on click on smartphone, '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')
  694. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  695. * @return string HTML code of text, picto, tooltip
  696. */
  697. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  698. {
  699. global $conf, $langs;
  700. //For backwards compatibility
  701. if ($type == '0') {
  702. $type = 'info';
  703. } elseif ($type == '1') {
  704. $type = 'help';
  705. }
  706. // Clean parameters
  707. $tooltiptrigger = preg_replace('/[^a-z0-9]/i', '', $tooltiptrigger);
  708. if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
  709. $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
  710. }
  711. $alt = '';
  712. if ($tooltiptrigger) {
  713. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  714. }
  715. // If info or help with no javascript, show only text
  716. if (empty($conf->use_javascript_ajax)) {
  717. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  718. return $text;
  719. } else {
  720. $alt = $htmltext;
  721. $htmltext = '';
  722. }
  723. }
  724. // If info or help with smartphone, show only text (tooltip hover can't works)
  725. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  726. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  727. return $text;
  728. }
  729. }
  730. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  731. //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
  732. //{
  733. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.'</a>';
  734. //}
  735. $img = '';
  736. if ($type == 'info') {
  737. $img = img_help(0, $alt);
  738. } elseif ($type == 'help') {
  739. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  740. } elseif ($type == 'helpclickable') {
  741. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  742. } elseif ($type == 'superadmin') {
  743. $img = img_picto($alt, 'redstar');
  744. } elseif ($type == 'admin') {
  745. $img = img_picto($alt, 'star');
  746. } elseif ($type == 'warning') {
  747. $img = img_warning($alt);
  748. } elseif ($type != 'none') {
  749. $img = img_picto($alt, $type); // $type can be an image path
  750. }
  751. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  752. }
  753. /**
  754. * Generate select HTML to choose massaction
  755. *
  756. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  757. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  758. * @param int $alwaysvisible 1=select button always visible
  759. * @param string $name Name for massaction
  760. * @param string $cssclass CSS class used to check for select
  761. * @return string|void Select list
  762. */
  763. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  764. {
  765. global $conf, $langs, $hookmanager;
  766. $disabled = 0;
  767. $ret = '<div class="centpercent center">';
  768. $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'select valignmiddle alignstart" id="' . $name . '" name="' . $name . '"' . ($disabled ? ' disabled="disabled"' : '') . '>';
  769. // 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.
  770. $parameters = array();
  771. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  772. // check if there is a mass action
  773. if (is_array($arrayofaction) && count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  774. return;
  775. }
  776. if (empty($reshook)) {
  777. $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
  778. if (is_array($arrayofaction)) {
  779. foreach ($arrayofaction as $code => $label) {
  780. $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . ' data-html="' . dol_escape_htmltag($label) . '">' . $label . '</option>';
  781. }
  782. }
  783. }
  784. $ret .= $hookmanager->resPrint;
  785. $ret .= '</select>';
  786. if (empty($conf->dol_optimize_smallscreen)) {
  787. $ret .= ajax_combobox('.' . $name . 'select');
  788. }
  789. // 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
  790. $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.
  791. $ret .= '<input type="submit" disabled name="confirmmassaction"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display: none"') . ' class="reposition button smallpaddingimp' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'confirmed" value="' . dol_escape_htmltag($langs->trans("Confirm")) . '">';
  792. $ret .= '</div>';
  793. if (!empty($conf->use_javascript_ajax)) {
  794. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  795. <script nonce="' . getNonce() . '">
  796. 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 */
  797. {
  798. atleastoneselected=0;
  799. jQuery("."+cssclass).each(function( index ) {
  800. /* console.log( index + ": " + $( this ).text() ); */
  801. if ($(this).is(\':checked\')) atleastoneselected++;
  802. });
  803. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  804. if (atleastoneselected || ' . $alwaysvisible . ')
  805. {
  806. jQuery("."+name).show();
  807. ' . ($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("' . $selected . '").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '') . '
  808. ' . ($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '') . '
  809. }
  810. else
  811. {
  812. jQuery("."+name).hide();
  813. jQuery("."+name+"other").hide();
  814. }
  815. }
  816. jQuery(document).ready(function () {
  817. initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
  818. jQuery(".' . $cssclass . '").click(function() {
  819. initCheckForSelect(1, "' . $name . '", "' . $cssclass . '");
  820. });
  821. jQuery(".' . $name . 'select").change(function() {
  822. var massaction = $( this ).val();
  823. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  824. if (massaction == "builddoc")
  825. {
  826. urlform = urlform + "#show_files";
  827. }
  828. $( this ).closest("form").attr("action", urlform);
  829. console.log("we select a mass action name=' . $name . ' massaction="+massaction+" - "+urlform);
  830. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  831. if ($(this).val() != \'0\')
  832. {
  833. jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
  834. jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
  835. jQuery(".' . $name . '"+massaction).show();
  836. }
  837. else
  838. {
  839. jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
  840. jQuery(".' . $name . 'other").hide(); /* To disable any div open */
  841. }
  842. });
  843. });
  844. </script>
  845. ';
  846. }
  847. return $ret;
  848. }
  849. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  850. /**
  851. * Return combo list of activated countries, into language of user
  852. *
  853. * @param string $selected Id or Code or Label of preselected country
  854. * @param string $htmlname Name of html select object
  855. * @param string $htmloption More html options on select object
  856. * @param integer $maxlength Max length for labels (0=no limit)
  857. * @param string $morecss More css class
  858. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  859. * @param int|string $showempty Show empty choice
  860. * @param int $disablefavorites 1=Disable favorites,
  861. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  862. * @param array $exclude_country_code Array of country code (iso2) to exclude
  863. * @param int $hideflags Hide flags
  864. * @return string HTML string with select
  865. */
  866. 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)
  867. {
  868. // phpcs:enable
  869. global $conf, $langs, $mysoc;
  870. $langs->load("dict");
  871. $out = '';
  872. $countryArray = array();
  873. $favorite = array();
  874. $label = array();
  875. $atleastonefavorite = 0;
  876. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  877. $sql .= " FROM " . $this->db->prefix() . "c_country";
  878. $sql .= " WHERE active > 0";
  879. //$sql.= " ORDER BY code ASC";
  880. dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
  881. $resql = $this->db->query($sql);
  882. if ($resql) {
  883. $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
  884. $num = $this->db->num_rows($resql);
  885. $i = 0;
  886. if ($num) {
  887. while ($i < $num) {
  888. $obj = $this->db->fetch_object($resql);
  889. $countryArray[$i]['rowid'] = $obj->rowid;
  890. $countryArray[$i]['code_iso'] = $obj->code_iso;
  891. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  892. $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 : ''));
  893. $countryArray[$i]['favorite'] = $obj->favorite;
  894. $countryArray[$i]['eec'] = $obj->eec;
  895. $favorite[$i] = $obj->favorite;
  896. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  897. $i++;
  898. }
  899. if (empty($disablefavorites)) {
  900. $array1_sort_order = SORT_DESC;
  901. $array2_sort_order = SORT_ASC;
  902. array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
  903. } else {
  904. $countryArray = dol_sort_array($countryArray, 'label');
  905. }
  906. if ($showempty) {
  907. if (is_numeric($showempty)) {
  908. $out .= '<option value="">&nbsp;</option>' . "\n";
  909. } else {
  910. $out .= '<option value="-1">' . $langs->trans($showempty) . '</option>' . "\n";
  911. }
  912. }
  913. if ($addspecialentries) { // Add dedicated entries for groups of countries
  914. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  915. $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  916. $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
  917. if ($mysoc->isInEEC()) {
  918. $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  919. }
  920. $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
  921. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  922. }
  923. foreach ($countryArray as $row) {
  924. //if (empty($showempty) && empty($row['rowid'])) continue;
  925. if (empty($row['rowid'])) {
  926. continue;
  927. }
  928. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  929. continue; // exclude some countries
  930. }
  931. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  932. $atleastonefavorite++;
  933. }
  934. if (empty($row['favorite']) && $atleastonefavorite) {
  935. $atleastonefavorite = 0;
  936. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  937. }
  938. $labeltoshow = '';
  939. if ($row['label']) {
  940. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  941. } else {
  942. $labeltoshow .= '&nbsp;';
  943. }
  944. if ($row['code_iso']) {
  945. $labeltoshow .= ' <span class="opacitymedium">(' . $row['code_iso'] . ')</span>';
  946. if (empty($hideflags)) {
  947. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  948. $labeltoshow = $tmpflag . ' ' . $labeltoshow;
  949. }
  950. }
  951. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  952. $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']) . '">';
  953. } else {
  954. $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']) . '">';
  955. }
  956. $out .= $labeltoshow;
  957. $out .= '</option>' . "\n";
  958. }
  959. }
  960. $out .= '</select>';
  961. } else {
  962. dol_print_error($this->db);
  963. }
  964. // Make select dynamic
  965. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  966. $out .= ajax_combobox('select' . $htmlname, array(), 0, 0, 'resolve');
  967. return $out;
  968. }
  969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  970. /**
  971. * Return select list of incoterms
  972. *
  973. * @param string $selected Id or Code of preselected incoterm
  974. * @param string $location_incoterms Value of input location
  975. * @param string $page Defined the form action
  976. * @param string $htmlname Name of html select object
  977. * @param string $htmloption Options html on select object
  978. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  979. * @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')))
  980. * @param int $disableautocomplete Disable autocomplete
  981. * @return string HTML string with select and input
  982. */
  983. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  984. {
  985. // phpcs:enable
  986. global $conf, $langs;
  987. $langs->load("dict");
  988. $out = '';
  989. $moreattrib = '';
  990. $incotermArray = array();
  991. $sql = "SELECT rowid, code";
  992. $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
  993. $sql .= " WHERE active > 0";
  994. $sql .= " ORDER BY code ASC";
  995. dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
  996. $resql = $this->db->query($sql);
  997. if ($resql) {
  998. if ($conf->use_javascript_ajax && !$forcecombo) {
  999. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1000. $out .= ajax_combobox($htmlname, $events);
  1001. }
  1002. if (!empty($page)) {
  1003. $out .= '<form method="post" action="' . $page . '">';
  1004. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  1005. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  1006. }
  1007. $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
  1008. $out .= '<option value="0">&nbsp;</option>';
  1009. $num = $this->db->num_rows($resql);
  1010. $i = 0;
  1011. if ($num) {
  1012. while ($i < $num) {
  1013. $obj = $this->db->fetch_object($resql);
  1014. $incotermArray[$i]['rowid'] = $obj->rowid;
  1015. $incotermArray[$i]['code'] = $obj->code;
  1016. $i++;
  1017. }
  1018. foreach ($incotermArray as $row) {
  1019. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  1020. $out .= '<option value="' . $row['rowid'] . '" selected>';
  1021. } else {
  1022. $out .= '<option value="' . $row['rowid'] . '">';
  1023. }
  1024. if ($row['code']) {
  1025. $out .= $row['code'];
  1026. }
  1027. $out .= '</option>';
  1028. }
  1029. }
  1030. $out .= '</select>';
  1031. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  1032. $out .= ajax_multiautocompleter('location_incoterms', array(), DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
  1033. $moreattrib .= ' autocomplete="off"';
  1034. }
  1035. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
  1036. if (!empty($page)) {
  1037. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
  1038. }
  1039. } else {
  1040. dol_print_error($this->db);
  1041. }
  1042. return $out;
  1043. }
  1044. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1045. /**
  1046. * Return list of types of lines (product or service)
  1047. * Example: 0=product, 1=service, 9=other (for external module)
  1048. *
  1049. * @param string $selected Preselected type
  1050. * @param string $htmlname Name of field in html form
  1051. * @param int $showempty Add an empty field
  1052. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  1053. * @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')
  1054. * @return void
  1055. */
  1056. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  1057. {
  1058. // phpcs:enable
  1059. global $langs;
  1060. // If product & services are enabled or both disabled.
  1061. if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
  1062. || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
  1063. if (empty($hidetext)) {
  1064. print $langs->trans("Type") . ': ';
  1065. }
  1066. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  1067. if ($showempty) {
  1068. print '<option value="-1"';
  1069. if ($selected == -1) {
  1070. print ' selected';
  1071. }
  1072. print '>&nbsp;</option>';
  1073. }
  1074. print '<option value="0"';
  1075. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1076. print ' selected';
  1077. }
  1078. print '>' . $langs->trans("Product");
  1079. print '<option value="1"';
  1080. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1081. print ' selected';
  1082. }
  1083. print '>' . $langs->trans("Service");
  1084. print '</select>';
  1085. print ajax_combobox('select_' . $htmlname);
  1086. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1087. }
  1088. if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
  1089. print $langs->trans("Service");
  1090. print '<input type="hidden" name="' . $htmlname . '" value="1">';
  1091. }
  1092. if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
  1093. print $langs->trans("Product");
  1094. print '<input type="hidden" name="' . $htmlname . '" value="0">';
  1095. }
  1096. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1097. 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
  1098. }
  1099. }
  1100. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1101. /**
  1102. * Load into cache cache_types_fees, array of types of fees
  1103. *
  1104. * @return int Nb of lines loaded, <0 if KO
  1105. */
  1106. public function load_cache_types_fees()
  1107. {
  1108. // phpcs:enable
  1109. global $langs;
  1110. $num = count($this->cache_types_fees);
  1111. if ($num > 0) {
  1112. return 0; // Cache already loaded
  1113. }
  1114. dol_syslog(__METHOD__, LOG_DEBUG);
  1115. $langs->load("trips");
  1116. $sql = "SELECT c.code, c.label";
  1117. $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
  1118. $sql .= " WHERE active > 0";
  1119. $resql = $this->db->query($sql);
  1120. if ($resql) {
  1121. $num = $this->db->num_rows($resql);
  1122. $i = 0;
  1123. while ($i < $num) {
  1124. $obj = $this->db->fetch_object($resql);
  1125. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1126. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1127. $this->cache_types_fees[$obj->code] = $label;
  1128. $i++;
  1129. }
  1130. asort($this->cache_types_fees);
  1131. return $num;
  1132. } else {
  1133. dol_print_error($this->db);
  1134. return -1;
  1135. }
  1136. }
  1137. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1138. /**
  1139. * Return list of types of notes
  1140. *
  1141. * @param string $selected Preselected type
  1142. * @param string $htmlname Name of field in form
  1143. * @param int $showempty Add an empty field
  1144. * @return void
  1145. */
  1146. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1147. {
  1148. // phpcs:enable
  1149. global $user, $langs;
  1150. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  1151. $this->load_cache_types_fees();
  1152. print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
  1153. if ($showempty) {
  1154. print '<option value="-1"';
  1155. if ($selected == -1) {
  1156. print ' selected';
  1157. }
  1158. print '>&nbsp;</option>';
  1159. }
  1160. foreach ($this->cache_types_fees as $key => $value) {
  1161. print '<option value="' . $key . '"';
  1162. if ($key == $selected) {
  1163. print ' selected';
  1164. }
  1165. print '>';
  1166. print $value;
  1167. print '</option>';
  1168. }
  1169. print '</select>';
  1170. if ($user->admin) {
  1171. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1172. }
  1173. }
  1174. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1175. /**
  1176. * Output html form to select a third party
  1177. *
  1178. * @param string $selected Preselected type
  1179. * @param string $htmlname Name of field in form
  1180. * @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)'). Do not use a filter coming from input of users.
  1181. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1182. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1183. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1184. * @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')))
  1185. * @param int $limit Maximum number of elements
  1186. * @param string $morecss Add more css styles to the SELECT component
  1187. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1188. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1189. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1190. * @param array $ajaxoptions Options for ajax_autocompleter
  1191. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1192. * @param array $excludeids Exclude IDs from the select combo
  1193. * @param int $showcode Show code
  1194. * @return string HTML string with select box for thirdparty.
  1195. */
  1196. 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(), $showcode = 0)
  1197. {
  1198. // phpcs:enable
  1199. global $conf, $user, $langs;
  1200. $out = '';
  1201. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT') && !$forcecombo) {
  1202. if (is_null($ajaxoptions)) {
  1203. $ajaxoptions = array();
  1204. }
  1205. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1206. // No immediate load of all database
  1207. $placeholder = '';
  1208. if ($selected && empty($selected_input_value)) {
  1209. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1210. $societetmp = new Societe($this->db);
  1211. $societetmp->fetch($selected);
  1212. $selected_input_value = $societetmp->name;
  1213. unset($societetmp);
  1214. }
  1215. // mode 1
  1216. $urloption = 'htmlname=' . urlencode(str_replace('.', '_', $htmlname)) . '&outjson=1&filter=' . urlencode($filter) . (empty($excludeids) ? '' : '&excludeids=' . join(',', $excludeids)) . ($showtype ? '&showtype=' . urlencode($showtype) : '') . ($showcode ? '&showcode=' . urlencode($showcode) : '');
  1217. $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
  1218. if (empty($hidelabel)) {
  1219. print $langs->trans("RefOrLabel") . ' : ';
  1220. } elseif ($hidelabel > 1) {
  1221. $placeholder = $langs->trans("RefOrLabel");
  1222. if ($hidelabel == 2) {
  1223. $out .= img_picto($langs->trans("Search"), 'search');
  1224. }
  1225. }
  1226. $out .= '<input type="text" class="' . $morecss . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '') . ' ' . (getDolGlobalString('THIRDPARTY_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  1227. if ($hidelabel == 3) {
  1228. $out .= img_picto($langs->trans("Search"), 'search');
  1229. }
  1230. $out .= ajax_event($htmlname, $events);
  1231. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1232. } else {
  1233. // Immediate load of all database
  1234. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1235. }
  1236. return $out;
  1237. }
  1238. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1239. /**
  1240. * Output html form to select a third party.
  1241. * 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.
  1242. *
  1243. * @param string $selected Preselected type
  1244. * @param string $htmlname Name of field in form
  1245. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>] are allowed here, example: 's.rowid <> x'
  1246. * If you need parenthesis, use the Universal Filter Syntax, example: '(s.client:in:1,3)'
  1247. * Do not use a filter coming from input of users.
  1248. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1249. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1250. * @param int $forcecombo Force to use standard HTML select component without beautification
  1251. * @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')))
  1252. * @param string $filterkey Filter on key value
  1253. * @param int $outputmode 0=HTML select string, 1=Array
  1254. * @param int $limit Limit number of answers
  1255. * @param string $morecss Add more css styles to the SELECT component
  1256. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1257. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1258. * @param array $excludeids Exclude IDs from the select combo
  1259. * @param int $showcode Show code in list
  1260. * @return array|string HTML string with
  1261. */
  1262. 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(), $showcode = 0)
  1263. {
  1264. // phpcs:enable
  1265. global $conf, $user, $langs;
  1266. global $hookmanager;
  1267. $out = '';
  1268. $num = 0;
  1269. $outarray = array();
  1270. if ($selected === '') {
  1271. $selected = array();
  1272. } elseif (!is_array($selected)) {
  1273. $selected = array($selected);
  1274. }
  1275. // Clean $filter that may contains sql conditions so sql code
  1276. if (function_exists('testSqlAndScriptInject')) {
  1277. if (testSqlAndScriptInject($filter, 3) > 0) {
  1278. $filter = '';
  1279. return 'SQLInjectionTryDetected';
  1280. }
  1281. }
  1282. if ($filter != '') { // If a filter was provided
  1283. if (preg_match('/[\(\)]/', $filter)) {
  1284. // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
  1285. $errormsg = '';
  1286. $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
  1287. // Redo clean $filter that may contains sql conditions so sql code
  1288. if (function_exists('testSqlAndScriptInject')) {
  1289. if (testSqlAndScriptInject($filter, 3) > 0) {
  1290. $filter = '';
  1291. return 'SQLInjectionTryDetected';
  1292. }
  1293. }
  1294. } else {
  1295. // If not, we do nothing. We already know that there is no parenthesis
  1296. // TODO Disallow this case in a future.
  1297. dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Syntax.", LOG_WARNING);
  1298. }
  1299. }
  1300. // We search companies
  1301. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1302. if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
  1303. $sql .= ", s.address, s.zip, s.town";
  1304. $sql .= ", dictp.code as country_code";
  1305. }
  1306. $sql .= " FROM " . $this->db->prefix() . "societe as s";
  1307. if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
  1308. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
  1309. }
  1310. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  1311. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  1312. }
  1313. $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
  1314. if (!empty($user->socid)) {
  1315. $sql .= " AND s.rowid = " . ((int) $user->socid);
  1316. }
  1317. if ($filter) {
  1318. // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
  1319. // if not, by testSqlAndScriptInject() only.
  1320. $sql .= " AND (" . $filter . ")";
  1321. }
  1322. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  1323. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  1324. }
  1325. if (getDolGlobalString('COMPANY_HIDE_INACTIVE_IN_COMBOBOX')) {
  1326. $sql .= " AND s.status <> 0";
  1327. }
  1328. if (!empty($excludeids)) {
  1329. $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(join(',', $excludeids)) . ")";
  1330. }
  1331. // Add where from hooks
  1332. $parameters = array();
  1333. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1334. $sql .= $hookmanager->resPrint;
  1335. // Add criteria
  1336. if ($filterkey && $filterkey != '') {
  1337. $sql .= " AND (";
  1338. $prefix = !getDolGlobalString('COMPANY_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1339. // For natural search
  1340. $scrit = explode(' ', $filterkey);
  1341. $i = 0;
  1342. if (count($scrit) > 1) {
  1343. $sql .= "(";
  1344. }
  1345. foreach ($scrit as $crit) {
  1346. if ($i > 0) {
  1347. $sql .= " AND ";
  1348. }
  1349. $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  1350. $i++;
  1351. }
  1352. if (count($scrit) > 1) {
  1353. $sql .= ")";
  1354. }
  1355. if (isModEnabled('barcode')) {
  1356. $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1357. }
  1358. $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1359. $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1360. $sql .= ")";
  1361. }
  1362. $sql .= $this->db->order("nom", "ASC");
  1363. $sql .= $this->db->plimit($limit, 0);
  1364. // Build output string
  1365. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1366. $resql = $this->db->query($sql);
  1367. if ($resql) {
  1368. if (!$forcecombo) {
  1369. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1370. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1371. }
  1372. // Construct $out and $outarray
  1373. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . '>' . "\n";
  1374. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1375. if (getDolGlobalString('COMPANY_USE_SEARCH_TO_SELECT')) {
  1376. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1377. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1378. if ($showempty && !is_numeric($showempty)) {
  1379. $textifempty = $langs->trans($showempty);
  1380. } else {
  1381. $textifempty .= $langs->trans("All");
  1382. }
  1383. }
  1384. if ($showempty) {
  1385. $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
  1386. }
  1387. $companytemp = new Societe($this->db);
  1388. $num = $this->db->num_rows($resql);
  1389. $i = 0;
  1390. if ($num) {
  1391. while ($i < $num) {
  1392. $obj = $this->db->fetch_object($resql);
  1393. $label = '';
  1394. if ($showcode || getDolGlobalString('SOCIETE_ADD_REF_IN_LIST')) {
  1395. if (($obj->client) && (!empty($obj->code_client))) {
  1396. $label = $obj->code_client . ' - ';
  1397. }
  1398. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1399. $label .= $obj->code_fournisseur . ' - ';
  1400. }
  1401. $label .= ' ' . $obj->name;
  1402. } else {
  1403. $label = $obj->name;
  1404. }
  1405. if (!empty($obj->name_alias)) {
  1406. $label .= ' (' . $obj->name_alias . ')';
  1407. }
  1408. if (getDolGlobalString('SOCIETE_SHOW_VAT_IN_LIST') && !empty($obj->tva_intra)) {
  1409. $label .= ' - '.$obj->tva_intra;
  1410. }
  1411. $labelhtml = $label;
  1412. if ($showtype) {
  1413. $companytemp->id = $obj->rowid;
  1414. $companytemp->client = $obj->client;
  1415. $companytemp->fournisseur = $obj->fournisseur;
  1416. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1417. if ($tmptype) {
  1418. $labelhtml .= ' ' . $tmptype;
  1419. }
  1420. if ($obj->client || $obj->fournisseur) {
  1421. $label .= ' (';
  1422. }
  1423. if ($obj->client == 1 || $obj->client == 3) {
  1424. $label .= $langs->trans("Customer");
  1425. }
  1426. if ($obj->client == 2 || $obj->client == 3) {
  1427. $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
  1428. }
  1429. if ($obj->fournisseur) {
  1430. $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
  1431. }
  1432. if ($obj->client || $obj->fournisseur) {
  1433. $label .= ')';
  1434. }
  1435. }
  1436. if (getDolGlobalString('COMPANY_SHOW_ADDRESS_SELECTLIST')) {
  1437. $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
  1438. if (!empty($obj->country_code)) {
  1439. $s .= ', ' . $langs->trans('Country' . $obj->country_code);
  1440. }
  1441. $label .= $s;
  1442. $labelhtml .= $s;
  1443. }
  1444. if (empty($outputmode)) {
  1445. if (in_array($obj->rowid, $selected)) {
  1446. $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  1447. } else {
  1448. $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  1449. }
  1450. } else {
  1451. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
  1452. }
  1453. $i++;
  1454. if (($i % 10) == 0) {
  1455. $out .= "\n";
  1456. }
  1457. }
  1458. }
  1459. $out .= '</select>' . "\n";
  1460. } else {
  1461. dol_print_error($this->db);
  1462. }
  1463. $this->result = array('nbofthirdparties' => $num);
  1464. if ($outputmode) {
  1465. return $outarray;
  1466. }
  1467. return $out;
  1468. }
  1469. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1470. /**
  1471. * Return HTML combo list of absolute discounts
  1472. *
  1473. * @param string $selected Id remise fixe pre-selectionnee
  1474. * @param string $htmlname Nom champ formulaire
  1475. * @param string $filter Criteres optionnels de filtre
  1476. * @param int $socid Id of thirdparty
  1477. * @param int $maxvalue Max value for lines that can be selected
  1478. * @return int Return number of qualifed lines in list
  1479. */
  1480. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1481. {
  1482. // phpcs:enable
  1483. global $langs, $conf;
  1484. // On recherche les remises
  1485. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1486. $sql .= " re.description, re.fk_facture_source";
  1487. $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
  1488. $sql .= " WHERE re.fk_soc = " . (int) $socid;
  1489. $sql .= " AND re.entity = " . $conf->entity;
  1490. if ($filter) {
  1491. $sql .= " AND " . $filter;
  1492. }
  1493. $sql .= " ORDER BY re.description ASC";
  1494. dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
  1495. $resql = $this->db->query($sql);
  1496. if ($resql) {
  1497. print '<select id="select_' . $htmlname . '" class="flat maxwidthonsmartphone" name="' . $htmlname . '">';
  1498. $num = $this->db->num_rows($resql);
  1499. $qualifiedlines = $num;
  1500. $i = 0;
  1501. if ($num) {
  1502. print '<option value="0">&nbsp;</option>';
  1503. while ($i < $num) {
  1504. $obj = $this->db->fetch_object($resql);
  1505. $desc = dol_trunc($obj->description, 40);
  1506. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1507. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1508. }
  1509. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1510. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1511. }
  1512. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1513. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1514. }
  1515. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1516. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1517. }
  1518. $selectstring = '';
  1519. if ($selected > 0 && $selected == $obj->rowid) {
  1520. $selectstring = ' selected';
  1521. }
  1522. $disabled = '';
  1523. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1524. $qualifiedlines--;
  1525. $disabled = ' disabled';
  1526. }
  1527. if (getDolGlobalString('MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST') && !empty($obj->fk_facture_source)) {
  1528. $tmpfac = new Facture($this->db);
  1529. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1530. $desc = $desc . ' - ' . $tmpfac->ref;
  1531. }
  1532. }
  1533. print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  1534. $i++;
  1535. }
  1536. }
  1537. print '</select>';
  1538. print ajax_combobox('select_' . $htmlname);
  1539. return $qualifiedlines;
  1540. } else {
  1541. dol_print_error($this->db);
  1542. return -1;
  1543. }
  1544. }
  1545. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1546. /**
  1547. * Return list of all contacts (for a third party or all)
  1548. *
  1549. * @param int $socid Id ot third party or 0 for all
  1550. * @param string $selected Id contact pre-selectionne
  1551. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1552. * @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
  1553. * @param string $exclude List of contacts id to exclude
  1554. * @param string $limitto Disable answers that are not id in this array list
  1555. * @param integer $showfunction Add function into label
  1556. * @param string $morecss Add more class to class style
  1557. * @param integer $showsoc Add company into label
  1558. * @param int $forcecombo Force to use combo box
  1559. * @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')))
  1560. * @param bool $options_only Return options only (for ajax treatment)
  1561. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1562. * @param string $htmlid Html id to use instead of htmlname
  1563. * @return int Return integer <0 if KO, Nb of contact in list if OK
  1564. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1565. */
  1566. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1567. {
  1568. // phpcs:enable
  1569. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1570. return $this->num;
  1571. }
  1572. /**
  1573. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1574. * This also set the number of contacts found into $this->num
  1575. *
  1576. * @since 9.0 Add afterSelectContactOptions hook
  1577. *
  1578. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1579. * @param array|int $selected Array of ID of pre-selected contact id
  1580. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1581. * @param int|string $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
  1582. * @param string $exclude List of contacts id to exclude
  1583. * @param string $limitto Disable answers that are not id in this array list
  1584. * @param integer $showfunction Add function into label
  1585. * @param string $morecss Add more class to class style
  1586. * @param bool $options_only Return options only (for ajax treatment)
  1587. * @param integer $showsoc Add company into label
  1588. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1589. * @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')))
  1590. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1591. * @param string $htmlid Html id to use instead of htmlname
  1592. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1593. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1594. * @return int|string Return integer <0 if KO, HTML with select string if OK.
  1595. */
  1596. public function selectcontacts($socid, $selected = array(), $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1597. {
  1598. global $conf, $langs, $hookmanager, $action;
  1599. $langs->load('companies');
  1600. if (empty($htmlid)) {
  1601. $htmlid = $htmlname;
  1602. }
  1603. $num = 0;
  1604. if ($selected === '') {
  1605. $selected = array();
  1606. } elseif (!is_array($selected)) {
  1607. $selected = array($selected);
  1608. }
  1609. $out = '';
  1610. if (!is_object($hookmanager)) {
  1611. include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  1612. $hookmanager = new HookManager($this->db);
  1613. }
  1614. // We search third parties
  1615. $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";
  1616. if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
  1617. $sql .= ", s.nom as company, s.town AS company_town";
  1618. }
  1619. $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
  1620. if ($showsoc > 0 || getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
  1621. $sql .= " LEFT OUTER JOIN " . $this->db->prefix() . "societe as s ON s.rowid=sp.fk_soc";
  1622. }
  1623. $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
  1624. if ($socid > 0 || $socid == -1) {
  1625. $sql .= " AND sp.fk_soc = " . ((int) $socid);
  1626. }
  1627. if (getDolGlobalString('CONTACT_HIDE_INACTIVE_IN_COMBOBOX')) {
  1628. $sql .= " AND sp.statut <> 0";
  1629. }
  1630. // Add where from hooks
  1631. $parameters = array();
  1632. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1633. $sql .= $hookmanager->resPrint;
  1634. $sql .= " ORDER BY sp.lastname ASC";
  1635. dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
  1636. $resql = $this->db->query($sql);
  1637. if ($resql) {
  1638. $num = $this->db->num_rows($resql);
  1639. if ($htmlname != 'none' && !$options_only) {
  1640. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
  1641. }
  1642. if ($showempty && !is_numeric($showempty)) {
  1643. $textforempty = $showempty;
  1644. $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>';
  1645. } else {
  1646. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
  1647. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
  1648. }
  1649. if ($showempty == 2) {
  1650. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
  1651. }
  1652. }
  1653. $i = 0;
  1654. if ($num) {
  1655. include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  1656. $contactstatic = new Contact($this->db);
  1657. while ($i < $num) {
  1658. $obj = $this->db->fetch_object($resql);
  1659. // Set email (or phones) and town extended infos
  1660. $extendedInfos = '';
  1661. if (getDolGlobalString('CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST')) {
  1662. $extendedInfos = array();
  1663. $email = trim($obj->email);
  1664. if (!empty($email)) {
  1665. $extendedInfos[] = $email;
  1666. } else {
  1667. $phone = trim($obj->phone);
  1668. $phone_perso = trim($obj->phone_perso);
  1669. $phone_mobile = trim($obj->phone_mobile);
  1670. if (!empty($phone)) {
  1671. $extendedInfos[] = $phone;
  1672. }
  1673. if (!empty($phone_perso)) {
  1674. $extendedInfos[] = $phone_perso;
  1675. }
  1676. if (!empty($phone_mobile)) {
  1677. $extendedInfos[] = $phone_mobile;
  1678. }
  1679. }
  1680. $contact_town = trim($obj->contact_town);
  1681. $company_town = trim($obj->company_town);
  1682. if (!empty($contact_town)) {
  1683. $extendedInfos[] = $contact_town;
  1684. } elseif (!empty($company_town)) {
  1685. $extendedInfos[] = $company_town;
  1686. }
  1687. $extendedInfos = implode(' - ', $extendedInfos);
  1688. if (!empty($extendedInfos)) {
  1689. $extendedInfos = ' - ' . $extendedInfos;
  1690. }
  1691. }
  1692. $contactstatic->id = $obj->rowid;
  1693. $contactstatic->lastname = $obj->lastname;
  1694. $contactstatic->firstname = $obj->firstname;
  1695. if ($obj->statut == 1) {
  1696. if ($htmlname != 'none') {
  1697. $disabled = 0;
  1698. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1699. $disabled = 1;
  1700. }
  1701. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1702. $disabled = 1;
  1703. }
  1704. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1705. $out .= '<option value="' . $obj->rowid . '"';
  1706. if ($disabled) {
  1707. $out .= ' disabled';
  1708. }
  1709. $out .= ' selected>';
  1710. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1711. if ($showfunction && $obj->poste) {
  1712. $out .= ' (' . $obj->poste . ')';
  1713. }
  1714. if (($showsoc > 0) && $obj->company) {
  1715. $out .= ' - (' . $obj->company . ')';
  1716. }
  1717. $out .= '</option>';
  1718. } else {
  1719. $out .= '<option value="' . $obj->rowid . '"';
  1720. if ($disabled) {
  1721. $out .= ' disabled';
  1722. }
  1723. $out .= '>';
  1724. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1725. if ($showfunction && $obj->poste) {
  1726. $out .= ' (' . $obj->poste . ')';
  1727. }
  1728. if (($showsoc > 0) && $obj->company) {
  1729. $out .= ' - (' . $obj->company . ')';
  1730. }
  1731. $out .= '</option>';
  1732. }
  1733. } else {
  1734. if (in_array($obj->rowid, $selected)) {
  1735. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1736. if ($showfunction && $obj->poste) {
  1737. $out .= ' (' . $obj->poste . ')';
  1738. }
  1739. if (($showsoc > 0) && $obj->company) {
  1740. $out .= ' - (' . $obj->company . ')';
  1741. }
  1742. }
  1743. }
  1744. }
  1745. $i++;
  1746. }
  1747. } else {
  1748. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1749. $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
  1750. $out .= $labeltoshow;
  1751. $out .= '</option>';
  1752. }
  1753. $parameters = array(
  1754. 'socid' => $socid,
  1755. 'htmlname' => $htmlname,
  1756. 'resql' => $resql,
  1757. 'out' => &$out,
  1758. 'showfunction' => $showfunction,
  1759. 'showsoc' => $showsoc,
  1760. );
  1761. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1762. if ($htmlname != 'none' && !$options_only) {
  1763. $out .= '</select>';
  1764. }
  1765. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1766. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1767. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1768. }
  1769. $this->num = $num;
  1770. return $out;
  1771. } else {
  1772. dol_print_error($this->db);
  1773. return -1;
  1774. }
  1775. }
  1776. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1777. /**
  1778. * Return the HTML select list of users
  1779. *
  1780. * @param string $selected Id user preselected
  1781. * @param string $htmlname Field name in form
  1782. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1783. * @param array $exclude Array list of users id to exclude
  1784. * @param int $disabled If select list must be disabled
  1785. * @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
  1786. * @param array|int $enableonly Array list of users id to be enabled. All other must be disabled
  1787. * @param string $force_entity '0' or Ids of environment to force
  1788. * @return void
  1789. * @deprecated Use select_dolusers instead
  1790. * @see select_dolusers()
  1791. */
  1792. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0')
  1793. {
  1794. // phpcs:enable
  1795. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1796. }
  1797. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1798. /**
  1799. * Return select list of users
  1800. *
  1801. * @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)
  1802. * @param string $htmlname Field name in form
  1803. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1804. * @param array|null $exclude Array list of users id to exclude
  1805. * @param int $disabled If select list must be disabled
  1806. * @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
  1807. * @param array|string $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1808. * @param string $force_entity '0' or list of Ids of environment to force separated by a coma
  1809. * @param int $maxlength Maximum length of string into list (0=no limit)
  1810. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1811. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1812. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1813. * @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.
  1814. * @param string $morecss More css
  1815. * @param int $notdisabled Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1816. * @param int $outputmode 0=HTML select string, 1=Array
  1817. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1818. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1819. * @return array|string HTML select string
  1820. * @see select_dolgroups()
  1821. */
  1822. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $notdisabled = 0, $outputmode = 0, $multiple = false, $forcecombo = 0)
  1823. {
  1824. // phpcs:enable
  1825. global $conf, $user, $langs, $hookmanager;
  1826. global $action;
  1827. // If no preselected user defined, we take current user
  1828. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && !getDolGlobalString('SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE')) {
  1829. $selected = $user->id;
  1830. }
  1831. if ($selected === '') {
  1832. $selected = array();
  1833. } elseif (!is_array($selected)) {
  1834. $selected = array($selected);
  1835. }
  1836. $excludeUsers = null;
  1837. $includeUsers = null;
  1838. // Exclude some users
  1839. if (is_array($exclude)) {
  1840. $excludeUsers = implode(",", $exclude);
  1841. }
  1842. // Include some uses
  1843. if (is_array($include)) {
  1844. $includeUsers = implode(",", $include);
  1845. } elseif ($include == 'hierarchy') {
  1846. // Build list includeUsers to have only hierarchy
  1847. $includeUsers = implode(",", $user->getAllChildIds(0));
  1848. } elseif ($include == 'hierarchyme') {
  1849. // Build list includeUsers to have only hierarchy and current user
  1850. $includeUsers = implode(",", $user->getAllChildIds(1));
  1851. }
  1852. $out = '';
  1853. $outarray = array();
  1854. $outarray2 = array();
  1855. // Forge request to select users
  1856. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1857. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1858. $sql .= ", e.label";
  1859. }
  1860. $sql .= " FROM " . $this->db->prefix() . "user as u";
  1861. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1862. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
  1863. if (!empty($force_entity)) {
  1864. $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
  1865. } else {
  1866. $sql .= " WHERE u.entity IS NOT NULL";
  1867. }
  1868. } else {
  1869. if (isModEnabled('multicompany') && getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE')) {
  1870. $sql .= " WHERE u.rowid IN (SELECT ug.fk_user FROM ".$this->db->prefix()."usergroup_user as ug WHERE ug.entity IN (".getEntity('usergroup')."))";
  1871. } else {
  1872. $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
  1873. }
  1874. }
  1875. if (!empty($user->socid)) {
  1876. $sql .= " AND u.fk_soc = " . ((int) $user->socid);
  1877. }
  1878. if (is_array($exclude) && $excludeUsers) {
  1879. $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
  1880. }
  1881. if ($includeUsers) {
  1882. $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
  1883. }
  1884. if (getDolGlobalString('USER_HIDE_INACTIVE_IN_COMBOBOX') || $notdisabled) {
  1885. $sql .= " AND u.statut <> 0";
  1886. }
  1887. if (!empty($morefilter)) {
  1888. $sql .= " " . $morefilter;
  1889. }
  1890. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1891. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1892. if (!empty($reshook)) {
  1893. $sql .= $hookmanager->resPrint;
  1894. }
  1895. if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1896. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1897. } else {
  1898. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1899. }
  1900. dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
  1901. $resql = $this->db->query($sql);
  1902. if ($resql) {
  1903. $num = $this->db->num_rows($resql);
  1904. $i = 0;
  1905. if ($num) {
  1906. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1907. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  1908. if ($show_empty && !$multiple) {
  1909. $textforempty = ' ';
  1910. if (!empty($conf->use_javascript_ajax)) {
  1911. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1912. }
  1913. if (!is_numeric($show_empty)) {
  1914. $textforempty = $show_empty;
  1915. }
  1916. $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  1917. }
  1918. if ($show_every) {
  1919. $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
  1920. }
  1921. $userstatic = new User($this->db);
  1922. while ($i < $num) {
  1923. $obj = $this->db->fetch_object($resql);
  1924. $userstatic->id = $obj->rowid;
  1925. $userstatic->lastname = $obj->lastname;
  1926. $userstatic->firstname = $obj->firstname;
  1927. $userstatic->photo = $obj->photo;
  1928. $userstatic->statut = $obj->status;
  1929. $userstatic->entity = $obj->entity;
  1930. $userstatic->admin = $obj->admin;
  1931. $disableline = '';
  1932. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1933. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1934. }
  1935. $labeltoshow = '';
  1936. $labeltoshowhtml = '';
  1937. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1938. $fullNameMode = 0;
  1939. if (!getDolGlobalString('MAIN_FIRSTNAME_NAME_POSITION')) {
  1940. $fullNameMode = 1; //Firstname+lastname
  1941. }
  1942. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1943. $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1944. if (empty($obj->firstname) && empty($obj->lastname)) {
  1945. $labeltoshow .= $obj->login;
  1946. $labeltoshowhtml .= $obj->login;
  1947. }
  1948. // Complete name with a more info string like: ' (info1 - info2 - ...)'
  1949. $moreinfo = '';
  1950. $moreinfohtml = '';
  1951. if (getDolGlobalString('MAIN_SHOW_LOGIN')) {
  1952. $moreinfo .= ($moreinfo ? ' - ' : ' (');
  1953. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
  1954. $moreinfo .= $obj->login;
  1955. $moreinfohtml .= $obj->login;
  1956. }
  1957. if ($showstatus >= 0) {
  1958. if ($obj->status == 1 && $showstatus == 1) {
  1959. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
  1960. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
  1961. }
  1962. if ($obj->status == 0 && $showstatus == 1) {
  1963. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
  1964. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
  1965. }
  1966. }
  1967. if (isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1 && !empty($user->admin) && empty($user->entity)) {
  1968. if (empty($obj->entity)) {
  1969. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
  1970. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
  1971. } else {
  1972. if ($obj->entity != $conf->entity) {
  1973. $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1974. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1975. }
  1976. }
  1977. }
  1978. $moreinfo .= (!empty($moreinfo) ? ')' : '');
  1979. $moreinfohtml .= (!empty($moreinfohtml) ? ')</span>' : '');
  1980. if (!empty($disableline) && $disableline != '1') {
  1981. // Add text from $enableonlytext parameter
  1982. $moreinfo .= ' - ' . $disableline;
  1983. $moreinfohtml .= ' - ' . $disableline;
  1984. }
  1985. $labeltoshow .= $moreinfo;
  1986. $labeltoshowhtml .= $moreinfohtml;
  1987. $out .= '<option value="' . $obj->rowid . '"';
  1988. if (!empty($disableline)) {
  1989. $out .= ' disabled';
  1990. }
  1991. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1992. $out .= ' selected';
  1993. }
  1994. $out .= ' data-html="';
  1995. $outhtml = $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
  1996. if ($showstatus >= 0 && $obj->status == 0) {
  1997. $outhtml .= '<strike class="opacitymediumxxx">';
  1998. }
  1999. $outhtml .= $labeltoshowhtml;
  2000. if ($showstatus >= 0 && $obj->status == 0) {
  2001. $outhtml .= '</strike>';
  2002. }
  2003. $out .= dol_escape_htmltag($outhtml);
  2004. $out .= '">';
  2005. $out .= $labeltoshow;
  2006. $out .= '</option>';
  2007. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
  2008. $outarray2[$userstatic->id] = array(
  2009. 'id'=>$userstatic->id,
  2010. 'label'=>$labeltoshow,
  2011. 'labelhtml'=>$labeltoshowhtml,
  2012. 'color'=>'',
  2013. 'picto'=>''
  2014. );
  2015. $i++;
  2016. }
  2017. } else {
  2018. $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
  2019. $out .= '<option value="">' . $langs->trans("None") . '</option>';
  2020. }
  2021. $out .= '</select>';
  2022. if ($num && !$forcecombo) {
  2023. // Enhance with select2
  2024. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2025. $out .= ajax_combobox($htmlname);
  2026. }
  2027. } else {
  2028. dol_print_error($this->db);
  2029. }
  2030. if ($outputmode == 2) {
  2031. return $outarray2;
  2032. } elseif ($outputmode) {
  2033. return $outarray;
  2034. }
  2035. return $out;
  2036. }
  2037. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2038. /**
  2039. * Return select list of users. Selected users are stored into session.
  2040. * List of users are provided into $_SESSION['assignedtouser'].
  2041. *
  2042. * @param string $action Value for $action
  2043. * @param string $htmlname Field name in form
  2044. * @param int $show_empty 0=list without the empty value, 1=add empty value
  2045. * @param array $exclude Array list of users id to exclude
  2046. * @param int $disabled If select list must be disabled
  2047. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  2048. * @param array|int $enableonly Array list of users id to be enabled. All other must be disabled
  2049. * @param string $force_entity '0' or Ids of environment to force
  2050. * @param int $maxlength Maximum length of string into list (0=no limit)
  2051. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  2052. * @param string $morefilter Add more filters into sql request
  2053. * @param int $showproperties Show properties of each attendees
  2054. * @param array $listofuserid Array with properties of each user
  2055. * @param array $listofcontactid Array with properties of each contact
  2056. * @param array $listofotherid Array with properties of each other contact
  2057. * @return string HTML select string
  2058. * @see select_dolgroups()
  2059. */
  2060. public function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = array(), $enableonly = array(), $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array())
  2061. {
  2062. // phpcs:enable
  2063. global $langs;
  2064. $userstatic = new User($this->db);
  2065. $out = '';
  2066. $assignedtouser = array();
  2067. if (!empty($_SESSION['assignedtouser'])) {
  2068. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  2069. }
  2070. $nbassignetouser = count($assignedtouser);
  2071. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  2072. if ($nbassignetouser) {
  2073. $out .= '<ul class="attendees">';
  2074. }
  2075. $i = 0;
  2076. $ownerid = 0;
  2077. foreach ($assignedtouser as $key => $value) {
  2078. if ($value['id'] == $ownerid) {
  2079. continue;
  2080. }
  2081. $out .= '<li>';
  2082. $userstatic->fetch($value['id']);
  2083. $out .= $userstatic->getNomUrl(-1);
  2084. if ($i == 0) {
  2085. $ownerid = $value['id'];
  2086. $out .= ' (' . $langs->trans("Owner") . ')';
  2087. }
  2088. if ($nbassignetouser > 1 && $action != 'view') {
  2089. $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 . '">';
  2090. }
  2091. // Show my availability
  2092. if ($showproperties) {
  2093. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  2094. $out .= '<div class="myavailability inline-block">';
  2095. $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>';
  2096. $out .= '</div>';
  2097. }
  2098. }
  2099. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2100. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2101. $out .= '</li>';
  2102. $i++;
  2103. }
  2104. if ($nbassignetouser) {
  2105. $out .= '</ul>';
  2106. }
  2107. // Method with no ajax
  2108. if ($action != 'view') {
  2109. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2110. $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
  2111. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2112. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2113. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
  2114. $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
  2115. $out .= '});';
  2116. $out .= '})</script>';
  2117. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2118. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
  2119. $out .= '<br>';
  2120. }
  2121. return $out;
  2122. }
  2123. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2124. /**
  2125. * Return select list of resources. Selected resources are stored into session.
  2126. * List of resources are provided into $_SESSION['assignedtoresource'].
  2127. *
  2128. * @param string $action Value for $action
  2129. * @param string $htmlname Field name in form
  2130. * @param int $show_empty 0=list without the empty value, 1=add empty value
  2131. * @param array $exclude Array list of users id to exclude
  2132. * @param int $disabled If select list must be disabled
  2133. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  2134. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  2135. * @param string $force_entity '0' or Ids of environment to force
  2136. * @param int $maxlength Maximum length of string into list (0=no limit)
  2137. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  2138. * @param string $morefilter Add more filters into sql request
  2139. * @param int $showproperties Show properties of each attendees
  2140. * @param array $listofresourceid Array with properties of each resource
  2141. * @return string HTML select string
  2142. */
  2143. public function select_dolresources_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = array(), $enableonly = array(), $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofresourceid = array())
  2144. {
  2145. // phpcs:enable
  2146. global $langs;
  2147. require_once DOL_DOCUMENT_ROOT.'/resource/class/html.formresource.class.php';
  2148. require_once DOL_DOCUMENT_ROOT.'/resource/class/dolresource.class.php';
  2149. $formresources = new FormResource($this->db);
  2150. $resourcestatic = new Dolresource($this->db);
  2151. $out = '';
  2152. $assignedtoresource = array();
  2153. if (!empty($_SESSION['assignedtoresource'])) {
  2154. $assignedtoresource = json_decode($_SESSION['assignedtoresource'], true);
  2155. }
  2156. $nbassignetoresource = count($assignedtoresource);
  2157. //if ($nbassignetoresource && $action != 'view') $out .= '<br>';
  2158. if ($nbassignetoresource) {
  2159. $out .= '<ul class="attendees">';
  2160. }
  2161. $i = 0;
  2162. foreach ($assignedtoresource as $key => $value) {
  2163. $out .= '<li>';
  2164. $resourcestatic->fetch($value['id']);
  2165. $out .= $resourcestatic->getNomUrl(-1);
  2166. if ($nbassignetoresource > 1 && $action != 'view') {
  2167. $out .= ' <input type="image" style="border: 0px;" src="' . img_picto($langs->trans("Remove"), 'delete', '', 0, 1) . '" value="' . $resourcestatic->id . '" class="removedassigned reposition" id="removedassignedresource_' . $resourcestatic->id . '" name="removedassignedresource_' . $resourcestatic->id . '">';
  2168. }
  2169. // Show my availability
  2170. if ($showproperties) {
  2171. if (is_array($listofresourceid) && count($listofresourceid)) {
  2172. $out .= '<div class="myavailability inline-block">';
  2173. $out .= '<span class="hideonsmartphone">&nbsp;-&nbsp;<span class="opacitymedium">' . $langs->trans("Availability") . ':</span> </span><input id="transparencyresource" class="paddingrightonly" ' . ($action == 'view' ? 'disabled' : '') . ' type="checkbox" name="transparency"' . ($listofresourceid[$value['id']]['transparency'] ? ' checked' : '') . '><label for="transparency">' . $langs->trans("Busy") . '</label>';
  2174. $out .= '</div>';
  2175. }
  2176. }
  2177. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2178. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2179. $out .= '</li>';
  2180. $i++;
  2181. }
  2182. if ($nbassignetoresource) {
  2183. $out .= '</ul>';
  2184. }
  2185. // Method with no ajax
  2186. if ($action != 'view') {
  2187. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassignedresource" value="">';
  2188. $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
  2189. $out .= 'jQuery(".removedassignedresource").click(function() { jQuery(".removedassignedresourcehidden").val(jQuery(this).val()); });';
  2190. $out .= 'jQuery(".assignedtoresource").change(function() { console.log(jQuery(".assignedtoresource option:selected").val());';
  2191. $out .= ' if (jQuery(".assignedtoresource option:selected").val() > 0) { jQuery("#' . $action . 'assignedtoresource").attr("disabled", false); }';
  2192. $out .= ' else { jQuery("#' . $action . 'assignedtoresource").attr("disabled", true); }';
  2193. $out .= '});';
  2194. $out .= '})</script>';
  2195. $events = array();
  2196. $out .= img_picto('', 'resource', 'class="pictofixedwidth"');
  2197. $out .= $formresources->select_resource_list('', $htmlname, '', 1, 1, 0, $events, '', 2, null);
  2198. //$out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2199. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="' . $action . 'assignedtoresource" name="' . $action . 'assignedtoresource" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
  2200. $out .= '<br>';
  2201. }
  2202. return $out;
  2203. }
  2204. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2205. /**
  2206. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2207. *
  2208. * @param int $selected Preselected products
  2209. * @param string $htmlname Name of HTML select field (must be unique in page).
  2210. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2211. * @param int $limit Limit on number of returned lines
  2212. * @param int $price_level Level of price to show
  2213. * @param int $status Sell status: -1=No filter on sell status, 0=Products not on sell, 1=Products on sell
  2214. * @param int $finished 2=all, 1=finished, 0=raw material
  2215. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2216. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2217. * @param array $ajaxoptions Options for ajax_autocompleter
  2218. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2219. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2220. * @param int $forcecombo Force to use combo box
  2221. * @param string $morecss Add more css on select
  2222. * @param int $hidepriceinlabel 1=Hide prices in label
  2223. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2224. * 'warehouseopen' = count products from open warehouses,
  2225. * 'warehouseclosed' = count products from closed warehouses,
  2226. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2227. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2228. * @param string $nooutput No print, return the output into a string
  2229. * @param int $status_purchase Purchase status: -1=No filter on purchase status, 0=Products not on purchase, 1=Products on purchase
  2230. * @return void|string
  2231. */
  2232. public function select_produits($selected = 0, $htmlname = 'productid', $filtertype = '', $limit = 0, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = null, $nooutput = 0, $status_purchase = -1)
  2233. {
  2234. // phpcs:enable
  2235. global $langs, $conf;
  2236. $out = '';
  2237. // check parameters
  2238. $price_level = (!empty($price_level) ? $price_level : 0);
  2239. if (is_null($ajaxoptions)) {
  2240. $ajaxoptions = array();
  2241. }
  2242. if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
  2243. if (isModEnabled("product") && !isModEnabled('service')) {
  2244. $filtertype = '0';
  2245. } elseif (!isModEnabled('product') && isModEnabled("service")) {
  2246. $filtertype = '1';
  2247. }
  2248. }
  2249. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
  2250. $placeholder = '';
  2251. if ($selected && empty($selected_input_value)) {
  2252. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2253. $producttmpselect = new Product($this->db);
  2254. $producttmpselect->fetch($selected);
  2255. $selected_input_value = $producttmpselect->ref;
  2256. unset($producttmpselect);
  2257. }
  2258. // handle case where product or service module is disabled + no filter specified
  2259. if ($filtertype == '') {
  2260. if (!isModEnabled('product')) { // when product module is disabled, show services only
  2261. $filtertype = 1;
  2262. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2263. $filtertype = 0;
  2264. }
  2265. }
  2266. // mode=1 means customers products
  2267. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=1&status=' . $status . '&status_purchase=' . $status_purchase . '&finished=' . $finished . '&hidepriceinlabel=' . $hidepriceinlabel . '&warehousestatus=' . $warehouseStatus;
  2268. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2269. if (isModEnabled('variants') && is_array($selected_combinations)) {
  2270. // Code to automatically insert with javascript the select of attributes under the select of product
  2271. // when a parent of variant has been selected.
  2272. $out .= '
  2273. <!-- script to auto show attributes select tags if a variant was selected -->
  2274. <script nonce="' . getNonce() . '">
  2275. // auto show attributes fields
  2276. selected = ' . json_encode($selected_combinations) . ';
  2277. combvalues = {};
  2278. jQuery(document).ready(function () {
  2279. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2280. if (jQuery(this).val() == \'free\') {
  2281. jQuery(\'div#attributes_box\').empty();
  2282. }
  2283. });
  2284. jQuery("input#' . $htmlname . '").change(function () {
  2285. if (!jQuery(this).val()) {
  2286. jQuery(\'div#attributes_box\').empty();
  2287. return;
  2288. }
  2289. console.log("A change has started. We get variants fields to inject html select");
  2290. jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
  2291. id: jQuery(this).val()
  2292. }, function (data) {
  2293. jQuery(\'div#attributes_box\').empty();
  2294. jQuery.each(data, function (key, val) {
  2295. combvalues[val.id] = val.values;
  2296. var span = jQuery(document.createElement(\'div\')).css({
  2297. \'display\': \'table-row\'
  2298. });
  2299. span.append(
  2300. jQuery(document.createElement(\'div\')).text(val.label).css({
  2301. \'font-weight\': \'bold\',
  2302. \'display\': \'table-cell\'
  2303. })
  2304. );
  2305. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2306. \'margin-left\': \'15px\',
  2307. \'white-space\': \'pre\'
  2308. }).append(
  2309. jQuery(document.createElement(\'option\')).val(\'\')
  2310. );
  2311. jQuery.each(combvalues[val.id], function (key, val) {
  2312. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2313. if (selected[val.fk_product_attribute] == val.id) {
  2314. tag.attr(\'selected\', \'selected\');
  2315. }
  2316. html.append(tag);
  2317. });
  2318. span.append(html);
  2319. jQuery(\'div#attributes_box\').append(span);
  2320. });
  2321. })
  2322. });
  2323. ' . ($selected ? 'jQuery("input#' . $htmlname . '").change();' : '') . '
  2324. });
  2325. </script>
  2326. ';
  2327. }
  2328. if (empty($hidelabel)) {
  2329. $out .= $langs->trans("RefOrLabel") . ' : ';
  2330. } elseif ($hidelabel > 1) {
  2331. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  2332. if ($hidelabel == 2) {
  2333. $out .= img_picto($langs->trans("Search"), 'search');
  2334. }
  2335. }
  2336. $out .= '<input type="text" class="minwidth100' . ($morecss ? ' ' . $morecss : '') . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  2337. if ($hidelabel == 3) {
  2338. $out .= img_picto($langs->trans("Search"), 'search');
  2339. }
  2340. } else {
  2341. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2342. }
  2343. if (empty($nooutput)) {
  2344. print $out;
  2345. } else {
  2346. return $out;
  2347. }
  2348. }
  2349. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2350. /**
  2351. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2352. *
  2353. * @param string $selected Preselected BOM id
  2354. * @param string $htmlname Name of HTML select field (must be unique in page).
  2355. * @param int $limit Limit on number of returned lines
  2356. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2357. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2358. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2359. * @param string $morecss Add more css on select
  2360. * @param string $nooutput No print, return the output into a string
  2361. * @param int $forcecombo Force to use combo box
  2362. * @param array $TProducts Add filter on a defined product
  2363. * @return void|string
  2364. */
  2365. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2366. {
  2367. // phpcs:enable
  2368. global $conf, $user, $langs, $db;
  2369. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2370. $error = 0;
  2371. $out = '';
  2372. if (!$forcecombo) {
  2373. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2374. $events = array();
  2375. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2376. }
  2377. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2378. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2379. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'bom_bom as b';
  2380. $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
  2381. if (!empty($status)) {
  2382. $sql .= ' AND status = ' . (int) $status;
  2383. }
  2384. if (!empty($type)) {
  2385. $sql .= ' AND bomtype = ' . (int) $type;
  2386. }
  2387. if (!empty($TProducts)) {
  2388. $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
  2389. }
  2390. if (!empty($limit)) {
  2391. $sql .= ' LIMIT ' . (int) $limit;
  2392. }
  2393. $resql = $db->query($sql);
  2394. if ($resql) {
  2395. if ($showempty) {
  2396. $out .= '<option value="-1"';
  2397. if (empty($selected)) {
  2398. $out .= ' selected';
  2399. }
  2400. $out .= '>&nbsp;</option>';
  2401. }
  2402. while ($obj = $db->fetch_object($resql)) {
  2403. $product = new Product($db);
  2404. $res = $product->fetch($obj->fk_product);
  2405. $out .= '<option value="' . $obj->rowid . '"';
  2406. if ($obj->rowid == $selected) {
  2407. $out .= 'selected';
  2408. }
  2409. $out .= '>' . $obj->ref . ' - ' . $product->label . ' - ' . $obj->label . '</option>';
  2410. }
  2411. } else {
  2412. $error++;
  2413. dol_print_error($db);
  2414. }
  2415. $out .= '</select>';
  2416. if (empty($nooutput)) {
  2417. print $out;
  2418. } else {
  2419. return $out;
  2420. }
  2421. }
  2422. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2423. /**
  2424. * Return list of products for a customer.
  2425. * Called by select_produits.
  2426. *
  2427. * @param int $selected Preselected product
  2428. * @param string $htmlname Name of select html
  2429. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2430. * @param int $limit Limit on number of returned lines
  2431. * @param int $price_level Level of price to show
  2432. * @param string $filterkey Filter on product
  2433. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2434. * @param int $finished Filter on finished field: 2=No filter
  2435. * @param int $outputmode 0=HTML select string, 1=Array
  2436. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2437. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2438. * @param int $forcecombo Force to use combo box
  2439. * @param string $morecss Add more css on select
  2440. * @param int $hidepriceinlabel 1=Hide prices in label
  2441. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2442. * 'warehouseopen' = count products from open warehouses,
  2443. * 'warehouseclosed' = count products from closed warehouses,
  2444. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2445. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2446. * @return array|string Array of keys for json
  2447. */
  2448. public function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $status_purchase = -1)
  2449. {
  2450. // phpcs:enable
  2451. global $langs, $conf;
  2452. global $hookmanager;
  2453. $out = '';
  2454. $outarray = array();
  2455. // Units
  2456. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2457. $langs->load('other');
  2458. }
  2459. $warehouseStatusArray = array();
  2460. if (!empty($warehouseStatus)) {
  2461. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2462. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2463. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2464. }
  2465. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2466. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2467. }
  2468. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2469. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2470. }
  2471. }
  2472. $selectFields = " p.rowid, p.ref, p.label, p.description, p.barcode, p.fk_country, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.default_vat_code, p.duration, p.fk_price_expression";
  2473. if (count($warehouseStatusArray)) {
  2474. $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
  2475. } else {
  2476. $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", 0, "p.stock") . " AS stock";
  2477. }
  2478. $sql = "SELECT ";
  2479. // Add select from hooks
  2480. $parameters = array();
  2481. $reshook = $hookmanager->executeHooks('selectProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
  2482. if (empty($reshook)) {
  2483. $sql .= $selectFields.$selectFieldsGrouped.$hookmanager->resPrint;
  2484. } else {
  2485. $sql .= $hookmanager->resPrint;
  2486. }
  2487. if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
  2488. //Product category
  2489. $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
  2490. FROM " . $this->db->prefix() . "categorie_product
  2491. WHERE " . $this->db->prefix() . "categorie_product.fk_product=p.rowid
  2492. LIMIT 1
  2493. ) AS categorie_product_id ";
  2494. }
  2495. //Price by customer
  2496. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') && !empty($socid)) {
  2497. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2498. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx, pcp.default_vat_code as custdefault_vat_code, pcp.ref_customer as custref';
  2499. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2500. }
  2501. // Units
  2502. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2503. $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";
  2504. $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';
  2505. }
  2506. // Multilang : we add translation
  2507. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2508. $sql .= ", pl.label as label_translated";
  2509. $sql .= ", pl.description as description_translated";
  2510. $selectFields .= ", label_translated";
  2511. $selectFields .= ", description_translated";
  2512. }
  2513. // Price by quantity
  2514. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  2515. $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
  2516. if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  2517. $sql .= " AND price_level = " . ((int) $price_level);
  2518. }
  2519. $sql .= " ORDER BY date_price";
  2520. $sql .= " DESC LIMIT 1) as price_rowid";
  2521. $sql .= ", (SELECT pp.price_by_qty FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable
  2522. if ($price_level >= 1 && getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES')) {
  2523. $sql .= " AND price_level = " . ((int) $price_level);
  2524. }
  2525. $sql .= " ORDER BY date_price";
  2526. $sql .= " DESC LIMIT 1) as price_by_qty";
  2527. $selectFields .= ", price_rowid, price_by_qty";
  2528. }
  2529. $sql .= " FROM ".$this->db->prefix()."product as p";
  2530. // Add from (left join) from hooks
  2531. $parameters = array();
  2532. $reshook = $hookmanager->executeHooks('selectProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
  2533. $sql .= $hookmanager->resPrint;
  2534. if (count($warehouseStatusArray)) {
  2535. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps on ps.fk_product = p.rowid";
  2536. $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
  2537. $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.
  2538. }
  2539. // include search in supplier ref
  2540. if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
  2541. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2542. }
  2543. //Price by customer
  2544. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') && !empty($socid)) {
  2545. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_customer_price as pcp ON pcp.fk_soc=" . ((int) $socid) . " AND pcp.fk_product=p.rowid";
  2546. }
  2547. // Units
  2548. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2549. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  2550. }
  2551. // Multilang : we add translation
  2552. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2553. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid ";
  2554. if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE') && !empty($socid)) {
  2555. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  2556. $soc = new Societe($this->db);
  2557. $result = $soc->fetch($socid);
  2558. if ($result > 0 && !empty($soc->default_lang)) {
  2559. $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
  2560. } else {
  2561. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2562. }
  2563. } else {
  2564. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2565. }
  2566. }
  2567. if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD')) {
  2568. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2569. }
  2570. $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
  2571. if (getDolGlobalString('PRODUIT_ATTRIBUTES_HIDECHILD')) {
  2572. $sql .= " AND pac.rowid IS NULL";
  2573. }
  2574. if ($finished == 0) {
  2575. $sql .= " AND p.finished = " . ((int) $finished);
  2576. } elseif ($finished == 1) {
  2577. $sql .= " AND p.finished = ".((int) $finished);
  2578. }
  2579. if ($status >= 0) {
  2580. $sql .= " AND p.tosell = ".((int) $status);
  2581. }
  2582. if ($status_purchase >= 0) {
  2583. $sql .= " AND p.tobuy = " . ((int) $status_purchase);
  2584. }
  2585. // Filter by product type
  2586. if (strval($filtertype) != '') {
  2587. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  2588. } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
  2589. $sql .= " AND p.fk_product_type = 1";
  2590. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2591. $sql .= " AND p.fk_product_type = 0";
  2592. }
  2593. // Add where from hooks
  2594. $parameters = array();
  2595. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2596. $sql .= $hookmanager->resPrint;
  2597. // Add criteria on ref/label
  2598. if ($filterkey != '') {
  2599. $sql .= ' AND (';
  2600. $prefix = !getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2601. // For natural search
  2602. $scrit = explode(' ', $filterkey);
  2603. $i = 0;
  2604. if (count($scrit) > 1) {
  2605. $sql .= "(";
  2606. }
  2607. foreach ($scrit as $crit) {
  2608. if ($i > 0) {
  2609. $sql .= " AND ";
  2610. }
  2611. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2612. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2613. $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2614. }
  2615. if (getDolGlobalString('PRODUIT_CUSTOMER_PRICES') && !empty($socid)) {
  2616. $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2617. }
  2618. if (getDolGlobalString('PRODUCT_AJAX_SEARCH_ON_DESCRIPTION')) {
  2619. $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2620. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2621. $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2622. }
  2623. }
  2624. if (getDolGlobalString('MAIN_SEARCH_PRODUCT_BY_FOURN_REF')) {
  2625. $sql .= " OR pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2626. }
  2627. $sql .= ")";
  2628. $i++;
  2629. }
  2630. if (count($scrit) > 1) {
  2631. $sql .= ")";
  2632. }
  2633. if (isModEnabled('barcode')) {
  2634. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  2635. }
  2636. $sql .= ')';
  2637. }
  2638. if (count($warehouseStatusArray)) {
  2639. $sql .= " GROUP BY " . $selectFields;
  2640. }
  2641. //Sort by category
  2642. if (getDolGlobalString('PRODUCT_SORT_BY_CATEGORY')) {
  2643. $sql .= " ORDER BY categorie_product_id ";
  2644. //ASC OR DESC order
  2645. (getDolGlobalInt('PRODUCT_SORT_BY_CATEGORY') == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2646. } else {
  2647. $sql .= $this->db->order("p.ref");
  2648. }
  2649. $sql .= $this->db->plimit($limit, 0);
  2650. // Build output string
  2651. dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
  2652. $result = $this->db->query($sql);
  2653. if ($result) {
  2654. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2655. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2656. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  2657. $num = $this->db->num_rows($result);
  2658. $events = null;
  2659. if (!$forcecombo) {
  2660. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2661. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2662. }
  2663. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2664. $textifempty = '';
  2665. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2666. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2667. if (getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
  2668. if ($showempty && !is_numeric($showempty)) {
  2669. $textifempty = $langs->trans($showempty);
  2670. } else {
  2671. $textifempty .= $langs->trans("All");
  2672. }
  2673. } else {
  2674. if ($showempty && !is_numeric($showempty)) {
  2675. $textifempty = $langs->trans($showempty);
  2676. }
  2677. }
  2678. if ($showempty) {
  2679. $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
  2680. }
  2681. $i = 0;
  2682. while ($num && $i < $num) {
  2683. $opt = '';
  2684. $optJson = array();
  2685. $objp = $this->db->fetch_object($result);
  2686. if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('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
  2687. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2688. $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
  2689. $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
  2690. $sql .= " ORDER BY quantity ASC";
  2691. dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
  2692. $result2 = $this->db->query($sql);
  2693. if ($result2) {
  2694. $nb_prices = $this->db->num_rows($result2);
  2695. $j = 0;
  2696. while ($nb_prices && $j < $nb_prices) {
  2697. $objp2 = $this->db->fetch_object($result2);
  2698. $objp->price_by_qty_rowid = $objp2->rowid;
  2699. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2700. $objp->price_by_qty_quantity = $objp2->quantity;
  2701. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2702. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2703. // For backward compatibility
  2704. $objp->quantity = $objp2->quantity;
  2705. $objp->price = $objp2->price;
  2706. $objp->unitprice = $objp2->unitprice;
  2707. $objp->remise_percent = $objp2->remise_percent;
  2708. //$objp->tva_tx is not overwritten by $objp2 value
  2709. //$objp->default_vat_code is not overwritten by $objp2 value
  2710. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2711. $j++;
  2712. // Add new entry
  2713. // "key" value of json key array is used by jQuery automatically as selected value
  2714. // "label" value of json key array is used by jQuery automatically as text for combo box
  2715. $out .= $opt;
  2716. array_push($outarray, $optJson);
  2717. }
  2718. }
  2719. } else {
  2720. if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
  2721. $price_product = new Product($this->db);
  2722. $price_product->fetch($objp->rowid, '', '', 1);
  2723. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2724. $priceparser = new PriceParser($this->db);
  2725. $price_result = $priceparser->parseProduct($price_product);
  2726. if ($price_result >= 0) {
  2727. $objp->price = $price_result;
  2728. $objp->unitprice = $price_result;
  2729. //Calculate the VAT
  2730. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2731. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2732. }
  2733. }
  2734. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2735. // Add new entry
  2736. // "key" value of json key array is used by jQuery automatically as selected value
  2737. // "label" value of json key array is used by jQuery automatically as text for combo box
  2738. $out .= $opt;
  2739. array_push($outarray, $optJson);
  2740. }
  2741. $i++;
  2742. }
  2743. $out .= '</select>';
  2744. $this->db->free($result);
  2745. if (empty($outputmode)) {
  2746. return $out;
  2747. }
  2748. return $outarray;
  2749. } else {
  2750. dol_print_error($this->db);
  2751. }
  2752. return '';
  2753. }
  2754. /**
  2755. * Function to forge the string with OPTIONs of SELECT.
  2756. * This define value for &$opt and &$optJson.
  2757. * This function is called by select_produits_list().
  2758. *
  2759. * @param object $objp Resultset of fetch
  2760. * @param string $opt Option (var used for returned value in string option format)
  2761. * @param array $optJson Option (var used for returned value in json format)
  2762. * @param int $price_level Price level
  2763. * @param string $selected Preselected value
  2764. * @param int $hidepriceinlabel Hide price in label
  2765. * @param string $filterkey Filter key to highlight
  2766. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2767. * @return void
  2768. */
  2769. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2770. {
  2771. global $langs, $conf, $user;
  2772. global $hookmanager;
  2773. $outkey = '';
  2774. $outval = '';
  2775. $outref = '';
  2776. $outlabel = '';
  2777. $outlabel_translated = '';
  2778. $outdesc = '';
  2779. $outdesc_translated = '';
  2780. $outbarcode = '';
  2781. $outorigin = '';
  2782. $outtype = '';
  2783. $outprice_ht = '';
  2784. $outprice_ttc = '';
  2785. $outpricebasetype = '';
  2786. $outtva_tx = '';
  2787. $outdefault_vat_code = '';
  2788. $outqty = 1;
  2789. $outdiscount = 0;
  2790. $maxlengtharticle = (!getDolGlobalString('PRODUCT_MAX_LENGTH_COMBO') ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2791. $label = $objp->label;
  2792. if (!empty($objp->label_translated)) {
  2793. $label = $objp->label_translated;
  2794. }
  2795. if (!empty($filterkey) && $filterkey != '') {
  2796. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  2797. }
  2798. $outkey = $objp->rowid;
  2799. $outref = $objp->ref;
  2800. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2801. $outlabel = $objp->label;
  2802. $outdesc = $objp->description;
  2803. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2804. $outlabel_translated = $objp->label_translated;
  2805. $outdesc_translated = $objp->description_translated;
  2806. }
  2807. $outbarcode = $objp->barcode;
  2808. $outorigin = $objp->fk_country;
  2809. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2810. $outtype = $objp->fk_product_type;
  2811. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2812. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  2813. if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
  2814. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2815. }
  2816. // Units
  2817. $outvalUnits = '';
  2818. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2819. if (!empty($objp->unit_short)) {
  2820. $outvalUnits .= ' - ' . $objp->unit_short;
  2821. }
  2822. }
  2823. if (getDolGlobalString('PRODUCT_SHOW_DIMENSIONS_IN_COMBO')) {
  2824. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2825. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2826. $outvalUnits .= ' - ' . $unitToShow;
  2827. }
  2828. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2829. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  2830. $outvalUnits .= ' - ' . $unitToShow;
  2831. }
  2832. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2833. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2834. $outvalUnits .= ' - ' . $unitToShow;
  2835. }
  2836. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2837. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2838. $outvalUnits .= ' - ' . $unitToShow;
  2839. }
  2840. }
  2841. if ($outdurationvalue && $outdurationunit) {
  2842. $da = array(
  2843. 'h' => $langs->trans('Hour'),
  2844. 'd' => $langs->trans('Day'),
  2845. 'w' => $langs->trans('Week'),
  2846. 'm' => $langs->trans('Month'),
  2847. 'y' => $langs->trans('Year')
  2848. );
  2849. if (isset($da[$outdurationunit])) {
  2850. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  2851. }
  2852. }
  2853. $opt = '<option value="' . $objp->rowid . '"';
  2854. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2855. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2856. $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 . '"';
  2857. }
  2858. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
  2859. if ($user->hasRight('stock', 'lire')) {
  2860. if ($objp->stock > 0) {
  2861. $opt .= ' class="product_line_stock_ok"';
  2862. } elseif ($objp->stock <= 0) {
  2863. $opt .= ' class="product_line_stock_too_low"';
  2864. }
  2865. }
  2866. }
  2867. if (getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
  2868. $opt .= ' data-labeltrans="' . $outlabel_translated . '"';
  2869. $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
  2870. }
  2871. $opt .= '>';
  2872. $opt .= $objp->ref;
  2873. if (!empty($objp->custref)) {
  2874. $opt .= ' (' . $objp->custref . ')';
  2875. }
  2876. if ($outbarcode) {
  2877. $opt .= ' (' . $outbarcode . ')';
  2878. }
  2879. $opt .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2880. if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
  2881. $opt .= ' (' . getCountry($outorigin, 1) . ')';
  2882. }
  2883. $objRef = $objp->ref;
  2884. if (!empty($objp->custref)) {
  2885. $objRef .= ' (' . $objp->custref . ')';
  2886. }
  2887. if (!empty($filterkey) && $filterkey != '') {
  2888. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  2889. }
  2890. $outval .= $objRef;
  2891. if ($outbarcode) {
  2892. $outval .= ' (' . $outbarcode . ')';
  2893. }
  2894. $outval .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2895. if ($outorigin && getDolGlobalString('PRODUCT_SHOW_ORIGIN_IN_COMBO')) {
  2896. $outval .= ' (' . getCountry($outorigin, 1) . ')';
  2897. }
  2898. // Units
  2899. $opt .= $outvalUnits;
  2900. $outval .= $outvalUnits;
  2901. $found = 0;
  2902. // Multiprice
  2903. // If we need a particular price level (from 1 to n)
  2904. if (empty($hidepriceinlabel) && $price_level >= 1 && (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) {
  2905. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2906. $sql .= " FROM " . $this->db->prefix() . "product_price";
  2907. $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
  2908. $sql .= " AND entity IN (" . getEntity('productprice') . ")";
  2909. $sql .= " AND price_level = " . ((int) $price_level);
  2910. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2911. $sql .= " LIMIT 1";
  2912. dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level, LOG_DEBUG);
  2913. $result2 = $this->db->query($sql);
  2914. if ($result2) {
  2915. $objp2 = $this->db->fetch_object($result2);
  2916. if ($objp2) {
  2917. $found = 1;
  2918. if ($objp2->price_base_type == 'HT') {
  2919. $opt .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2920. $outval .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2921. } else {
  2922. $opt .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2923. $outval .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2924. }
  2925. $outprice_ht = price($objp2->price);
  2926. $outprice_ttc = price($objp2->price_ttc);
  2927. $outpricebasetype = $objp2->price_base_type;
  2928. if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) { // using this option is a bug. kept for backward compatibility
  2929. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2930. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2931. } else {
  2932. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2933. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2934. }
  2935. }
  2936. } else {
  2937. dol_print_error($this->db);
  2938. }
  2939. }
  2940. // Price by quantity
  2941. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) {
  2942. $found = 1;
  2943. $outqty = $objp->quantity;
  2944. $outdiscount = $objp->remise_percent;
  2945. if ($objp->quantity == 1) {
  2946. $opt .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
  2947. $outval .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
  2948. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2949. $outval .= $langs->transnoentities("Unit");
  2950. } else {
  2951. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2952. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2953. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2954. $outval .= $langs->transnoentities("Units");
  2955. }
  2956. $outprice_ht = price($objp->unitprice);
  2957. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2958. $outpricebasetype = $objp->price_base_type;
  2959. $outtva_tx = $objp->tva_tx; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2960. $outdefault_vat_code = $objp->default_vat_code; // This value is the value on product when constructProductListOption is called by select_produits_list even if other field $objp-> are from table price_by_qty
  2961. }
  2962. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2963. $opt .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2964. $outval .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2965. }
  2966. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2967. $opt .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2968. $outval .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2969. }
  2970. // Price by customer
  2971. if (empty($hidepriceinlabel) && getDolGlobalString('PRODUIT_CUSTOMER_PRICES')) {
  2972. if (!empty($objp->idprodcustprice)) {
  2973. $found = 1;
  2974. if ($objp->custprice_base_type == 'HT') {
  2975. $opt .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2976. $outval .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2977. } else {
  2978. $opt .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2979. $outval .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2980. }
  2981. $outprice_ht = price($objp->custprice);
  2982. $outprice_ttc = price($objp->custprice_ttc);
  2983. $outpricebasetype = $objp->custprice_base_type;
  2984. $outtva_tx = $objp->custtva_tx;
  2985. $outdefault_vat_code = $objp->custdefault_vat_code;
  2986. }
  2987. }
  2988. // If level no defined or multiprice not found, we used the default price
  2989. if (empty($hidepriceinlabel) && !$found) {
  2990. if ($objp->price_base_type == 'HT') {
  2991. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2992. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2993. } else {
  2994. $opt .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2995. $outval .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2996. }
  2997. $outprice_ht = price($objp->price);
  2998. $outprice_ttc = price($objp->price_ttc);
  2999. $outpricebasetype = $objp->price_base_type;
  3000. $outtva_tx = $objp->tva_tx;
  3001. $outdefault_vat_code = $objp->default_vat_code;
  3002. }
  3003. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
  3004. if ($user->hasRight('stock', 'lire')) {
  3005. $opt .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3006. if ($objp->stock > 0) {
  3007. $outval .= ' - <span class="product_line_stock_ok">';
  3008. } elseif ($objp->stock <= 0) {
  3009. $outval .= ' - <span class="product_line_stock_too_low">';
  3010. }
  3011. $outval .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3012. $outval .= '</span>';
  3013. if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
  3014. $langs->load("stocks");
  3015. $tmpproduct = new Product($this->db);
  3016. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3017. $tmpproduct->load_virtual_stock();
  3018. $virtualstock = $tmpproduct->stock_theorique;
  3019. $opt .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  3020. $outval .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  3021. if ($virtualstock > 0) {
  3022. $outval .= '<span class="product_line_stock_ok">';
  3023. } elseif ($virtualstock <= 0) {
  3024. $outval .= '<span class="product_line_stock_too_low">';
  3025. }
  3026. $outval .= $virtualstock;
  3027. $outval .= '</span>';
  3028. unset($tmpproduct);
  3029. }
  3030. }
  3031. }
  3032. $parameters = array('objp'=>$objp);
  3033. $reshook = $hookmanager->executeHooks('constructProductListOption', $parameters); // Note that $action and $object may have been modified by hook
  3034. if (empty($reshook)) {
  3035. $opt .= $hookmanager->resPrint;
  3036. } else {
  3037. $opt = $hookmanager->resPrint;
  3038. }
  3039. $opt .= "</option>\n";
  3040. $optJson = array(
  3041. 'key' => $outkey,
  3042. 'value' => $outref,
  3043. 'label' => $outval,
  3044. 'label2' => $outlabel,
  3045. 'desc' => $outdesc,
  3046. 'type' => $outtype,
  3047. 'price_ht' => price2num($outprice_ht),
  3048. 'price_ttc' => price2num($outprice_ttc),
  3049. 'price_ht_locale' => price(price2num($outprice_ht)),
  3050. 'price_ttc_locale' => price(price2num($outprice_ttc)),
  3051. 'pricebasetype' => $outpricebasetype,
  3052. 'tva_tx' => $outtva_tx,
  3053. 'default_vat_code' => $outdefault_vat_code,
  3054. 'qty' => $outqty,
  3055. 'discount' => $outdiscount,
  3056. 'duration_value' => $outdurationvalue,
  3057. 'duration_unit' => $outdurationunit,
  3058. 'pbq' => $outpbq,
  3059. 'labeltrans' => $outlabel_translated,
  3060. 'desctrans' => $outdesc_translated,
  3061. 'ref_customer' => $outrefcust
  3062. );
  3063. }
  3064. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3065. /**
  3066. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  3067. *
  3068. * @param int $socid Id third party
  3069. * @param string $selected Preselected product
  3070. * @param string $htmlname Name of HTML Select
  3071. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  3072. * @param string $filtre For a SQL filter
  3073. * @param array $ajaxoptions Options for ajax_autocompleter
  3074. * @param int $hidelabel Hide label (0=no, 1=yes)
  3075. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  3076. * @param string $morecss More CSS
  3077. * @param string $placeholder Placeholder
  3078. * @return void
  3079. */
  3080. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  3081. {
  3082. // phpcs:enable
  3083. global $langs, $conf;
  3084. global $price_level, $status, $finished;
  3085. if (!isset($status)) {
  3086. $status = 1;
  3087. }
  3088. $selected_input_value = '';
  3089. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('PRODUIT_USE_SEARCH_TO_SELECT')) {
  3090. if ($selected > 0) {
  3091. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  3092. $producttmpselect = new Product($this->db);
  3093. $producttmpselect->fetch($selected);
  3094. $selected_input_value = $producttmpselect->ref;
  3095. unset($producttmpselect);
  3096. }
  3097. // mode=2 means suppliers products
  3098. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
  3099. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  3100. print($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="minwidth300" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . '>';
  3101. } else {
  3102. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  3103. }
  3104. }
  3105. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3106. /**
  3107. * Return list of suppliers products
  3108. *
  3109. * @param int $socid Id of supplier thirdparty (0 = no filter)
  3110. * @param string $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  3111. * @param string $htmlname Name of HTML select
  3112. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  3113. * @param string $filtre Generic filter. Data must not come from user input.
  3114. * @param string $filterkey Filter of produdts
  3115. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  3116. * @param int $outputmode 0=HTML select string, 1=Array
  3117. * @param int $limit Limit of line number
  3118. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  3119. * @param string $morecss Add more CSS
  3120. * @param int $showstockinlist Show stock information (slower).
  3121. * @param string $placeholder Placeholder
  3122. * @return array|string Array of keys for json or HTML component
  3123. */
  3124. 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 = '')
  3125. {
  3126. // phpcs:enable
  3127. global $langs, $conf, $user;
  3128. global $hookmanager;
  3129. $out = '';
  3130. $outarray = array();
  3131. $maxlengtharticle = (!getDolGlobalString('PRODUCT_MAX_LENGTH_COMBO') ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  3132. $langs->load('stocks');
  3133. // Units
  3134. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3135. $langs->load('other');
  3136. }
  3137. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock, p.tva_tx as tva_tx_sale, p.default_vat_code as default_vat_code_sale,";
  3138. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  3139. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  3140. $sql .= " pfp.supplier_reputation";
  3141. // if we use supplier description of the products
  3142. if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
  3143. $sql .= ", pfp.desc_fourn as description";
  3144. } else {
  3145. $sql .= ", p.description";
  3146. }
  3147. // Units
  3148. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3149. $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";
  3150. }
  3151. if (isModEnabled('barcode')) {
  3152. $sql .= ", pfp.barcode";
  3153. }
  3154. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3155. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
  3156. if ($socid > 0) {
  3157. $sql .= " AND pfp.fk_soc = " . ((int) $socid);
  3158. }
  3159. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3160. // Units
  3161. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3162. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  3163. }
  3164. $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
  3165. if ($statut != -1) {
  3166. $sql .= " AND p.tobuy = " . ((int) $statut);
  3167. }
  3168. if (strval($filtertype) != '') {
  3169. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  3170. }
  3171. if (!empty($filtre)) {
  3172. $sql .= " " . $filtre;
  3173. }
  3174. // Add where from hooks
  3175. $parameters = array();
  3176. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3177. $sql .= $hookmanager->resPrint;
  3178. // Add criteria on ref/label
  3179. if ($filterkey != '') {
  3180. $sql .= ' AND (';
  3181. $prefix = !getDolGlobalString('PRODUCT_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  3182. // For natural search
  3183. $scrit = explode(' ', $filterkey);
  3184. $i = 0;
  3185. if (count($scrit) > 1) {
  3186. $sql .= "(";
  3187. }
  3188. foreach ($scrit as $crit) {
  3189. if ($i > 0) {
  3190. $sql .= " AND ";
  3191. }
  3192. $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) . "%'";
  3193. if (getDolGlobalString('PRODUIT_FOURN_TEXTS')) {
  3194. $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  3195. }
  3196. $sql .= ")";
  3197. $i++;
  3198. }
  3199. if (count($scrit) > 1) {
  3200. $sql .= ")";
  3201. }
  3202. if (isModEnabled('barcode')) {
  3203. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3204. $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3205. }
  3206. $sql .= ')';
  3207. }
  3208. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3209. $sql .= $this->db->plimit($limit, 0);
  3210. // Build output string
  3211. dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
  3212. $result = $this->db->query($sql);
  3213. if ($result) {
  3214. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3215. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  3216. $num = $this->db->num_rows($result);
  3217. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3218. $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
  3219. if (!$selected) {
  3220. $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3221. } else {
  3222. $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3223. }
  3224. $i = 0;
  3225. while ($i < $num) {
  3226. $objp = $this->db->fetch_object($result);
  3227. if (is_null($objp->idprodfournprice)) {
  3228. // There is no supplier price found, we will use the vat rate for sale
  3229. $objp->tva_tx = $objp->tva_tx_sale;
  3230. $objp->default_vat_code = $objp->default_vat_code_sale;
  3231. }
  3232. $outkey = $objp->idprodfournprice; // id in table of price
  3233. if (!$outkey && $alsoproductwithnosupplierprice) {
  3234. $outkey = 'idprod_' . $objp->rowid; // id of product
  3235. }
  3236. $outref = $objp->ref;
  3237. $outbarcode = $objp->barcode;
  3238. $outqty = 1;
  3239. $outdiscount = 0;
  3240. $outtype = $objp->fk_product_type;
  3241. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3242. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  3243. // Units
  3244. $outvalUnits = '';
  3245. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3246. if (!empty($objp->unit_short)) {
  3247. $outvalUnits .= ' - ' . $objp->unit_short;
  3248. }
  3249. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3250. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3251. $outvalUnits .= ' - ' . $unitToShow;
  3252. }
  3253. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3254. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  3255. $outvalUnits .= ' - ' . $unitToShow;
  3256. }
  3257. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3258. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3259. $outvalUnits .= ' - ' . $unitToShow;
  3260. }
  3261. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3262. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3263. $outvalUnits .= ' - ' . $unitToShow;
  3264. }
  3265. if ($outdurationvalue && $outdurationunit) {
  3266. $da = array(
  3267. 'h' => $langs->trans('Hour'),
  3268. 'd' => $langs->trans('Day'),
  3269. 'w' => $langs->trans('Week'),
  3270. 'm' => $langs->trans('Month'),
  3271. 'y' => $langs->trans('Year')
  3272. );
  3273. if (isset($da[$outdurationunit])) {
  3274. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  3275. }
  3276. }
  3277. }
  3278. $objRef = $objp->ref;
  3279. if ($filterkey && $filterkey != '') {
  3280. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  3281. }
  3282. $objRefFourn = $objp->ref_fourn;
  3283. if ($filterkey && $filterkey != '') {
  3284. $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3285. }
  3286. $label = $objp->label;
  3287. if ($filterkey && $filterkey != '') {
  3288. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  3289. }
  3290. switch ($objp->fk_product_type) {
  3291. case Product::TYPE_PRODUCT:
  3292. $picto = 'product';
  3293. break;
  3294. case Product::TYPE_SERVICE:
  3295. $picto = 'service';
  3296. break;
  3297. default:
  3298. $picto = '';
  3299. break;
  3300. }
  3301. if (empty($picto)) {
  3302. $optlabel = '';
  3303. } else {
  3304. $optlabel = img_object('', $picto, 'class="paddingright classfortooltip"', 0, 0, 1);
  3305. }
  3306. $optlabel .= $objp->ref;
  3307. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3308. $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
  3309. }
  3310. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3311. $optlabel .= ' (' . $outbarcode . ')';
  3312. }
  3313. $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3314. $outvallabel = $objRef;
  3315. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3316. $outvallabel .= ' (' . $objRefFourn . ')';
  3317. }
  3318. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3319. $outvallabel .= ' (' . $outbarcode . ')';
  3320. }
  3321. $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3322. // Units
  3323. $optlabel .= $outvalUnits;
  3324. $outvallabel .= $outvalUnits;
  3325. if (!empty($objp->idprodfournprice)) {
  3326. $outqty = $objp->quantity;
  3327. $outdiscount = $objp->remise_percent;
  3328. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3329. $prod_supplier = new ProductFournisseur($this->db);
  3330. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3331. $prod_supplier->id = $objp->fk_product;
  3332. $prod_supplier->fourn_qty = $objp->quantity;
  3333. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3334. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3335. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3336. $priceparser = new PriceParser($this->db);
  3337. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3338. if ($price_result >= 0) {
  3339. $objp->fprice = $price_result;
  3340. if ($objp->quantity >= 1) {
  3341. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3342. }
  3343. }
  3344. }
  3345. if ($objp->quantity == 1) {
  3346. $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3347. $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
  3348. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3349. $outvallabel .= $langs->transnoentities("Unit");
  3350. } else {
  3351. $optlabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  3352. $outvallabel .= ' - ' . price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  3353. $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3354. $outvallabel .= ' ' . $langs->transnoentities("Units");
  3355. }
  3356. if ($objp->quantity > 1) {
  3357. $optlabel .= " (" . price($objp->unitprice * (getDolGlobalString('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
  3358. $outvallabel .= " (" . price($objp->unitprice * (getDolGlobalString('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
  3359. }
  3360. if ($objp->remise_percent >= 1) {
  3361. $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3362. $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3363. }
  3364. if ($objp->duration) {
  3365. $optlabel .= " - " . $objp->duration;
  3366. $outvallabel .= " - " . $objp->duration;
  3367. }
  3368. if (!$socid) {
  3369. $optlabel .= " - " . dol_trunc($objp->name, 8);
  3370. $outvallabel .= " - " . dol_trunc($objp->name, 8);
  3371. }
  3372. if ($objp->supplier_reputation) {
  3373. //TODO dictionary
  3374. $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
  3375. $optlabel .= " - " . $reputations[$objp->supplier_reputation];
  3376. $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
  3377. }
  3378. } else {
  3379. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3380. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3381. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3382. } else { // No supplier price defined for product, even on other suppliers
  3383. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3384. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3385. }
  3386. }
  3387. if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES'))) {
  3388. $novirtualstock = ($showstockinlist == 2);
  3389. if ($user->hasRight('stock', 'lire')) {
  3390. $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3391. if ($objp->stock > 0) {
  3392. $optlabel .= ' - <span class="product_line_stock_ok">';
  3393. } elseif ($objp->stock <= 0) {
  3394. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3395. }
  3396. $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
  3397. $optlabel .= '</span>';
  3398. if (empty($novirtualstock) && getDolGlobalString('STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO')) { // Warning, this option may slow down combo list generation
  3399. $langs->load("stocks");
  3400. $tmpproduct = new Product($this->db);
  3401. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3402. $tmpproduct->load_virtual_stock();
  3403. $virtualstock = $tmpproduct->stock_theorique;
  3404. $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  3405. $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  3406. if ($virtualstock > 0) {
  3407. $optlabel .= '<span class="product_line_stock_ok">';
  3408. } elseif ($virtualstock <= 0) {
  3409. $optlabel .= '<span class="product_line_stock_too_low">';
  3410. }
  3411. $optlabel .= $virtualstock;
  3412. $optlabel .= '</span>';
  3413. unset($tmpproduct);
  3414. }
  3415. }
  3416. }
  3417. $optstart = '<option value="' . $outkey . '"';
  3418. if ($selected && $selected == $objp->idprodfournprice) {
  3419. $optstart .= ' selected';
  3420. }
  3421. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3422. $optstart .= ' disabled';
  3423. }
  3424. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3425. $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
  3426. $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
  3427. $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
  3428. $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"';
  3429. $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"';
  3430. $optstart .= ' data-discount="' . dol_escape_htmltag($outdiscount) . '"';
  3431. $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"';
  3432. $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"';
  3433. $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
  3434. $optstart .= ' data-supplier-ref="' . dol_escape_htmltag($objp->ref_fourn) . '"';
  3435. }
  3436. $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
  3437. $outarrayentry = array(
  3438. 'key' => $outkey,
  3439. 'value' => $outref,
  3440. 'label' => $outvallabel,
  3441. 'qty' => $outqty,
  3442. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3443. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3444. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3445. 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
  3446. 'tva_tx' => price2num($objp->tva_tx),
  3447. 'default_vat_code' => $objp->default_vat_code,
  3448. 'discount' => $outdiscount,
  3449. 'type' => $outtype,
  3450. 'duration_value' => $outdurationvalue,
  3451. 'duration_unit' => $outdurationunit,
  3452. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3453. 'description' => $objp->description
  3454. );
  3455. $parameters = array(
  3456. 'objp' => &$objp,
  3457. 'optstart' => &$optstart,
  3458. 'optlabel' => &$optlabel,
  3459. 'outvallabel' => &$outvallabel,
  3460. 'outarrayentry' => &$outarrayentry
  3461. );
  3462. $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
  3463. // Add new entry
  3464. // "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
  3465. // "label" value of json key array is used by jQuery automatically as text for combo box
  3466. $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";
  3467. array_push(
  3468. $outarray,
  3469. array('key' => $outkey,
  3470. 'value' => $outref,
  3471. 'label' => $outvallabel,
  3472. 'qty' => $outqty,
  3473. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3474. 'price_qty_ht_locale' => price($objp->fprice),
  3475. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3476. 'price_unit_ht_locale' => price($objp->unitprice),
  3477. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3478. 'tva_tx_formated' => price($objp->tva_tx),
  3479. 'tva_tx' => price2num($objp->tva_tx),
  3480. 'default_vat_code' => $objp->default_vat_code,
  3481. 'discount' => $outdiscount,
  3482. 'type' => $outtype,
  3483. 'duration_value' => $outdurationvalue,
  3484. 'duration_unit' => $outdurationunit,
  3485. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3486. 'description' => $objp->description
  3487. )
  3488. );
  3489. // Exemple of var_dump $outarray
  3490. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3491. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3492. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3493. //}
  3494. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3495. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3496. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3497. $i++;
  3498. }
  3499. $out .= '</select>';
  3500. $this->db->free($result);
  3501. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3502. $out .= ajax_combobox($htmlname);
  3503. } else {
  3504. dol_print_error($this->db);
  3505. }
  3506. if (empty($outputmode)) {
  3507. return $out;
  3508. }
  3509. return $outarray;
  3510. }
  3511. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3512. /**
  3513. * Return list of suppliers prices for a product
  3514. *
  3515. * @param int $productid Id of product
  3516. * @param string $htmlname Name of HTML field
  3517. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3518. * @return string
  3519. */
  3520. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = 0)
  3521. {
  3522. // phpcs:enable
  3523. global $langs, $conf;
  3524. $langs->load('stocks');
  3525. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3526. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3527. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3528. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3529. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3530. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3531. $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
  3532. $sql .= " AND p.tobuy = 1";
  3533. $sql .= " AND s.fournisseur = 1";
  3534. $sql .= " AND p.rowid = " . ((int) $productid);
  3535. if (!getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED')) {
  3536. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3537. } else {
  3538. $sql .= " ORDER BY pfp.unitprice ASC";
  3539. }
  3540. dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
  3541. $result = $this->db->query($sql);
  3542. if ($result) {
  3543. $num = $this->db->num_rows($result);
  3544. $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3545. if (!$num) {
  3546. $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
  3547. } else {
  3548. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3549. $form .= '<option value="0">&nbsp;</option>';
  3550. $i = 0;
  3551. while ($i < $num) {
  3552. $objp = $this->db->fetch_object($result);
  3553. $opt = '<option value="' . $objp->idprodfournprice . '"';
  3554. //if there is only one supplier, preselect it
  3555. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && getDolGlobalString('PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED'))) {
  3556. $opt .= ' selected';
  3557. }
  3558. $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
  3559. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3560. $prod_supplier = new ProductFournisseur($this->db);
  3561. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3562. $prod_supplier->id = $productid;
  3563. $prod_supplier->fourn_qty = $objp->quantity;
  3564. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3565. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3566. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3567. $priceparser = new PriceParser($this->db);
  3568. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3569. if ($price_result >= 0) {
  3570. $objp->fprice = $price_result;
  3571. if ($objp->quantity >= 1) {
  3572. $objp->unitprice = $objp->fprice / $objp->quantity;
  3573. }
  3574. }
  3575. }
  3576. if ($objp->quantity == 1) {
  3577. $opt .= price($objp->fprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3578. }
  3579. $opt .= $objp->quantity . ' ';
  3580. if ($objp->quantity == 1) {
  3581. $opt .= $langs->trans("Unit");
  3582. } else {
  3583. $opt .= $langs->trans("Units");
  3584. }
  3585. if ($objp->quantity > 1) {
  3586. $opt .= " - ";
  3587. $opt .= price($objp->unitprice * (getDolGlobalString('DISPLAY_DISCOUNTED_SUPPLIER_PRICE') ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit");
  3588. }
  3589. if ($objp->duration) {
  3590. $opt .= " - " . $objp->duration;
  3591. }
  3592. $opt .= "</option>\n";
  3593. $form .= $opt;
  3594. $i++;
  3595. }
  3596. }
  3597. $form .= '</select>';
  3598. $this->db->free($result);
  3599. return $form;
  3600. } else {
  3601. dol_print_error($this->db);
  3602. return '';
  3603. }
  3604. }
  3605. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3606. /**
  3607. * Load into cache list of payment terms
  3608. *
  3609. * @return int Nb of lines loaded, <0 if KO
  3610. */
  3611. public function load_cache_conditions_paiements()
  3612. {
  3613. // phpcs:enable
  3614. global $langs;
  3615. $num = count($this->cache_conditions_paiements);
  3616. if ($num > 0) {
  3617. return 0; // Cache already loaded
  3618. }
  3619. dol_syslog(__METHOD__, LOG_DEBUG);
  3620. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3621. $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
  3622. $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
  3623. $sql .= " AND active > 0";
  3624. $sql .= " ORDER BY sortorder";
  3625. $resql = $this->db->query($sql);
  3626. if ($resql) {
  3627. $num = $this->db->num_rows($resql);
  3628. $i = 0;
  3629. while ($i < $num) {
  3630. $obj = $this->db->fetch_object($resql);
  3631. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3632. $label = ($langs->trans("PaymentConditionShort" . $obj->code) != "PaymentConditionShort" . $obj->code ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3633. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3634. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3635. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3636. $i++;
  3637. }
  3638. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3639. return $num;
  3640. } else {
  3641. dol_print_error($this->db);
  3642. return -1;
  3643. }
  3644. }
  3645. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3646. /**
  3647. * Load int a cache property th elist of possible delivery delays.
  3648. *
  3649. * @return int Nb of lines loaded, <0 if KO
  3650. */
  3651. public function load_cache_availability()
  3652. {
  3653. // phpcs:enable
  3654. global $langs;
  3655. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3656. if ($num > 0) {
  3657. return 0; // Cache already loaded
  3658. }
  3659. dol_syslog(__METHOD__, LOG_DEBUG);
  3660. $langs->load('propal');
  3661. $sql = "SELECT rowid, code, label, position";
  3662. $sql .= " FROM " . $this->db->prefix() . 'c_availability';
  3663. $sql .= " WHERE active > 0";
  3664. $resql = $this->db->query($sql);
  3665. if ($resql) {
  3666. $num = $this->db->num_rows($resql);
  3667. $i = 0;
  3668. while ($i < $num) {
  3669. $obj = $this->db->fetch_object($resql);
  3670. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3671. $label = ($langs->trans("AvailabilityType" . $obj->code) != "AvailabilityType" . $obj->code ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3672. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3673. $this->cache_availability[$obj->rowid]['label'] = $label;
  3674. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3675. $i++;
  3676. }
  3677. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3678. return $num;
  3679. } else {
  3680. dol_print_error($this->db);
  3681. return -1;
  3682. }
  3683. }
  3684. /**
  3685. * Retourne la liste des types de delais de livraison possibles
  3686. *
  3687. * @param string $selected Id du type de delais pre-selectionne
  3688. * @param string $htmlname Nom de la zone select
  3689. * @param string $filtertype To add a filter
  3690. * @param int $addempty Add empty entry
  3691. * @param string $morecss More CSS
  3692. * @return void
  3693. */
  3694. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3695. {
  3696. global $langs, $user;
  3697. $this->load_cache_availability();
  3698. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3699. print '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3700. if ($addempty) {
  3701. print '<option value="0">&nbsp;</option>';
  3702. }
  3703. foreach ($this->cache_availability as $id => $arrayavailability) {
  3704. if ($selected == $id) {
  3705. print '<option value="' . $id . '" selected>';
  3706. } else {
  3707. print '<option value="' . $id . '">';
  3708. }
  3709. print dol_escape_htmltag($arrayavailability['label']);
  3710. print '</option>';
  3711. }
  3712. print '</select>';
  3713. if ($user->admin) {
  3714. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3715. }
  3716. print ajax_combobox($htmlname);
  3717. }
  3718. /**
  3719. * Load into cache cache_demand_reason, array of input reasons
  3720. *
  3721. * @return int Nb of lines loaded, <0 if KO
  3722. */
  3723. public function loadCacheInputReason()
  3724. {
  3725. global $langs;
  3726. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3727. if ($num > 0) {
  3728. return 0; // Cache already loaded
  3729. }
  3730. $sql = "SELECT rowid, code, label";
  3731. $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
  3732. $sql .= " WHERE active > 0";
  3733. $resql = $this->db->query($sql);
  3734. if ($resql) {
  3735. $num = $this->db->num_rows($resql);
  3736. $i = 0;
  3737. $tmparray = array();
  3738. while ($i < $num) {
  3739. $obj = $this->db->fetch_object($resql);
  3740. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3741. $label = ($obj->label != '-' ? $obj->label : '');
  3742. if ($langs->trans("DemandReasonType" . $obj->code) != "DemandReasonType" . $obj->code) {
  3743. $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3744. }
  3745. if ($langs->trans($obj->code) != $obj->code) {
  3746. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3747. }
  3748. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3749. $tmparray[$obj->rowid]['code'] = $obj->code;
  3750. $tmparray[$obj->rowid]['label'] = $label;
  3751. $i++;
  3752. }
  3753. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3754. unset($tmparray);
  3755. return $num;
  3756. } else {
  3757. dol_print_error($this->db);
  3758. return -1;
  3759. }
  3760. }
  3761. /**
  3762. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3763. * List found into table c_input_reason loaded by loadCacheInputReason
  3764. *
  3765. * @param string $selected Id or code of type origin to select by default
  3766. * @param string $htmlname Nom de la zone select
  3767. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3768. * @param int $addempty Add an empty entry
  3769. * @param string $morecss Add more css to the HTML select component
  3770. * @param int $notooltip Do not show the tooltip for admin
  3771. * @return void
  3772. */
  3773. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3774. {
  3775. global $langs, $user;
  3776. $this->loadCacheInputReason();
  3777. print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3778. if ($addempty) {
  3779. print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
  3780. }
  3781. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3782. if ($arraydemandreason['code'] == $exclude) {
  3783. continue;
  3784. }
  3785. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3786. print '<option value="' . $arraydemandreason['id'] . '" selected>';
  3787. } else {
  3788. print '<option value="' . $arraydemandreason['id'] . '">';
  3789. }
  3790. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3791. print $langs->trans($label);
  3792. print '</option>';
  3793. }
  3794. print '</select>';
  3795. if ($user->admin && empty($notooltip)) {
  3796. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3797. }
  3798. print ajax_combobox('select_' . $htmlname);
  3799. }
  3800. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3801. /**
  3802. * Charge dans cache la liste des types de paiements possibles
  3803. *
  3804. * @return int Nb of lines loaded, <0 if KO
  3805. */
  3806. public function load_cache_types_paiements()
  3807. {
  3808. // phpcs:enable
  3809. global $langs;
  3810. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3811. if ($num > 0) {
  3812. return $num; // Cache already loaded
  3813. }
  3814. dol_syslog(__METHOD__, LOG_DEBUG);
  3815. $this->cache_types_paiements = array();
  3816. $sql = "SELECT id, code, libelle as label, type, active";
  3817. $sql .= " FROM " . $this->db->prefix() . "c_paiement";
  3818. $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
  3819. $resql = $this->db->query($sql);
  3820. if ($resql) {
  3821. $num = $this->db->num_rows($resql);
  3822. $i = 0;
  3823. while ($i < $num) {
  3824. $obj = $this->db->fetch_object($resql);
  3825. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3826. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3827. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3828. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3829. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3830. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3831. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3832. $i++;
  3833. }
  3834. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3835. return $num;
  3836. } else {
  3837. dol_print_error($this->db);
  3838. return -1;
  3839. }
  3840. }
  3841. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3842. /**
  3843. * print list of payment modes.
  3844. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can be used to set default value but scope is all application, probably not what you want.
  3845. * See instead to force the default value by the caller.
  3846. *
  3847. * @param int $selected Id of payment term to preselect by default
  3848. * @param string $htmlname Nom de la zone select
  3849. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3850. * @param int $addempty Add an empty entry
  3851. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3852. * @param string $morecss Add more CSS on select tag
  3853. * @param int $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3854. * 0 : use default deposit percentage from entry
  3855. * > 0 : force deposit percentage (for example, from company object)
  3856. * @return void
  3857. * @deprecated
  3858. */
  3859. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3860. {
  3861. // phpcs:enable
  3862. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
  3863. }
  3864. /**
  3865. * Return list of payment modes.
  3866. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can be used to set default value but scope is all application, probably not what you want.
  3867. * See instead to force the default value by the caller.
  3868. *
  3869. * @param int $selected Id of payment term to preselect by default
  3870. * @param string $htmlname Nom de la zone select
  3871. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3872. * @param int $addempty Add an empty entry
  3873. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3874. * @param string $morecss Add more CSS on select tag
  3875. * @param int $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3876. * 0 : use default deposit percentage from entry
  3877. * > 0 : force deposit percentage (for example, from company object)
  3878. * @return string String for the HTML select component
  3879. */
  3880. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3881. {
  3882. global $langs, $user, $conf;
  3883. $out = '';
  3884. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3885. $this->load_cache_conditions_paiements();
  3886. // Set default value if not already set by caller
  3887. if (empty($selected) && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TERM_ID')) {
  3888. dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TERM_ID", LOG_NOTICE);
  3889. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3890. }
  3891. $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3892. if ($addempty) {
  3893. $out .= '<option value="0">&nbsp;</option>';
  3894. }
  3895. $selectedDepositPercent = null;
  3896. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3897. if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
  3898. continue;
  3899. }
  3900. if ($selected == $id) {
  3901. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3902. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3903. } else {
  3904. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3905. }
  3906. $label = $arrayconditions['label'];
  3907. if (!empty($arrayconditions['deposit_percent'])) {
  3908. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3909. }
  3910. $out .= $label;
  3911. $out .= '</option>';
  3912. }
  3913. $out .= '</select>';
  3914. if ($user->admin && empty($noinfoadmin)) {
  3915. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3916. }
  3917. $out .= ajax_combobox($htmlname);
  3918. if ($deposit_percent >= 0) {
  3919. $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3920. $out .= $langs->trans('DepositPercent') . ' : ';
  3921. $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
  3922. $out .= '</span>';
  3923. $out .= '
  3924. <script nonce="' . getNonce() . '">
  3925. $(document).ready(function () {
  3926. $("#' . $htmlname . '").change(function () {
  3927. let $selected = $(this).find("option:selected");
  3928. let depositPercent = $selected.attr("data-deposit_percent");
  3929. if (depositPercent.length > 0) {
  3930. $("#' . $htmlname . '_deposit_percent_container").show().find("#' . $htmlname . '_deposit_percent").val(depositPercent);
  3931. } else {
  3932. $("#' . $htmlname . '_deposit_percent_container").hide();
  3933. }
  3934. return true;
  3935. });
  3936. });
  3937. </script>';
  3938. }
  3939. return $out;
  3940. }
  3941. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3942. /**
  3943. * Return list of payment methods
  3944. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3945. *
  3946. * @param string $selected Id or code or preselected payment mode
  3947. * @param string $htmlname Name of select field
  3948. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3949. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3950. * @param int $empty 1=can be empty, 0 otherwise
  3951. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3952. * @param int $maxlength Max length of label
  3953. * @param int $active Active or not, -1 = all
  3954. * @param string $morecss Add more CSS on select tag
  3955. * @param int $nooutput 1=Return string, do not send to output
  3956. * @return string|void String for the HTML select component
  3957. */
  3958. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3959. {
  3960. // phpcs:enable
  3961. global $langs, $user, $conf;
  3962. $out = '';
  3963. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
  3964. $filterarray = array();
  3965. if ($filtertype == 'CRDT') {
  3966. $filterarray = array(0, 2, 3);
  3967. } elseif ($filtertype == 'DBIT') {
  3968. $filterarray = array(1, 2, 3);
  3969. } elseif ($filtertype != '' && $filtertype != '-1') {
  3970. $filterarray = explode(',', $filtertype);
  3971. }
  3972. $this->load_cache_types_paiements();
  3973. // Set default value if not already set by caller
  3974. if (empty($selected) && getDolGlobalString('MAIN_DEFAULT_PAYMENT_TYPE_ID')) {
  3975. dol_syslog(__METHOD__ . "Using deprecated option MAIN_DEFAULT_PAYMENT_TYPE_ID", LOG_NOTICE);
  3976. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3977. }
  3978. $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3979. if ($empty) {
  3980. $out .= '<option value="">&nbsp;</option>';
  3981. }
  3982. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3983. // If not good status
  3984. if ($active >= 0 && $arraytypes['active'] != $active) {
  3985. continue;
  3986. }
  3987. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3988. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3989. continue;
  3990. }
  3991. // We discard empty line if showempty is on because an empty line has already been output.
  3992. if ($empty && empty($arraytypes['code'])) {
  3993. continue;
  3994. }
  3995. if ($format == 0) {
  3996. $out .= '<option value="' . $id . '"';
  3997. } elseif ($format == 1) {
  3998. $out .= '<option value="' . $arraytypes['code'] . '"';
  3999. } elseif ($format == 2) {
  4000. $out .= '<option value="' . $arraytypes['code'] . '"';
  4001. } elseif ($format == 3) {
  4002. $out .= '<option value="' . $id . '"';
  4003. }
  4004. // Print attribute selected or not
  4005. if ($format == 1 || $format == 2) {
  4006. if ($selected == $arraytypes['code']) {
  4007. $out .= ' selected';
  4008. }
  4009. } else {
  4010. if ($selected == $id) {
  4011. $out .= ' selected';
  4012. }
  4013. }
  4014. $out .= '>';
  4015. $value = '';
  4016. if ($format == 0) {
  4017. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4018. } elseif ($format == 1) {
  4019. $value = $arraytypes['code'];
  4020. } elseif ($format == 2) {
  4021. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4022. } elseif ($format == 3) {
  4023. $value = $arraytypes['code'];
  4024. }
  4025. $out .= $value ? $value : '&nbsp;';
  4026. $out .= '</option>';
  4027. }
  4028. $out .= '</select>';
  4029. if ($user->admin && !$noadmininfo) {
  4030. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4031. }
  4032. $out .= ajax_combobox('select' . $htmlname);
  4033. if (empty($nooutput)) {
  4034. print $out;
  4035. } else {
  4036. return $out;
  4037. }
  4038. }
  4039. /**
  4040. * Selection HT or TTC
  4041. *
  4042. * @param string $selected Id pre-selectionne
  4043. * @param string $htmlname Nom de la zone select
  4044. * @param int $addjscombo Add js combo
  4045. * @return string Code of HTML select to chose tax or not
  4046. */
  4047. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  4048. {
  4049. global $langs;
  4050. $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  4051. $options = array(
  4052. 'HT' => $langs->trans("HT"),
  4053. 'TTC' => $langs->trans("TTC")
  4054. );
  4055. foreach ($options as $id => $value) {
  4056. if ($selected == $id) {
  4057. $return .= '<option value="' . $id . '" selected>' . $value;
  4058. } else {
  4059. $return .= '<option value="' . $id . '">' . $value;
  4060. }
  4061. $return .= '</option>';
  4062. }
  4063. $return .= '</select>';
  4064. if ($addjscombo) {
  4065. $return .= ajax_combobox('select_' . $htmlname);
  4066. }
  4067. return $return;
  4068. }
  4069. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4070. /**
  4071. * Load in cache list of transport mode
  4072. *
  4073. * @return int Nb of lines loaded, <0 if KO
  4074. */
  4075. public function load_cache_transport_mode()
  4076. {
  4077. // phpcs:enable
  4078. global $langs;
  4079. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  4080. if ($num > 0) {
  4081. return $num; // Cache already loaded
  4082. }
  4083. dol_syslog(__METHOD__, LOG_DEBUG);
  4084. $this->cache_transport_mode = array();
  4085. $sql = "SELECT rowid, code, label, active";
  4086. $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
  4087. $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
  4088. $resql = $this->db->query($sql);
  4089. if ($resql) {
  4090. $num = $this->db->num_rows($resql);
  4091. $i = 0;
  4092. while ($i < $num) {
  4093. $obj = $this->db->fetch_object($resql);
  4094. // If traduction exist, we use it else we take the default label
  4095. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != "PaymentTypeShort" . $obj->code ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  4096. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  4097. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  4098. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  4099. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  4100. $i++;
  4101. }
  4102. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  4103. return $num;
  4104. } else {
  4105. dol_print_error($this->db);
  4106. return -1;
  4107. }
  4108. }
  4109. /**
  4110. * Return list of transport mode for intracomm report
  4111. *
  4112. * @param string $selected Id of the transport mode pre-selected
  4113. * @param string $htmlname Name of the select field
  4114. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  4115. * @param int $empty 1=can be empty, 0 else
  4116. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  4117. * @param int $maxlength Max length of label
  4118. * @param int $active Active or not, -1 = all
  4119. * @param string $morecss Add more CSS on select tag
  4120. * @return void
  4121. */
  4122. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  4123. {
  4124. global $langs, $user;
  4125. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
  4126. $this->load_cache_transport_mode();
  4127. print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  4128. if ($empty) {
  4129. print '<option value="">&nbsp;</option>';
  4130. }
  4131. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  4132. // If not good status
  4133. if ($active >= 0 && $arraytypes['active'] != $active) {
  4134. continue;
  4135. }
  4136. // We discard empty line if showempty is on because an empty line has already been output.
  4137. if ($empty && empty($arraytypes['code'])) {
  4138. continue;
  4139. }
  4140. if ($format == 0) {
  4141. print '<option value="' . $id . '"';
  4142. } elseif ($format == 1) {
  4143. print '<option value="' . $arraytypes['code'] . '"';
  4144. } elseif ($format == 2) {
  4145. print '<option value="' . $arraytypes['code'] . '"';
  4146. } elseif ($format == 3) {
  4147. print '<option value="' . $id . '"';
  4148. }
  4149. // If text is selected, we compare with code, else with id
  4150. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  4151. print ' selected';
  4152. } elseif ($selected == $id) {
  4153. print ' selected';
  4154. }
  4155. print '>';
  4156. $value = '';
  4157. if ($format == 0) {
  4158. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4159. } elseif ($format == 1) {
  4160. $value = $arraytypes['code'];
  4161. } elseif ($format == 2) {
  4162. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4163. } elseif ($format == 3) {
  4164. $value = $arraytypes['code'];
  4165. }
  4166. print $value ? $value : '&nbsp;';
  4167. print '</option>';
  4168. }
  4169. print '</select>';
  4170. if ($user->admin && !$noadmininfo) {
  4171. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4172. }
  4173. }
  4174. /**
  4175. * Return a HTML select list of shipping mode
  4176. *
  4177. * @param string $selected Id shipping mode pre-selected
  4178. * @param string $htmlname Name of select zone
  4179. * @param string $filtre To filter list. This parameter must not come from input of users
  4180. * @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.
  4181. * @param string $moreattrib To add more attribute on select
  4182. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  4183. * @param string $morecss More CSS
  4184. * @return void
  4185. */
  4186. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  4187. {
  4188. global $langs, $user;
  4189. $langs->load("admin");
  4190. $langs->load("deliveries");
  4191. $sql = "SELECT rowid, code, libelle as label";
  4192. $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
  4193. $sql .= " WHERE active > 0";
  4194. if ($filtre) {
  4195. $sql .= " AND " . $filtre;
  4196. }
  4197. $sql .= " ORDER BY libelle ASC";
  4198. dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
  4199. $result = $this->db->query($sql);
  4200. if ($result) {
  4201. $num = $this->db->num_rows($result);
  4202. $i = 0;
  4203. if ($num) {
  4204. print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4205. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4206. print '<option value="-1">&nbsp;</option>';
  4207. }
  4208. while ($i < $num) {
  4209. $obj = $this->db->fetch_object($result);
  4210. if ($selected == $obj->rowid) {
  4211. print '<option value="' . $obj->rowid . '" selected>';
  4212. } else {
  4213. print '<option value="' . $obj->rowid . '">';
  4214. }
  4215. print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
  4216. print '</option>';
  4217. $i++;
  4218. }
  4219. print "</select>";
  4220. if ($user->admin && empty($noinfoadmin)) {
  4221. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4222. }
  4223. print ajax_combobox('select' . $htmlname);
  4224. } else {
  4225. print $langs->trans("NoShippingMethodDefined");
  4226. }
  4227. } else {
  4228. dol_print_error($this->db);
  4229. }
  4230. }
  4231. /**
  4232. * Display form to select shipping mode
  4233. *
  4234. * @param string $page Page
  4235. * @param string $selected Id of shipping mode
  4236. * @param string $htmlname Name of select html field
  4237. * @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.
  4238. * @return void
  4239. */
  4240. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4241. {
  4242. global $langs;
  4243. $langs->load("deliveries");
  4244. if ($htmlname != "none") {
  4245. print '<form method="POST" action="' . $page . '">';
  4246. print '<input type="hidden" name="action" value="setshippingmethod">';
  4247. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4248. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4249. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  4250. print '</form>';
  4251. } else {
  4252. if ($selected) {
  4253. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4254. print $langs->trans("SendingMethod" . strtoupper($code));
  4255. } else {
  4256. print "&nbsp;";
  4257. }
  4258. }
  4259. }
  4260. /**
  4261. * Creates HTML last in cycle situation invoices selector
  4262. *
  4263. * @param string $selected Preselected ID
  4264. * @param int $socid Company ID
  4265. *
  4266. * @return string HTML select
  4267. */
  4268. public function selectSituationInvoices($selected = '', $socid = 0)
  4269. {
  4270. global $langs;
  4271. $langs->load('bills');
  4272. $opt = '<option value="" selected></option>';
  4273. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4274. $sql .= ' FROM ' . $this->db->prefix() . 'facture';
  4275. $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
  4276. $sql .= ' AND situation_counter >= 1';
  4277. $sql .= ' AND fk_soc = ' . (int) $socid;
  4278. $sql .= ' AND type <> 2';
  4279. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4280. $resql = $this->db->query($sql);
  4281. if ($resql && $this->db->num_rows($resql) > 0) {
  4282. // Last seen cycle
  4283. $ref = 0;
  4284. while ($obj = $this->db->fetch_object($resql)) {
  4285. //Same cycle ?
  4286. if ($obj->situation_cycle_ref != $ref) {
  4287. // Just seen this cycle
  4288. $ref = $obj->situation_cycle_ref;
  4289. //not final ?
  4290. if ($obj->situation_final != 1) {
  4291. //Not prov?
  4292. if (substr($obj->ref, 1, 4) != 'PROV') {
  4293. if ($selected == $obj->rowid) {
  4294. $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
  4295. } else {
  4296. $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
  4297. }
  4298. }
  4299. }
  4300. }
  4301. }
  4302. } else {
  4303. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  4304. }
  4305. if ($opt == '<option value ="" selected></option>') {
  4306. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  4307. }
  4308. return $opt;
  4309. }
  4310. /**
  4311. * Creates HTML units selector (code => label)
  4312. *
  4313. * @param string $selected Preselected Unit ID
  4314. * @param string $htmlname Select name
  4315. * @param int $showempty Add a nempty line
  4316. * @param string $unit_type Restrict to one given unit type
  4317. * @return string HTML select
  4318. */
  4319. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4320. {
  4321. global $langs;
  4322. $langs->load('products');
  4323. $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
  4324. $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
  4325. $sql .= ' WHERE active > 0';
  4326. if (!empty($unit_type)) {
  4327. $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
  4328. }
  4329. $sql .= " ORDER BY sortorder";
  4330. $resql = $this->db->query($sql);
  4331. if ($resql && $this->db->num_rows($resql) > 0) {
  4332. if ($showempty) {
  4333. $return .= '<option value="none"></option>';
  4334. }
  4335. while ($res = $this->db->fetch_object($resql)) {
  4336. $unitLabel = $res->label;
  4337. if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
  4338. $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
  4339. }
  4340. if ($selected == $res->rowid) {
  4341. $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
  4342. } else {
  4343. $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
  4344. }
  4345. }
  4346. $return .= '</select>';
  4347. }
  4348. return $return;
  4349. }
  4350. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4351. /**
  4352. * Return a HTML select list of bank accounts
  4353. *
  4354. * @param string $selected Id account pre-selected
  4355. * @param string $htmlname Name of select zone
  4356. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4357. * @param string $filtre To filter list. This parameter must not come from input of users
  4358. * @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.
  4359. * @param string $moreattrib To add more attribute on select
  4360. * @param int $showcurrency Show currency in label
  4361. * @param string $morecss More CSS
  4362. * @param int $nooutput 1=Return string, do not send to output
  4363. * @return int Return integer <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4364. */
  4365. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4366. {
  4367. // phpcs:enable
  4368. global $langs, $conf;
  4369. $out = '';
  4370. $langs->load("admin");
  4371. $num = 0;
  4372. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4373. $sql .= " FROM " . $this->db->prefix() . "bank_account";
  4374. $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
  4375. if ($status != 2) {
  4376. $sql .= " AND clos = " . (int) $status;
  4377. }
  4378. if ($filtre) {
  4379. $sql .= " AND " . $filtre;
  4380. }
  4381. $sql .= " ORDER BY label";
  4382. dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
  4383. $result = $this->db->query($sql);
  4384. if ($result) {
  4385. $num = $this->db->num_rows($result);
  4386. $i = 0;
  4387. if ($num) {
  4388. $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4389. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4390. $out .= '<option value="-1">&nbsp;</option>';
  4391. }
  4392. while ($i < $num) {
  4393. $obj = $this->db->fetch_object($result);
  4394. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4395. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" selected>';
  4396. } else {
  4397. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '">';
  4398. }
  4399. $out .= trim($obj->label);
  4400. if ($showcurrency) {
  4401. $out .= ' (' . $obj->currency_code . ')';
  4402. }
  4403. if ($status == 2 && $obj->status == 1) {
  4404. $out .= ' (' . $langs->trans("Closed") . ')';
  4405. }
  4406. $out .= '</option>';
  4407. $i++;
  4408. }
  4409. $out .= "</select>";
  4410. $out .= ajax_combobox('select' . $htmlname);
  4411. } else {
  4412. if ($status == 0) {
  4413. $out .= '<span class="opacitymedium">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
  4414. } else {
  4415. $out .= '<span class="opacitymedium">' . $langs->trans("NoBankAccountFound") . '</span>';
  4416. }
  4417. }
  4418. } else {
  4419. dol_print_error($this->db);
  4420. }
  4421. // Output or return
  4422. if (empty($nooutput)) {
  4423. print $out;
  4424. } else {
  4425. return $out;
  4426. }
  4427. return $num;
  4428. }
  4429. /**
  4430. * Return a HTML select list of establishment
  4431. *
  4432. * @param string $selected Id establishment pre-selected
  4433. * @param string $htmlname Name of select zone
  4434. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4435. * @param string $filtre To filter list. This parameter must not come from input of users
  4436. * @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.
  4437. * @param string $moreattrib To add more attribute on select
  4438. * @return int Return integer <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4439. */
  4440. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4441. {
  4442. global $langs, $conf;
  4443. $langs->load("admin");
  4444. $num = 0;
  4445. $sql = "SELECT rowid, name, fk_country, status, entity";
  4446. $sql .= " FROM " . $this->db->prefix() . "establishment";
  4447. $sql .= " WHERE 1=1";
  4448. if ($status != 2) {
  4449. $sql .= " AND status = " . (int) $status;
  4450. }
  4451. if ($filtre) {
  4452. $sql .= " AND " . $filtre;
  4453. }
  4454. $sql .= " ORDER BY name";
  4455. dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
  4456. $result = $this->db->query($sql);
  4457. if ($result) {
  4458. $num = $this->db->num_rows($result);
  4459. $i = 0;
  4460. if ($num) {
  4461. print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4462. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4463. print '<option value="-1">&nbsp;</option>';
  4464. }
  4465. while ($i < $num) {
  4466. $obj = $this->db->fetch_object($result);
  4467. if ($selected == $obj->rowid) {
  4468. print '<option value="' . $obj->rowid . '" selected>';
  4469. } else {
  4470. print '<option value="' . $obj->rowid . '">';
  4471. }
  4472. print trim($obj->name);
  4473. if ($status == 2 && $obj->status == 1) {
  4474. print ' (' . $langs->trans("Closed") . ')';
  4475. }
  4476. print '</option>';
  4477. $i++;
  4478. }
  4479. print "</select>";
  4480. } else {
  4481. if ($status == 0) {
  4482. print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
  4483. } else {
  4484. print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
  4485. }
  4486. }
  4487. return $num;
  4488. } else {
  4489. dol_print_error($this->db);
  4490. return -1;
  4491. }
  4492. }
  4493. /**
  4494. * Display form to select bank account
  4495. *
  4496. * @param string $page Page
  4497. * @param string $selected Id of bank account
  4498. * @param string $htmlname Name of select html field
  4499. * @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.
  4500. * @return void
  4501. */
  4502. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4503. {
  4504. global $langs;
  4505. if ($htmlname != "none") {
  4506. print '<form method="POST" action="' . $page . '">';
  4507. print '<input type="hidden" name="action" value="setbankaccount">';
  4508. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4509. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4510. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4511. if ($nbaccountfound > 0) {
  4512. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  4513. }
  4514. print '</form>';
  4515. } else {
  4516. $langs->load('banks');
  4517. if ($selected) {
  4518. require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
  4519. $bankstatic = new Account($this->db);
  4520. $result = $bankstatic->fetch($selected);
  4521. if ($result) {
  4522. print $bankstatic->getNomUrl(1);
  4523. }
  4524. } else {
  4525. print "&nbsp;";
  4526. }
  4527. }
  4528. }
  4529. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4530. /**
  4531. * Return list of categories having choosed type
  4532. *
  4533. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4534. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4535. * @param string $htmlname HTML field name
  4536. * @param int $maxlength Maximum length for labels
  4537. * @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.
  4538. * $markafterid can be an :
  4539. * - int (id of category)
  4540. * - string (categories ids seprated by comma)
  4541. * - array (list of categories ids)
  4542. * @param int $outputmode 0=HTML select string, 1=Array with full label only, 2=Array extended, 3=Array with full picto + label
  4543. * @param int $include [=0] Removed or 1=Keep only
  4544. * @param string $morecss More CSS
  4545. * @return string|array String list or Array of categories
  4546. * @see select_categories()
  4547. */
  4548. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4549. {
  4550. // phpcs:enable
  4551. global $conf, $langs;
  4552. $langs->load("categories");
  4553. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  4554. // For backward compatibility
  4555. if (is_numeric($type)) {
  4556. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4557. }
  4558. if ($type === Categorie::TYPE_BANK_LINE) {
  4559. // TODO Move this into common category feature
  4560. $cate_arbo = array();
  4561. $sql = "SELECT c.label, c.rowid";
  4562. $sql .= " FROM " . $this->db->prefix() . "bank_categ as c";
  4563. $sql .= " WHERE entity = " . $conf->entity;
  4564. $sql .= " ORDER BY c.label";
  4565. $result = $this->db->query($sql);
  4566. if ($result) {
  4567. $num = $this->db->num_rows($result);
  4568. $i = 0;
  4569. while ($i < $num) {
  4570. $objp = $this->db->fetch_object($result);
  4571. if ($objp) {
  4572. $cate_arbo[$objp->rowid] = array('id' => $objp->rowid, 'fulllabel' => $objp->label, 'color' => '', 'picto' => 'category');
  4573. }
  4574. $i++;
  4575. }
  4576. $this->db->free($result);
  4577. } else {
  4578. dol_print_error($this->db);
  4579. }
  4580. } else {
  4581. $cat = new Categorie($this->db);
  4582. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4583. }
  4584. $outarray = array();
  4585. $outarrayrichhtml = array();
  4586. $output = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  4587. if (is_array($cate_arbo)) {
  4588. if (!count($cate_arbo)) {
  4589. $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
  4590. } else {
  4591. $output .= '<option value="-1">&nbsp;</option>';
  4592. foreach ($cate_arbo as $key => $value) {
  4593. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4594. $add = 'selected ';
  4595. } else {
  4596. $add = '';
  4597. }
  4598. $labeltoshow = img_picto('', 'category', 'class="pictofixedwidth" style="color: #' . $cate_arbo[$key]['color'] . '"');
  4599. $labeltoshow .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4600. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4601. $outarrayrichhtml[$cate_arbo[$key]['id']] = $labeltoshow;
  4602. $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
  4603. $output .= ' data-html="' . dol_escape_htmltag($labeltoshow) . '"';
  4604. $output .= '>';
  4605. $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4606. $output .= '</option>';
  4607. }
  4608. }
  4609. }
  4610. $output .= '</select>';
  4611. $output .= "\n";
  4612. if ($outputmode == 2) {
  4613. return $cate_arbo;
  4614. } elseif ($outputmode == 1) {
  4615. return $outarray;
  4616. } elseif ($outputmode == 3) {
  4617. return $outarrayrichhtml;
  4618. }
  4619. return $output;
  4620. }
  4621. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4622. /**
  4623. * Show a confirmation HTML form or AJAX popup
  4624. *
  4625. * @param string $page Url of page to call if confirmation is OK
  4626. * @param string $title Title
  4627. * @param string $question Question
  4628. * @param string $action Action
  4629. * @param array $formquestion An array with forms complementary inputs
  4630. * @param string $selectedchoice "" or "no" or "yes"
  4631. * @param int|string $useajax 0=No, 1=Yes use Ajax to show the popup, 2=Yes and also submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4632. * @param int $height Force height of box
  4633. * @param int $width Force width of box
  4634. * @return void
  4635. * @deprecated
  4636. * @see formconfirm()
  4637. */
  4638. public function form_confirm($page, $title, $question, $action, $formquestion = array(), $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4639. {
  4640. // phpcs:enable
  4641. dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4642. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4643. }
  4644. /**
  4645. * Show a confirmation HTML form or AJAX popup.
  4646. * Easiest way to use this is with useajax=1.
  4647. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4648. * just after calling this method. For example:
  4649. * print '<script nonce="'.getNonce().'" type="text/javascript">'."\n";
  4650. * print 'jQuery(document).ready(function() {'."\n";
  4651. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4652. * print '});'."\n";
  4653. * print '</script>'."\n";
  4654. *
  4655. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4656. * @param string $title Title
  4657. * @param string $question Question
  4658. * @param string $action Action
  4659. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...'))
  4660. * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss',
  4661. * 'other', 'onecolumn' or 'hidden'...
  4662. * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0
  4663. * @param int|string $useajax 0=No, 1=Yes use Ajax to show the popup, 2=Yes and also submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4664. * @param int|string $height Force height of box (0 = auto)
  4665. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4666. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4667. * @param string $labelbuttonyes Label for Yes
  4668. * @param string $labelbuttonno Label for No
  4669. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4670. */
  4671. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4672. {
  4673. global $langs, $conf;
  4674. $more = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
  4675. $formconfirm = '';
  4676. $inputok = array();
  4677. $inputko = array();
  4678. // Clean parameters
  4679. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4680. if ($conf->browser->layout == 'phone') {
  4681. $width = '95%';
  4682. }
  4683. // Set height automatically if not defined
  4684. if (empty($height)) {
  4685. $height = 220;
  4686. if (is_array($formquestion) && count($formquestion) > 2) {
  4687. $height += ((count($formquestion) - 2) * 24);
  4688. }
  4689. }
  4690. if (is_array($formquestion) && !empty($formquestion)) {
  4691. // First add hidden fields and value
  4692. foreach ($formquestion as $key => $input) {
  4693. if (is_array($input) && !empty($input)) {
  4694. if ($input['type'] == 'hidden') {
  4695. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4696. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4697. $more .= '<input type="hidden" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '" value="' . dol_escape_htmltag($input['value']) . '" class="' . $morecss . '"' . $moreattr . '>' . "\n";
  4698. }
  4699. }
  4700. }
  4701. // Now add questions
  4702. $moreonecolumn = '';
  4703. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
  4704. foreach ($formquestion as $key => $input) {
  4705. if (is_array($input) && !empty($input)) {
  4706. $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
  4707. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4708. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4709. if ($input['type'] == 'text') {
  4710. $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="' . (empty($input['value']) ? '' : $input['value']) . '"' . $moreattr . ' /></div></div>' . "\n";
  4711. } elseif ($input['type'] == 'password') {
  4712. $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="' . (empty($input['value']) ? '' : $input['value']) . '"' . $moreattr . ' /></div></div>' . "\n";
  4713. } elseif ($input['type'] == 'textarea') {
  4714. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4715. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4716. $more .= $input['value'];
  4717. $more .= '</textarea>';
  4718. $more .= '</div></div>'."\n";*/
  4719. $moreonecolumn .= '<div class="margintoponly">';
  4720. $moreonecolumn .= $input['label'] . '<br>';
  4721. $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
  4722. $moreonecolumn .= $input['value'];
  4723. $moreonecolumn .= '</textarea>';
  4724. $moreonecolumn .= '</div>';
  4725. } elseif (in_array($input['type'], ['select', 'multiselect'])) {
  4726. if (empty($morecss)) {
  4727. $morecss = 'minwidth100';
  4728. }
  4729. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4730. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4731. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4732. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4733. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4734. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4735. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4736. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
  4737. if (!empty($input['label'])) {
  4738. $more .= $input['label'] . '</div><div class="tagtd left">';
  4739. }
  4740. if ($input['type'] == 'select') {
  4741. $more .= $this->selectarray($input['name'], $input['values'], isset($input['default']) ? $input['default'] : '-1', $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4742. } else {
  4743. $more .= $this->multiselectarray($input['name'], $input['values'], is_array($input['default']) ? $input['default'] : [$input['default']], $key_in_label, $value_as_key, $morecss, $translate, $maxlen, $moreattr);
  4744. }
  4745. $more .= '</div></div>' . "\n";
  4746. } elseif ($input['type'] == 'checkbox') {
  4747. $more .= '<div class="tagtr">';
  4748. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '"><label for="' . dol_escape_htmltag($input['name']) . '">' . $input['label'] . '</label></div><div class="tagtd">';
  4749. $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
  4750. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4751. $more .= ' checked';
  4752. }
  4753. if (is_bool($input['value']) && $input['value']) {
  4754. $more .= ' checked';
  4755. }
  4756. if (isset($input['disabled'])) {
  4757. $more .= ' disabled';
  4758. }
  4759. $more .= ' /></div>';
  4760. $more .= '</div>' . "\n";
  4761. } elseif ($input['type'] == 'radio') {
  4762. $i = 0;
  4763. foreach ($input['values'] as $selkey => $selval) {
  4764. $more .= '<div class="tagtr">';
  4765. if (isset($input['label'])) {
  4766. if ($i == 0) {
  4767. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4768. } else {
  4769. $more .= '<div clas="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
  4770. }
  4771. }
  4772. $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;
  4773. if (!empty($input['disabled'])) {
  4774. $more .= ' disabled';
  4775. }
  4776. if (isset($input['default']) && $input['default'] === $selkey) {
  4777. $more .= ' checked="checked"';
  4778. }
  4779. $more .= ' /> ';
  4780. $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
  4781. $more .= '</div></div>' . "\n";
  4782. $i++;
  4783. }
  4784. } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
  4785. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4786. $more .= '<div class="tagtd">';
  4787. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4788. $h = $m = 0;
  4789. if ($input['type'] == 'datetime') {
  4790. $h = isset($input['hours']) ? $input['hours'] : 1;
  4791. $m = isset($input['minutes']) ? $input['minutes'] : 1;
  4792. }
  4793. $more .= $this->selectDate($input['value'], $input['name'], $h, $m, 0, '', 1, $addnowlink);
  4794. $more .= '</div></div>'."\n";
  4795. $formquestion[] = array('name'=>$input['name'].'day');
  4796. $formquestion[] = array('name'=>$input['name'].'month');
  4797. $formquestion[] = array('name'=>$input['name'].'year');
  4798. $formquestion[] = array('name'=>$input['name'].'hour');
  4799. $formquestion[] = array('name'=>$input['name'].'min');
  4800. } elseif ($input['type'] == 'other') { // can be 1 column or 2 depending if label is set or not
  4801. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4802. if (!empty($input['label'])) {
  4803. $more .= $input['label'] . '</div><div class="tagtd">';
  4804. }
  4805. $more .= $input['value'];
  4806. $more .= '</div></div>' . "\n";
  4807. } elseif ($input['type'] == 'onecolumn') {
  4808. $moreonecolumn .= '<div class="margintoponly">';
  4809. $moreonecolumn .= $input['value'];
  4810. $moreonecolumn .= '</div>' . "\n";
  4811. } elseif ($input['type'] == 'hidden') {
  4812. // Do nothing more, already added by a previous loop
  4813. } elseif ($input['type'] == 'separator') {
  4814. $more .= '<br>';
  4815. } else {
  4816. $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
  4817. }
  4818. }
  4819. }
  4820. $more .= '</div>' . "\n";
  4821. $more .= $moreonecolumn;
  4822. }
  4823. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4824. // 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
  4825. // See page product/card.php for example
  4826. if (!empty($conf->dol_use_jmobile)) {
  4827. $useajax = 0;
  4828. }
  4829. if (empty($conf->use_javascript_ajax)) {
  4830. $useajax = 0;
  4831. }
  4832. if ($useajax) {
  4833. $autoOpen = true;
  4834. $dialogconfirm = 'dialog-confirm';
  4835. $button = '';
  4836. if (!is_numeric($useajax)) {
  4837. $button = $useajax;
  4838. $useajax = 1;
  4839. $autoOpen = false;
  4840. $dialogconfirm .= '-' . $button;
  4841. }
  4842. $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
  4843. $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
  4844. // Add input fields into list of fields to read during submit (inputok and inputko)
  4845. if (is_array($formquestion)) {
  4846. foreach ($formquestion as $key => $input) {
  4847. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4848. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4849. if (is_array($input) && isset($input['name'])) {
  4850. if (strpos($input['name'], ',') > 0) {
  4851. $inputok = array_merge($inputok, explode(',', $input['name']));
  4852. } else {
  4853. array_push($inputok, $input['name']);
  4854. }
  4855. }
  4856. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4857. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4858. array_push($inputko, $input['name']);
  4859. }
  4860. }
  4861. }
  4862. // Show JQuery confirm box.
  4863. $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
  4864. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4865. $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
  4866. }
  4867. if (!empty($more)) {
  4868. $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
  4869. }
  4870. $formconfirm .= ($question ? '<div class="confirmmessage">' . img_help('', '') . ' ' . $question . '</div>' : '');
  4871. $formconfirm .= '</div>' . "\n";
  4872. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
  4873. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  4874. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4875. $formconfirm .= 'jQuery(document).ready(function() {
  4876. $(function() {
  4877. $( "#' . $dialogconfirm . '" ).dialog(
  4878. {
  4879. autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
  4880. if ($newselectedchoice == 'no') {
  4881. $formconfirm .= '
  4882. open: function() {
  4883. $(this).parent().find("button.ui-button:eq(2)").focus();
  4884. },';
  4885. }
  4886. $jsforcursor = '';
  4887. if ($useajax == 1) {
  4888. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
  4889. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
  4890. }
  4891. $postconfirmas = 'GET';
  4892. $formconfirm .= '
  4893. resizable: false,
  4894. height: "' . $height . '",
  4895. width: "' . $width . '",
  4896. modal: true,
  4897. closeOnEscape: false,
  4898. buttons: {
  4899. "' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '": function() {
  4900. var options = "token=' . urlencode(newToken()) . '";
  4901. var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
  4902. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4903. var pageyes = "' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '";
  4904. if (inputok.length > 0) {
  4905. $.each(inputok, function(i, inputname) {
  4906. var more = "";
  4907. var inputvalue;
  4908. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4909. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4910. } else {
  4911. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4912. inputvalue = $("#" + inputname + more).val();
  4913. }
  4914. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4915. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4916. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4917. });
  4918. }
  4919. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
  4920. if (pageyes.length > 0) {';
  4921. if ($postconfirmas == 'GET') {
  4922. $formconfirm .= 'location.href = urljump;';
  4923. } else {
  4924. $formconfirm .= $jsforcursor;
  4925. $formconfirm .= 'var post = $.post(
  4926. pageyes,
  4927. options,
  4928. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4929. );';
  4930. }
  4931. $formconfirm .= '
  4932. console.log("after post ok");
  4933. }
  4934. $(this).dialog("close");
  4935. },
  4936. "' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '": function() {
  4937. var options = "token=' . urlencode(newToken()) . '";
  4938. var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
  4939. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4940. var pageno="' . dol_escape_js(!empty($pageno) ? $pageno : '') . '";
  4941. if (inputko.length > 0) {
  4942. $.each(inputko, function(i, inputname) {
  4943. var more = "";
  4944. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4945. var inputvalue = $("#" + inputname + more).val();
  4946. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4947. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4948. });
  4949. }
  4950. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
  4951. //alert(urljump);
  4952. if (pageno.length > 0) {';
  4953. if ($postconfirmas == 'GET') {
  4954. $formconfirm .= 'location.href = urljump;';
  4955. } else {
  4956. $formconfirm .= $jsforcursor;
  4957. $formconfirm .= 'var post = $.post(
  4958. pageno,
  4959. options,
  4960. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4961. );';
  4962. }
  4963. $formconfirm .= '
  4964. console.log("after post ko");
  4965. }
  4966. $(this).dialog("close");
  4967. }
  4968. }
  4969. }
  4970. );
  4971. var button = "' . $button . '";
  4972. if (button.length > 0) {
  4973. $( "#" + button ).click(function() {
  4974. $("#' . $dialogconfirm . '").dialog("open");
  4975. });
  4976. }
  4977. });
  4978. });
  4979. </script>';
  4980. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4981. } else {
  4982. $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
  4983. if (empty($disableformtag)) {
  4984. $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftroright">' . "\n";
  4985. }
  4986. $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
  4987. $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
  4988. $formconfirm .= '<table class="valid centpercent">' . "\n";
  4989. // Line title
  4990. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4991. $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
  4992. $formconfirm .= '</td></tr>' . "\n";
  4993. // Line text
  4994. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4995. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . $formquestion['text'] . '</td></tr>' . "\n";
  4996. }
  4997. // Line form fields
  4998. if ($more) {
  4999. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . "\n";
  5000. $formconfirm .= $more;
  5001. $formconfirm .= '</td></tr>' . "\n";
  5002. }
  5003. // Line with question
  5004. $formconfirm .= '<tr class="valid">';
  5005. $formconfirm .= '<td class="valid">' . $question . '</td>';
  5006. $formconfirm .= '<td class="valid center">';
  5007. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  5008. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
  5009. $formconfirm .= '</td>';
  5010. $formconfirm .= '</tr>' . "\n";
  5011. $formconfirm .= '</table>' . "\n";
  5012. if (empty($disableformtag)) {
  5013. $formconfirm .= "</form>\n";
  5014. }
  5015. $formconfirm .= '<br>';
  5016. if (!empty($conf->use_javascript_ajax)) {
  5017. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  5018. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  5019. $formconfirm .= '
  5020. $(document).ready(function () {
  5021. $(".confirmvalidatebutton").on("click", function() {
  5022. console.log("We click on button confirmvalidatebutton");
  5023. $(this).attr("disabled", "disabled");
  5024. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  5025. //console.log($(this).closest("form"));
  5026. $(this).closest("form").submit();
  5027. });
  5028. });
  5029. ';
  5030. $formconfirm .= '</script>' . "\n";
  5031. }
  5032. $formconfirm .= "<!-- end formconfirm -->\n";
  5033. }
  5034. return $formconfirm;
  5035. }
  5036. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5037. /**
  5038. * Show a form to select a project
  5039. *
  5040. * @param int $page Page
  5041. * @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)
  5042. * @param string $selected Id pre-selected project
  5043. * @param string $htmlname Name of select field
  5044. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  5045. * @param int $maxlength Max length
  5046. * @param int $forcefocus Force focus on field (works with javascript only)
  5047. * @param int $nooutput No print is done. String is returned.
  5048. * @param string $textifnoproject Text to show if no project
  5049. * @param string $morecss More CSS
  5050. * @return string Return html content
  5051. */
  5052. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
  5053. {
  5054. // phpcs:enable
  5055. global $langs;
  5056. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  5057. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  5058. $out = '';
  5059. $formproject = new FormProjets($this->db);
  5060. $langs->load("project");
  5061. if ($htmlname != "none") {
  5062. $out .= '<form method="post" action="' . $page . '">';
  5063. $out .= '<input type="hidden" name="action" value="classin">';
  5064. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5065. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
  5066. $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5067. $out .= '</form>';
  5068. } else {
  5069. $out .= '<span class="project_head_block">';
  5070. if ($selected) {
  5071. $projet = new Project($this->db);
  5072. $projet->fetch($selected);
  5073. $out .= $projet->getNomUrl(0, '', 1);
  5074. } else {
  5075. $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
  5076. }
  5077. $out .= '</span>';
  5078. }
  5079. if (empty($nooutput)) {
  5080. print $out;
  5081. return '';
  5082. }
  5083. return $out;
  5084. }
  5085. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5086. /**
  5087. * Show a form to select payment conditions
  5088. *
  5089. * @param int $page Page
  5090. * @param string $selected Id condition pre-selectionne
  5091. * @param string $htmlname Name of select html field
  5092. * @param int $addempty Add empty entry
  5093. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5094. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  5095. * @param int $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  5096. * 0 : use default deposit percentage from entry
  5097. * > 0 : force deposit percentage (for example, from company object)
  5098. * @param int $nooutput No print is done. String is returned.
  5099. * @return string HTML output or ''
  5100. */
  5101. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
  5102. {
  5103. // phpcs:enable
  5104. global $langs;
  5105. $out = '';
  5106. if ($htmlname != "none") {
  5107. $out .= '<form method="POST" action="' . $page . '">';
  5108. $out .= '<input type="hidden" name="action" value="setconditions">';
  5109. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5110. if ($type) {
  5111. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5112. }
  5113. $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  5114. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5115. $out .= '</form>';
  5116. } else {
  5117. if ($selected) {
  5118. $this->load_cache_conditions_paiements();
  5119. if (isset($this->cache_conditions_paiements[$selected])) {
  5120. $label = $this->cache_conditions_paiements[$selected]['label'];
  5121. if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  5122. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  5123. }
  5124. $out .= $label;
  5125. } else {
  5126. $langs->load('errors');
  5127. $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
  5128. }
  5129. } else {
  5130. $out .= '&nbsp;';
  5131. }
  5132. }
  5133. if (empty($nooutput)) {
  5134. print $out;
  5135. return '';
  5136. }
  5137. return $out;
  5138. }
  5139. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5140. /**
  5141. * Show a form to select a delivery delay
  5142. *
  5143. * @param int $page Page
  5144. * @param string $selected Id condition pre-selectionne
  5145. * @param string $htmlname Name of select html field
  5146. * @param int $addempty Add an empty entry
  5147. * @return void
  5148. */
  5149. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  5150. {
  5151. // phpcs:enable
  5152. global $langs;
  5153. if ($htmlname != "none") {
  5154. print '<form method="post" action="' . $page . '">';
  5155. print '<input type="hidden" name="action" value="setavailability">';
  5156. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5157. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  5158. print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5159. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
  5160. print '</form>';
  5161. } else {
  5162. if ($selected) {
  5163. $this->load_cache_availability();
  5164. print $this->cache_availability[$selected]['label'];
  5165. } else {
  5166. print "&nbsp;";
  5167. }
  5168. }
  5169. }
  5170. /**
  5171. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  5172. * List found into table c_input_reason loaded by loadCacheInputReason
  5173. *
  5174. * @param string $page Page
  5175. * @param string $selected Id condition pre-selectionne
  5176. * @param string $htmlname Name of select html field
  5177. * @param int $addempty Add empty entry
  5178. * @return void
  5179. */
  5180. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  5181. {
  5182. global $langs;
  5183. if ($htmlname != "none") {
  5184. print '<form method="post" action="' . $page . '">';
  5185. print '<input type="hidden" name="action" value="setdemandreason">';
  5186. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5187. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  5188. print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5189. print '</form>';
  5190. } else {
  5191. if ($selected) {
  5192. $this->loadCacheInputReason();
  5193. foreach ($this->cache_demand_reason as $key => $val) {
  5194. if ($val['id'] == $selected) {
  5195. print $val['label'];
  5196. break;
  5197. }
  5198. }
  5199. } else {
  5200. print "&nbsp;";
  5201. }
  5202. }
  5203. }
  5204. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5205. /**
  5206. * Show a form + html select a date
  5207. *
  5208. * @param string $page Page
  5209. * @param string $selected Date preselected
  5210. * @param string $htmlname Html name of date input fields or 'none'
  5211. * @param int $displayhour Display hour selector
  5212. * @param int $displaymin Display minutes selector
  5213. * @param int $nooutput 1=No print output, return string
  5214. * @param string $type 'direct-debit' or 'bank-transfer'
  5215. * @return string
  5216. * @see selectDate()
  5217. */
  5218. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  5219. {
  5220. // phpcs:enable
  5221. global $langs;
  5222. $ret = '';
  5223. if ($htmlname != "none") {
  5224. $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5225. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5226. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5227. if ($type) {
  5228. $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5229. }
  5230. $ret .= '<table class="nobordernopadding">';
  5231. $ret .= '<tr><td>';
  5232. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
  5233. $ret .= '</td>';
  5234. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5235. $ret .= '</tr></table></form>';
  5236. } else {
  5237. if ($displayhour) {
  5238. $ret .= dol_print_date($selected, 'dayhour');
  5239. } else {
  5240. $ret .= dol_print_date($selected, 'day');
  5241. }
  5242. }
  5243. if (empty($nooutput)) {
  5244. print $ret;
  5245. }
  5246. return $ret;
  5247. }
  5248. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5249. /**
  5250. * Show a select form to choose a user
  5251. *
  5252. * @param string $page Page
  5253. * @param string $selected Id of user preselected
  5254. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  5255. * @param array $exclude List of users id to exclude
  5256. * @param array $include List of users id to include
  5257. * @return void
  5258. */
  5259. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = array(), $include = array())
  5260. {
  5261. // phpcs:enable
  5262. global $langs;
  5263. if ($htmlname != "none") {
  5264. print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5265. print '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5266. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5267. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5268. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5269. print '</form>';
  5270. } else {
  5271. if ($selected) {
  5272. require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
  5273. $theuser = new User($this->db);
  5274. $theuser->fetch($selected);
  5275. print $theuser->getNomUrl(1);
  5276. } else {
  5277. print "&nbsp;";
  5278. }
  5279. }
  5280. }
  5281. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5282. /**
  5283. * Show form with payment mode
  5284. *
  5285. * @param string $page Page
  5286. * @param string $selected Id mode pre-selectionne
  5287. * @param string $htmlname Name of select html field
  5288. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5289. * @param int $active Active or not, -1 = all
  5290. * @param int $addempty 1=Add empty entry
  5291. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5292. * @param int $nooutput 1=Return string, no output
  5293. * @return string HTML output or ''
  5294. */
  5295. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
  5296. {
  5297. // phpcs:enable
  5298. global $langs;
  5299. $out = '';
  5300. if ($htmlname != "none") {
  5301. $out .= '<form method="POST" action="' . $page . '">';
  5302. $out .= '<input type="hidden" name="action" value="setmode">';
  5303. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5304. if ($type) {
  5305. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5306. }
  5307. $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5308. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5309. $out .= '</form>';
  5310. } else {
  5311. if ($selected) {
  5312. $this->load_cache_types_paiements();
  5313. $out .= $this->cache_types_paiements[$selected]['label'];
  5314. } else {
  5315. $out .= "&nbsp;";
  5316. }
  5317. }
  5318. if ($nooutput) {
  5319. return $out;
  5320. } else {
  5321. print $out;
  5322. }
  5323. return '';
  5324. }
  5325. /**
  5326. * Show form with transport mode
  5327. *
  5328. * @param string $page Page
  5329. * @param string $selected Id mode pre-select
  5330. * @param string $htmlname Name of select html field
  5331. * @param int $active Active or not, -1 = all
  5332. * @param int $addempty 1=Add empty entry
  5333. * @return void
  5334. */
  5335. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5336. {
  5337. global $langs;
  5338. if ($htmlname != "none") {
  5339. print '<form method="POST" action="' . $page . '">';
  5340. print '<input type="hidden" name="action" value="settransportmode">';
  5341. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5342. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5343. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5344. print '</form>';
  5345. } else {
  5346. if ($selected) {
  5347. $this->load_cache_transport_mode();
  5348. print $this->cache_transport_mode[$selected]['label'];
  5349. } else {
  5350. print "&nbsp;";
  5351. }
  5352. }
  5353. }
  5354. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5355. /**
  5356. * Show form with multicurrency code
  5357. *
  5358. * @param string $page Page
  5359. * @param string $selected code pre-selectionne
  5360. * @param string $htmlname Name of select html field
  5361. * @return void
  5362. */
  5363. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5364. {
  5365. // phpcs:enable
  5366. global $langs;
  5367. if ($htmlname != "none") {
  5368. print '<form method="POST" action="' . $page . '">';
  5369. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5370. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5371. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5372. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5373. print '</form>';
  5374. } else {
  5375. dol_include_once('/core/lib/company.lib.php');
  5376. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5377. }
  5378. }
  5379. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5380. /**
  5381. * Show form with multicurrency rate
  5382. *
  5383. * @param string $page Page
  5384. * @param double $rate Current rate
  5385. * @param string $htmlname Name of select html field
  5386. * @param string $currency Currency code to explain the rate
  5387. * @return void
  5388. */
  5389. public function form_multicurrency_rate($page, $rate = 0.0, $htmlname = 'multicurrency_tx', $currency = '')
  5390. {
  5391. // phpcs:enable
  5392. global $langs, $mysoc, $conf;
  5393. if ($htmlname != "none") {
  5394. print '<form method="POST" action="' . $page . '">';
  5395. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5396. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5397. print '<input type="text" class="maxwidth100" name="' . $htmlname . '" value="' . (!empty($rate) ? price(price2num($rate, 'CU')) : 1) . '" /> ';
  5398. print '<select name="calculation_mode">';
  5399. print '<option value="1">Change ' . $langs->trans("PriceUHT") . ' of lines</option>';
  5400. print '<option value="2">Change ' . $langs->trans("PriceUHTCurrency") . ' of lines</option>';
  5401. print '</select> ';
  5402. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5403. print '</form>';
  5404. } else {
  5405. if (!empty($rate)) {
  5406. print price($rate, 1, $langs, 0, 0);
  5407. if ($currency && $rate != 1) {
  5408. print ' &nbsp; (' . price($rate, 1, $langs, 0, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')';
  5409. }
  5410. } else {
  5411. print 1;
  5412. }
  5413. }
  5414. }
  5415. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5416. /**
  5417. * Show a select box with available absolute discounts
  5418. *
  5419. * @param string $page Page URL where form is shown
  5420. * @param int $selected Value pre-selected
  5421. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5422. * @param int $socid Third party id
  5423. * @param float $amount Total amount available
  5424. * @param string $filter SQL filter on discounts
  5425. * @param int $maxvalue Max value for lines that can be selected
  5426. * @param string $more More string to add
  5427. * @param int $hidelist 1=Hide list
  5428. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5429. * @return void
  5430. */
  5431. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5432. {
  5433. // phpcs:enable
  5434. global $conf, $langs;
  5435. if ($htmlname != "none") {
  5436. print '<form method="post" action="' . $page . '">';
  5437. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5438. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5439. print '<div class="inline-block">';
  5440. if (!empty($discount_type)) {
  5441. if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
  5442. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5443. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5444. } else {
  5445. $translationKey = 'HasCreditNoteFromSupplier';
  5446. }
  5447. } else {
  5448. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5449. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5450. } else {
  5451. $translationKey = 'HasCreditNoteFromSupplier';
  5452. }
  5453. }
  5454. } else {
  5455. if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
  5456. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5457. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5458. } else {
  5459. $translationKey = 'CompanyHasCreditNote';
  5460. }
  5461. } else {
  5462. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5463. $translationKey = 'CompanyHasAbsoluteDiscount';
  5464. } else {
  5465. $translationKey = 'CompanyHasCreditNote';
  5466. }
  5467. }
  5468. }
  5469. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5470. if (empty($hidelist)) {
  5471. print ' ';
  5472. }
  5473. print '</div>';
  5474. if (empty($hidelist)) {
  5475. print '<div class="inline-block" style="padding-right: 10px">';
  5476. $newfilter = 'discount_type=' . intval($discount_type);
  5477. if (!empty($discount_type)) {
  5478. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5479. } else {
  5480. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5481. }
  5482. if ($filter) {
  5483. $newfilter .= ' AND (' . $filter . ')';
  5484. }
  5485. // output the combo of discounts
  5486. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5487. if ($nbqualifiedlines > 0) {
  5488. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
  5489. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5490. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5491. }
  5492. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5493. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5494. }
  5495. print '>';
  5496. }
  5497. print '</div>';
  5498. }
  5499. if ($more) {
  5500. print '<div class="inline-block">';
  5501. print $more;
  5502. print '</div>';
  5503. }
  5504. print '</form>';
  5505. } else {
  5506. if ($selected) {
  5507. print $selected;
  5508. } else {
  5509. print "0";
  5510. }
  5511. }
  5512. }
  5513. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5514. /**
  5515. * Show forms to select a contact
  5516. *
  5517. * @param string $page Page
  5518. * @param Societe $societe Filter on third party
  5519. * @param string $selected Id contact pre-selectionne
  5520. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5521. * @return void
  5522. */
  5523. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5524. {
  5525. // phpcs:enable
  5526. global $langs, $conf;
  5527. if ($htmlname != "none") {
  5528. print '<form method="post" action="' . $page . '">';
  5529. print '<input type="hidden" name="action" value="set_contact">';
  5530. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5531. print '<table class="nobordernopadding">';
  5532. print '<tr><td>';
  5533. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5534. $num = $this->num;
  5535. if ($num == 0) {
  5536. $addcontact = (getDolGlobalString('SOCIETE_ADDRESSES_MANAGEMENT') ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5537. print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&amp;action=create&amp;backtoreferer=1">' . $addcontact . '</a>';
  5538. }
  5539. print '</td>';
  5540. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5541. print '</tr></table></form>';
  5542. } else {
  5543. if ($selected) {
  5544. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  5545. $contact = new Contact($this->db);
  5546. $contact->fetch($selected);
  5547. print $contact->getFullName($langs);
  5548. } else {
  5549. print "&nbsp;";
  5550. }
  5551. }
  5552. }
  5553. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5554. /**
  5555. * Output html select to select thirdparty
  5556. *
  5557. * @param string $page Page
  5558. * @param string $selected Id preselected
  5559. * @param string $htmlname Name of HTML select
  5560. * @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)'). Do not use a filter coming from input of users.
  5561. * @param int $showempty Add an empty field
  5562. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5563. * @param int $forcecombo Force to use combo box
  5564. * @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')))
  5565. * @param int $nooutput No print output. Return it only.
  5566. * @param array $excludeids Exclude IDs from the select combo
  5567. * @param string $textifnothirdparty Text to show if no thirdparty
  5568. * @return string HTML output or ''
  5569. */
  5570. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
  5571. {
  5572. // phpcs:enable
  5573. global $langs;
  5574. $out = '';
  5575. if ($htmlname != "none") {
  5576. $out .= '<form method="post" action="' . $page . '">';
  5577. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5578. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5579. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5580. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5581. $out .= '</form>';
  5582. } else {
  5583. if ($selected) {
  5584. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  5585. $soc = new Societe($this->db);
  5586. $soc->fetch($selected);
  5587. $out .= $soc->getNomUrl(0, '');
  5588. } else {
  5589. $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
  5590. }
  5591. }
  5592. if ($nooutput) {
  5593. return $out;
  5594. } else {
  5595. print $out;
  5596. }
  5597. return '';
  5598. }
  5599. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5600. /**
  5601. * Retourne la liste des devises, dans la langue de l'utilisateur
  5602. *
  5603. * @param string $selected preselected currency code
  5604. * @param string $htmlname name of HTML select list
  5605. * @deprecated
  5606. * @return void
  5607. */
  5608. public function select_currency($selected = '', $htmlname = 'currency_id')
  5609. {
  5610. // phpcs:enable
  5611. print $this->selectCurrency($selected, $htmlname);
  5612. }
  5613. /**
  5614. * Retourne la liste des devises, dans la langue de l'utilisateur
  5615. *
  5616. * @param string $selected preselected currency code
  5617. * @param string $htmlname name of HTML select list
  5618. * @param int $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5619. * @param string $useempty '1'=Allow empty value
  5620. * @return string
  5621. */
  5622. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5623. {
  5624. global $conf, $langs, $user;
  5625. $langs->loadCacheCurrencies('');
  5626. $out = '';
  5627. if ($selected == 'euro' || $selected == 'euros') {
  5628. $selected = 'EUR'; // Pour compatibilite
  5629. }
  5630. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
  5631. if ($useempty) {
  5632. $out .= '<option value="-1" selected></option>';
  5633. }
  5634. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5635. $labeltoshow = $currency['label'];
  5636. if ($mode == 1) {
  5637. $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
  5638. } else {
  5639. $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
  5640. }
  5641. if ($selected && $selected == $code_iso) {
  5642. $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5643. } else {
  5644. $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5645. }
  5646. $out .= $labeltoshow;
  5647. $out .= '</option>';
  5648. }
  5649. $out .= '</select>';
  5650. if ($user->admin) {
  5651. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5652. }
  5653. // Make select dynamic
  5654. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5655. $out .= ajax_combobox($htmlname);
  5656. return $out;
  5657. }
  5658. /**
  5659. * Return array of currencies in user language
  5660. *
  5661. * @param string $selected Preselected currency code
  5662. * @param string $htmlname Name of HTML select list
  5663. * @param integer $useempty 1=Add empty line
  5664. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5665. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5666. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5667. * @param string $morecss More css
  5668. * @return string
  5669. */
  5670. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5671. {
  5672. global $conf, $langs;
  5673. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5674. $TCurrency = array();
  5675. $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
  5676. $sql .= " WHERE entity IN ('" . getEntity('mutlicurrency') . "')";
  5677. if ($filter) {
  5678. $sql .= " AND " . $filter;
  5679. }
  5680. $resql = $this->db->query($sql);
  5681. if ($resql) {
  5682. while ($obj = $this->db->fetch_object($resql)) {
  5683. $TCurrency[$obj->code] = $obj->code;
  5684. }
  5685. }
  5686. $out = '';
  5687. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  5688. if ($useempty) {
  5689. $out .= '<option value="">&nbsp;</option>';
  5690. }
  5691. // If company current currency not in table, we add it into list. Should always be available.
  5692. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5693. $TCurrency[$conf->currency] = $conf->currency;
  5694. }
  5695. if (count($TCurrency) > 0) {
  5696. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5697. if (isset($TCurrency[$code_iso])) {
  5698. if (!empty($selected) && $selected == $code_iso) {
  5699. $out .= '<option value="' . $code_iso . '" selected="selected">';
  5700. } else {
  5701. $out .= '<option value="' . $code_iso . '">';
  5702. }
  5703. $out .= $currency['label'];
  5704. $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
  5705. $out .= '</option>';
  5706. }
  5707. }
  5708. }
  5709. $out .= '</select>';
  5710. // Make select dynamic
  5711. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5712. $out .= ajax_combobox($htmlname);
  5713. return $out;
  5714. }
  5715. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5716. /**
  5717. * Load into the cache vat rates of a country
  5718. *
  5719. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5720. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5721. */
  5722. public function load_cache_vatrates($country_code)
  5723. {
  5724. // phpcs:enable
  5725. global $langs, $user;
  5726. $num = count($this->cache_vatrates);
  5727. if ($num > 0) {
  5728. return $num; // Cache already loaded
  5729. }
  5730. dol_syslog(__METHOD__, LOG_DEBUG);
  5731. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5732. $sql .= " FROM " . $this->db->prefix() . "c_tva as t, " . $this->db->prefix() . "c_country as c";
  5733. $sql .= " WHERE t.fk_pays = c.rowid";
  5734. $sql .= " AND t.active > 0";
  5735. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  5736. $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
  5737. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5738. $resql = $this->db->query($sql);
  5739. if ($resql) {
  5740. $num = $this->db->num_rows($resql);
  5741. if ($num) {
  5742. for ($i = 0; $i < $num; $i++) {
  5743. $obj = $this->db->fetch_object($resql);
  5744. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5745. $this->cache_vatrates[$i]['code'] = $obj->code;
  5746. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5747. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5748. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5749. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5750. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5751. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5752. $this->cache_vatrates[$i]['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
  5753. $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
  5754. $positiverates = '';
  5755. if ($obj->taux) {
  5756. $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
  5757. }
  5758. if ($obj->localtax1) {
  5759. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
  5760. }
  5761. if ($obj->localtax2) {
  5762. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
  5763. }
  5764. if (empty($positiverates)) {
  5765. $positiverates = '0';
  5766. }
  5767. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
  5768. }
  5769. return $num;
  5770. } else {
  5771. $this->error = '<span class="error">';
  5772. $this->error .= $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code);
  5773. $reg = array();
  5774. if (!empty($user) && $user->admin && preg_match('/\'(..)\'/', $country_code, $reg)) {
  5775. $langs->load("errors");
  5776. $new_country_code = $reg[1];
  5777. $country_id = dol_getIdFromCode($this->db, $new_country_code, 'c_pays', 'code', 'rowid');
  5778. $this->error .= '<br>'.$langs->trans("ErrorFixThisHere", DOL_URL_ROOT.'/admin/dict.php?id=10'.($country_id > 0 ? '&countryidforinsert='.$country_id : ''));
  5779. }
  5780. $this->error .= '</span>';
  5781. return -1;
  5782. }
  5783. } else {
  5784. $this->error = '<span class="error">' . $this->db->error() . '</span>';
  5785. return -2;
  5786. }
  5787. }
  5788. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5789. /**
  5790. * Output an HTML select vat rate.
  5791. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5792. *
  5793. * @param string $htmlname Name of HTML select field
  5794. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5795. * @param Societe $societe_vendeuse Thirdparty seller
  5796. * @param Societe $societe_acheteuse Thirdparty buyer
  5797. * @param int $idprod Id product. O if unknown of NA.
  5798. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5799. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5800. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5801. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5802. * 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.
  5803. * Si vendeur et acheteur dans Communauté européenne et acheteur=particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5804. * Si vendeur et acheteur dans Communauté européenne et acheteur=entreprise alors TVA par défaut=0. Fin de règle.
  5805. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5806. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5807. * @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
  5808. * @return string
  5809. */
  5810. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = null, $societe_acheteuse = null, $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5811. {
  5812. // phpcs:enable
  5813. global $langs, $conf, $mysoc;
  5814. $langs->load('errors');
  5815. $return = '';
  5816. // Define defaultnpr, defaultttx and defaultcode
  5817. $defaultnpr = ($info_bits & 0x01);
  5818. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5819. $defaulttx = str_replace('*', '', $selectedrate);
  5820. $defaultcode = '';
  5821. $reg = array();
  5822. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5823. $defaultcode = $reg[1];
  5824. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5825. }
  5826. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5827. // Check parameters
  5828. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5829. if ($societe_vendeuse->id == $mysoc->id) {
  5830. $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
  5831. } else {
  5832. $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
  5833. }
  5834. return $return;
  5835. }
  5836. //var_dump($societe_acheteuse);
  5837. //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";
  5838. //exit;
  5839. // Define list of countries to use to search VAT rates to show
  5840. // First we defined code_country to use to find list
  5841. if (is_object($societe_vendeuse)) {
  5842. $code_country = "'" . $societe_vendeuse->country_code . "'";
  5843. } else {
  5844. $code_country = "'" . $mysoc->country_code . "'"; // Pour compatibilite ascendente
  5845. }
  5846. if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) { // If option to have vat for end customer for services is on
  5847. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  5848. // If SERVICE_ARE_ECOMMERCE_200238EC=1 combo list vat rate of purchaser and seller countries
  5849. // If SERVICE_ARE_ECOMMERCE_200238EC=2 combo list only the vat rate of the purchaser country
  5850. $selectVatComboMode = getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC');
  5851. if (isInEEC($societe_vendeuse) && isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()) {
  5852. // We also add the buyer country code
  5853. if (is_numeric($type)) {
  5854. if ($type == 1) { // We know product is a service
  5855. switch ($selectVatComboMode) {
  5856. case '1':
  5857. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5858. break;
  5859. case '2':
  5860. $code_country = "'" . $societe_acheteuse->country_code . "'";
  5861. break;
  5862. }
  5863. }
  5864. } elseif (!$idprod) { // We don't know type of product
  5865. switch ($selectVatComboMode) {
  5866. case '1':
  5867. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5868. break;
  5869. case '2':
  5870. $code_country = "'" . $societe_acheteuse->country_code . "'";
  5871. break;
  5872. }
  5873. } else {
  5874. $prodstatic = new Product($this->db);
  5875. $prodstatic->fetch($idprod);
  5876. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5877. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5878. }
  5879. }
  5880. }
  5881. }
  5882. // Now we get list
  5883. $num = $this->load_cache_vatrates($code_country); // If no vat at all defined for this country, return -1 with message into this->error
  5884. if ($num > 0) {
  5885. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5886. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5887. $tmpthirdparty = new Societe($this->db);
  5888. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5889. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5890. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5891. $defaultcode = $reg[1];
  5892. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5893. }
  5894. if (empty($defaulttx)) {
  5895. $defaultnpr = 0;
  5896. }
  5897. }
  5898. // If we fails to find a default vat rate, we take the last one in list
  5899. // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
  5900. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5901. if (!getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS')) {
  5902. // We take the last one found in list
  5903. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5904. } else {
  5905. // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
  5906. $defaulttx = '';
  5907. if (getDolGlobalString('MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS') != 'none') {
  5908. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5909. }
  5910. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5911. $defaultcode = $reg[1];
  5912. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5913. }
  5914. }
  5915. }
  5916. // Disabled if seller is not subject to VAT
  5917. $disabled = false;
  5918. $title = '';
  5919. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5920. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5921. // of using supplier invoices (this is a very bad idea !)
  5922. if (!getDolGlobalString('EXPENSEREPORT_OVERRIDE_VAT')) {
  5923. $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
  5924. $disabled = true;
  5925. }
  5926. }
  5927. if (!$options_only) {
  5928. $return .= '<select class="flat minwidth50imp maxwidth100" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
  5929. }
  5930. $selectedfound = false;
  5931. foreach ($this->cache_vatrates as $rate) {
  5932. // Keep only 0 if seller is not subject to VAT
  5933. if ($disabled && $rate['txtva'] != 0) {
  5934. continue;
  5935. }
  5936. // Define key to use into select list
  5937. $key = $rate['txtva'];
  5938. $key .= $rate['nprtva'] ? '*' : '';
  5939. if ($mode > 0 && $rate['code']) {
  5940. $key .= ' (' . $rate['code'] . ')';
  5941. }
  5942. if ($mode < 0) {
  5943. $key = $rate['rowid'];
  5944. }
  5945. $return .= '<option value="' . $key . '"';
  5946. if (!$selectedfound) {
  5947. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5948. if ($defaultcode == $rate['code']) {
  5949. $return .= ' selected';
  5950. $selectedfound = true;
  5951. }
  5952. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5953. $return .= ' selected';
  5954. $selectedfound = true;
  5955. }
  5956. }
  5957. $return .= '>';
  5958. // Show label of VAT
  5959. if ($mysoc->country_code == 'IN' || getDolGlobalString('MAIN_VAT_LABEL_IS_POSITIVE_RATES')) {
  5960. // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
  5961. $return .= $rate['labelpositiverates'];
  5962. } else {
  5963. // Simple label
  5964. $return .= vatrate($rate['label']);
  5965. }
  5966. //$return.=($rate['code']?' '.$rate['code']:'');
  5967. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5968. $return .= '</option>';
  5969. }
  5970. if (!$options_only) {
  5971. $return .= '</select>';
  5972. //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
  5973. }
  5974. } else {
  5975. $return .= $this->error;
  5976. }
  5977. $this->num = $num;
  5978. return $return;
  5979. }
  5980. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5981. /**
  5982. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5983. * Fields are preselected with :
  5984. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5985. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5986. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5987. *
  5988. * @param integer|string $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).
  5989. * @param string $prefix Prefix for fields name
  5990. * @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
  5991. * @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
  5992. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5993. * @param string $form_name Not used
  5994. * @param int $d 1=Show days, month, years
  5995. * @param int $addnowlink Add a link "Now"
  5996. * @param int $nooutput Do not output html string but return it
  5997. * @param int $disabled Disable input fields
  5998. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5999. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  6000. * @param int|string $adddateof Add a link "Date of invoice" using the following date.
  6001. * @return string '' or HTML component string if nooutput is 1
  6002. * @deprecated
  6003. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  6004. */
  6005. 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 = 0, $addplusone = '', $adddateof = '')
  6006. {
  6007. // phpcs:enable
  6008. dol_syslog(__METHOD__ . ': using select_date is deprecated. Use selectDate instead.', LOG_WARNING);
  6009. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  6010. if (!empty($nooutput)) {
  6011. return $retstring;
  6012. }
  6013. print $retstring;
  6014. return '';
  6015. }
  6016. /**
  6017. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  6018. * Fields are preselected with :
  6019. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  6020. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  6021. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  6022. *
  6023. * @param integer|string $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).
  6024. * @param integer|string $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).
  6025. * @param string $prefix Prefix for fields name
  6026. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  6027. * @param int $forcenewline Force new line between the 2 dates.
  6028. * @return string Html for selectDate
  6029. * @see form_date(), select_month(), select_year(), select_dayofweek()
  6030. */
  6031. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  6032. {
  6033. global $langs;
  6034. $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  6035. if ($forcenewline) {
  6036. $ret .= '<br>';
  6037. }
  6038. $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  6039. return $ret;
  6040. }
  6041. /**
  6042. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  6043. * Fields are preselected with :
  6044. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  6045. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  6046. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  6047. *
  6048. * @param integer|string $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).
  6049. * @param string $prefix Prefix for fields name
  6050. * @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
  6051. * @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
  6052. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  6053. * @param string $form_name Not used
  6054. * @param int $d 1=Show days, month, years
  6055. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  6056. * @param int $disabled Disable input fields
  6057. * @param int|string $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')
  6058. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  6059. * @param int|string|array $adddateof Add a link "Date of ..." using the following date. Must be array(array('adddateof'=>..., 'labeladddateof'=>...))
  6060. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  6061. * @param int $stepminutes Specify step for minutes between 1 and 30
  6062. * @param string $labeladddateof Label to use for the $adddateof parameter. Deprecated. Used only when $adddateof is not an array.
  6063. * @param string $placeholder Placeholder
  6064. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  6065. * @return string Html for selectDate
  6066. * @see form_date(), select_month(), select_year(), select_dayofweek()
  6067. */
  6068. 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')
  6069. {
  6070. global $conf, $langs;
  6071. if ($gm === 'auto') {
  6072. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  6073. }
  6074. $retstring = '';
  6075. if ($prefix == '') {
  6076. $prefix = 're';
  6077. }
  6078. if ($h == '') {
  6079. $h = 0;
  6080. }
  6081. if ($m == '') {
  6082. $m = 0;
  6083. }
  6084. $emptydate = 0;
  6085. $emptyhours = 0;
  6086. if ($stepminutes <= 0 || $stepminutes > 30) {
  6087. $stepminutes = 1;
  6088. }
  6089. if ($empty == 1) {
  6090. $emptydate = 1;
  6091. $emptyhours = 1;
  6092. }
  6093. if ($empty == 2) {
  6094. $emptydate = 0;
  6095. $emptyhours = 1;
  6096. }
  6097. $orig_set_time = $set_time;
  6098. if ($set_time === '' && $emptydate == 0) {
  6099. include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6100. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  6101. $set_time = dol_now($gm);
  6102. } else {
  6103. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  6104. }
  6105. }
  6106. // Analysis of the pre-selection date
  6107. $reg = array();
  6108. $shour = '';
  6109. $smin = '';
  6110. $ssec = '';
  6111. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  6112. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  6113. $syear = (!empty($reg[1]) ? $reg[1] : '');
  6114. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  6115. $sday = (!empty($reg[3]) ? $reg[3] : '');
  6116. $shour = (!empty($reg[4]) ? $reg[4] : '');
  6117. $smin = (!empty($reg[5]) ? $reg[5] : '');
  6118. } elseif (strval($set_time) != '' && $set_time != -1) {
  6119. // set_time est un timestamps (0 possible)
  6120. $syear = dol_print_date($set_time, "%Y", $gm);
  6121. $smonth = dol_print_date($set_time, "%m", $gm);
  6122. $sday = dol_print_date($set_time, "%d", $gm);
  6123. if ($orig_set_time != '') {
  6124. $shour = dol_print_date($set_time, "%H", $gm);
  6125. $smin = dol_print_date($set_time, "%M", $gm);
  6126. $ssec = dol_print_date($set_time, "%S", $gm);
  6127. }
  6128. } else {
  6129. // Date est '' ou vaut -1
  6130. $syear = '';
  6131. $smonth = '';
  6132. $sday = '';
  6133. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  6134. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  6135. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  6136. }
  6137. if ($h == 3) {
  6138. $shour = '';
  6139. }
  6140. if ($m == 3) {
  6141. $smin = '';
  6142. }
  6143. $nowgmt = dol_now('gmt');
  6144. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  6145. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  6146. $usecalendar = 'combo';
  6147. if (!empty($conf->use_javascript_ajax) && (!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') != "none")) {
  6148. $usecalendar = ((!getDolGlobalString('MAIN_POPUP_CALENDAR') || getDolGlobalString('MAIN_POPUP_CALENDAR') == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  6149. }
  6150. if ($d) {
  6151. // Show date with popup
  6152. if ($usecalendar != 'combo') {
  6153. $formated_date = '';
  6154. //print "e".$set_time." t ".$conf->format_date_short;
  6155. if (strval($set_time) != '' && $set_time != -1) {
  6156. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  6157. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6158. }
  6159. // Calendrier popup version eldy
  6160. if ($usecalendar == "eldy") {
  6161. // Input area to enter date manually
  6162. $retstring .= '<input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate" maxlength="11" value="' . $formated_date . '"';
  6163. $retstring .= ($disabled ? ' disabled' : '');
  6164. $retstring .= ' onChange="dpChangeDay(\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6165. $retstring .= '>';
  6166. // Icon calendar
  6167. $retstringbuttom = '';
  6168. if (!$disabled) {
  6169. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
  6170. $base = DOL_URL_ROOT . '/core/';
  6171. $retstringbuttom .= ' onClick="showDP(\'' . $base . '\',\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\',\'' . $langs->defaultlang . '\');"';
  6172. $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"') . '</button>';
  6173. } else {
  6174. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6175. }
  6176. $retstring = $retstringbuttom . $retstring;
  6177. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6178. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6179. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6180. } elseif ($usecalendar == 'jquery') {
  6181. if (!$disabled) {
  6182. // Output javascript for datepicker
  6183. $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (date('Y') - 100));
  6184. $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (date('Y') + 100));
  6185. $retstring .= '<script nonce="' . getNonce() . '" type="text/javascript">';
  6186. $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
  6187. dateFormat: '" . $langs->trans("FormatDateShortJQueryInput") . "',
  6188. autoclose: true,
  6189. todayHighlight: true,
  6190. yearRange: '" . $minYear . ":" . $maxYear . "',";
  6191. if (!empty($conf->dol_use_jmobile)) {
  6192. $retstring .= "
  6193. beforeShow: function (input, datePicker) {
  6194. input.disabled = true;
  6195. },
  6196. onClose: function (dateText, datePicker) {
  6197. this.disabled = false;
  6198. },
  6199. ";
  6200. }
  6201. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  6202. if (!getDolGlobalString('MAIN_POPUP_CALENDAR_ON_FOCUS')) {
  6203. $retstring .= "
  6204. showOn: 'button', /* both has problem with autocompletion */
  6205. buttonImage: '" . DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png',
  6206. buttonImageOnly: true";
  6207. }
  6208. $retstring .= "
  6209. }) });";
  6210. $retstring .= "</script>";
  6211. }
  6212. // Zone de saisie manuelle de la date
  6213. $retstring .= '<div class="nowraponall inline-block divfordateinput">';
  6214. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  6215. $retstring .= ($disabled ? ' disabled' : '');
  6216. $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
  6217. $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6218. $retstring .= '>';
  6219. // Icone calendrier
  6220. if (!$disabled) {
  6221. /* Not required. Managed by option buttonImage of jquery
  6222. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  6223. $retstring.='<script nonce="'.getNonce().'" type="text/javascript">';
  6224. $retstring.="jQuery(document).ready(function() {";
  6225. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  6226. $retstring.=" jQuery('#".$prefix."').focus();";
  6227. $retstring.=' });';
  6228. $retstring.='});';
  6229. $retstring.="</script>";*/
  6230. } else {
  6231. $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6232. $retsring = $retstringbutton . $retstring;
  6233. }
  6234. $retstring .= '</div>';
  6235. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6236. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6237. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6238. } else {
  6239. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  6240. }
  6241. } else {
  6242. // Show date with combo selects
  6243. // Day
  6244. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
  6245. if ($emptydate || $set_time == -1) {
  6246. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6247. }
  6248. for ($day = 1; $day <= 31; $day++) {
  6249. $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
  6250. }
  6251. $retstring .= "</select>";
  6252. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
  6253. if ($emptydate || $set_time == -1) {
  6254. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6255. }
  6256. // Month
  6257. for ($month = 1; $month <= 12; $month++) {
  6258. $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
  6259. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  6260. $retstring .= "</option>";
  6261. }
  6262. $retstring .= "</select>";
  6263. // Year
  6264. if ($emptydate || $set_time == -1) {
  6265. $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 . '">';
  6266. } else {
  6267. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
  6268. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  6269. $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
  6270. }
  6271. $retstring .= "</select>\n";
  6272. }
  6273. }
  6274. }
  6275. if ($d && $h) {
  6276. $retstring .= ($h == 2 ? '<br>' : ' ');
  6277. $retstring .= '<span class="nowraponall">';
  6278. }
  6279. if ($h) {
  6280. $hourstart = 0;
  6281. $hourend = 24;
  6282. if ($openinghours != '') {
  6283. $openinghours = explode(',', $openinghours);
  6284. $hourstart = $openinghours[0];
  6285. $hourend = $openinghours[1];
  6286. if ($hourend < $hourstart) {
  6287. $hourend = $hourstart;
  6288. }
  6289. }
  6290. // Show hour
  6291. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
  6292. if ($emptyhours) {
  6293. $retstring .= '<option value="-1">&nbsp;</option>';
  6294. }
  6295. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  6296. if (strlen($hour) < 2) {
  6297. $hour = "0" . $hour;
  6298. }
  6299. $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
  6300. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  6301. $retstring .= '</option>';
  6302. }
  6303. $retstring .= '</select>';
  6304. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  6305. if ($m) {
  6306. $retstring .= ":";
  6307. }
  6308. }
  6309. if ($m) {
  6310. // Show minutes
  6311. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
  6312. if ($emptyhours) {
  6313. $retstring .= '<option value="-1">&nbsp;</option>';
  6314. }
  6315. for ($min = 0; $min < 60; $min += $stepminutes) {
  6316. if (strlen($min) < 2) {
  6317. $min = "0" . $min;
  6318. }
  6319. $retstring .= '<option value="' . $min . '"' . (($min == $smin) ? ' selected' : '') . '>' . $min . (empty($conf->dol_optimize_smallscreen) ? '' : '') . '</option>';
  6320. }
  6321. $retstring .= '</select>';
  6322. $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
  6323. }
  6324. if ($d && $h) {
  6325. $retstring .= '</span>';
  6326. }
  6327. // Add a "Now" link
  6328. if (!empty($conf->use_javascript_ajax) && $addnowlink) {
  6329. // Script which will be inserted in the onClick of the "Now" link
  6330. $reset_scripts = "";
  6331. if ($addnowlink == 2) { // local computer time
  6332. // pad add leading 0 on numbers
  6333. $reset_scripts .= "Number.prototype.pad = function(size) {
  6334. var s = String(this);
  6335. while (s.length < (size || 2)) {s = '0' + s;}
  6336. return s;
  6337. };
  6338. var d = new Date();";
  6339. }
  6340. // Generate the date part, depending on the use or not of the javascript calendar
  6341. if ($addnowlink == 1) { // server time expressed in user time setup
  6342. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6343. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6344. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6345. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6346. } elseif ($addnowlink == 2) {
  6347. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6348. * This break application for foreign languages.
  6349. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6350. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6351. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6352. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6353. */
  6354. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6355. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6356. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6357. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6358. }
  6359. /*if ($usecalendar == "eldy")
  6360. {
  6361. $base=DOL_URL_ROOT.'/core/';
  6362. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6363. }
  6364. else
  6365. {
  6366. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6367. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6368. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6369. }*/
  6370. // Update the hour part
  6371. if ($h) {
  6372. if ($fullday) {
  6373. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6374. }
  6375. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6376. if ($addnowlink == 1) {
  6377. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6378. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6379. } elseif ($addnowlink == 2) {
  6380. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
  6381. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6382. }
  6383. if ($fullday) {
  6384. $reset_scripts .= ' } ';
  6385. }
  6386. }
  6387. // Update the minute part
  6388. if ($m) {
  6389. if ($fullday) {
  6390. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6391. }
  6392. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6393. if ($addnowlink == 1) {
  6394. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6395. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6396. } elseif ($addnowlink == 2) {
  6397. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
  6398. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6399. }
  6400. if ($fullday) {
  6401. $reset_scripts .= ' } ';
  6402. }
  6403. }
  6404. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6405. if ($reset_scripts && !getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  6406. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
  6407. $retstring .= $langs->trans("Now");
  6408. $retstring .= '</button> ';
  6409. }
  6410. }
  6411. // Add a "Plus one hour" link
  6412. if ($conf->use_javascript_ajax && $addplusone) {
  6413. // Script which will be inserted in the onClick of the "Add plusone" link
  6414. $reset_scripts = "";
  6415. // Generate the date part, depending on the use or not of the javascript calendar
  6416. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
  6417. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6418. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6419. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6420. // Update the hour part
  6421. if ($h) {
  6422. if ($fullday) {
  6423. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6424. }
  6425. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6426. if ($fullday) {
  6427. $reset_scripts .= ' } ';
  6428. }
  6429. }
  6430. // Update the minute part
  6431. if ($m) {
  6432. if ($fullday) {
  6433. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6434. }
  6435. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6436. if ($fullday) {
  6437. $reset_scripts .= ' } ';
  6438. }
  6439. }
  6440. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6441. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6442. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
  6443. $retstring .= $langs->trans("DateStartPlusOne");
  6444. $retstring .= '</button> ';
  6445. }
  6446. }
  6447. // Add a link to set data
  6448. if ($conf->use_javascript_ajax && !empty($adddateof)) {
  6449. if (!is_array($adddateof)) {
  6450. $arrayofdateof = array(array('adddateof'=>$adddateof, 'labeladddateof'=>$labeladddateof));
  6451. } else {
  6452. $arrayofdateof = $adddateof;
  6453. }
  6454. foreach ($arrayofdateof as $valuedateof) {
  6455. $tmpadddateof = empty($valuedateof['adddateof']) ? 0 : $valuedateof['adddateof'];
  6456. $tmplabeladddateof = empty($valuedateof['labeladddateof']) ? '' : $valuedateof['labeladddateof'];
  6457. $tmparray = dol_getdate($tmpadddateof);
  6458. if (empty($tmplabeladddateof)) {
  6459. $tmplabeladddateof = $langs->trans("DateInvoice");
  6460. }
  6461. $reset_scripts = 'console.log(\'Click on now link\'); ';
  6462. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($tmpadddateof, 'dayinputnoreduce').'\');';
  6463. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
  6464. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
  6465. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
  6466. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$tmplabeladddateof.'</button>';
  6467. }
  6468. }
  6469. return $retstring;
  6470. }
  6471. /**
  6472. * selectTypeDuration
  6473. *
  6474. * @param string $prefix Prefix
  6475. * @param string $selected Selected duration type
  6476. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6477. * @return string HTML select string
  6478. */
  6479. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6480. {
  6481. global $langs;
  6482. $TDurationTypes = array(
  6483. 'y' => $langs->trans('Years'),
  6484. 'm' => $langs->trans('Month'),
  6485. 'w' => $langs->trans('Weeks'),
  6486. 'd' => $langs->trans('Days'),
  6487. 'h' => $langs->trans('Hours'),
  6488. 'i' => $langs->trans('Minutes')
  6489. );
  6490. // Removed undesired duration types
  6491. foreach ($excludetypes as $value) {
  6492. unset($TDurationTypes[$value]);
  6493. }
  6494. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
  6495. foreach ($TDurationTypes as $key => $typeduration) {
  6496. $retstring .= '<option value="' . $key . '"';
  6497. if ($key == $selected) {
  6498. $retstring .= " selected";
  6499. }
  6500. $retstring .= ">" . $typeduration . "</option>";
  6501. }
  6502. $retstring .= "</select>";
  6503. $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
  6504. return $retstring;
  6505. }
  6506. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6507. /**
  6508. * Function to show a form to select a duration on a page
  6509. *
  6510. * @param string $prefix Prefix for input fields
  6511. * @param int|string $iSecond Default preselected duration (number of seconds or '')
  6512. * @param int $disabled Disable the combo box
  6513. * @param string $typehour If 'select' then input hour and input min is a combo,
  6514. * If 'text' input hour is in text and input min is a text,
  6515. * If 'textselect' input hour is in text and input min is a combo
  6516. * @param integer $minunderhours If 1, show minutes selection under the hours
  6517. * @param int $nooutput Do not output html string but return it
  6518. * @return string HTML component
  6519. */
  6520. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6521. {
  6522. // phpcs:enable
  6523. global $langs;
  6524. $retstring = '<span class="nowraponall">';
  6525. $hourSelected = '';
  6526. $minSelected = '';
  6527. // Hours
  6528. if ($iSecond != '') {
  6529. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6530. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6531. $minSelected = convertSecondToTime($iSecond, 'min');
  6532. }
  6533. if ($typehour == 'select') {
  6534. $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
  6535. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6536. $retstring .= '<option value="' . $hour . '"';
  6537. if (is_numeric($hourSelected) && $hourSelected == $hour) {
  6538. $retstring .= " selected";
  6539. }
  6540. $retstring .= ">" . $hour . "</option>";
  6541. }
  6542. $retstring .= "</select>";
  6543. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6544. $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour right" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
  6545. } else {
  6546. return 'BadValueForParameterTypeHour';
  6547. }
  6548. if ($typehour != 'text') {
  6549. $retstring .= ' ' . $langs->trans('HourShort');
  6550. } else {
  6551. $retstring .= '<span class="">:</span>';
  6552. }
  6553. // Minutes
  6554. if ($minunderhours) {
  6555. $retstring .= '<br>';
  6556. } else {
  6557. if ($typehour != 'text') {
  6558. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6559. }
  6560. }
  6561. if ($typehour == 'select' || $typehour == 'textselect') {
  6562. $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
  6563. for ($min = 0; $min <= 55; $min = $min + 5) {
  6564. $retstring .= '<option value="' . $min . '"';
  6565. if (is_numeric($minSelected) && $minSelected == $min) {
  6566. $retstring .= ' selected';
  6567. }
  6568. $retstring .= '>' . $min . '</option>';
  6569. }
  6570. $retstring .= "</select>";
  6571. } elseif ($typehour == 'text') {
  6572. $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute right" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
  6573. }
  6574. if ($typehour != 'text') {
  6575. $retstring .= ' ' . $langs->trans('MinuteShort');
  6576. }
  6577. $retstring .= "</span>";
  6578. if (!empty($nooutput)) {
  6579. return $retstring;
  6580. }
  6581. print $retstring;
  6582. return '';
  6583. }
  6584. /**
  6585. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6586. *
  6587. * @param string $selected Preselected tickets
  6588. * @param string $htmlname Name of HTML select field (must be unique in page).
  6589. * @param string $filtertype To add a filter
  6590. * @param int $limit Limit on number of returned lines
  6591. * @param int $status Ticket status
  6592. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6593. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6594. * @param array $ajaxoptions Options for ajax_autocompleter
  6595. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6596. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6597. * @param int $forcecombo Force to use combo box
  6598. * @param string $morecss Add more css on select
  6599. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6600. * @param int $nooutput No print, return the output into a string
  6601. * @return string
  6602. */
  6603. 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)
  6604. {
  6605. global $langs, $conf;
  6606. $out = '';
  6607. // check parameters
  6608. if (is_null($ajaxoptions)) {
  6609. $ajaxoptions = array();
  6610. }
  6611. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  6612. $placeholder = '';
  6613. if ($selected && empty($selected_input_value)) {
  6614. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6615. $tickettmpselect = new Ticket($this->db);
  6616. $tickettmpselect->fetch($selected);
  6617. $selected_input_value = $tickettmpselect->ref;
  6618. unset($tickettmpselect);
  6619. }
  6620. $urloption = '';
  6621. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6622. if (empty($hidelabel)) {
  6623. $out .= $langs->trans("RefOrLabel") . ' : ';
  6624. } elseif ($hidelabel > 1) {
  6625. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6626. if ($hidelabel == 2) {
  6627. $out .= img_picto($langs->trans("Search"), 'search');
  6628. }
  6629. }
  6630. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  6631. if ($hidelabel == 3) {
  6632. $out .= img_picto($langs->trans("Search"), 'search');
  6633. }
  6634. } else {
  6635. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6636. }
  6637. if (empty($nooutput)) {
  6638. print $out;
  6639. } else {
  6640. return $out;
  6641. }
  6642. return '';
  6643. }
  6644. /**
  6645. * Return list of tickets.
  6646. * Called by selectTickets.
  6647. *
  6648. * @param string $selected Preselected ticket
  6649. * @param string $htmlname Name of select html
  6650. * @param string $filtertype Filter on ticket type
  6651. * @param int $limit Limit on number of returned lines
  6652. * @param string $filterkey Filter on ticket ref or subject
  6653. * @param int $status Ticket status
  6654. * @param int $outputmode 0=HTML select string, 1=Array
  6655. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6656. * @param int $forcecombo Force to use combo box
  6657. * @param string $morecss Add more css on select
  6658. * @return array|string Array of keys for json or HTML component
  6659. */
  6660. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6661. {
  6662. global $langs, $conf;
  6663. $out = '';
  6664. $outarray = array();
  6665. $selectFields = " p.rowid, p.ref, p.message";
  6666. $sql = "SELECT ";
  6667. $sql .= $selectFields;
  6668. $sql .= " FROM " . $this->db->prefix() . "ticket as p";
  6669. $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
  6670. // Add criteria on ref/label
  6671. if ($filterkey != '') {
  6672. $sql .= ' AND (';
  6673. $prefix = !getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6674. // For natural search
  6675. $scrit = explode(' ', $filterkey);
  6676. $i = 0;
  6677. if (count($scrit) > 1) {
  6678. $sql .= "(";
  6679. }
  6680. foreach ($scrit as $crit) {
  6681. if ($i > 0) {
  6682. $sql .= " AND ";
  6683. }
  6684. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6685. $sql .= ")";
  6686. $i++;
  6687. }
  6688. if (count($scrit) > 1) {
  6689. $sql .= ")";
  6690. }
  6691. $sql .= ')';
  6692. }
  6693. $sql .= $this->db->plimit($limit, 0);
  6694. // Build output string
  6695. dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
  6696. $result = $this->db->query($sql);
  6697. if ($result) {
  6698. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6699. require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
  6700. $num = $this->db->num_rows($result);
  6701. $events = null;
  6702. if (!$forcecombo) {
  6703. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6704. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6705. }
  6706. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6707. $textifempty = '';
  6708. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6709. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6710. if (getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  6711. if ($showempty && !is_numeric($showempty)) {
  6712. $textifempty = $langs->trans($showempty);
  6713. } else {
  6714. $textifempty .= $langs->trans("All");
  6715. }
  6716. } else {
  6717. if ($showempty && !is_numeric($showempty)) {
  6718. $textifempty = $langs->trans($showempty);
  6719. }
  6720. }
  6721. if ($showempty) {
  6722. $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6723. }
  6724. $i = 0;
  6725. while ($num && $i < $num) {
  6726. $opt = '';
  6727. $optJson = array();
  6728. $objp = $this->db->fetch_object($result);
  6729. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6730. // Add new entry
  6731. // "key" value of json key array is used by jQuery automatically as selected value
  6732. // "label" value of json key array is used by jQuery automatically as text for combo box
  6733. $out .= $opt;
  6734. array_push($outarray, $optJson);
  6735. $i++;
  6736. }
  6737. $out .= '</select>';
  6738. $this->db->free($result);
  6739. if (empty($outputmode)) {
  6740. return $out;
  6741. }
  6742. return $outarray;
  6743. } else {
  6744. dol_print_error($this->db);
  6745. }
  6746. return array();
  6747. }
  6748. /**
  6749. * constructTicketListOption.
  6750. * This define value for &$opt and &$optJson.
  6751. *
  6752. * @param object $objp Result set of fetch
  6753. * @param string $opt Option (var used for returned value in string option format)
  6754. * @param array $optJson Option (var used for returned value in json format)
  6755. * @param string $selected Preselected value
  6756. * @param string $filterkey Filter key to highlight
  6757. * @return void
  6758. */
  6759. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6760. {
  6761. $outkey = '';
  6762. $outref = '';
  6763. $outtype = '';
  6764. $outkey = $objp->rowid;
  6765. $outref = $objp->ref;
  6766. $outtype = $objp->fk_product_type;
  6767. $opt = '<option value="' . $objp->rowid . '"';
  6768. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6769. $opt .= '>';
  6770. $opt .= $objp->ref;
  6771. $objRef = $objp->ref;
  6772. if (!empty($filterkey) && $filterkey != '') {
  6773. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6774. }
  6775. $opt .= "</option>\n";
  6776. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6777. }
  6778. /**
  6779. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6780. *
  6781. * @param string $selected Preselected tickets
  6782. * @param string $htmlname Name of HTML select field (must be unique in page).
  6783. * @param string $filtertype To add a filter
  6784. * @param int $limit Limit on number of returned lines
  6785. * @param int $status Ticket status
  6786. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6787. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6788. * @param array $ajaxoptions Options for ajax_autocompleter
  6789. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6790. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6791. * @param int $forcecombo Force to use combo box
  6792. * @param string $morecss Add more css on select
  6793. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6794. * @param int $nooutput No print, return the output into a string
  6795. * @return string
  6796. */
  6797. public function selectProjects($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6798. {
  6799. global $langs, $conf;
  6800. $out = '';
  6801. // check parameters
  6802. if (is_null($ajaxoptions)) {
  6803. $ajaxoptions = array();
  6804. }
  6805. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  6806. $placeholder = '';
  6807. if ($selected && empty($selected_input_value)) {
  6808. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6809. $projecttmpselect = new Project($this->db);
  6810. $projecttmpselect->fetch($selected);
  6811. $selected_input_value = $projecttmpselect->ref;
  6812. unset($projecttmpselect);
  6813. }
  6814. $urloption = '';
  6815. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6816. if (empty($hidelabel)) {
  6817. $out .= $langs->trans("RefOrLabel") . ' : ';
  6818. } elseif ($hidelabel > 1) {
  6819. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6820. if ($hidelabel == 2) {
  6821. $out .= img_picto($langs->trans("Search"), 'search');
  6822. }
  6823. }
  6824. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  6825. if ($hidelabel == 3) {
  6826. $out .= img_picto($langs->trans("Search"), 'search');
  6827. }
  6828. } else {
  6829. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6830. }
  6831. if (empty($nooutput)) {
  6832. print $out;
  6833. } else {
  6834. return $out;
  6835. }
  6836. return '';
  6837. }
  6838. /**
  6839. * Return list of projects.
  6840. * Called by selectProjects.
  6841. *
  6842. * @param string $selected Preselected project
  6843. * @param string $htmlname Name of select html
  6844. * @param string $filtertype Filter on project type
  6845. * @param int $limit Limit on number of returned lines
  6846. * @param string $filterkey Filter on project ref or subject
  6847. * @param int $status Ticket status
  6848. * @param int $outputmode 0=HTML select string, 1=Array
  6849. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6850. * @param int $forcecombo Force to use combo box
  6851. * @param string $morecss Add more css on select
  6852. * @return array|string Array of keys for json or HTML component
  6853. */
  6854. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6855. {
  6856. global $langs, $conf;
  6857. $out = '';
  6858. $outarray = array();
  6859. $selectFields = " p.rowid, p.ref";
  6860. $sql = "SELECT ";
  6861. $sql .= $selectFields;
  6862. $sql .= " FROM " . $this->db->prefix() . "projet as p";
  6863. $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
  6864. // Add criteria on ref/label
  6865. if ($filterkey != '') {
  6866. $sql .= ' AND (';
  6867. $prefix = !getDolGlobalString('TICKET_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6868. // For natural search
  6869. $scrit = explode(' ', $filterkey);
  6870. $i = 0;
  6871. if (count($scrit) > 1) {
  6872. $sql .= "(";
  6873. }
  6874. foreach ($scrit as $crit) {
  6875. if ($i > 0) {
  6876. $sql .= " AND ";
  6877. }
  6878. $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6879. $sql .= "";
  6880. $i++;
  6881. }
  6882. if (count($scrit) > 1) {
  6883. $sql .= ")";
  6884. }
  6885. $sql .= ')';
  6886. }
  6887. $sql .= $this->db->plimit($limit, 0);
  6888. // Build output string
  6889. dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
  6890. $result = $this->db->query($sql);
  6891. if ($result) {
  6892. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6893. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  6894. $num = $this->db->num_rows($result);
  6895. $events = null;
  6896. if (!$forcecombo) {
  6897. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6898. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6899. }
  6900. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6901. $textifempty = '';
  6902. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6903. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6904. if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
  6905. if ($showempty && !is_numeric($showempty)) {
  6906. $textifempty = $langs->trans($showempty);
  6907. } else {
  6908. $textifempty .= $langs->trans("All");
  6909. }
  6910. } else {
  6911. if ($showempty && !is_numeric($showempty)) {
  6912. $textifempty = $langs->trans($showempty);
  6913. }
  6914. }
  6915. if ($showempty) {
  6916. $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6917. }
  6918. $i = 0;
  6919. while ($num && $i < $num) {
  6920. $opt = '';
  6921. $optJson = array();
  6922. $objp = $this->db->fetch_object($result);
  6923. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6924. // Add new entry
  6925. // "key" value of json key array is used by jQuery automatically as selected value
  6926. // "label" value of json key array is used by jQuery automatically as text for combo box
  6927. $out .= $opt;
  6928. array_push($outarray, $optJson);
  6929. $i++;
  6930. }
  6931. $out .= '</select>';
  6932. $this->db->free($result);
  6933. if (empty($outputmode)) {
  6934. return $out;
  6935. }
  6936. return $outarray;
  6937. } else {
  6938. dol_print_error($this->db);
  6939. }
  6940. return array();
  6941. }
  6942. /**
  6943. * constructProjectListOption.
  6944. * This define value for &$opt and &$optJson.
  6945. *
  6946. * @param object $objp Result set of fetch
  6947. * @param string $opt Option (var used for returned value in string option format)
  6948. * @param array $optJson Option (var used for returned value in json format)
  6949. * @param string $selected Preselected value
  6950. * @param string $filterkey Filter key to highlight
  6951. * @return void
  6952. */
  6953. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6954. {
  6955. $outkey = '';
  6956. $outref = '';
  6957. $outtype = '';
  6958. $label = $objp->label;
  6959. $outkey = $objp->rowid;
  6960. $outref = $objp->ref;
  6961. $outlabel = $objp->label;
  6962. $outtype = $objp->fk_product_type;
  6963. $opt = '<option value="' . $objp->rowid . '"';
  6964. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6965. $opt .= '>';
  6966. $opt .= $objp->ref;
  6967. $objRef = $objp->ref;
  6968. if (!empty($filterkey) && $filterkey != '') {
  6969. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6970. }
  6971. $opt .= "</option>\n";
  6972. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6973. }
  6974. /**
  6975. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6976. *
  6977. * @param string $selected Preselected tickets
  6978. * @param string $htmlname Name of HTML select field (must be unique in page).
  6979. * @param string $filtertype To add a filter
  6980. * @param int $limit Limit on number of returned lines
  6981. * @param int $status Ticket status
  6982. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6983. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6984. * @param array $ajaxoptions Options for ajax_autocompleter
  6985. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6986. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6987. * @param int $forcecombo Force to use combo box
  6988. * @param string $morecss Add more css on select
  6989. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6990. * @param int $nooutput No print, return the output into a string
  6991. * @return string
  6992. */
  6993. public function selectMembers($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 0, $status = 1, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $selected_combinations = null, $nooutput = 0)
  6994. {
  6995. global $langs, $conf;
  6996. $out = '';
  6997. // check parameters
  6998. if (is_null($ajaxoptions)) {
  6999. $ajaxoptions = array();
  7000. }
  7001. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('TICKET_USE_SEARCH_TO_SELECT')) {
  7002. $placeholder = '';
  7003. $urloption = '';
  7004. if ($selected && empty($selected_input_value)) {
  7005. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  7006. $adherenttmpselect = new Adherent($this->db);
  7007. $adherenttmpselect->fetch($selected);
  7008. $selected_input_value = $adherenttmpselect->ref;
  7009. unset($adherenttmpselect);
  7010. }
  7011. $urloption = '';
  7012. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  7013. if (empty($hidelabel)) {
  7014. $out .= $langs->trans("RefOrLabel") . ' : ';
  7015. } elseif ($hidelabel > 1) {
  7016. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  7017. if ($hidelabel == 2) {
  7018. $out .= img_picto($langs->trans("Search"), 'search');
  7019. }
  7020. }
  7021. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (getDolGlobalString('PRODUCT_SEARCH_AUTOFOCUS') ? 'autofocus' : '') . ' />';
  7022. if ($hidelabel == 3) {
  7023. $out .= img_picto($langs->trans("Search"), 'search');
  7024. }
  7025. } else {
  7026. $filterkey = '';
  7027. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  7028. }
  7029. if (empty($nooutput)) {
  7030. print $out;
  7031. } else {
  7032. return $out;
  7033. }
  7034. return '';
  7035. }
  7036. /**
  7037. * Return list of adherents.
  7038. * Called by selectMembers.
  7039. *
  7040. * @param string $selected Preselected adherent
  7041. * @param string $htmlname Name of select html
  7042. * @param string $filtertype Filter on adherent type
  7043. * @param int $limit Limit on number of returned lines
  7044. * @param string $filterkey Filter on member status
  7045. * @param int $status Member status
  7046. * @param int $outputmode 0=HTML select string, 1=Array
  7047. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  7048. * @param int $forcecombo Force to use combo box
  7049. * @param string $morecss Add more css on select
  7050. * @return array|string Array of keys for json or HTML string component
  7051. */
  7052. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  7053. {
  7054. global $langs, $conf;
  7055. $out = '';
  7056. $outarray = array();
  7057. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname, p.fk_adherent_type";
  7058. $sql = "SELECT ";
  7059. $sql .= $selectFields;
  7060. $sql .= " FROM " . $this->db->prefix() . "adherent as p";
  7061. $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
  7062. // Add criteria on ref/label
  7063. if ($filterkey != '') {
  7064. $sql .= ' AND (';
  7065. $prefix = !getDolGlobalString('MEMBER_DONOTSEARCH_ANYWHERE') ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  7066. // For natural search
  7067. $scrit = explode(' ', $filterkey);
  7068. $i = 0;
  7069. if (count($scrit) > 1) {
  7070. $sql .= "(";
  7071. }
  7072. foreach ($scrit as $crit) {
  7073. if ($i > 0) {
  7074. $sql .= " AND ";
  7075. }
  7076. $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  7077. $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  7078. $i++;
  7079. }
  7080. if (count($scrit) > 1) {
  7081. $sql .= ")";
  7082. }
  7083. $sql .= ')';
  7084. }
  7085. if ($status != -1) {
  7086. $sql .= ' AND statut = ' . ((int) $status);
  7087. }
  7088. $sql .= $this->db->plimit($limit, 0);
  7089. // Build output string
  7090. dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
  7091. $result = $this->db->query($sql);
  7092. if ($result) {
  7093. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  7094. require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
  7095. $num = $this->db->num_rows($result);
  7096. $events = null;
  7097. if (!$forcecombo) {
  7098. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7099. $out .= ajax_combobox($htmlname, $events, getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT') ? $conf->global->PROJECT_USE_SEARCH_TO_SELECT : '');
  7100. }
  7101. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  7102. $textifempty = '';
  7103. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  7104. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7105. if (getDolGlobalString('PROJECT_USE_SEARCH_TO_SELECT')) {
  7106. if ($showempty && !is_numeric($showempty)) {
  7107. $textifempty = $langs->trans($showempty);
  7108. } else {
  7109. $textifempty .= $langs->trans("All");
  7110. }
  7111. } else {
  7112. if ($showempty && !is_numeric($showempty)) {
  7113. $textifempty = $langs->trans($showempty);
  7114. }
  7115. }
  7116. if ($showempty) {
  7117. $out .= '<option value="-1" selected>' . $textifempty . '</option>';
  7118. }
  7119. $i = 0;
  7120. while ($num && $i < $num) {
  7121. $opt = '';
  7122. $optJson = array();
  7123. $objp = $this->db->fetch_object($result);
  7124. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  7125. // Add new entry
  7126. // "key" value of json key array is used by jQuery automatically as selected value
  7127. // "label" value of json key array is used by jQuery automatically as text for combo box
  7128. $out .= $opt;
  7129. array_push($outarray, $optJson);
  7130. $i++;
  7131. }
  7132. $out .= '</select>';
  7133. $this->db->free($result);
  7134. if (empty($outputmode)) {
  7135. return $out;
  7136. }
  7137. return $outarray;
  7138. } else {
  7139. dol_print_error($this->db);
  7140. }
  7141. return array();
  7142. }
  7143. /**
  7144. * constructMemberListOption.
  7145. * This define value for &$opt and &$optJson.
  7146. *
  7147. * @param object $objp Result set of fetch
  7148. * @param string $opt Option (var used for returned value in string option format)
  7149. * @param array $optJson Option (var used for returned value in json format)
  7150. * @param string $selected Preselected value
  7151. * @param string $filterkey Filter key to highlight
  7152. * @return void
  7153. */
  7154. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  7155. {
  7156. $outkey = '';
  7157. $outlabel = '';
  7158. $outtype = '';
  7159. $outkey = $objp->rowid;
  7160. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  7161. $outtype = $objp->fk_adherent_type;
  7162. $opt = '<option value="' . $objp->rowid . '"';
  7163. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  7164. $opt .= '>';
  7165. if (!empty($filterkey) && $filterkey != '') {
  7166. $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
  7167. }
  7168. $opt .= $outlabel;
  7169. $opt .= "</option>\n";
  7170. $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
  7171. }
  7172. /**
  7173. * Generic method to select a component from a combo list.
  7174. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  7175. * This is the generic method that will replace all specific existing methods.
  7176. *
  7177. * @param string $objectdesc 'ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'. For hard coded custom needs. Try to prefer method using $objectfield instead of $objectdesc.
  7178. * @param string $htmlname Name of HTML select component
  7179. * @param int $preSelectedValue Preselected value (ID of element)
  7180. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7181. * @param string $searchkey Search criteria
  7182. * @param string $placeholder Place holder
  7183. * @param string $morecss More CSS
  7184. * @param string $moreparams More params provided to ajax call
  7185. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7186. * @param int $disabled 1=Html component is disabled
  7187. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  7188. * @param string $objectfield Object:Field that contains the definition (in table $fields or $extrafields). Example: 'Object:xxx' or 'Module_Object:xxx' or 'Object:options_xxx' or 'Module_Object:options_xxx'
  7189. * @return string Return HTML string
  7190. * @see selectForFormsList(), select_thirdparty_list()
  7191. */
  7192. public function selectForForms($objectdesc, $htmlname, $preSelectedValue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '', $objectfield = '')
  7193. {
  7194. global $conf, $extrafields, $user;
  7195. //var_dump($objectdesc); debug_print_backtrace();
  7196. $objectdescorig = $objectdesc;
  7197. $objecttmp = null;
  7198. $InfoFieldList = array();
  7199. if ($objectfield) { // We must retreive the objectdesc from the field or extrafield
  7200. // Example: $objectfield = 'product:options_package'
  7201. $tmparray = explode(':', $objectfield);
  7202. // Load object according to $id and $element
  7203. $objectforfieldstmp = fetchObjectByElement(0, strtolower($tmparray[0]));
  7204. if (is_object($objectforfieldstmp)) {
  7205. $objectdesc = '';
  7206. $reg = array();
  7207. if (preg_match('/^options_(.*)$/', $tmparray[1], $reg)) {
  7208. // For a property in extrafields
  7209. $key = $reg[1];
  7210. // fetch optionals attributes and labels
  7211. $extrafields->fetch_name_optionals_label($objectforfieldstmp->table_element);
  7212. if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key]) && $extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key] == 'link') {
  7213. if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options'])) {
  7214. $tmpextrafields = array_keys($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options']);
  7215. $objectdesc = $tmpextrafields[0];
  7216. }
  7217. }
  7218. } else {
  7219. // For a property in ->fields
  7220. if (array_key_exists($tmparray[1], $objectforfieldstmp->fields)) {
  7221. $objectdesc = $objectforfieldstmp->fields[$tmparray[1]]['type'];
  7222. $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc);
  7223. }
  7224. }
  7225. }
  7226. }
  7227. if ($objectdesc) {
  7228. // Example of value for $objectdesc:
  7229. // Bom:bom/class/bom.class.php:0:t.status=1
  7230. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  7231. // Bom:bom/class/bom.class.php:0:(t.status:=:1) OR (t.field2:=:2):ref
  7232. $InfoFieldList = explode(":", $objectdesc, 4);
  7233. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  7234. $reg = array();
  7235. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  7236. $InfoFieldList[4] = $reg[1]; // take the sort field
  7237. }
  7238. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  7239. $classname = $InfoFieldList[0];
  7240. $classpath = empty($InfoFieldList[1]) ? '' : $InfoFieldList[1];
  7241. //$addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  7242. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  7243. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  7244. // Load object according to $id and $element
  7245. $objecttmp = fetchObjectByElement(0, strtolower($InfoFieldList[0]));
  7246. // Fallback to another solution to get $objecttmp
  7247. if (empty($objecttmp) && !empty($classpath)) {
  7248. dol_include_once($classpath);
  7249. if ($classname && class_exists($classname)) {
  7250. $objecttmp = new $classname($this->db);
  7251. }
  7252. }
  7253. }
  7254. // Make some replacement in $filter. May not be used if we used the ajax mode with $objectfield. In such a case
  7255. // we propagate the $objectfield and not the filter and replacement is done by the ajax/selectobject.php component.
  7256. $sharedentities = getEntity($objecttmp->element);
  7257. $filter = str_replace(
  7258. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  7259. array($conf->entity, $sharedentities, $user->id),
  7260. $filter
  7261. );
  7262. if (!is_object($objecttmp)) {
  7263. dol_syslog('selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.$objectfield.', objectdesc='.$objectdesc, LOG_WARNING);
  7264. return 'selectForForms: Error bad setup of field objectdescorig=' . $objectdescorig.', objectfield='.$objectfield.', objectdesc='.$objectdesc;
  7265. }
  7266. //var_dump($filter);
  7267. $prefixforautocompletemode = $objecttmp->element;
  7268. if ($prefixforautocompletemode == 'societe') {
  7269. $prefixforautocompletemode = 'company';
  7270. }
  7271. if ($prefixforautocompletemode == 'product') {
  7272. $prefixforautocompletemode = 'produit';
  7273. }
  7274. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7275. dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
  7276. // Generate the combo HTML component
  7277. $out = '';
  7278. if (!empty($conf->use_javascript_ajax) && getDolGlobalString($confkeyforautocompletemode) && !$forcecombo) {
  7279. // No immediate load of all database
  7280. $placeholder = '';
  7281. if ($preSelectedValue && empty($selected_input_value)) {
  7282. $objecttmp->fetch($preSelectedValue);
  7283. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  7284. $oldValueForShowOnCombobox = 0;
  7285. foreach ($objecttmp->fields as $fieldK => $fielV) {
  7286. if (!$fielV['showoncombobox'] || empty($objecttmp->$fieldK)) continue;
  7287. if (!$oldValueForShowOnCombobox) {
  7288. $selected_input_value = '';
  7289. }
  7290. $selected_input_value .= $oldValueForShowOnCombobox ? ' - ' : '';
  7291. $selected_input_value .= $objecttmp->$fieldK;
  7292. $oldValueForShowOnCombobox = empty($fielV['showoncombobox']) ? 0 : $fielV['showoncombobox'];
  7293. }
  7294. }
  7295. // Set url and param to call to get json of the search results
  7296. $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
  7297. $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdescorig) . '&objectfield='.urlencode($objectfield) . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
  7298. // Activate the auto complete using ajax call.
  7299. $out .= ajax_autocompleter($preSelectedValue, $htmlname, $urlforajaxcall, $urloption, getDolGlobalString($confkeyforautocompletemode), 0);
  7300. $out .= '<!-- force css to be higher than dialog popup --><style type="text/css">.ui-autocomplete { z-index: 1010; }</style>';
  7301. $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) . '"' : '') . ' />';
  7302. } else {
  7303. // Immediate load of table record.
  7304. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preSelectedValue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
  7305. }
  7306. return $out;
  7307. }
  7308. /**
  7309. * Output html form to select an object.
  7310. * Note, this function is called by selectForForms or by ajax selectobject.php
  7311. *
  7312. * @param Object $objecttmp Object to know the table to scan for combo.
  7313. * @param string $htmlname Name of HTML select component
  7314. * @param int $preselectedvalue Preselected value (ID of element)
  7315. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7316. * @param string $searchkey Search value
  7317. * @param string $placeholder Place holder
  7318. * @param string $morecss More CSS
  7319. * @param string $moreparams More params provided to ajax call
  7320. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7321. * @param int $outputmode 0=HTML select string, 1=Array
  7322. * @param int $disabled 1=Html component is disabled
  7323. * @param string $sortfield Sort field
  7324. * @param string $filter Add more filter (Universal Search Filter)
  7325. * @return string|array Return HTML string
  7326. * @see selectForForms()
  7327. */
  7328. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '')
  7329. {
  7330. global $langs, $user, $hookmanager;
  7331. //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
  7332. $prefixforautocompletemode = $objecttmp->element;
  7333. if ($prefixforautocompletemode == 'societe') {
  7334. $prefixforautocompletemode = 'company';
  7335. }
  7336. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7337. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  7338. $tmpfieldstoshow = '';
  7339. foreach ($objecttmp->fields as $key => $val) {
  7340. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  7341. continue;
  7342. }
  7343. if (!empty($val['showoncombobox'])) {
  7344. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
  7345. }
  7346. }
  7347. if ($tmpfieldstoshow) {
  7348. $fieldstoshow = $tmpfieldstoshow;
  7349. }
  7350. } else {
  7351. // For backward compatibility
  7352. $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'showoncombobox' => 1);
  7353. }
  7354. if (empty($fieldstoshow)) {
  7355. if (isset($objecttmp->fields['ref'])) {
  7356. $fieldstoshow = 't.ref';
  7357. } else {
  7358. $langs->load("errors");
  7359. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  7360. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  7361. }
  7362. }
  7363. $out = '';
  7364. $outarray = array();
  7365. $tmparray = array();
  7366. $num = 0;
  7367. // Search data
  7368. $sql = "SELECT t.rowid, " . $fieldstoshow . " FROM " . $this->db->prefix() . $objecttmp->table_element . " as t";
  7369. if (!empty($objecttmp->isextrafieldmanaged)) {
  7370. $sql .= " LEFT JOIN " . $this->db->prefix() . $objecttmp->table_element . "_extrafields as e ON t.rowid=e.fk_object";
  7371. }
  7372. if (isset($objecttmp->ismultientitymanaged)) {
  7373. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7374. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  7375. $sql .= " INNER JOIN " . $this->db->prefix() . $tmparray[1] . " as parenttable ON parenttable.rowid = t." . $tmparray[0];
  7376. }
  7377. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7378. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  7379. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  7380. }
  7381. }
  7382. }
  7383. // Add where from hooks
  7384. $parameters = array(
  7385. 'object' => $objecttmp,
  7386. 'htmlname' => $htmlname,
  7387. 'filter' => $filter,
  7388. 'searchkey' => $searchkey
  7389. );
  7390. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  7391. if (!empty($hookmanager->resPrint)) {
  7392. $sql .= $hookmanager->resPrint;
  7393. } else {
  7394. $sql .= " WHERE 1=1";
  7395. if (isset($objecttmp->ismultientitymanaged)) {
  7396. if ($objecttmp->ismultientitymanaged == 1) {
  7397. $sql .= " AND t.entity IN (" . getEntity($objecttmp->table_element) . ")";
  7398. }
  7399. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7400. $sql .= " AND parenttable.entity = t." . $tmparray[0];
  7401. }
  7402. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  7403. if ($objecttmp->element == 'societe') {
  7404. $sql .= " AND t.rowid = " . ((int) $user->socid);
  7405. } else {
  7406. $sql .= " AND t.fk_soc = " . ((int) $user->socid);
  7407. }
  7408. }
  7409. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7410. if (!$user->hasRight('societe', 'client', 'voir') && !$user->socid) {
  7411. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  7412. }
  7413. }
  7414. }
  7415. if ($searchkey != '') {
  7416. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  7417. }
  7418. if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  7419. $errormessage = '';
  7420. $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
  7421. if ($errormessage) {
  7422. return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
  7423. }
  7424. }
  7425. }
  7426. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7427. //$sql.=$this->db->plimit($limit, 0);
  7428. //print $sql;
  7429. // Build output string
  7430. $resql = $this->db->query($sql);
  7431. if ($resql) {
  7432. // Construct $out and $outarray
  7433. $out .= '<select id="' . $htmlname . '" class="flat minwidth100' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
  7434. // 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
  7435. $textifempty = '&nbsp;';
  7436. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7437. if (getDolGlobalInt($confkeyforautocompletemode)) {
  7438. if ($showempty && !is_numeric($showempty)) {
  7439. $textifempty = $langs->trans($showempty);
  7440. } else {
  7441. $textifempty .= $langs->trans("All");
  7442. }
  7443. }
  7444. if ($showempty) {
  7445. $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
  7446. }
  7447. $num = $this->db->num_rows($resql);
  7448. $i = 0;
  7449. if ($num) {
  7450. while ($i < $num) {
  7451. $obj = $this->db->fetch_object($resql);
  7452. $label = '';
  7453. $labelhtml = '';
  7454. $tmparray = explode(',', $fieldstoshow);
  7455. $oldvalueforshowoncombobox = 0;
  7456. foreach ($tmparray as $key => $val) {
  7457. $val = preg_replace('/t\./', '', $val);
  7458. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7459. $labelhtml .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7460. $label .= $obj->$val;
  7461. $labelhtml .= $obj->$val;
  7462. $oldvalueforshowoncombobox = empty($objecttmp->fields[$val]['showoncombobox']) ? 0 : $objecttmp->fields[$val]['showoncombobox'];
  7463. }
  7464. if (empty($outputmode)) {
  7465. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7466. $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  7467. } else {
  7468. $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml, 0, 0, '', 0, 1) . '">' . dol_escape_htmltag($label, 0, 0, '', 0, 1) . '</option>';
  7469. }
  7470. } else {
  7471. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
  7472. }
  7473. $i++;
  7474. if (($i % 10) == 0) {
  7475. $out .= "\n";
  7476. }
  7477. }
  7478. }
  7479. $out .= '</select>' . "\n";
  7480. if (!$forcecombo) {
  7481. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7482. $out .= ajax_combobox($htmlname, null, getDolGlobalInt($confkeyforautocompletemode, 0));
  7483. }
  7484. } else {
  7485. dol_print_error($this->db);
  7486. }
  7487. $this->result = array('nbofelement' => $num);
  7488. if ($outputmode) {
  7489. return $outarray;
  7490. }
  7491. return $out;
  7492. }
  7493. /**
  7494. * Return a HTML select string, built from an array of key+value.
  7495. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7496. *
  7497. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7498. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7499. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7500. * @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.
  7501. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7502. * @param int $value_as_key 1 to use value as key
  7503. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7504. * @param int $translate 1=Translate and encode value
  7505. * @param int $maxlen Length maximum for labels
  7506. * @param int $disabled Html select box is disabled
  7507. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7508. * @param string $morecss Add more class to css styles
  7509. * @param int $addjscombo Add js combo
  7510. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7511. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7512. * @param int $nohtmlescape No html escaping.
  7513. * @return string HTML select string.
  7514. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7515. */
  7516. 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 = 'minwidth75', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  7517. {
  7518. global $conf, $langs;
  7519. // Do we want a multiselect ?
  7520. //$jsbeautify = 0;
  7521. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7522. $jsbeautify = 1;
  7523. if ($value_as_key) {
  7524. $array = array_combine($array, $array);
  7525. }
  7526. $out = '';
  7527. if ($addjscombo < 0) {
  7528. if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  7529. $addjscombo = 1;
  7530. } else {
  7531. $addjscombo = 0;
  7532. }
  7533. }
  7534. $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
  7535. $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . ' selectformat"';
  7536. $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
  7537. $out .= '>'."\n";
  7538. if ($show_empty) {
  7539. $textforempty = ' ';
  7540. if (!empty($conf->use_javascript_ajax)) {
  7541. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7542. }
  7543. if (!is_numeric($show_empty)) {
  7544. $textforempty = $show_empty;
  7545. }
  7546. $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . (((int) $show_empty) < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  7547. }
  7548. if (is_array($array)) {
  7549. // Translate
  7550. if ($translate) {
  7551. foreach ($array as $key => $value) {
  7552. if (!is_array($value)) {
  7553. $array[$key] = $langs->trans($value);
  7554. } else {
  7555. $array[$key]['label'] = $langs->trans($value['label']);
  7556. }
  7557. }
  7558. }
  7559. // Sort
  7560. if ($sort == 'ASC') {
  7561. asort($array);
  7562. } elseif ($sort == 'DESC') {
  7563. arsort($array);
  7564. }
  7565. foreach ($array as $key => $tmpvalue) {
  7566. if (is_array($tmpvalue)) {
  7567. $value = $tmpvalue['label'];
  7568. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7569. $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
  7570. } else {
  7571. $value = $tmpvalue;
  7572. $disabled = '';
  7573. $style = '';
  7574. }
  7575. if (!empty($disablebademail)) {
  7576. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7577. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7578. $disabled = ' disabled';
  7579. $style = ' class="warning"';
  7580. }
  7581. }
  7582. if ($key_in_label) {
  7583. if (empty($nohtmlescape)) {
  7584. $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
  7585. } else {
  7586. $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
  7587. }
  7588. } else {
  7589. if (empty($nohtmlescape)) {
  7590. $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
  7591. } else {
  7592. $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
  7593. }
  7594. if ($value == '' || $value == '-') {
  7595. $selectOptionValue = '&nbsp;';
  7596. }
  7597. }
  7598. $out .= '<option value="' . $key . '"';
  7599. $out .= $style . $disabled;
  7600. if (is_array($id)) {
  7601. if (in_array($key, $id) && !$disabled) {
  7602. $out .= ' selected'; // To preselect a value
  7603. }
  7604. } else {
  7605. $id = (string) $id; // if $id = 0, then $id = '0'
  7606. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7607. $out .= ' selected'; // To preselect a value
  7608. }
  7609. }
  7610. if ($nohtmlescape) {
  7611. $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
  7612. }
  7613. if (is_array($tmpvalue)) {
  7614. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7615. if (preg_match('/^data-/', $keyforvalue)) {
  7616. $out .= ' '.$keyforvalue.'="'.dol_escape_htmltag($valueforvalue).'"';
  7617. }
  7618. }
  7619. }
  7620. $out .= '>';
  7621. $out .= $selectOptionValue;
  7622. $out .= "</option>\n";
  7623. }
  7624. }
  7625. $out .= "</select>";
  7626. // Add code for jquery to use multiselect
  7627. if ($addjscombo && $jsbeautify) {
  7628. // Enhance with select2
  7629. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7630. $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', (((int) $show_empty) < 0 ? (string) $show_empty : '-1'), $morecss);
  7631. }
  7632. return $out;
  7633. }
  7634. /**
  7635. * 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.
  7636. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7637. *
  7638. * @param string $htmlname Name of html select area
  7639. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7640. * @param string $id Preselected key
  7641. * @param string $moreparam Add more parameters onto the select tag
  7642. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7643. * @param int $disabled Html select box is disabled
  7644. * @param int $minimumInputLength Minimum Input Length
  7645. * @param string $morecss Add more class to css styles
  7646. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7647. * @param string $placeholder String to use as placeholder
  7648. * @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)
  7649. * @return string HTML select string
  7650. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7651. */
  7652. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7653. {
  7654. global $conf, $langs;
  7655. global $delayedhtmlcontent; // Will be used later outside of this function
  7656. // TODO Use an internal dolibarr component instead of select2
  7657. if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7658. return '';
  7659. }
  7660. $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
  7661. $outdelayed = '';
  7662. if (!empty($conf->use_javascript_ajax)) {
  7663. $tmpplugin = 'select2';
  7664. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7665. <script nonce="' . getNonce() . '">
  7666. $(document).ready(function () {
  7667. ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
  7668. $(".' . $htmlname . '").select2({
  7669. ajax: {
  7670. dir: "ltr",
  7671. url: "' . $url . '",
  7672. dataType: \'json\',
  7673. delay: 250,
  7674. data: function (params) {
  7675. return {
  7676. q: params.term, // search term
  7677. page: params.page
  7678. }
  7679. },
  7680. processResults: function (data) {
  7681. // parse the results into the format expected by Select2.
  7682. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7683. //console.log(data);
  7684. saveRemoteData = data;
  7685. /* format json result for select2 */
  7686. result = []
  7687. $.each( data, function( key, value ) {
  7688. result.push({id: key, text: value.text});
  7689. });
  7690. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7691. //console.log(result);
  7692. return {results: result, more: false}
  7693. },
  7694. cache: true
  7695. },
  7696. language: select2arrayoflanguage,
  7697. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7698. placeholder: "' . dol_escape_js($placeholder) . '",
  7699. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7700. minimumInputLength: ' . ((int) $minimumInputLength) . ',
  7701. formatResult: function (result, container, query, escapeMarkup) {
  7702. return escapeMarkup(result.text);
  7703. },
  7704. });
  7705. ' . ($callurlonselect ? '
  7706. /* Code to execute a GET when we select a value */
  7707. $(".' . $htmlname . '").change(function() {
  7708. var selected = $(".' . $htmlname . '").val();
  7709. console.log("We select in selectArrayAjax the entry "+selected)
  7710. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7711. $.each( saveRemoteData, function( key, value ) {
  7712. if (key == selected)
  7713. {
  7714. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7715. location.assign(value.url);
  7716. }
  7717. });
  7718. });' : '') . '
  7719. });
  7720. </script>';
  7721. }
  7722. if ($acceptdelayedhtml) {
  7723. $delayedhtmlcontent .= $outdelayed;
  7724. } else {
  7725. $out .= $outdelayed;
  7726. }
  7727. return $out;
  7728. }
  7729. /**
  7730. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7731. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7732. *
  7733. * @param string $htmlname Name of html select area
  7734. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7735. * @param string $id Preselected key
  7736. * @param string $moreparam Add more parameters onto the select tag
  7737. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7738. * @param int $disabled Html select box is disabled
  7739. * @param int $minimumInputLength Minimum Input Length
  7740. * @param string $morecss Add more class to css styles
  7741. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7742. * @param string $placeholder String to use as placeholder
  7743. * @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)
  7744. * @param string $textfortitle Text to show on title.
  7745. * @return string HTML select string
  7746. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7747. */
  7748. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0, $textfortitle = '')
  7749. {
  7750. global $conf, $langs;
  7751. global $delayedhtmlcontent; // Will be used later outside of this function
  7752. // TODO Use an internal dolibarr component instead of select2
  7753. if (!getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7754. return '';
  7755. }
  7756. $out = '<select type="text"'.($textfortitle ? ' title="'.dol_escape_htmltag($textfortitle).'"' : '').' id="'.$htmlname.'" class="'.$htmlname.($morecss ? ' ' . $morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.'"><option></option></select>';
  7757. $formattedarrayresult = array();
  7758. foreach ($array as $key => $value) {
  7759. $o = new stdClass();
  7760. $o->id = $key;
  7761. $o->text = $value['text'];
  7762. $o->url = $value['url'];
  7763. $formattedarrayresult[] = $o;
  7764. }
  7765. $outdelayed = '';
  7766. if (!empty($conf->use_javascript_ajax)) {
  7767. $tmpplugin = 'select2';
  7768. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7769. <script nonce="' . getNonce() . '">
  7770. $(document).ready(function () {
  7771. var data = ' . json_encode($formattedarrayresult) . ';
  7772. ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
  7773. $(".' . $htmlname . '").select2({
  7774. data: data,
  7775. language: select2arrayoflanguage,
  7776. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7777. placeholder: "' . dol_escape_js($placeholder) . '",
  7778. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7779. minimumInputLength: ' . $minimumInputLength . ',
  7780. formatResult: function (result, container, query, escapeMarkup) {
  7781. return escapeMarkup(result.text);
  7782. },
  7783. matcher: function (params, data) {
  7784. if(! data.id) return null;';
  7785. if ($callurlonselect) {
  7786. // We forge the url with 'sall='
  7787. $outdelayed .= '
  7788. var urlBase = data.url;
  7789. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7790. /* console.log("params.term="+params.term); */
  7791. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7792. saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7793. }
  7794. if (!$disableFiltering) {
  7795. $outdelayed .= '
  7796. if(data.text.match(new RegExp(params.term))) {
  7797. return data;
  7798. }
  7799. return null;';
  7800. } else {
  7801. $outdelayed .= '
  7802. return data;';
  7803. }
  7804. $outdelayed .= '
  7805. }
  7806. });
  7807. ' . ($callurlonselect ? '
  7808. /* Code to execute a GET when we select a value */
  7809. $(".' . $htmlname . '").change(function() {
  7810. var selected = $(".' . $htmlname . '").val();
  7811. console.log("We select "+selected)
  7812. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7813. $.each( saveRemoteData, function( key, value ) {
  7814. if (key == selected)
  7815. {
  7816. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7817. location.assign(value.url);
  7818. }
  7819. });
  7820. });' : '') . '
  7821. });
  7822. </script>';
  7823. }
  7824. if ($acceptdelayedhtml) {
  7825. $delayedhtmlcontent .= $outdelayed;
  7826. } else {
  7827. $out .= $outdelayed;
  7828. }
  7829. return $out;
  7830. }
  7831. /**
  7832. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7833. *
  7834. * @param string $htmlname Name of select
  7835. * @param array $array Array(key=>value) or Array(key=>array('id'=>key, 'label'=>value, 'color'=> , 'picto'=> , 'labelhtml'=> ))
  7836. * @param array $selected Array of keys preselected
  7837. * @param int $key_in_label 1 to show key like in "[key] value"
  7838. * @param int $value_as_key 1 to use value as key
  7839. * @param string $morecss Add more css style
  7840. * @param int $translate Translate and encode value
  7841. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7842. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7843. * @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.
  7844. * @param string $placeholder String to use as placeholder
  7845. * @param int $addjscombo Add js combo
  7846. * @return string HTML multiselect string
  7847. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7848. */
  7849. 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)
  7850. {
  7851. global $conf, $langs;
  7852. $out = '';
  7853. if ($addjscombo < 0) {
  7854. if (!getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  7855. $addjscombo = 1;
  7856. } else {
  7857. $addjscombo = 0;
  7858. }
  7859. }
  7860. $useenhancedmultiselect = 0;
  7861. if (!empty($conf->use_javascript_ajax) && (getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT'))) {
  7862. if ($addjscombo) {
  7863. $useenhancedmultiselect = 1; // Use the js multiselect in one line. Possible only if $addjscombo not 0.
  7864. }
  7865. }
  7866. // We need a hidden field because when using the multiselect, if we unselect all, there is no
  7867. // variable submitted at all, so no way to make a difference between variable not submited and variable
  7868. // submited to nothing.
  7869. $out .= '<input type="hidden" name="'.$htmlname.'_multiselect" value="1">';
  7870. // Output select component
  7871. $out .= '<select id="' . $htmlname . '" class="multiselect' . ($useenhancedmultiselect ? ' multiselectononeline' : '') . ($morecss ? ' ' . $morecss : '') . '" multiple name="' . $htmlname . '[]"' . ($moreattrib ? ' ' . $moreattrib : '') . ($width ? ' style="width: ' . (preg_match('/%/', $width) ? $width : $width . 'px') . '"' : '') . '>' . "\n";
  7872. if (is_array($array) && !empty($array)) {
  7873. if ($value_as_key) {
  7874. $array = array_combine($array, $array);
  7875. }
  7876. if (!empty($array)) {
  7877. foreach ($array as $key => $value) {
  7878. $tmpkey = $key;
  7879. $tmpvalue = $value;
  7880. $tmpcolor = '';
  7881. $tmppicto = '';
  7882. $tmplabelhtml = '';
  7883. if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
  7884. $tmpkey = $value['id'];
  7885. $tmpvalue = empty($value['label']) ? '' : $value['label'];
  7886. $tmpcolor = empty($value['color']) ? '' : $value['color'];
  7887. $tmppicto = empty($value['picto']) ? '' : $value['picto'];
  7888. $tmplabelhtml = empty($value['labelhtml']) ? '' : $value['labelhtml'];
  7889. }
  7890. $newval = ($translate ? $langs->trans($tmpvalue) : $tmpvalue);
  7891. $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
  7892. $out .= '<option value="' . $tmpkey . '"';
  7893. if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
  7894. $out .= ' selected';
  7895. }
  7896. if (!empty($tmplabelhtml)) {
  7897. $out .= ' data-html="' . dol_escape_htmltag($tmplabelhtml, 0, 0, '', 0, 1) . '"';
  7898. } else {
  7899. $tmplabelhtml = ($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval;
  7900. $out .= ' data-html="' . dol_escape_htmltag($tmplabelhtml, 0, 0, '', 0, 1) . '"';
  7901. }
  7902. $out .= '>';
  7903. $out .= dol_htmlentitiesbr($newval);
  7904. $out .= '</option>' . "\n";
  7905. }
  7906. }
  7907. }
  7908. $out .= '</select>' . "\n";
  7909. // Add code for jquery to use multiselect
  7910. if (!empty($conf->use_javascript_ajax) && getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7911. $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
  7912. $out .= "\n" . '<script nonce="' . getNonce() . '">' . "\n";
  7913. if ($addjscombo == 1) {
  7914. $tmpplugin = !getDolGlobalString('MAIN_USE_JQUERY_MULTISELECT') ? constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7915. $out .= 'function formatResult(record, container) {' . "\n";
  7916. // If property html set, we decode html entities and use this.
  7917. // Note that HTML content must have been sanitized from js with dol_escape_htmltag(xxx, 0, 0, '', 0, 1) when building the select option.
  7918. $out .= ' if ($(record.element).attr("data-html") != undefined) { return htmlEntityDecodeJs($(record.element).attr("data-html")); }'."\n";
  7919. $out .= ' return record.text;';
  7920. $out .= '}' . "\n";
  7921. $out .= 'function formatSelection(record) {' . "\n";
  7922. if ($elemtype == 'category') {
  7923. $out .= 'return \'<span><img src="' . DOL_URL_ROOT . '/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7924. } else {
  7925. $out .= 'return record.text;';
  7926. }
  7927. $out .= '}' . "\n";
  7928. $out .= '$(document).ready(function () {
  7929. $(\'#' . $htmlname . '\').' . $tmpplugin . '({';
  7930. if ($placeholder) {
  7931. $out .= '
  7932. placeholder: {
  7933. id: \'-1\',
  7934. text: \'' . dol_escape_js($placeholder) . '\'
  7935. },';
  7936. }
  7937. $out .= ' dir: \'ltr\',
  7938. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag (ko with multiselect) */
  7939. dropdownCssClass: \'' . $morecss . '\', /* Line to add class on the new <span class="select2-selection...> tag (ok with multiselect) */
  7940. // Specify format function for dropdown item
  7941. formatResult: formatResult,
  7942. templateResult: formatResult, /* For 4.0 */
  7943. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7944. // Specify format function for selected item
  7945. formatSelection: formatSelection,
  7946. templateSelection: formatSelection /* For 4.0 */
  7947. });
  7948. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7949. the size only if component is not hidden by default on load */
  7950. $(\'#' . $htmlname . ' + .select2\').addClass(\'' . $morecss . '\');
  7951. });' . "\n";
  7952. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7953. // Add other js lib
  7954. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7955. // ...
  7956. $out .= 'console.log(\'addjscombo=2 for htmlname=' . $htmlname . '\');';
  7957. $out .= '$(document).ready(function () {
  7958. $(\'#' . $htmlname . '\').multiSelect({
  7959. containerHTML: \'<div class="multi-select-container">\',
  7960. menuHTML: \'<div class="multi-select-menu">\',
  7961. buttonHTML: \'<span class="multi-select-button ' . $morecss . '">\',
  7962. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7963. activeClass: \'multi-select-container--open\',
  7964. noneText: \'' . $placeholder . '\'
  7965. });
  7966. })';
  7967. }
  7968. $out .= '</script>';
  7969. }
  7970. return $out;
  7971. }
  7972. /**
  7973. * 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.
  7974. *
  7975. * @param string $htmlname Name of HTML field
  7976. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7977. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7978. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7979. * @return string HTML multiselect string
  7980. * @see selectarray()
  7981. */
  7982. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7983. {
  7984. global $conf, $langs, $user, $extrafields;
  7985. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  7986. return '';
  7987. }
  7988. if (empty($array)) {
  7989. return '';
  7990. }
  7991. $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
  7992. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7993. $tmparray = explode(',', $user->conf->$tmpvar);
  7994. foreach ($array as $key => $val) {
  7995. //var_dump($key);
  7996. //var_dump($tmparray);
  7997. if (in_array($key, $tmparray)) {
  7998. $array[$key]['checked'] = 1;
  7999. } else {
  8000. $array[$key]['checked'] = 0;
  8001. }
  8002. }
  8003. } else { // There is no list of fields already customized for user
  8004. foreach ($array as $key => $val) {
  8005. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  8006. $array[$key]['checked'] = 0;
  8007. }
  8008. }
  8009. }
  8010. $listoffieldsforselection = '';
  8011. $listcheckedstring = '';
  8012. foreach ($array as $key => $val) {
  8013. // var_dump($val);
  8014. // var_dump(array_key_exists('enabled', $val));
  8015. // var_dump(!$val['enabled']);
  8016. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  8017. unset($array[$key]); // We don't want this field
  8018. continue;
  8019. }
  8020. if (!empty($val['type']) && $val['type'] == 'separate') {
  8021. // Field remains in array but we don't add it into $listoffieldsforselection
  8022. //$listoffieldsforselection .= '<li>-----</li>';
  8023. continue;
  8024. }
  8025. if ($val['label']) {
  8026. if (!empty($val['langfile']) && is_object($langs)) {
  8027. $langs->load($val['langfile']);
  8028. }
  8029. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  8030. $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>';
  8031. $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
  8032. }
  8033. }
  8034. $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
  8035. <dl class="dropdown">
  8036. <dt>
  8037. <a href="#' . $htmlname . '">
  8038. ' . img_picto('', 'list') . '
  8039. </a>
  8040. <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
  8041. </dt>
  8042. <dd class="dropdowndd">
  8043. <div class="multiselectcheckbox'.$htmlname.'">
  8044. <ul class="'.$htmlname.($pos == '1' ? 'left' : '').'">
  8045. <li><input class="inputsearch_dropdownselectedfields width90p minwidth200imp" style="width:90%;" type="text" placeholder="'.$langs->trans('Search').'"></li>
  8046. '.$listoffieldsforselection.'
  8047. </ul>
  8048. </div>
  8049. </dd>
  8050. </dl>
  8051. <script nonce="' . getNonce() . '" type="text/javascript">
  8052. jQuery(document).ready(function () {
  8053. $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on(\'click\', function () {
  8054. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  8055. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  8056. var title = $(this).val() + ",";
  8057. if ($(this).is(\':checked\')) {
  8058. $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
  8059. }
  8060. else {
  8061. $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
  8062. }
  8063. // Now, we submit page
  8064. //$(this).parents(\'form:first\').submit();
  8065. });
  8066. $("input.inputsearch_dropdownselectedfields").on("keyup", function() {
  8067. var value = $(this).val().toLowerCase();
  8068. $(\'.multiselectcheckbox'.$htmlname.' li > label\').filter(function() {
  8069. $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
  8070. });
  8071. });
  8072. });
  8073. </script>
  8074. ';
  8075. return $out;
  8076. }
  8077. /**
  8078. * Render list of categories linked to object with id $id and type $type
  8079. *
  8080. * @param int $id Id of object
  8081. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  8082. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  8083. * @param int $nolink 1=Do not add html links
  8084. * @return string String with categories
  8085. */
  8086. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  8087. {
  8088. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  8089. $cat = new Categorie($this->db);
  8090. $categories = $cat->containing($id, $type);
  8091. if ($rendermode == 1) {
  8092. $toprint = array();
  8093. foreach ($categories as $c) {
  8094. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  8095. foreach ($ways as $way) {
  8096. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>';
  8097. }
  8098. }
  8099. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  8100. }
  8101. if ($rendermode == 0) {
  8102. $arrayselected = array();
  8103. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  8104. foreach ($categories as $c) {
  8105. $arrayselected[] = $c->id;
  8106. }
  8107. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  8108. }
  8109. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  8110. }
  8111. /**
  8112. * Show linked object block.
  8113. *
  8114. * @param CommonObject $object Object we want to show links to
  8115. * @param string $morehtmlright More html to show on right of title
  8116. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  8117. * @param string $title Title
  8118. * @return int Return integer <0 if KO, >=0 if OK
  8119. */
  8120. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = array(), $title = 'RelatedObjects')
  8121. {
  8122. global $conf, $langs, $hookmanager;
  8123. global $bc, $action;
  8124. $object->fetchObjectLinked();
  8125. // Bypass the default method
  8126. $hookmanager->initHooks(array('commonobject'));
  8127. $parameters = array(
  8128. 'morehtmlright' => $morehtmlright,
  8129. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  8130. );
  8131. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8132. $nbofdifferenttypes = count($object->linkedObjects);
  8133. if (empty($reshook)) {
  8134. print '<!-- showLinkedObjectBlock -->';
  8135. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  8136. print '<div class="div-table-responsive-no-min">';
  8137. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
  8138. print '<tr class="liste_titre">';
  8139. print '<td>' . $langs->trans("Type") . '</td>';
  8140. print '<td>' . $langs->trans("Ref") . '</td>';
  8141. print '<td class="center"></td>';
  8142. print '<td class="center">' . $langs->trans("Date") . '</td>';
  8143. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  8144. print '<td class="right">' . $langs->trans("Status") . '</td>';
  8145. print '<td></td>';
  8146. print '</tr>';
  8147. $nboftypesoutput = 0;
  8148. foreach ($object->linkedObjects as $objecttype => $objects) {
  8149. $tplpath = $element = $subelement = $objecttype;
  8150. // to display inport button on tpl
  8151. $showImportButton = false;
  8152. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  8153. $showImportButton = true;
  8154. }
  8155. $regs = array();
  8156. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  8157. $element = $regs[1];
  8158. $subelement = $regs[2];
  8159. $tplpath = $element . '/' . $subelement;
  8160. }
  8161. $tplname = 'linkedobjectblock';
  8162. // To work with non standard path
  8163. if ($objecttype == 'facture') {
  8164. $tplpath = 'compta/' . $element;
  8165. if (!isModEnabled('facture')) {
  8166. continue; // Do not show if module disabled
  8167. }
  8168. } elseif ($objecttype == 'facturerec') {
  8169. $tplpath = 'compta/facture';
  8170. $tplname = 'linkedobjectblockForRec';
  8171. if (!isModEnabled('facture')) {
  8172. continue; // Do not show if module disabled
  8173. }
  8174. } elseif ($objecttype == 'propal') {
  8175. $tplpath = 'comm/' . $element;
  8176. if (!isModEnabled('propal')) {
  8177. continue; // Do not show if module disabled
  8178. }
  8179. } elseif ($objecttype == 'supplier_proposal') {
  8180. if (!isModEnabled('supplier_proposal')) {
  8181. continue; // Do not show if module disabled
  8182. }
  8183. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
  8184. $tplpath = 'expedition';
  8185. if (!isModEnabled('expedition')) {
  8186. continue; // Do not show if module disabled
  8187. }
  8188. } elseif ($objecttype == 'reception') {
  8189. $tplpath = 'reception';
  8190. if (!isModEnabled('reception')) {
  8191. continue; // Do not show if module disabled
  8192. }
  8193. } elseif ($objecttype == 'delivery') {
  8194. $tplpath = 'delivery';
  8195. if (!isModEnabled('expedition')) {
  8196. continue; // Do not show if module disabled
  8197. }
  8198. } elseif ($objecttype == 'ficheinter') {
  8199. $tplpath = 'fichinter';
  8200. if (!isModEnabled('ficheinter')) {
  8201. continue; // Do not show if module disabled
  8202. }
  8203. } elseif ($objecttype == 'invoice_supplier') {
  8204. $tplpath = 'fourn/facture';
  8205. } elseif ($objecttype == 'order_supplier') {
  8206. $tplpath = 'fourn/commande';
  8207. } elseif ($objecttype == 'expensereport') {
  8208. $tplpath = 'expensereport';
  8209. } elseif ($objecttype == 'subscription') {
  8210. $tplpath = 'adherents';
  8211. } elseif ($objecttype == 'conferenceorbooth') {
  8212. $tplpath = 'eventorganization';
  8213. } elseif ($objecttype == 'conferenceorboothattendee') {
  8214. $tplpath = 'eventorganization';
  8215. } elseif ($objecttype == 'mo') {
  8216. $tplpath = 'mrp';
  8217. if (!isModEnabled('mrp')) {
  8218. continue; // Do not show if module disabled
  8219. }
  8220. }
  8221. global $linkedObjectBlock;
  8222. $linkedObjectBlock = $objects;
  8223. // Output template part (modules that overwrite templates must declare this into descriptor)
  8224. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
  8225. foreach ($dirtpls as $reldir) {
  8226. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  8227. global $noMoreLinkedObjectBlockAfter;
  8228. $noMoreLinkedObjectBlockAfter = 1;
  8229. }
  8230. $res = @include dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
  8231. if ($res) {
  8232. $nboftypesoutput++;
  8233. break;
  8234. }
  8235. }
  8236. }
  8237. if (!$nboftypesoutput) {
  8238. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
  8239. }
  8240. print '</table>';
  8241. if (!empty($compatibleImportElementsList)) {
  8242. $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
  8243. }
  8244. print '</div>';
  8245. }
  8246. return $nbofdifferenttypes;
  8247. }
  8248. /**
  8249. * Show block with links to link to other objects.
  8250. *
  8251. * @param CommonObject $object Object we want to show links to
  8252. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  8253. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  8254. * @return string HTML block
  8255. */
  8256. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  8257. {
  8258. global $conf, $langs, $hookmanager;
  8259. global $action;
  8260. $linktoelem = '';
  8261. $linktoelemlist = '';
  8262. $listofidcompanytoscan = '';
  8263. if (!is_object($object->thirdparty)) {
  8264. $object->fetch_thirdparty();
  8265. }
  8266. $possiblelinks = array();
  8267. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  8268. $listofidcompanytoscan = $object->thirdparty->id;
  8269. if (($object->thirdparty->parent > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PARENT_IN_LINKTO')) {
  8270. $listofidcompanytoscan .= ',' . $object->thirdparty->parent;
  8271. }
  8272. if (($object->fk_project > 0) && getDolGlobalString('THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO')) {
  8273. include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  8274. $tmpproject = new Project($this->db);
  8275. $tmpproject->fetch($object->fk_project);
  8276. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  8277. $listofidcompanytoscan .= ',' . $tmpproject->socid;
  8278. }
  8279. unset($tmpproject);
  8280. }
  8281. $possiblelinks = array(
  8282. 'propal' => array(
  8283. 'enabled' => isModEnabled('propal'),
  8284. 'perms' => 1,
  8285. 'label' => 'LinkToProposal',
  8286. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('propal') . ')'),
  8287. 'shipping' => array(
  8288. 'enabled' => isModEnabled('expedition'),
  8289. 'perms' => 1,
  8290. 'label' => 'LinkToExpedition',
  8291. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "expedition as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('shipping') . ')'),
  8292. 'order' => array(
  8293. 'enabled' => isModEnabled('commande'),
  8294. 'perms' => 1,
  8295. 'label' => 'LinkToOrder',
  8296. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('commande') . ')'),
  8297. 'invoice' => array(
  8298. 'enabled' => isModEnabled('facture'),
  8299. 'perms' => 1,
  8300. 'label' => 'LinkToInvoice',
  8301. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('invoice') . ')'),
  8302. 'invoice_template' => array(
  8303. 'enabled' => isModEnabled('facture'),
  8304. 'perms' => 1,
  8305. 'label' => 'LinkToTemplateInvoice',
  8306. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('invoice') . ')'),
  8307. 'contrat' => array(
  8308. 'enabled' => isModEnabled('contrat'),
  8309. 'perms' => 1,
  8310. 'label' => 'LinkToContract',
  8311. '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
  8312. FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "contrat as t, " . $this->db->prefix() . "contratdet as td WHERE t.fk_soc = s.rowid AND td.fk_contrat = t.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('contract') . ') GROUP BY s.rowid, s.nom, s.client, t.rowid, t.ref, t.ref_customer, t.ref_supplier'
  8313. ),
  8314. 'fichinter' => array(
  8315. 'enabled' => isModEnabled('ficheinter'),
  8316. 'perms' => 1,
  8317. 'label' => 'LinkToIntervention',
  8318. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('intervention') . ')'),
  8319. 'supplier_proposal' => array(
  8320. 'enabled' => isModEnabled('supplier_proposal'),
  8321. 'perms' => 1,
  8322. 'label' => 'LinkToSupplierProposal',
  8323. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('supplier_proposal') . ')'),
  8324. 'order_supplier' => array(
  8325. 'enabled' => isModEnabled("supplier_order"),
  8326. 'perms' => 1,
  8327. 'label' => 'LinkToSupplierOrder',
  8328. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('commande_fournisseur') . ')'),
  8329. 'invoice_supplier' => array(
  8330. 'enabled' => isModEnabled("supplier_invoice"),
  8331. 'perms' => 1, 'label' => 'LinkToSupplierInvoice',
  8332. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('facture_fourn') . ')'),
  8333. 'ticket' => array(
  8334. 'enabled' => isModEnabled('ticket'),
  8335. 'perms' => 1,
  8336. 'label' => 'LinkToTicket',
  8337. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM " . $this->db->prefix() . "societe as s, " . $this->db->prefix() . "ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('ticket') . ')'),
  8338. 'mo' => array(
  8339. 'enabled' => isModEnabled('mrp'),
  8340. 'perms' => 1,
  8341. 'label' => 'LinkToMo',
  8342. 'sql' => "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM " . $this->db->prefix() . "societe as s INNER JOIN " . $this->db->prefix() . "mrp_mo as t ON t.fk_soc = s.rowid WHERE t.fk_soc IN (" . $this->db->sanitize($listofidcompanytoscan) . ') AND t.entity IN (' . getEntity('mo') . ')')
  8343. );
  8344. }
  8345. if ($object->table_element == 'commande_fournisseur') {
  8346. $possiblelinks['mo']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.rowid, '0' as total_ht FROM ".$this->db->prefix()."societe as s INNER JOIN ".$this->db->prefix().'mrp_mo as t ON t.fk_soc = s.rowid WHERE t.entity IN ('.getEntity('mo').')';
  8347. } elseif ($object->table_element == 'mrp_mo') {
  8348. $possiblelinks['order_supplier']['sql'] = "SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".$this->db->prefix()."societe as s, ".$this->db->prefix().'commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.entity IN ('.getEntity('commande_fournisseur').')';
  8349. }
  8350. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  8351. // Can complete the possiblelink array
  8352. $hookmanager->initHooks(array('commonobject'));
  8353. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  8354. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8355. }
  8356. if (empty($reshook)) {
  8357. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8358. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  8359. }
  8360. } elseif ($reshook > 0) {
  8361. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8362. $possiblelinks = $hookmanager->resArray;
  8363. }
  8364. }
  8365. foreach ($possiblelinks as $key => $possiblelink) {
  8366. $num = 0;
  8367. if (empty($possiblelink['enabled'])) {
  8368. continue;
  8369. }
  8370. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  8371. print '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
  8372. if (getDolGlobalString('MAIN_LINK_BY_REF_IN_LINKTO')) {
  8373. print '<br>'."\n";
  8374. print '<!-- form to add a link from anywhere -->'."\n";
  8375. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  8376. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8377. print '<input type="hidden" name="action" value="addlinkbyref">';
  8378. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8379. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8380. print '<table class="noborder">';
  8381. print '<tr>';
  8382. //print '<td>' . $langs->trans("Ref") . '</td>';
  8383. print '<td class="center"><input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Ref")).'" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;';
  8384. print '<input type="submit" class="button small valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
  8385. print '<input type="submit" class="button small" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  8386. print '</tr>';
  8387. print '</table>';
  8388. print '</form>';
  8389. }
  8390. $sql = $possiblelink['sql'];
  8391. $resqllist = $this->db->query($sql);
  8392. if ($resqllist) {
  8393. $num = $this->db->num_rows($resqllist);
  8394. $i = 0;
  8395. print '<br>';
  8396. print '<!-- form to add a link from object to same thirdparty -->'."\n";
  8397. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
  8398. print '<input type="hidden" name="action" value="addlink">';
  8399. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8400. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8401. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8402. print '<table class="noborder">';
  8403. print '<tr class="liste_titre">';
  8404. print '<td class="nowrap"></td>';
  8405. print '<td class="center">' . $langs->trans("Ref") . '</td>';
  8406. print '<td class="left">' . $langs->trans("RefCustomer") . '</td>';
  8407. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  8408. print '<td class="left">' . $langs->trans("Company") . '</td>';
  8409. print '</tr>';
  8410. while ($i < $num) {
  8411. $objp = $this->db->fetch_object($resqllist);
  8412. print '<tr class="oddeven">';
  8413. print '<td class="left">';
  8414. print '<input type="radio" name="idtolinkto" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
  8415. print '</td>';
  8416. print '<td class="center"><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
  8417. print '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
  8418. print '<td class="right">';
  8419. if ($possiblelink['label'] == 'LinkToContract') {
  8420. $form = new Form($this->db);
  8421. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
  8422. }
  8423. print '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
  8424. print '</td>';
  8425. print '<td>' . $objp->name . '</td>';
  8426. print '</tr>';
  8427. $i++;
  8428. }
  8429. print '</table>';
  8430. print '<div class="center">';
  8431. if ($num) {
  8432. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly small" value="' . $langs->trans('ToLink') . '">';
  8433. }
  8434. if (empty($conf->use_javascript_ajax)) {
  8435. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly small" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8436. } else {
  8437. print '<input type="submit" onclick="jQuery(\'#' . $key . 'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly small" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8438. }
  8439. print '</form>';
  8440. $this->db->free($resqllist);
  8441. } else {
  8442. dol_print_error($this->db);
  8443. }
  8444. print '</div>';
  8445. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  8446. if ($num > 0 || getDolGlobalString('MAIN_LINK_BY_REF_IN_LINKTO')) {
  8447. $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $num . ')</a></li>';
  8448. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  8449. } else {
  8450. $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  8451. }
  8452. }
  8453. }
  8454. if ($linktoelemlist) {
  8455. $linktoelem = '
  8456. <dl class="dropdown" id="linktoobjectname">
  8457. ';
  8458. if (!empty($conf->use_javascript_ajax)) {
  8459. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
  8460. }
  8461. $linktoelem .= '<dd>
  8462. <div class="multiselectlinkto">
  8463. <ul class="ulselectedfields">' . $linktoelemlist . '
  8464. </ul>
  8465. </div>
  8466. </dd>
  8467. </dl>';
  8468. } else {
  8469. $linktoelem = '';
  8470. }
  8471. if (!empty($conf->use_javascript_ajax)) {
  8472. print '<!-- Add js to show linkto box -->
  8473. <script nonce="' . getNonce() . '">
  8474. jQuery(document).ready(function() {
  8475. jQuery(".linkto").click(function() {
  8476. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  8477. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  8478. });
  8479. });
  8480. </script>
  8481. ';
  8482. }
  8483. return $linktoelem;
  8484. }
  8485. /**
  8486. * Return an html string with a select combo box to choose yes or no
  8487. *
  8488. * @param string $htmlname Name of html select field
  8489. * @param string $value Pre-selected value
  8490. * @param int $option 0 return yes/no, 1 return 1/0
  8491. * @param bool $disabled true or false
  8492. * @param int $useempty 1=Add empty line
  8493. * @param int $addjscombo 1=Add js beautifier on combo box
  8494. * @param string $morecss More CSS
  8495. * @param string $labelyes Label for Yes
  8496. * @param string $labelno Label for No
  8497. * @return string See option
  8498. */
  8499. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8500. {
  8501. global $langs;
  8502. $yes = "yes";
  8503. $no = "no";
  8504. if ($option) {
  8505. $yes = "1";
  8506. $no = "0";
  8507. }
  8508. $disabled = ($disabled ? ' disabled' : '');
  8509. $resultyesno = '<select class="flat width75' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
  8510. if ($useempty) {
  8511. $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8512. }
  8513. if (("$value" == 'yes') || ($value == 1)) {
  8514. $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
  8515. $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
  8516. } else {
  8517. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8518. $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
  8519. $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
  8520. }
  8521. $resultyesno .= '</select>' . "\n";
  8522. if ($addjscombo) {
  8523. $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
  8524. }
  8525. return $resultyesno;
  8526. }
  8527. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8528. /**
  8529. * Return list of export templates
  8530. *
  8531. * @param string $selected Id modele pre-selectionne
  8532. * @param string $htmlname Name of HTML select
  8533. * @param string $type Type of searched templates
  8534. * @param int $useempty Affiche valeur vide dans liste
  8535. * @return void
  8536. */
  8537. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8538. {
  8539. // phpcs:enable
  8540. $sql = "SELECT rowid, label";
  8541. $sql .= " FROM " . $this->db->prefix() . "export_model";
  8542. $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
  8543. $sql .= " ORDER BY rowid";
  8544. $result = $this->db->query($sql);
  8545. if ($result) {
  8546. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  8547. if ($useempty) {
  8548. print '<option value="-1">&nbsp;</option>';
  8549. }
  8550. $num = $this->db->num_rows($result);
  8551. $i = 0;
  8552. while ($i < $num) {
  8553. $obj = $this->db->fetch_object($result);
  8554. if ($selected == $obj->rowid) {
  8555. print '<option value="' . $obj->rowid . '" selected>';
  8556. } else {
  8557. print '<option value="' . $obj->rowid . '">';
  8558. }
  8559. print $obj->label;
  8560. print '</option>';
  8561. $i++;
  8562. }
  8563. print "</select>";
  8564. } else {
  8565. dol_print_error($this->db);
  8566. }
  8567. }
  8568. /**
  8569. * Return a HTML area with the reference of object and a navigation bar for a business object
  8570. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8571. *
  8572. * @param object $object Object to show.
  8573. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8574. * @param string $morehtml More html content to output just before the nav bar.
  8575. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8576. * @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.
  8577. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8578. * @param string $morehtmlref More html to show after ref.
  8579. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8580. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8581. * @param string $morehtmlleft More html code to show before ref.
  8582. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8583. * @param string $morehtmlright More html code to show after ref.
  8584. * @return string Portion HTML with ref + navigation buttons
  8585. */
  8586. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8587. {
  8588. global $conf, $langs, $hookmanager, $extralanguages;
  8589. $ret = '';
  8590. if (empty($fieldid)) {
  8591. $fieldid = 'rowid';
  8592. }
  8593. if (empty($fieldref)) {
  8594. $fieldref = 'ref';
  8595. }
  8596. // Preparing gender's display if there is one
  8597. $addgendertxt = '';
  8598. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8599. $addgendertxt = ' ';
  8600. switch ($object->gender) {
  8601. case 'man':
  8602. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8603. break;
  8604. case 'woman':
  8605. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8606. break;
  8607. case 'other':
  8608. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8609. break;
  8610. }
  8611. }
  8612. // Add where from hooks
  8613. if (is_object($hookmanager)) {
  8614. $parameters = array('showrefnav' => true);
  8615. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8616. $object->next_prev_filter .= $hookmanager->resPrint;
  8617. }
  8618. $previous_ref = $next_ref = '';
  8619. if ($shownav) {
  8620. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8621. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8622. $navurl = $_SERVER["PHP_SELF"];
  8623. // Special case for project/task page
  8624. if ($paramid == 'project_ref') {
  8625. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8626. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8627. $paramid = 'ref';
  8628. }
  8629. }
  8630. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8631. // accesskey is for Mac: CTRL + key for all browsers
  8632. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8633. if ($conf->browser->name == 'chrome') {
  8634. $stringforfirstkey .= ' ALT +';
  8635. } elseif ($conf->browser->name == 'firefox') {
  8636. $stringforfirstkey .= ' ALT + SHIFT +';
  8637. } else {
  8638. $stringforfirstkey .= ' CTL +';
  8639. }
  8640. $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>';
  8641. $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>';
  8642. }
  8643. //print "xx".$previous_ref."x".$next_ref;
  8644. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8645. // Right part of banner
  8646. if ($morehtmlright) {
  8647. $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
  8648. }
  8649. if ($previous_ref || $next_ref || $morehtml) {
  8650. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8651. }
  8652. if ($morehtml) {
  8653. $ret .= '<li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
  8654. }
  8655. if ($shownav && ($previous_ref || $next_ref)) {
  8656. $ret .= '<li class="pagination">' . $previous_ref . '</li>';
  8657. $ret .= '<li class="pagination">' . $next_ref . '</li>';
  8658. }
  8659. if ($previous_ref || $next_ref || $morehtml) {
  8660. $ret .= '</ul></div>';
  8661. }
  8662. // Status
  8663. $parameters = array('morehtmlstatus' => $morehtmlstatus);
  8664. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8665. if (empty($reshook)) {
  8666. $morehtmlstatus .= $hookmanager->resPrint;
  8667. } else {
  8668. $morehtmlstatus = $hookmanager->resPrint;
  8669. }
  8670. if ($morehtmlstatus) {
  8671. $ret .= '<div class="statusref">' . $morehtmlstatus . '</div>';
  8672. }
  8673. $parameters = array();
  8674. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8675. if (empty($reshook)) {
  8676. $morehtmlref .= $hookmanager->resPrint;
  8677. } elseif ($reshook > 0) {
  8678. $morehtmlref = $hookmanager->resPrint;
  8679. }
  8680. // Left part of banner
  8681. if ($morehtmlleft) {
  8682. if ($conf->browser->layout == 'phone') {
  8683. $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>';
  8684. } else {
  8685. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
  8686. }
  8687. }
  8688. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8689. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
  8690. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8691. if ($object->element == 'societe') {
  8692. $ret .= dol_htmlentities($object->name);
  8693. // List of extra languages
  8694. $arrayoflangcode = array();
  8695. if (getDolGlobalString('PDF_USE_ALSO_LANGUAGE_CODE')) {
  8696. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8697. }
  8698. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8699. if (!is_object($extralanguages)) {
  8700. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  8701. $extralanguages = new ExtraLanguages($this->db);
  8702. }
  8703. $extralanguages->fetch_name_extralanguages('societe');
  8704. if (!empty($extralanguages->attributes['societe']['name'])) {
  8705. $object->fetchValuesForExtraLanguages();
  8706. $htmltext = '';
  8707. // If there is extra languages
  8708. foreach ($arrayoflangcode as $extralangcode) {
  8709. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8710. if ($object->array_languages['name'][$extralangcode]) {
  8711. $htmltext .= $object->array_languages['name'][$extralangcode];
  8712. } else {
  8713. $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
  8714. }
  8715. }
  8716. $ret .= '<!-- Show translations of name -->' . "\n";
  8717. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8718. }
  8719. }
  8720. } elseif ($object->element == 'member') {
  8721. $ret .= $object->ref . '<br>';
  8722. $fullname = $object->getFullName($langs);
  8723. if ($object->morphy == 'mor' && $object->societe) {
  8724. $ret .= dol_htmlentities($object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '');
  8725. } else {
  8726. $ret .= dol_htmlentities($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities($object->societe) . ')' : '');
  8727. }
  8728. } elseif (in_array($object->element, array('contact', 'user'))) {
  8729. $ret .= dol_htmlentities($object->getFullName($langs)) . $addgendertxt;
  8730. } elseif ($object->element == 'usergroup') {
  8731. $ret .= dol_htmlentities($object->name);
  8732. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8733. $ret .= $object->ref . '<br>' . $object->label;
  8734. } elseif (in_array($object->element, array('adherent_type'))) {
  8735. $ret .= $object->label;
  8736. } elseif ($object->element == 'ecm_directories') {
  8737. $ret .= '';
  8738. } elseif ($fieldref != 'none') {
  8739. $ret .= dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "");
  8740. }
  8741. if ($morehtmlref) {
  8742. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8743. if (substr($morehtmlref, 0, 4) != '<div') {
  8744. $ret .= ' ';
  8745. }
  8746. $ret .= $morehtmlref;
  8747. }
  8748. $ret .= '</div>';
  8749. $ret .= '</div><!-- End banner content -->';
  8750. return $ret;
  8751. }
  8752. /**
  8753. * Return HTML code to output a barcode
  8754. *
  8755. * @param Object $object Object containing data to retrieve file name
  8756. * @param int $width Width of photo
  8757. * @param string $morecss More CSS on img of barcode
  8758. * @return string HTML code to output barcode
  8759. */
  8760. public function showbarcode(&$object, $width = 100, $morecss = '')
  8761. {
  8762. global $conf;
  8763. //Check if barcode is filled in the card
  8764. if (empty($object->barcode)) {
  8765. return '';
  8766. }
  8767. // Complete object if not complete
  8768. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8769. $result = $object->fetch_barcode();
  8770. //Check if fetch_barcode() failed
  8771. if ($result < 1) {
  8772. return '<!-- ErrorFetchBarcode -->';
  8773. }
  8774. }
  8775. // Barcode image
  8776. $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
  8777. $out = '<!-- url barcode = ' . $url . ' -->';
  8778. $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
  8779. return $out;
  8780. }
  8781. /**
  8782. * Return HTML code to output a photo
  8783. *
  8784. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8785. * @param object $object Object containing data to retrieve file name
  8786. * @param int $width Width of photo
  8787. * @param int $height Height of photo (auto if 0)
  8788. * @param int $caneditfield Add edit fields
  8789. * @param string $cssclass CSS name to use on img for photo
  8790. * @param string $imagesize 'mini', 'small' or '' (original)
  8791. * @param int $addlinktofullsize Add link to fullsize image
  8792. * @param int $cache 1=Accept to use image in cache
  8793. * @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 ''.
  8794. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8795. * @return string HTML code to output photo
  8796. */
  8797. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8798. {
  8799. global $conf, $langs;
  8800. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  8801. $id = (empty($object->id) ? $object->rowid : $object->id);
  8802. $ret = '';
  8803. $dir = '';
  8804. $file = '';
  8805. $originalfile = '';
  8806. $altfile = '';
  8807. $email = '';
  8808. $capture = '';
  8809. if ($modulepart == 'societe') {
  8810. $dir = $conf->societe->multidir_output[$entity];
  8811. if (!empty($object->logo)) {
  8812. if (dolIsAllowedForPreview($object->logo)) {
  8813. if ((string) $imagesize == 'mini') {
  8814. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8815. } elseif ((string) $imagesize == 'small') {
  8816. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
  8817. } else {
  8818. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8819. }
  8820. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8821. }
  8822. }
  8823. $email = $object->email;
  8824. } elseif ($modulepart == 'contact') {
  8825. $dir = $conf->societe->multidir_output[$entity] . '/contact';
  8826. if (!empty($object->photo)) {
  8827. if (dolIsAllowedForPreview($object->photo)) {
  8828. if ((string) $imagesize == 'mini') {
  8829. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8830. } elseif ((string) $imagesize == 'small') {
  8831. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8832. } else {
  8833. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8834. }
  8835. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8836. }
  8837. }
  8838. $email = $object->email;
  8839. $capture = 'user';
  8840. } elseif ($modulepart == 'userphoto') {
  8841. $dir = $conf->user->dir_output;
  8842. if (!empty($object->photo)) {
  8843. if (dolIsAllowedForPreview($object->photo)) {
  8844. if ((string) $imagesize == 'mini') {
  8845. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8846. } elseif ((string) $imagesize == 'small') {
  8847. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8848. } else {
  8849. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8850. }
  8851. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8852. }
  8853. }
  8854. if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
  8855. $altfile = $object->id . ".jpg"; // For backward compatibility
  8856. }
  8857. $email = $object->email;
  8858. $capture = 'user';
  8859. } elseif ($modulepart == 'memberphoto') {
  8860. $dir = $conf->adherent->dir_output;
  8861. if (!empty($object->photo)) {
  8862. if (dolIsAllowedForPreview($object->photo)) {
  8863. if ((string) $imagesize == 'mini') {
  8864. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8865. } elseif ((string) $imagesize == 'small') {
  8866. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8867. } else {
  8868. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8869. }
  8870. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8871. }
  8872. }
  8873. if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
  8874. $altfile = $object->id . ".jpg"; // For backward compatibility
  8875. }
  8876. $email = $object->email;
  8877. $capture = 'user';
  8878. } else {
  8879. // Generic case to show photos
  8880. $dir = $conf->$modulepart->dir_output;
  8881. if (!empty($object->photo)) {
  8882. if (dolIsAllowedForPreview($object->photo)) {
  8883. if ((string) $imagesize == 'mini') {
  8884. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8885. } elseif ((string) $imagesize == 'small') {
  8886. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8887. } else {
  8888. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8889. }
  8890. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8891. }
  8892. }
  8893. if (getDolGlobalString('MAIN_OLD_IMAGE_LINKS')) {
  8894. $altfile = $object->id . ".jpg"; // For backward compatibility
  8895. }
  8896. $email = $object->email;
  8897. }
  8898. if ($forcecapture) {
  8899. $capture = $forcecapture;
  8900. }
  8901. if ($dir) {
  8902. if ($file && file_exists($dir . "/" . $file)) {
  8903. if ($addlinktofullsize) {
  8904. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8905. if ($urladvanced) {
  8906. $ret .= '<a href="' . $urladvanced . '">';
  8907. } else {
  8908. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8909. }
  8910. }
  8911. $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 . '">';
  8912. if ($addlinktofullsize) {
  8913. $ret .= '</a>';
  8914. }
  8915. } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
  8916. if ($addlinktofullsize) {
  8917. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8918. if ($urladvanced) {
  8919. $ret .= '<a href="' . $urladvanced . '">';
  8920. } else {
  8921. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8922. }
  8923. }
  8924. $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 . '">';
  8925. if ($addlinktofullsize) {
  8926. $ret .= '</a>';
  8927. }
  8928. } else {
  8929. $nophoto = '/public/theme/common/nophoto.png';
  8930. $defaultimg = 'identicon'; // For gravatar
  8931. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8932. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && !empty($object->morphy) && strpos($object->morphy, 'mor')) !== false) {
  8933. $nophoto = 'company';
  8934. } else {
  8935. $nophoto = '/public/theme/common/user_anonymous.png';
  8936. if (!empty($object->gender) && $object->gender == 'man') {
  8937. $nophoto = '/public/theme/common/user_man.png';
  8938. }
  8939. if (!empty($object->gender) && $object->gender == 'woman') {
  8940. $nophoto = '/public/theme/common/user_woman.png';
  8941. }
  8942. }
  8943. }
  8944. if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
  8945. // see https://gravatar.com/site/implement/images/php/
  8946. $ret .= '<!-- Put link to gravatar -->';
  8947. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" title="' . $email . ' Gravatar avatar" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="https://www.gravatar.com/avatar/' . dol_hash(strtolower(trim($email)), 'sha256', 1) . '?s=' . $width . '&d=' . $defaultimg . '">'; // gravatar need md5 hash
  8948. } else {
  8949. if ($nophoto == 'company') {
  8950. $ret .= '<div class="divforspanimg photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
  8951. $ret .= '<div class="difforspanimgright"></div>';
  8952. } else {
  8953. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
  8954. }
  8955. }
  8956. }
  8957. if ($caneditfield) {
  8958. if ($object->photo) {
  8959. $ret .= "<br>\n";
  8960. }
  8961. $ret .= '<table class="nobordernopadding centpercent">';
  8962. if ($object->photo) {
  8963. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
  8964. }
  8965. $ret .= '<tr><td class="tdoverflow">';
  8966. $maxfilesizearray = getMaxFileSizeArray();
  8967. $maxmin = $maxfilesizearray['maxmin'];
  8968. if ($maxmin > 0) {
  8969. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
  8970. }
  8971. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . $capture . '"' : '') . '>';
  8972. $ret .= '</td></tr>';
  8973. $ret .= '</table>';
  8974. }
  8975. }
  8976. return $ret;
  8977. }
  8978. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8979. /**
  8980. * Return select list of groups
  8981. *
  8982. * @param string|object $selected Id group or group preselected
  8983. * @param string $htmlname Field name in form
  8984. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8985. * @param string|array $exclude Array list of groups id to exclude
  8986. * @param int $disabled If select list must be disabled
  8987. * @param string|array $include Array list of groups id to include
  8988. * @param array $enableonly Array list of groups id to be enabled. All other must be disabled
  8989. * @param string $force_entity '0' or Ids of environment to force
  8990. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8991. * @param string $morecss More css to add to html component
  8992. * @return string
  8993. * @see select_dolusers()
  8994. */
  8995. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = array(), $force_entity = '0', $multiple = false, $morecss = '')
  8996. {
  8997. // phpcs:enable
  8998. global $conf, $user, $langs;
  8999. // Permettre l'exclusion de groupes
  9000. $excludeGroups = null;
  9001. if (is_array($exclude)) {
  9002. $excludeGroups = implode(",", $exclude);
  9003. }
  9004. // Permettre l'inclusion de groupes
  9005. $includeGroups = null;
  9006. if (is_array($include)) {
  9007. $includeGroups = implode(",", $include);
  9008. }
  9009. if (!is_array($selected)) {
  9010. $selected = array($selected);
  9011. }
  9012. $out = '';
  9013. // On recherche les groupes
  9014. $sql = "SELECT ug.rowid, ug.nom as name";
  9015. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  9016. $sql .= ", e.label";
  9017. }
  9018. $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
  9019. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  9020. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
  9021. if ($force_entity) {
  9022. $sql .= " WHERE ug.entity IN (0, " . $force_entity . ")";
  9023. } else {
  9024. $sql .= " WHERE ug.entity IS NOT NULL";
  9025. }
  9026. } else {
  9027. $sql .= " WHERE ug.entity IN (0, " . $conf->entity . ")";
  9028. }
  9029. if (is_array($exclude) && $excludeGroups) {
  9030. $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
  9031. }
  9032. if (is_array($include) && $includeGroups) {
  9033. $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
  9034. }
  9035. $sql .= " ORDER BY ug.nom ASC";
  9036. dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
  9037. $resql = $this->db->query($sql);
  9038. if ($resql) {
  9039. // Enhance with select2
  9040. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9041. $out .= '<select class="flat minwidth200' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  9042. $num = $this->db->num_rows($resql);
  9043. $i = 0;
  9044. if ($num) {
  9045. if ($show_empty && !$multiple) {
  9046. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  9047. }
  9048. while ($i < $num) {
  9049. $obj = $this->db->fetch_object($resql);
  9050. $disableline = 0;
  9051. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  9052. $disableline = 1;
  9053. }
  9054. $label = $obj->name;
  9055. $labelhtml = $obj->name;
  9056. if (isModEnabled('multicompany') && !getDolGlobalInt('MULTICOMPANY_TRANSVERSE_MODE') && $conf->entity == 1) {
  9057. $label .= " (" . $obj->label . ")";
  9058. $labelhtml .= ' <span class="opacitymedium">(' . $obj->label . ')</span>';
  9059. }
  9060. $out .= '<option value="' . $obj->rowid . '"';
  9061. if ($disableline) {
  9062. $out .= ' disabled';
  9063. }
  9064. if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $obj->rowid) || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($obj->rowid, $selected))) {
  9065. $out .= ' selected';
  9066. }
  9067. $out .= ' data-html="'.dol_escape_htmltag($labelhtml).'"';
  9068. $out .= '>';
  9069. $out .= $label;
  9070. $out .= '</option>';
  9071. $i++;
  9072. }
  9073. } else {
  9074. if ($show_empty) {
  9075. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
  9076. }
  9077. $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
  9078. }
  9079. $out .= '</select>';
  9080. $out .= ajax_combobox($htmlname);
  9081. } else {
  9082. dol_print_error($this->db);
  9083. }
  9084. return $out;
  9085. }
  9086. /**
  9087. * Return HTML to show the search and clear seach button
  9088. *
  9089. * @param string $pos Position of colon on the list. Value 'left' or 'right'
  9090. * @return string
  9091. */
  9092. public function showFilterButtons($pos = '')
  9093. {
  9094. $out = '<div class="nowraponall">';
  9095. if ($pos == 'left') {
  9096. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fas fa-search"></span></button>';
  9097. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fas fa-times"></span></button>';
  9098. } else {
  9099. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fas fa-search"></span></button>';
  9100. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fas fa-times"></span></button>';
  9101. }
  9102. $out .= '</div>';
  9103. return $out;
  9104. }
  9105. /**
  9106. * Return HTML to show the search and clear search button
  9107. *
  9108. * @param string $cssclass CSS class
  9109. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  9110. * @param string $massactionname Mass action button name that will launch an action on the selected items
  9111. * @return string
  9112. */
  9113. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  9114. {
  9115. global $conf;
  9116. $out = '';
  9117. if (!empty($conf->use_javascript_ajax)) {
  9118. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
  9119. }
  9120. $out .= '<script nonce="' . getNonce() . '">
  9121. $(document).ready(function() {
  9122. $("#' . $cssclass . 's").click(function() {
  9123. if($(this).is(\':checked\')){
  9124. console.log("We check all ' . $cssclass . ' and trigger the change method");
  9125. $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
  9126. }
  9127. else
  9128. {
  9129. console.log("We uncheck all");
  9130. $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
  9131. }' . "\n";
  9132. if ($calljsfunction) {
  9133. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  9134. }
  9135. $out .= ' });
  9136. $(".' . $cssclass . '").change(function() {
  9137. $(this).closest("tr").toggleClass("highlight", this.checked);
  9138. });
  9139. });
  9140. </script>';
  9141. return $out;
  9142. }
  9143. /**
  9144. * Return HTML to show the search and clear seach button
  9145. *
  9146. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  9147. * @param string $cssclass CSS class
  9148. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  9149. * @param string $massactionname Mass action name
  9150. * @return string
  9151. */
  9152. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  9153. {
  9154. $out = $this->showFilterButtons();
  9155. if ($addcheckuncheckall) {
  9156. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  9157. }
  9158. return $out;
  9159. }
  9160. /**
  9161. * Return HTML to show the select of expense categories
  9162. *
  9163. * @param string $selected preselected category
  9164. * @param string $htmlname name of HTML select list
  9165. * @param integer $useempty 1=Add empty line
  9166. * @param array $excludeid id to exclude
  9167. * @param string $target htmlname of target select to bind event
  9168. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  9169. * @param array $params param to give
  9170. * @param int $info_admin Show the tooltip help picto to setup list
  9171. * @return string
  9172. */
  9173. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  9174. {
  9175. global $langs, $user;
  9176. $out = '';
  9177. $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
  9178. $sql .= " AND entity IN (0," . getEntity('exp_tax_cat') . ")";
  9179. if (!empty($excludeid)) {
  9180. $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
  9181. }
  9182. $sql .= " ORDER BY label";
  9183. $resql = $this->db->query($sql);
  9184. if ($resql) {
  9185. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
  9186. if ($useempty) {
  9187. $out .= '<option value="0">&nbsp;</option>';
  9188. }
  9189. while ($obj = $this->db->fetch_object($resql)) {
  9190. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
  9191. }
  9192. $out .= '</select>';
  9193. $out .= ajax_combobox('select_' . $htmlname);
  9194. if (!empty($htmlname) && $user->admin && $info_admin) {
  9195. $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  9196. }
  9197. if (!empty($target)) {
  9198. $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  9199. $resql = $this->db->query($sql);
  9200. if ($resql) {
  9201. if ($this->db->num_rows($resql) > 0) {
  9202. $obj = $this->db->fetch_object($resql);
  9203. $out .= '<script nonce="' . getNonce() . '">
  9204. $(function() {
  9205. $("select[name=' . $target . ']").on("change", function() {
  9206. var current_val = $(this).val();
  9207. if (current_val == ' . $obj->id . ') {';
  9208. if (!empty($default_selected) || !empty($selected)) {
  9209. $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
  9210. }
  9211. $out .= '
  9212. $("select[name=' . $htmlname . ']").change();
  9213. }
  9214. });
  9215. $("select[name=' . $htmlname . ']").change(function() {
  9216. if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
  9217. // get price of kilometer to fill the unit price
  9218. $.ajax({
  9219. method: "POST",
  9220. dataType: "json",
  9221. data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
  9222. url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . join('&', $params)) . '",
  9223. }).done(function( data, textStatus, jqXHR ) {
  9224. console.log(data);
  9225. if (typeof data.up != "undefined") {
  9226. $("input[name=value_unit]").val(data.up);
  9227. $("select[name=' . $htmlname . ']").attr("title", data.title);
  9228. } else {
  9229. $("input[name=value_unit]").val("");
  9230. $("select[name=' . $htmlname . ']").attr("title", "");
  9231. }
  9232. });
  9233. }
  9234. });
  9235. });
  9236. </script>';
  9237. }
  9238. }
  9239. }
  9240. } else {
  9241. dol_print_error($this->db);
  9242. }
  9243. return $out;
  9244. }
  9245. /**
  9246. * Return HTML to show the select ranges of expense range
  9247. *
  9248. * @param string $selected preselected category
  9249. * @param string $htmlname name of HTML select list
  9250. * @param integer $useempty 1=Add empty line
  9251. * @return string
  9252. */
  9253. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  9254. {
  9255. global $conf, $langs;
  9256. $out = '';
  9257. $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
  9258. $sql .= " WHERE entity = " . $conf->entity . " AND active = 1";
  9259. $resql = $this->db->query($sql);
  9260. if ($resql) {
  9261. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9262. if ($useempty) {
  9263. $out .= '<option value="0"></option>';
  9264. }
  9265. while ($obj = $this->db->fetch_object($resql)) {
  9266. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
  9267. }
  9268. $out .= '</select>';
  9269. } else {
  9270. dol_print_error($this->db);
  9271. }
  9272. return $out;
  9273. }
  9274. /**
  9275. * Return HTML to show a select of expense
  9276. *
  9277. * @param string $selected preselected category
  9278. * @param string $htmlname name of HTML select list
  9279. * @param integer $useempty 1=Add empty choice
  9280. * @param integer $allchoice 1=Add all choice
  9281. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  9282. * @return string
  9283. */
  9284. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  9285. {
  9286. global $langs;
  9287. $out = '';
  9288. $sql = "SELECT id, code, label";
  9289. $sql .= " FROM ".$this->db->prefix()."c_type_fees";
  9290. $sql .= " WHERE active = 1";
  9291. $resql = $this->db->query($sql);
  9292. if ($resql) {
  9293. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9294. if ($useempty) {
  9295. $out .= '<option value="0"></option>';
  9296. }
  9297. if ($allchoice) {
  9298. $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
  9299. }
  9300. $field = 'code';
  9301. if ($useid) {
  9302. $field = 'id';
  9303. }
  9304. while ($obj = $this->db->fetch_object($resql)) {
  9305. $key = $langs->trans($obj->code);
  9306. $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
  9307. }
  9308. $out .= '</select>';
  9309. $out .= ajax_combobox('select_'.$htmlname);
  9310. } else {
  9311. dol_print_error($this->db);
  9312. }
  9313. return $out;
  9314. }
  9315. /**
  9316. * Output a combo list with invoices qualified for a third party
  9317. *
  9318. * @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)
  9319. * @param string $selected Id invoice preselected
  9320. * @param string $htmlname Name of HTML select
  9321. * @param int $maxlength Maximum length of label
  9322. * @param int $option_only Return only html options lines without the select tag
  9323. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9324. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  9325. * @param int $forcefocus Force focus on field (works with javascript only)
  9326. * @param int $disabled Disabled
  9327. * @param string $morecss More css added to the select component
  9328. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  9329. * @param string $showproject 'all' = Show project info, ''=Hide project info
  9330. * @param User $usertofilter User object to use for filtering
  9331. * @return string HTML Select Invoice
  9332. */
  9333. 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)
  9334. {
  9335. global $user, $conf, $langs;
  9336. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  9337. if (is_null($usertofilter)) {
  9338. $usertofilter = $user;
  9339. }
  9340. $out = '';
  9341. $hideunselectables = false;
  9342. if (getDolGlobalString('PROJECT_HIDE_UNSELECTABLES')) {
  9343. $hideunselectables = true;
  9344. }
  9345. if (empty($projectsListId)) {
  9346. if (!$usertofilter->hasRight('projet', 'all', 'lire')) {
  9347. $projectstatic = new Project($this->db);
  9348. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  9349. }
  9350. }
  9351. // Search all projects
  9352. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  9353. p.title, p.fk_soc, p.fk_statut, p.public,";
  9354. $sql .= ' s.nom as name';
  9355. $sql .= ' FROM ' . $this->db->prefix() . 'projet as p';
  9356. $sql .= ' LEFT JOIN ' . $this->db->prefix() . 'societe as s ON s.rowid = p.fk_soc,';
  9357. $sql .= ' ' . $this->db->prefix() . 'facture as f';
  9358. $sql .= " WHERE p.entity IN (" . getEntity('project') . ")";
  9359. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  9360. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  9361. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  9362. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  9363. $sql .= " ORDER BY p.ref, f.ref ASC";
  9364. $resql = $this->db->query($sql);
  9365. if ($resql) {
  9366. // Use select2 selector
  9367. if (!empty($conf->use_javascript_ajax)) {
  9368. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9369. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9370. $out .= $comboenhancement;
  9371. $morecss = 'minwidth200imp maxwidth500';
  9372. }
  9373. if (empty($option_only)) {
  9374. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9375. }
  9376. if (!empty($show_empty)) {
  9377. $out .= '<option value="0" class="optiongrey">';
  9378. if (!is_numeric($show_empty)) {
  9379. $out .= $show_empty;
  9380. } else {
  9381. $out .= '&nbsp;';
  9382. }
  9383. $out .= '</option>';
  9384. }
  9385. $num = $this->db->num_rows($resql);
  9386. $i = 0;
  9387. if ($num) {
  9388. while ($i < $num) {
  9389. $obj = $this->db->fetch_object($resql);
  9390. // 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.
  9391. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$usertofilter->hasRight('societe', 'lire')) {
  9392. // Do nothing
  9393. } else {
  9394. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  9395. $i++;
  9396. continue;
  9397. }
  9398. $labeltoshow = '';
  9399. if ($showproject == 'all') {
  9400. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  9401. if ($obj->name) {
  9402. $labeltoshow .= ' - ' . $obj->name; // Soc name
  9403. }
  9404. $disabled = 0;
  9405. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  9406. $disabled = 1;
  9407. $labeltoshow .= ' - ' . $langs->trans("Draft");
  9408. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  9409. if ($discard_closed == 2) {
  9410. $disabled = 1;
  9411. }
  9412. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9413. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  9414. $disabled = 1;
  9415. $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
  9416. }
  9417. }
  9418. if (!empty($selected) && $selected == $obj->rowid) {
  9419. $out .= '<option value="' . $obj->rowid . '" selected';
  9420. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9421. $out .= '>' . $labeltoshow . '</option>';
  9422. } else {
  9423. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  9424. $resultat = '';
  9425. } else {
  9426. $resultat = '<option value="' . $obj->rowid . '"';
  9427. if ($disabled) {
  9428. $resultat .= ' disabled';
  9429. }
  9430. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  9431. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  9432. $resultat .= '>';
  9433. $resultat .= $labeltoshow;
  9434. $resultat .= '</option>';
  9435. }
  9436. $out .= $resultat;
  9437. }
  9438. }
  9439. $i++;
  9440. }
  9441. }
  9442. if (empty($option_only)) {
  9443. $out .= '</select>';
  9444. }
  9445. $this->db->free($resql);
  9446. return $out;
  9447. } else {
  9448. dol_print_error($this->db);
  9449. return '';
  9450. }
  9451. }
  9452. /**
  9453. * Output a combo list with invoices qualified for a third party
  9454. *
  9455. * @param string $selected Id invoice preselected
  9456. * @param string $htmlname Name of HTML select
  9457. * @param int $maxlength Maximum length of label
  9458. * @param int $option_only Return only html options lines without the select tag
  9459. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9460. * @param int $forcefocus Force focus on field (works with javascript only)
  9461. * @param int $disabled Disabled
  9462. * @param string $morecss More css added to the select component
  9463. * @return int Nbr of project if OK, <0 if KO
  9464. */
  9465. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  9466. {
  9467. global $conf, $langs;
  9468. $out = '';
  9469. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  9470. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  9471. //$sql.= ', el.fk_source';
  9472. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  9473. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  9474. $sql .= " ORDER BY f.titre ASC";
  9475. $resql = $this->db->query($sql);
  9476. if ($resql) {
  9477. // Use select2 selector
  9478. if (!empty($conf->use_javascript_ajax)) {
  9479. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9480. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9481. $out .= $comboenhancement;
  9482. $morecss = 'minwidth200imp maxwidth500';
  9483. }
  9484. if (empty($option_only)) {
  9485. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9486. }
  9487. if (!empty($show_empty)) {
  9488. $out .= '<option value="0" class="optiongrey">';
  9489. if (!is_numeric($show_empty)) {
  9490. $out .= $show_empty;
  9491. } else {
  9492. $out .= '&nbsp;';
  9493. }
  9494. $out .= '</option>';
  9495. }
  9496. $num = $this->db->num_rows($resql);
  9497. if ($num) {
  9498. while ($obj = $this->db->fetch_object($resql)) {
  9499. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9500. $disabled = 0;
  9501. if (!empty($obj->suspended)) {
  9502. $disabled = 1;
  9503. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9504. }
  9505. if (!empty($selected) && $selected == $obj->rowid) {
  9506. $out .= '<option value="' . $obj->rowid . '" selected';
  9507. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9508. $out .= '>' . $labeltoshow . '</option>';
  9509. } else {
  9510. if ($disabled && ($selected != $obj->rowid)) {
  9511. $resultat = '';
  9512. } else {
  9513. $resultat = '<option value="' . $obj->rowid . '"';
  9514. if ($disabled) {
  9515. $resultat .= ' disabled';
  9516. }
  9517. $resultat .= '>';
  9518. $resultat .= $labeltoshow;
  9519. $resultat .= '</option>';
  9520. }
  9521. $out .= $resultat;
  9522. }
  9523. }
  9524. }
  9525. if (empty($option_only)) {
  9526. $out .= '</select>';
  9527. }
  9528. print $out;
  9529. $this->db->free($resql);
  9530. return $num;
  9531. } else {
  9532. $this->errors[] = $this->db->lasterror;
  9533. return -1;
  9534. }
  9535. }
  9536. /**
  9537. * Output the component to make advanced search criteries
  9538. *
  9539. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9540. * @param array $search_component_params Array of selected search criterias
  9541. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9542. * @param string $search_component_params_hidden String with $search_component_params criterias
  9543. * @return string HTML component for advanced search
  9544. */
  9545. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9546. {
  9547. global $langs;
  9548. if ($search_component_params_hidden != '' && !preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9549. $search_component_params_hidden = '(' . $search_component_params_hidden . ')';
  9550. }
  9551. $ret = '';
  9552. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9553. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9554. $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
  9555. $ret .= '</a>';
  9556. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9557. // Show select fields as tags.
  9558. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9559. if ($search_component_params_hidden) {
  9560. // Split the criteria on each AND
  9561. //var_dump($search_component_params_hidden);
  9562. $nbofchars = dol_strlen($search_component_params_hidden);
  9563. $arrayofandtags = array();
  9564. $i = 0;
  9565. $s = '';
  9566. $countparenthesis = 0;
  9567. while ($i < $nbofchars) {
  9568. $char = dol_substr($search_component_params_hidden, $i, 1);
  9569. if ($char == '(') {
  9570. $countparenthesis++;
  9571. } elseif ($char == ')') {
  9572. $countparenthesis--;
  9573. }
  9574. if ($countparenthesis == 0) {
  9575. $char2 = dol_substr($search_component_params_hidden, $i+1, 1);
  9576. $char3 = dol_substr($search_component_params_hidden, $i+2, 1);
  9577. if ($char == 'A' && $char2 == 'N' && $char3 == 'D') {
  9578. // We found a AND
  9579. $arrayofandtags[] = trim($s);
  9580. $s = '';
  9581. $i+=2;
  9582. } else {
  9583. $s .= $char;
  9584. }
  9585. } else {
  9586. $s .= $char;
  9587. }
  9588. $i++;
  9589. }
  9590. if ($s) {
  9591. $arrayofandtags[] = trim($s);
  9592. }
  9593. // Show each AND part
  9594. foreach ($arrayofandtags as $tmpkey => $tmpval) {
  9595. $errormessage = '';
  9596. $searchtags = forgeSQLFromUniversalSearchCriteria($tmpval, $errormessage, 1, 1);
  9597. if ($errormessage) {
  9598. $this->error = 'ERROR in parsing search string: '.$errormessage;
  9599. }
  9600. // Remove first and last parenthesis but only if first is the opening and last the closing of the same group
  9601. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  9602. $searchtags = removeGlobalParenthesis($searchtags);
  9603. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch" data-ufilterid="'.($tmpkey+1).'" data-ufilter="'.dol_escape_htmltag($tmpval).'">';
  9604. $ret .= '<span class="tagsearchdelete select2-selection__choice__remove" data-ufilterid="'.($tmpkey+1).'">x</span> ';
  9605. $ret .= dol_escape_htmltag($searchtags);
  9606. $ret .= '</span>';
  9607. }
  9608. }
  9609. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9610. //$ret .= search_component_params
  9611. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9612. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9613. $show_search_component_params_hidden = 1;
  9614. if ($show_search_component_params_hidden) {
  9615. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9616. }
  9617. $ret .= "<!-- We store the full Universal Search String into this field. For example: (t.ref:like:'SO-%') AND ((t.ref:like:'CO-%') OR (t.ref:like:'AA%')) -->";
  9618. $ret .= '<input type="hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
  9619. // $ret .= "<!-- sql= ".forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage)." -->";
  9620. // For compatibility with forms that show themself the search criteria in addition of this component, we output these fields
  9621. foreach ($arrayofcriterias as $criterias) {
  9622. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9623. if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9624. continue;
  9625. }
  9626. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9627. continue;
  9628. }
  9629. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9630. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
  9631. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
  9632. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
  9633. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
  9634. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
  9635. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
  9636. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
  9637. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
  9638. } else {
  9639. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
  9640. }
  9641. }
  9642. }
  9643. $ret .= '</div>';
  9644. $ret .= "<!-- Field to enter a generic filter string: t.ref:like:'SO-%', t.date_creation:<:'20160101', t.date_creation:<:'2016-01-01 12:30:00', t.nature:is:NULL, t.field2:isnot:NULL -->\n";
  9645. $ret .= '<input type="text" placeholder="' . $langs->trans("Search") . '" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9646. $ret .= '</div>';
  9647. $ret .= '</div>';
  9648. $ret .= '<script>
  9649. jQuery(".tagsearchdelete").click(function() {
  9650. var filterid = $(this).parents().data("ufilterid");
  9651. console.log("We click to delete a criteria nb "+filterid);
  9652. // TODO Update the search_component_params_hidden with all data-ufilter except the one delete and post page
  9653. });
  9654. </script>
  9655. ';
  9656. return $ret;
  9657. }
  9658. /**
  9659. * selectModelMail
  9660. *
  9661. * @param string $prefix Prefix
  9662. * @param string $modelType Model type
  9663. * @param int $default 1=Show also Default mail template
  9664. * @param int $addjscombo Add js combobox
  9665. * @return string HTML select string
  9666. */
  9667. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9668. {
  9669. global $langs, $user;
  9670. $retstring = '';
  9671. $TModels = array();
  9672. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  9673. $formmail = new FormMail($this->db);
  9674. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9675. if ($default) {
  9676. $TModels[0] = $langs->trans('DefaultMailModel');
  9677. }
  9678. if ($result > 0) {
  9679. foreach ($formmail->lines_model as $model) {
  9680. $TModels[$model->id] = $model->label;
  9681. }
  9682. }
  9683. $retstring .= '<select class="flat" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
  9684. foreach ($TModels as $id_model => $label_model) {
  9685. $retstring .= '<option value="' . $id_model . '"';
  9686. $retstring .= ">" . $label_model . "</option>";
  9687. }
  9688. $retstring .= "</select>";
  9689. if ($addjscombo) {
  9690. $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
  9691. }
  9692. return $retstring;
  9693. }
  9694. /**
  9695. * Output the buttons to submit a creation/edit form
  9696. *
  9697. * @param string $save_label Alternative label for save button
  9698. * @param string $cancel_label Alternative label for cancel button
  9699. * @param array $morebuttons Add additional buttons between save and cancel
  9700. * @param bool $withoutdiv Option to remove enclosing centered div
  9701. * @param string $morecss More CSS
  9702. * @param string $dol_openinpopup If the button are shown in a context of a page shown inside a popup, we put here the string name of popup.
  9703. * @return string Html code with the buttons
  9704. */
  9705. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = false, $morecss = '', $dol_openinpopup = '')
  9706. {
  9707. global $langs;
  9708. $buttons = array();
  9709. $save = array(
  9710. 'name' => 'save',
  9711. 'label_key' => $save_label,
  9712. );
  9713. if ($save_label == 'Create' || $save_label == 'Add') {
  9714. $save['name'] = 'add';
  9715. } elseif ($save_label == 'Modify') {
  9716. $save['name'] = 'edit';
  9717. }
  9718. $cancel = array(
  9719. 'name' => 'cancel',
  9720. 'label_key' => 'Cancel',
  9721. );
  9722. !empty($save_label) ? $buttons[] = $save : '';
  9723. if (!empty($morebuttons)) {
  9724. $buttons[] = $morebuttons;
  9725. }
  9726. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9727. $retstring = $withoutdiv ? '' : '<div class="center">';
  9728. foreach ($buttons as $button) {
  9729. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9730. $retstring .= '<input type="submit" class="button button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->trans($button['label_key'])) . '">';
  9731. }
  9732. $retstring .= $withoutdiv ? '' : '</div>';
  9733. if ($dol_openinpopup) {
  9734. $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . $dol_openinpopup . ' context, so we enable the close of dialog on cancel -->' . "\n";
  9735. $retstring .= '<script nonce="' . getNonce() . '">';
  9736. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9737. e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . $dol_openinpopup . '\');
  9738. window.parent.jQuery(\'#idfordialog' . $dol_openinpopup . '\').dialog(\'close\');
  9739. });';
  9740. $retstring .= '</script>';
  9741. }
  9742. return $retstring;
  9743. }
  9744. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  9745. /**
  9746. * Load into cache list of invoice subtypes
  9747. *
  9748. * @return int Nb of lines loaded, <0 if KO
  9749. */
  9750. public function load_cache_invoice_subtype()
  9751. {
  9752. // phpcs:enable
  9753. global $langs;
  9754. $num = count($this->cache_invoice_subtype);
  9755. if ($num > 0) {
  9756. return 0; // Cache already loaded
  9757. }
  9758. dol_syslog(__METHOD__, LOG_DEBUG);
  9759. $sql = "SELECT rowid, code, label as label";
  9760. $sql .= " FROM " . MAIN_DB_PREFIX . 'c_invoice_subtype';
  9761. $sql .= " WHERE active = 1";
  9762. $resql = $this->db->query($sql);
  9763. if ($resql) {
  9764. $num = $this->db->num_rows($resql);
  9765. $i = 0;
  9766. while ($i < $num) {
  9767. $obj = $this->db->fetch_object($resql);
  9768. // If translation exists, we use it, otherwise we take the default wording
  9769. $label = ($langs->trans("InvoiceSubtype" . $obj->rowid) != "InvoiceSubtype" . $obj->rowid) ? $langs->trans("InvoiceSubtype" . $obj->rowid) : (($obj->label != '-') ? $obj->label : '');
  9770. $this->cache_invoice_subtype[$obj->rowid]['rowid'] = $obj->rowid;
  9771. $this->cache_invoice_subtype[$obj->rowid]['code'] = $obj->code;
  9772. $this->cache_invoice_subtype[$obj->rowid]['label'] = $label;
  9773. $i++;
  9774. }
  9775. $this->cache_invoice_subtype = dol_sort_array($this->cache_invoice_subtype, 'code', 'asc', 0, 0, 1);
  9776. return $num;
  9777. } else {
  9778. dol_print_error($this->db);
  9779. return -1;
  9780. }
  9781. }
  9782. /**
  9783. * Return list of invoice subtypes.
  9784. *
  9785. * @param int $selected Id of invoice subtype to preselect by default
  9786. * @param string $htmlname Select field name
  9787. * @param int $addempty Add an empty entry
  9788. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  9789. * @param string $morecss Add more CSS on select tag
  9790. * @return string String for the HTML select component
  9791. */
  9792. public function getSelectInvoiceSubtype($selected = 0, $htmlname = 'subtypeid', $addempty = 0, $noinfoadmin = 0, $morecss = '')
  9793. {
  9794. global $langs, $user;
  9795. $out = '';
  9796. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  9797. $this->load_cache_invoice_subtype();
  9798. $out .= '<select id="' . $htmlname . '" class="flat selectsubtype' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  9799. if ($addempty) {
  9800. $out .= '<option value="0">&nbsp;</option>';
  9801. }
  9802. foreach ($this->cache_invoice_subtype as $rowid => $subtype) {
  9803. $label = $subtype['label'];
  9804. $out .= '<option value="' . $subtype['rowid'] . '"';
  9805. if ($selected == $subtype['rowid']) {
  9806. $out .= ' selected="selected"';
  9807. }
  9808. $out .= '>';
  9809. $out .= $label;
  9810. $out .= '</option>';
  9811. }
  9812. $out .= '</select>';
  9813. if ($user->admin && empty($noinfoadmin)) {
  9814. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  9815. }
  9816. $out .= ajax_combobox($htmlname);
  9817. return $out;
  9818. }
  9819. }