html.form.class.php 446 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682
  1. <?php
  2. /* Copyright (c) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2006 Marc Barilley/Ocebo <marc@ocebo.com>
  10. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerker@telenet.be>
  11. * Copyright (C) 2007 Patrick Raguin <patrick.raguin@gmail.com>
  12. * Copyright (C) 2010 Juanjo Menent <jmenent@2byte.es>
  13. * Copyright (C) 2010-2021 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2011 Herve Prot <herve.prot@symeos.com>
  15. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  16. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  17. * Copyright (C) 2012-2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  18. * Copyright (C) 2014-2020 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018-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. *
  26. * This program is free software; you can redistribute it and/or modify
  27. * it under the terms of the GNU General Public License as published by
  28. * the Free Software Foundation; either version 3 of the License, or
  29. * (at your option) any later version.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU General Public License
  37. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  38. */
  39. /**
  40. * \file htdocs/core/class/html.form.class.php
  41. * \ingroup core
  42. * \brief File of class with all html predefined components
  43. */
  44. /**
  45. * Class to manage generation of HTML components
  46. * Only common components must be here.
  47. *
  48. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  49. */
  50. class Form
  51. {
  52. /**
  53. * @var DoliDB Database handler.
  54. */
  55. public $db;
  56. /**
  57. * @var string Error code (or message)
  58. */
  59. public $error = '';
  60. /**
  61. * @var string[] Array of error strings
  62. */
  63. public $errors = array();
  64. public $num;
  65. // Cache arrays
  66. public $cache_types_paiements = array();
  67. public $cache_conditions_paiements = array();
  68. public $cache_transport_mode = array();
  69. public $cache_availability = array();
  70. public $cache_demand_reason = array();
  71. public $cache_types_fees = array();
  72. public $cache_vatrates = array();
  73. /**
  74. * Constructor
  75. *
  76. * @param DoliDB $db Database handler
  77. */
  78. public function __construct($db)
  79. {
  80. $this->db = $db;
  81. }
  82. /**
  83. * Output key field for an editable field
  84. *
  85. * @param string $text Text of label or key to translate
  86. * @param string $htmlname Name of select field ('edit' prefix will be added)
  87. * @param string $preselected Value to show/edit (not used in this function)
  88. * @param object $object Object (on the page we show)
  89. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  90. * @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]'...)
  91. * @param string $moreparam More param to add on a href URL.
  92. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  93. * @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 ' '
  94. * @param string $paramid Key of parameter for id ('id', 'socid')
  95. * @param string $help Tooltip help
  96. * @return string HTML edit field
  97. */
  98. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  99. {
  100. global $conf, $langs;
  101. $ret = '';
  102. // TODO change for compatibility
  103. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  104. if (!empty($perm)) {
  105. $tmp = explode(':', $typeofdata);
  106. $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
  107. if ($fieldrequired) {
  108. $ret .= '<span class="fieldrequired">';
  109. }
  110. if ($help) {
  111. $ret .= $this->textwithpicto($langs->trans($text), $help);
  112. } else {
  113. $ret .= $langs->trans($text);
  114. }
  115. if ($fieldrequired) {
  116. $ret .= '</span>';
  117. }
  118. $ret .= '</div>' . "\n";
  119. } else {
  120. if ($fieldrequired) {
  121. $ret .= '<span class="fieldrequired">';
  122. }
  123. if ($help) {
  124. $ret .= $this->textwithpicto($langs->trans($text), $help);
  125. } else {
  126. $ret .= $langs->trans($text);
  127. }
  128. if ($fieldrequired) {
  129. $ret .= '</span>';
  130. }
  131. }
  132. } else {
  133. if (empty($notabletag) && $perm) {
  134. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  135. }
  136. if ($fieldrequired) {
  137. $ret .= '<span class="fieldrequired">';
  138. }
  139. if ($help) {
  140. $ret .= $this->textwithpicto($langs->trans($text), $help);
  141. } else {
  142. $ret .= $langs->trans($text);
  143. }
  144. if ($fieldrequired) {
  145. $ret .= '</span>';
  146. }
  147. if (!empty($notabletag)) {
  148. $ret .= ' ';
  149. }
  150. if (empty($notabletag) && $perm) {
  151. $ret .= '</td>';
  152. }
  153. if (empty($notabletag) && $perm) {
  154. $ret .= '<td class="right">';
  155. }
  156. if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
  157. $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>';
  158. }
  159. if (!empty($notabletag) && $notabletag == 1) {
  160. if ($text) {
  161. $ret .= ' : ';
  162. } else {
  163. $ret .= ' ';
  164. }
  165. }
  166. if (!empty($notabletag) && $notabletag == 3) {
  167. $ret .= ' ';
  168. }
  169. if (empty($notabletag) && $perm) {
  170. $ret .= '</td>';
  171. }
  172. if (empty($notabletag) && $perm) {
  173. $ret .= '</tr></table>';
  174. }
  175. }
  176. return $ret;
  177. }
  178. /**
  179. * Output value of a field for an editable field
  180. *
  181. * @param string $text Text of label (not used in this function)
  182. * @param string $htmlname Name of select field
  183. * @param string $value Value to show/edit
  184. * @param object $object Object (that we want to show)
  185. * @param boolean $perm Permission to allow button to edit parameter
  186. * @param string $typeofdata Type of data ('string' by default, 'checkbox', 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', '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,...')
  187. * @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
  188. * @param object $extObject External object ???
  189. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  190. * @param string $moreparam More param to add on the form on action href URL parameter
  191. * @param int $notabletag Do no output table tags
  192. * @param string $formatfunc Call a specific method of $object->$formatfunc to output field in view mode (For example: 'dol_print_email')
  193. * @param string $paramid Key of parameter for id ('id', 'socid')
  194. * @param string $gm 'auto' or 'tzuser' or 'tzuserrel' or 'tzserver' (when $typeofdata is a date)
  195. * @param array $moreoptions Array with more options. For example array('addnowlink'=>1), array('valuealreadyhtmlescaped'=>1)
  196. * @param string $editaction [=''] use GETPOST default action or set action to edit mode
  197. * @return string HTML edit field
  198. */
  199. 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 = '')
  200. {
  201. global $conf, $langs;
  202. $ret = '';
  203. // Check parameters
  204. if (empty($typeofdata)) {
  205. return 'ErrorBadParameter typeofdata is empty';
  206. }
  207. // Clean paramater $typeofdata
  208. if ($typeofdata == 'datetime') {
  209. $typeofdata = 'dayhour';
  210. }
  211. $reg = array();
  212. if (preg_match('/^(\w+)\((\d+)\)$/', $typeofdata, $reg)) {
  213. if ($reg[1] == 'varchar') {
  214. $typeofdata = 'string';
  215. } elseif ($reg[1] == 'int') {
  216. $typeofdata = 'numeric';
  217. } else {
  218. return 'ErrorBadParameter ' . $typeofdata;
  219. }
  220. }
  221. // When option to edit inline is activated
  222. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  223. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  224. } else {
  225. if ($editaction == '') {
  226. $editaction = GETPOST('action', 'aZ09');
  227. }
  228. $editmode = ($editaction == 'edit' . $htmlname);
  229. if ($editmode) {
  230. $ret .= "\n";
  231. $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
  232. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  233. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  234. $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
  235. if (empty($notabletag)) {
  236. $ret .= '<table class="nobordernopadding centpercent">';
  237. }
  238. if (empty($notabletag)) {
  239. $ret .= '<tr><td>';
  240. }
  241. if (preg_match('/^(string|safehtmlstring|email|url)/', $typeofdata)) {
  242. $tmp = explode(':', $typeofdata);
  243. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  244. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  245. $tmp = explode(':', $typeofdata);
  246. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  247. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $valuetoshow . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  248. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  249. $tmp = explode(':', $typeofdata);
  250. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  251. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  252. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  253. $tmp = explode(':', $typeofdata);
  254. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($value ? $value : 'on') . '"' . ($value ? ' checked' : '') . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
  255. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  256. $tmp = explode(':', $typeofdata);
  257. $cols = (empty($tmp[2]) ? '' : $tmp[2]);
  258. $morealt = '';
  259. if (preg_match('/%/', $cols)) {
  260. $morealt = ' style="width: ' . $cols . '"';
  261. $cols = '';
  262. }
  263. $valuetoshow = ($editvalue ? $editvalue : $value);
  264. $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . (empty($tmp[1]) ? '20' : $tmp[1]) . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '" autofocus>';
  265. // textarea convert automatically entities chars into simple chars.
  266. // 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.
  267. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  268. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  269. $ret .= '</textarea>';
  270. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  271. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  272. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  273. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  274. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  275. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  276. $addnowlink = empty($moreoptions['addnowlink']) ? 0 : $moreoptions['addnowlink'];
  277. $adddateof = empty($moreoptions['adddateof']) ? '' : $moreoptions['adddateof'];
  278. $labeladddateof = empty($moreoptions['labeladddateof']) ? '' : $moreoptions['labeladddateof'];
  279. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, $addnowlink, 0, '', '', $adddateof, '', 1, $labeladddateof, '', $gm);
  280. } elseif (preg_match('/^select;/', $typeofdata)) {
  281. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  282. $arraylist = array();
  283. foreach ($arraydata as $val) {
  284. $tmp = explode(':', $val);
  285. $tmpkey = str_replace('|', ':', $tmp[0]);
  286. $arraylist[$tmpkey] = $tmp[1];
  287. }
  288. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  289. } elseif (preg_match('/^link/', $typeofdata)) {
  290. // TODO Not yet implemented. See code for extrafields
  291. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  292. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  293. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  294. $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]));
  295. $ret .= $doleditor->Create(1);
  296. } elseif ($typeofdata == 'asis') {
  297. $ret .= ($editvalue ? $editvalue : $value);
  298. }
  299. if (empty($notabletag)) {
  300. $ret .= '</td>';
  301. }
  302. // Button save-cancel
  303. if (empty($notabletag)) {
  304. $ret .= '<td>';
  305. }
  306. //else $ret.='<div class="clearboth"></div>';
  307. $ret .= '<input type="submit" class="smallpaddingimp button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Modify") . '">';
  308. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  309. $ret .= '<br>' . "\n";
  310. }
  311. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
  312. if (empty($notabletag)) {
  313. $ret .= '</td>';
  314. }
  315. if (empty($notabletag)) {
  316. $ret .= '</tr></table>' . "\n";
  317. }
  318. $ret .= '</form>' . "\n";
  319. } else {
  320. if (preg_match('/^(email)/', $typeofdata)) {
  321. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  322. } elseif (preg_match('/^url/', $typeofdata)) {
  323. $ret .= dol_print_url($value, '_blank', 32, 1);
  324. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  325. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  326. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  327. $tmp = explode(':', $typeofdata);
  328. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($value ? ' checked' : '') . ($tmp[1] ? $tmp[1] : '') . '/>';
  329. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  330. $ret .= dol_htmlentitiesbr($value);
  331. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  332. $ret .= dol_string_onlythesehtmltags($value);
  333. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  334. $ret .= dol_string_onlythesehtmltags($value);
  335. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  336. $ret .= '<span class="valuedate">' . dol_print_date($value, 'day', $gm) . '</span>';
  337. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  338. $ret .= '<span class="valuedate">' . dol_print_date($value, 'dayhour', $gm) . '</span>';
  339. } elseif (preg_match('/^select;/', $typeofdata)) {
  340. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  341. $arraylist = array();
  342. foreach ($arraydata as $val) {
  343. $tmp = explode(':', $val);
  344. $arraylist[$tmp[0]] = $tmp[1];
  345. }
  346. $ret .= $arraylist[$value];
  347. if ($htmlname == 'fk_product_type') {
  348. if ($value == 0) {
  349. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  350. } else {
  351. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  352. }
  353. }
  354. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  355. $tmpcontent = dol_htmlentitiesbr($value);
  356. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  357. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  358. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  359. $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  360. }
  361. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  362. // clean data from some dangerous html
  363. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  364. } else {
  365. if (empty($moreoptions['valuealreadyhtmlescaped'])) {
  366. $ret .= dol_escape_htmltag($value);
  367. } else {
  368. $ret .= $value; // $value must be already html escaped.
  369. }
  370. }
  371. if ($formatfunc && method_exists($object, $formatfunc)) {
  372. $ret = $object->$formatfunc($ret);
  373. }
  374. }
  375. }
  376. return $ret;
  377. }
  378. /**
  379. * Output edit in place form
  380. *
  381. * @param string $fieldname Name of the field
  382. * @param object $object Object
  383. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  384. * @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]'...)
  385. * @param string $check Same coe than $check parameter of GETPOST()
  386. * @param string $morecss More CSS
  387. * @return string HTML code for the edit of alternative language
  388. */
  389. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  390. {
  391. global $conf, $langs, $extralanguages;
  392. $result = '';
  393. // List of extra languages
  394. $arrayoflangcode = array();
  395. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  396. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  397. }
  398. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  399. if (!is_object($extralanguages)) {
  400. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  401. $extralanguages = new ExtraLanguages($this->db);
  402. }
  403. $extralanguages->fetch_name_extralanguages('societe');
  404. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  405. return ''; // No extralang field to show
  406. }
  407. $result .= '<!-- Widget for translation -->' . "\n";
  408. $result .= '<div class="inline-block paddingleft image-' . $object->element . '-' . $fieldname . '">';
  409. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  410. $result .= $s;
  411. $result .= '</div>';
  412. $result .= '<div class="inline-block hidden field-' . $object->element . '-' . $fieldname . '">';
  413. $resultforextrlang = '';
  414. foreach ($arrayoflangcode as $langcode) {
  415. $valuetoshow = GETPOSTISSET('field-' . $object->element . "-" . $fieldname . "-" . $langcode) ? GETPOST('field-' . $object->element . '-' . $fieldname . "-" . $langcode, $check) : '';
  416. if (empty($valuetoshow)) {
  417. $object->fetchValuesForExtraLanguages();
  418. //var_dump($object->array_languages);
  419. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  420. }
  421. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  422. $resultforextrlang .= $s;
  423. // TODO Use the showInputField() method of ExtraLanguages object
  424. if ($typeofdata == 'textarea') {
  425. $resultforextrlang .= '<textarea name="field-' . $object->element . "-" . $fieldname . "-" . $langcode . '" id="' . $fieldname . "-" . $langcode . '" class="' . $morecss . '" rows="' . ROWS_2 . '" wrap="soft">';
  426. $resultforextrlang .= $valuetoshow;
  427. $resultforextrlang .= '</textarea>';
  428. } else {
  429. $resultforextrlang .= '<input type="text" class="inputfieldforlang ' . ($morecss ? ' ' . $morecss : '') . '" name="field-' . $object->element . '-' . $fieldname . '-' . $langcode . '" value="' . $valuetoshow . '">';
  430. }
  431. }
  432. $result .= $resultforextrlang;
  433. $result .= '</div>';
  434. $result .= '<script nonce="' . getNonce() . '">$(".image-' . $object->element . '-' . $fieldname . '").click(function() { console.log("Toggle lang widget"); jQuery(".field-' . $object->element . '-' . $fieldname . '").toggle(); });</script>';
  435. }
  436. return $result;
  437. }
  438. /**
  439. * Output edit in place form
  440. *
  441. * @param object $object Object
  442. * @param string $value Value to show/edit
  443. * @param string $htmlname DIV ID (field name)
  444. * @param int $condition Condition to edit
  445. * @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')
  446. * @param string $editvalue When in edit mode, use this value as $value instead of value
  447. * @param object $extObject External object
  448. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  449. * @return string HTML edit in place
  450. */
  451. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  452. {
  453. global $conf;
  454. $out = '';
  455. // Check parameters
  456. if (preg_match('/^text/', $inputType)) {
  457. $value = dol_nl2br($value);
  458. } elseif (preg_match('/^numeric/', $inputType)) {
  459. $value = price($value);
  460. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  461. $value = dol_print_date($value, 'day');
  462. }
  463. if ($condition) {
  464. $element = false;
  465. $table_element = false;
  466. $fk_element = false;
  467. $loadmethod = false;
  468. $savemethod = false;
  469. $ext_element = false;
  470. $button_only = false;
  471. $inputOption = '';
  472. $rows = '';
  473. $cols = '';
  474. if (is_object($object)) {
  475. $element = $object->element;
  476. $table_element = $object->table_element;
  477. $fk_element = $object->id;
  478. }
  479. if (is_object($extObject)) {
  480. $ext_element = $extObject->element;
  481. }
  482. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  483. $tmp = explode(':', $inputType);
  484. $inputType = $tmp[0];
  485. if (!empty($tmp[1])) {
  486. $inputOption = $tmp[1];
  487. }
  488. if (!empty($tmp[2])) {
  489. $savemethod = $tmp[2];
  490. }
  491. $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
  492. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  493. $tmp = explode(':', $inputType);
  494. $inputType = $tmp[0];
  495. if (!empty($tmp[1])) {
  496. $inputOption = $tmp[1];
  497. }
  498. if (!empty($tmp[2])) {
  499. $savemethod = $tmp[2];
  500. }
  501. $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
  502. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  503. $tmp = explode(':', $inputType);
  504. $inputType = $tmp[0];
  505. $loadmethod = $tmp[1];
  506. if (!empty($tmp[2])) {
  507. $savemethod = $tmp[2];
  508. }
  509. if (!empty($tmp[3])) {
  510. $button_only = true;
  511. }
  512. } elseif (preg_match('/^textarea/', $inputType)) {
  513. $tmp = explode(':', $inputType);
  514. $inputType = $tmp[0];
  515. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  516. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  517. } elseif (preg_match('/^ckeditor/', $inputType)) {
  518. $tmp = explode(':', $inputType);
  519. $inputType = $tmp[0];
  520. $toolbar = $tmp[1];
  521. if (!empty($tmp[2])) {
  522. $width = $tmp[2];
  523. }
  524. if (!empty($tmp[3])) {
  525. $heigth = $tmp[3];
  526. }
  527. if (!empty($tmp[4])) {
  528. $savemethod = $tmp[4];
  529. }
  530. if (isModEnabled('fckeditor')) {
  531. $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
  532. } else {
  533. $inputType = 'textarea';
  534. }
  535. }
  536. $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
  537. $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
  538. $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
  539. $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
  540. if (!empty($savemethod)) {
  541. $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
  542. }
  543. if (!empty($ext_element)) {
  544. $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
  545. }
  546. if (!empty($custommsg)) {
  547. if (is_array($custommsg)) {
  548. if (!empty($custommsg['success'])) {
  549. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
  550. }
  551. if (!empty($custommsg['error'])) {
  552. $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
  553. }
  554. } else {
  555. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
  556. }
  557. }
  558. if ($inputType == 'textarea') {
  559. $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
  560. $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
  561. }
  562. $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
  563. $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
  564. } else {
  565. $out = $value;
  566. }
  567. return $out;
  568. }
  569. /**
  570. * Show a text and picto with tooltip on text or picto.
  571. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  572. *
  573. * @param string $text Text to show
  574. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  575. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  576. * @param int $direction -1=image is before, 0=no image, 1=image is after
  577. * @param string $img Html code for image (use img_xxx() function to get it)
  578. * @param string $extracss Add a CSS style to td tags
  579. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  580. * @param string $incbefore Include code before the text
  581. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  582. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  583. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  584. * @return string Code html du tooltip (texte+picto)
  585. * @see textwithpicto() Use thisfunction if you can.
  586. */
  587. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  588. {
  589. if ($incbefore) {
  590. $text = $incbefore . $text;
  591. }
  592. if (!$htmltext) {
  593. return $text;
  594. }
  595. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  596. $tag = 'td';
  597. if ($notabs == 2) {
  598. $tag = 'div';
  599. }
  600. if ($notabs == 3) {
  601. $tag = 'span';
  602. }
  603. // Sanitize tooltip
  604. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  605. $extrastyle = '';
  606. if ($direction < 0) {
  607. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  608. $extrastyle = 'padding: 0px; padding-left: 3px;';
  609. }
  610. if ($direction > 0) {
  611. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  612. $extrastyle = 'padding: 0px; padding-right: 3px;';
  613. }
  614. $classfortooltip = 'classfortooltip';
  615. $s = '';
  616. $textfordialog = '';
  617. if ($tooltiptrigger == '') {
  618. $htmltext = str_replace('"', '&quot;', $htmltext);
  619. } else {
  620. $classfortooltip = 'classfortooltiponclick';
  621. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext">' . $htmltext . '</div>';
  622. }
  623. if ($tooltipon == 2 || $tooltipon == 3) {
  624. $paramfortooltipimg = ' class="' . $classfortooltip . ($notabs != 3 ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
  625. if ($tooltiptrigger == '') {
  626. $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on img tag to store tooltip
  627. } else {
  628. $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
  629. }
  630. } else {
  631. $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  632. }
  633. if ($tooltipon == 1 || $tooltipon == 3) {
  634. $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ' inline-block' . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
  635. if ($tooltiptrigger == '') {
  636. $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on td tag to store tooltip
  637. } else {
  638. $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
  639. }
  640. } else {
  641. $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  642. }
  643. if (empty($notabs)) {
  644. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  645. } elseif ($notabs == 2) {
  646. $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
  647. }
  648. // Define value if value is before
  649. if ($direction < 0) {
  650. $s .= '<' . $tag . $paramfortooltipimg;
  651. if ($tag == 'td') {
  652. $s .= ' class="valigntop" width="14"';
  653. }
  654. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  655. }
  656. // Use another method to help avoid having a space in value in order to use this value with jquery
  657. // Define label
  658. if ((string) $text != '') {
  659. $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
  660. }
  661. // Define value if value is after
  662. if ($direction > 0) {
  663. $s .= '<' . $tag . $paramfortooltipimg;
  664. if ($tag == 'td') {
  665. $s .= ' class="valignmiddle" width="14"';
  666. }
  667. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  668. }
  669. if (empty($notabs)) {
  670. $s .= '</tr></table>';
  671. } elseif ($notabs == 2) {
  672. $s .= '</div>';
  673. }
  674. return $s;
  675. }
  676. /**
  677. * Show a text with a picto and a tooltip on picto
  678. *
  679. * @param string $text Text to show
  680. * @param string $htmltext Content of tooltip
  681. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  682. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  683. * @param string $extracss Add a CSS style to td, div or span tag
  684. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  685. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  686. * @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')
  687. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  688. * @return string HTML code of text, picto, tooltip
  689. */
  690. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  691. {
  692. global $conf, $langs;
  693. //For backwards compatibility
  694. if ($type == '0') {
  695. $type = 'info';
  696. } elseif ($type == '1') {
  697. $type = 'help';
  698. }
  699. if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
  700. $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
  701. }
  702. $alt = '';
  703. if ($tooltiptrigger) {
  704. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  705. }
  706. // If info or help with no javascript, show only text
  707. if (empty($conf->use_javascript_ajax)) {
  708. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  709. return $text;
  710. } else {
  711. $alt = $htmltext;
  712. $htmltext = '';
  713. }
  714. }
  715. // If info or help with smartphone, show only text (tooltip hover can't works)
  716. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  717. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  718. return $text;
  719. }
  720. }
  721. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  722. //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
  723. //{
  724. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.'</a>';
  725. //}
  726. $img = '';
  727. if ($type == 'info') {
  728. $img = img_help(0, $alt);
  729. } elseif ($type == 'help') {
  730. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  731. } elseif ($type == 'helpclickable') {
  732. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  733. } elseif ($type == 'superadmin') {
  734. $img = img_picto($alt, 'redstar');
  735. } elseif ($type == 'admin') {
  736. $img = img_picto($alt, 'star');
  737. } elseif ($type == 'warning') {
  738. $img = img_warning($alt);
  739. } elseif ($type != 'none') {
  740. $img = img_picto($alt, $type); // $type can be an image path
  741. }
  742. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  743. }
  744. /**
  745. * Generate select HTML to choose massaction
  746. *
  747. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  748. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  749. * @param int $alwaysvisible 1=select button always visible
  750. * @param string $name Name for massaction
  751. * @param string $cssclass CSS class used to check for select
  752. * @return string|void Select list
  753. */
  754. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  755. {
  756. global $conf, $langs, $hookmanager;
  757. $disabled = 0;
  758. $ret = '<div class="centpercent center">';
  759. $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'select valignmiddle alignstart" id="' . $name . '" name="' . $name . '"' . ($disabled ? ' disabled="disabled"' : '') . '>';
  760. // 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.
  761. $parameters = array();
  762. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  763. // check if there is a mass action
  764. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  765. return;
  766. }
  767. if (empty($reshook)) {
  768. $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
  769. foreach ($arrayofaction as $code => $label) {
  770. $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . ' data-html="' . dol_escape_htmltag($label) . '">' . $label . '</option>';
  771. }
  772. }
  773. $ret .= $hookmanager->resPrint;
  774. $ret .= '</select>';
  775. if (empty($conf->dol_optimize_smallscreen)) {
  776. $ret .= ajax_combobox('.' . $name . 'select');
  777. }
  778. // 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
  779. $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.
  780. $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")) . '">';
  781. $ret .= '</div>';
  782. if (!empty($conf->use_javascript_ajax)) {
  783. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  784. <script nonce="' . getNonce() . '">
  785. 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 */
  786. {
  787. atleastoneselected=0;
  788. jQuery("."+cssclass).each(function( index ) {
  789. /* console.log( index + ": " + $( this ).text() ); */
  790. if ($(this).is(\':checked\')) atleastoneselected++;
  791. });
  792. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  793. if (atleastoneselected || ' . $alwaysvisible . ')
  794. {
  795. jQuery("."+name).show();
  796. ' . ($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("' . $selected . '").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '') . '
  797. ' . ($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '') . '
  798. }
  799. else
  800. {
  801. jQuery("."+name).hide();
  802. jQuery("."+name+"other").hide();
  803. }
  804. }
  805. jQuery(document).ready(function () {
  806. initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
  807. jQuery(".' . $cssclass . '").click(function() {
  808. initCheckForSelect(1, "' . $name . '", "' . $cssclass . '");
  809. });
  810. jQuery(".' . $name . 'select").change(function() {
  811. var massaction = $( this ).val();
  812. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  813. if (massaction == "builddoc")
  814. {
  815. urlform = urlform + "#show_files";
  816. }
  817. $( this ).closest("form").attr("action", urlform);
  818. console.log("we select a mass action name=' . $name . ' massaction="+massaction+" - "+urlform);
  819. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  820. if ($(this).val() != \'0\')
  821. {
  822. jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
  823. jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
  824. jQuery(".' . $name . '"+massaction).show();
  825. }
  826. else
  827. {
  828. jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
  829. jQuery(".' . $name . 'other").hide(); /* To disable any div open */
  830. }
  831. });
  832. });
  833. </script>
  834. ';
  835. }
  836. return $ret;
  837. }
  838. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  839. /**
  840. * Return combo list of activated countries, into language of user
  841. *
  842. * @param string $selected Id or Code or Label of preselected country
  843. * @param string $htmlname Name of html select object
  844. * @param string $htmloption More html options on select object
  845. * @param integer $maxlength Max length for labels (0=no limit)
  846. * @param string $morecss More css class
  847. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  848. * @param int|string $showempty Show empty choice
  849. * @param int $disablefavorites 1=Disable favorites,
  850. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  851. * @param array $exclude_country_code Array of country code (iso2) to exclude
  852. * @param int $hideflags Hide flags
  853. * @return string HTML string with select
  854. */
  855. 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)
  856. {
  857. // phpcs:enable
  858. global $conf, $langs, $mysoc;
  859. $langs->load("dict");
  860. $out = '';
  861. $countryArray = array();
  862. $favorite = array();
  863. $label = array();
  864. $atleastonefavorite = 0;
  865. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  866. $sql .= " FROM " . $this->db->prefix() . "c_country";
  867. $sql .= " WHERE active > 0";
  868. //$sql.= " ORDER BY code ASC";
  869. dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
  870. $resql = $this->db->query($sql);
  871. if ($resql) {
  872. $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
  873. $num = $this->db->num_rows($resql);
  874. $i = 0;
  875. if ($num) {
  876. while ($i < $num) {
  877. $obj = $this->db->fetch_object($resql);
  878. $countryArray[$i]['rowid'] = $obj->rowid;
  879. $countryArray[$i]['code_iso'] = $obj->code_iso;
  880. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  881. $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 : ''));
  882. $countryArray[$i]['favorite'] = $obj->favorite;
  883. $countryArray[$i]['eec'] = $obj->eec;
  884. $favorite[$i] = $obj->favorite;
  885. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  886. $i++;
  887. }
  888. if (empty($disablefavorites)) {
  889. $array1_sort_order = SORT_DESC;
  890. $array2_sort_order = SORT_ASC;
  891. array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
  892. } else {
  893. $countryArray = dol_sort_array($countryArray, 'label');
  894. }
  895. if ($showempty) {
  896. if (is_numeric($showempty)) {
  897. $out .= '<option value="">&nbsp;</option>' . "\n";
  898. } else {
  899. $out .= '<option value="-1">' . $langs->trans($showempty) . '</option>' . "\n";
  900. }
  901. }
  902. if ($addspecialentries) { // Add dedicated entries for groups of countries
  903. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  904. $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  905. $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
  906. if ($mysoc->isInEEC()) {
  907. $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  908. }
  909. $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
  910. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  911. }
  912. foreach ($countryArray as $row) {
  913. //if (empty($showempty) && empty($row['rowid'])) continue;
  914. if (empty($row['rowid'])) {
  915. continue;
  916. }
  917. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  918. continue; // exclude some countries
  919. }
  920. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  921. $atleastonefavorite++;
  922. }
  923. if (empty($row['favorite']) && $atleastonefavorite) {
  924. $atleastonefavorite = 0;
  925. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  926. }
  927. $labeltoshow = '';
  928. if ($row['label']) {
  929. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  930. } else {
  931. $labeltoshow .= '&nbsp;';
  932. }
  933. if ($row['code_iso']) {
  934. $labeltoshow .= ' <span class="opacitymedium">(' . $row['code_iso'] . ')</span>';
  935. if (empty($hideflags)) {
  936. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  937. $labeltoshow = $tmpflag . ' ' . $labeltoshow;
  938. }
  939. }
  940. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  941. $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']) . '">';
  942. } else {
  943. $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']) . '">';
  944. }
  945. $out .= $labeltoshow;
  946. $out .= '</option>' . "\n";
  947. }
  948. }
  949. $out .= '</select>';
  950. } else {
  951. dol_print_error($this->db);
  952. }
  953. // Make select dynamic
  954. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  955. $out .= ajax_combobox('select' . $htmlname, array(), 0, 0, 'resolve');
  956. return $out;
  957. }
  958. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  959. /**
  960. * Return select list of incoterms
  961. *
  962. * @param string $selected Id or Code of preselected incoterm
  963. * @param string $location_incoterms Value of input location
  964. * @param string $page Defined the form action
  965. * @param string $htmlname Name of html select object
  966. * @param string $htmloption Options html on select object
  967. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  968. * @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')))
  969. * @param array $disableautocomplete Disable autocomplete
  970. * @return string HTML string with select and input
  971. */
  972. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  973. {
  974. // phpcs:enable
  975. global $conf, $langs;
  976. $langs->load("dict");
  977. $out = '';
  978. $moreattrib = '';
  979. $incotermArray = array();
  980. $sql = "SELECT rowid, code";
  981. $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
  982. $sql .= " WHERE active > 0";
  983. $sql .= " ORDER BY code ASC";
  984. dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
  985. $resql = $this->db->query($sql);
  986. if ($resql) {
  987. if ($conf->use_javascript_ajax && !$forcecombo) {
  988. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  989. $out .= ajax_combobox($htmlname, $events);
  990. }
  991. if (!empty($page)) {
  992. $out .= '<form method="post" action="' . $page . '">';
  993. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  994. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  995. }
  996. $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
  997. $out .= '<option value="0">&nbsp;</option>';
  998. $num = $this->db->num_rows($resql);
  999. $i = 0;
  1000. if ($num) {
  1001. while ($i < $num) {
  1002. $obj = $this->db->fetch_object($resql);
  1003. $incotermArray[$i]['rowid'] = $obj->rowid;
  1004. $incotermArray[$i]['code'] = $obj->code;
  1005. $i++;
  1006. }
  1007. foreach ($incotermArray as $row) {
  1008. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  1009. $out .= '<option value="' . $row['rowid'] . '" selected>';
  1010. } else {
  1011. $out .= '<option value="' . $row['rowid'] . '">';
  1012. }
  1013. if ($row['code']) {
  1014. $out .= $row['code'];
  1015. }
  1016. $out .= '</option>';
  1017. }
  1018. }
  1019. $out .= '</select>';
  1020. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  1021. $out .= ajax_multiautocompleter('location_incoterms', array(), DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
  1022. $moreattrib .= ' autocomplete="off"';
  1023. }
  1024. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
  1025. if (!empty($page)) {
  1026. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
  1027. }
  1028. } else {
  1029. dol_print_error($this->db);
  1030. }
  1031. return $out;
  1032. }
  1033. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1034. /**
  1035. * Return list of types of lines (product or service)
  1036. * Example: 0=product, 1=service, 9=other (for external module)
  1037. *
  1038. * @param string $selected Preselected type
  1039. * @param string $htmlname Name of field in html form
  1040. * @param int $showempty Add an empty field
  1041. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  1042. * @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')
  1043. * @return void
  1044. */
  1045. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  1046. {
  1047. // phpcs:enable
  1048. global $langs, $conf;
  1049. // If product & services are enabled or both disabled.
  1050. if ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
  1051. || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
  1052. if (empty($hidetext)) {
  1053. print $langs->trans("Type") . ': ';
  1054. }
  1055. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  1056. if ($showempty) {
  1057. print '<option value="-1"';
  1058. if ($selected == -1) {
  1059. print ' selected';
  1060. }
  1061. print '>&nbsp;</option>';
  1062. }
  1063. print '<option value="0"';
  1064. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1065. print ' selected';
  1066. }
  1067. print '>' . $langs->trans("Product");
  1068. print '<option value="1"';
  1069. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1070. print ' selected';
  1071. }
  1072. print '>' . $langs->trans("Service");
  1073. print '</select>';
  1074. print ajax_combobox('select_' . $htmlname);
  1075. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1076. }
  1077. if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
  1078. print $langs->trans("Service");
  1079. print '<input type="hidden" name="' . $htmlname . '" value="1">';
  1080. }
  1081. if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
  1082. print $langs->trans("Product");
  1083. print '<input type="hidden" name="' . $htmlname . '" value="0">';
  1084. }
  1085. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1086. 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
  1087. }
  1088. }
  1089. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1090. /**
  1091. * Load into cache cache_types_fees, array of types of fees
  1092. *
  1093. * @return int Nb of lines loaded, <0 if KO
  1094. */
  1095. public function load_cache_types_fees()
  1096. {
  1097. // phpcs:enable
  1098. global $langs;
  1099. $num = count($this->cache_types_fees);
  1100. if ($num > 0) {
  1101. return 0; // Cache already loaded
  1102. }
  1103. dol_syslog(__METHOD__, LOG_DEBUG);
  1104. $langs->load("trips");
  1105. $sql = "SELECT c.code, c.label";
  1106. $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
  1107. $sql .= " WHERE active > 0";
  1108. $resql = $this->db->query($sql);
  1109. if ($resql) {
  1110. $num = $this->db->num_rows($resql);
  1111. $i = 0;
  1112. while ($i < $num) {
  1113. $obj = $this->db->fetch_object($resql);
  1114. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1115. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1116. $this->cache_types_fees[$obj->code] = $label;
  1117. $i++;
  1118. }
  1119. asort($this->cache_types_fees);
  1120. return $num;
  1121. } else {
  1122. dol_print_error($this->db);
  1123. return -1;
  1124. }
  1125. }
  1126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1127. /**
  1128. * Return list of types of notes
  1129. *
  1130. * @param string $selected Preselected type
  1131. * @param string $htmlname Name of field in form
  1132. * @param int $showempty Add an empty field
  1133. * @return void
  1134. */
  1135. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1136. {
  1137. // phpcs:enable
  1138. global $user, $langs;
  1139. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  1140. $this->load_cache_types_fees();
  1141. print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
  1142. if ($showempty) {
  1143. print '<option value="-1"';
  1144. if ($selected == -1) {
  1145. print ' selected';
  1146. }
  1147. print '>&nbsp;</option>';
  1148. }
  1149. foreach ($this->cache_types_fees as $key => $value) {
  1150. print '<option value="' . $key . '"';
  1151. if ($key == $selected) {
  1152. print ' selected';
  1153. }
  1154. print '>';
  1155. print $value;
  1156. print '</option>';
  1157. }
  1158. print '</select>';
  1159. if ($user->admin) {
  1160. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1161. }
  1162. }
  1163. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1164. /**
  1165. * Output html form to select a third party
  1166. *
  1167. * @param string $selected Preselected type
  1168. * @param string $htmlname Name of field in form
  1169. * @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.
  1170. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1171. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1172. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1173. * @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')))
  1174. * @param int $limit Maximum number of elements
  1175. * @param string $morecss Add more css styles to the SELECT component
  1176. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1177. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1178. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1179. * @param array $ajaxoptions Options for ajax_autocompleter
  1180. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1181. * @param array $excludeids Exclude IDs from the select combo
  1182. * @param int $showcode Show code
  1183. * @return string HTML string with select box for thirdparty.
  1184. */
  1185. 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)
  1186. {
  1187. // phpcs:enable
  1188. global $conf, $user, $langs;
  1189. $out = '';
  1190. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1191. if (is_null($ajaxoptions)) {
  1192. $ajaxoptions = array();
  1193. }
  1194. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1195. // No immediate load of all database
  1196. $placeholder = '';
  1197. if ($selected && empty($selected_input_value)) {
  1198. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1199. $societetmp = new Societe($this->db);
  1200. $societetmp->fetch($selected);
  1201. $selected_input_value = $societetmp->name;
  1202. unset($societetmp);
  1203. }
  1204. // mode 1
  1205. $urloption = 'htmlname=' . urlencode(str_replace('.', '_', $htmlname)) . '&outjson=1&filter=' . urlencode($filter) . (empty($excludeids) ? '' : '&excludeids=' . join(',', $excludeids)) . ($showtype ? '&showtype=' . urlencode($showtype) : '') . ($showcode ? '&showcode=' . urlencode($showcode) : '');
  1206. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1207. if (empty($hidelabel)) {
  1208. print $langs->trans("RefOrLabel") . ' : ';
  1209. } elseif ($hidelabel > 1) {
  1210. $placeholder = $langs->trans("RefOrLabel");
  1211. if ($hidelabel == 2) {
  1212. $out .= img_picto($langs->trans("Search"), 'search');
  1213. }
  1214. }
  1215. $out .= '<input type="text" class="' . $morecss . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '') . ' ' . (!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  1216. if ($hidelabel == 3) {
  1217. $out .= img_picto($langs->trans("Search"), 'search');
  1218. }
  1219. $out .= ajax_event($htmlname, $events);
  1220. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1221. } else {
  1222. // Immediate load of all database
  1223. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1224. }
  1225. return $out;
  1226. }
  1227. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1228. /**
  1229. * Output html form to select a third party.
  1230. * 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.
  1231. *
  1232. * @param string $selected Preselected type
  1233. * @param string $htmlname Name of field in form
  1234. * @param string $filter Optional filters criteras. WARNING: To avoid SQL injection, only few chars [.a-z0-9 =<>] are allowed here, example: 's.rowid <> x'
  1235. * If you need parenthesis, use the Universal Filter Syntax, example: '(s.client:in:(1,3))'
  1236. * Do not use a filter coming from input of users.
  1237. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1238. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1239. * @param int $forcecombo Force to use standard HTML select component without beautification
  1240. * @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')))
  1241. * @param string $filterkey Filter on key value
  1242. * @param int $outputmode 0=HTML select string, 1=Array
  1243. * @param int $limit Limit number of answers
  1244. * @param string $morecss Add more css styles to the SELECT component
  1245. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1246. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1247. * @param array $excludeids Exclude IDs from the select combo
  1248. * @param int $showcode Show code in list
  1249. * @return array|string HTML string with
  1250. */
  1251. 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)
  1252. {
  1253. // phpcs:enable
  1254. global $conf, $user, $langs;
  1255. global $hookmanager;
  1256. $out = '';
  1257. $num = 0;
  1258. $outarray = array();
  1259. if ($selected === '') {
  1260. $selected = array();
  1261. } elseif (!is_array($selected)) {
  1262. $selected = array($selected);
  1263. }
  1264. // Clean $filter that may contains sql conditions so sql code
  1265. if (function_exists('testSqlAndScriptInject')) {
  1266. if (testSqlAndScriptInject($filter, 3) > 0) {
  1267. $filter = '';
  1268. return 'SQLInjectionTryDetected';
  1269. }
  1270. }
  1271. if (preg_match('/[\(\)]/', $filter)) {
  1272. // If there is one parenthesis inside the criteria, we assume it is an Universal Filter Syntax.
  1273. $errormsg = '';
  1274. $filter = forgeSQLFromUniversalSearchCriteria($filter, $errormsg, 1);
  1275. // Redo 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. } else {
  1283. // If not, we do nothing. We already no that there is no parenthesis
  1284. // TODO Disallow this case in a future.
  1285. dol_syslog("Warning, select_thirdparty_list was called with a filter criteria not using the Universal Search Syntax.", LOG_WARNING);
  1286. }
  1287. // We search companies
  1288. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1289. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1290. $sql .= ", s.address, s.zip, s.town";
  1291. $sql .= ", dictp.code as country_code";
  1292. }
  1293. $sql .= " FROM " . $this->db->prefix() . "societe as s";
  1294. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1295. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
  1296. }
  1297. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1298. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  1299. }
  1300. $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
  1301. if (!empty($user->socid)) {
  1302. $sql .= " AND s.rowid = " . ((int) $user->socid);
  1303. }
  1304. if ($filter) {
  1305. // $filter is safe because, if it contains '(' or ')', it has been sanitized by testSqlAndScriptInject() and forgeSQLFromUniversalSearchCriteria()
  1306. // if not, by testSqlAndScriptInject() only.
  1307. $sql .= " AND (" . $filter . ")";
  1308. }
  1309. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1310. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  1311. }
  1312. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1313. $sql .= " AND s.status <> 0";
  1314. }
  1315. if (!empty($excludeids)) {
  1316. $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(join(',', $excludeids)) . ")";
  1317. }
  1318. // Add where from hooks
  1319. $parameters = array();
  1320. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1321. $sql .= $hookmanager->resPrint;
  1322. // Add criteria
  1323. if ($filterkey && $filterkey != '') {
  1324. $sql .= " AND (";
  1325. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1326. // For natural search
  1327. $scrit = explode(' ', $filterkey);
  1328. $i = 0;
  1329. if (count($scrit) > 1) {
  1330. $sql .= "(";
  1331. }
  1332. foreach ($scrit as $crit) {
  1333. if ($i > 0) {
  1334. $sql .= " AND ";
  1335. }
  1336. $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  1337. $i++;
  1338. }
  1339. if (count($scrit) > 1) {
  1340. $sql .= ")";
  1341. }
  1342. if (isModEnabled('barcode')) {
  1343. $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1344. }
  1345. $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1346. $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1347. $sql .= ")";
  1348. }
  1349. $sql .= $this->db->order("nom", "ASC");
  1350. $sql .= $this->db->plimit($limit, 0);
  1351. // Build output string
  1352. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1353. $resql = $this->db->query($sql);
  1354. if ($resql) {
  1355. if (!$forcecombo) {
  1356. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1357. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1358. }
  1359. // Construct $out and $outarray
  1360. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . '>' . "\n";
  1361. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1362. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1363. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1364. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1365. if ($showempty && !is_numeric($showempty)) {
  1366. $textifempty = $langs->trans($showempty);
  1367. } else {
  1368. $textifempty .= $langs->trans("All");
  1369. }
  1370. }
  1371. if ($showempty) {
  1372. $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
  1373. }
  1374. $companytemp = new Societe($this->db);
  1375. $num = $this->db->num_rows($resql);
  1376. $i = 0;
  1377. if ($num) {
  1378. while ($i < $num) {
  1379. $obj = $this->db->fetch_object($resql);
  1380. $label = '';
  1381. if ($showcode || !empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) {
  1382. if (($obj->client) && (!empty($obj->code_client))) {
  1383. $label = $obj->code_client . ' - ';
  1384. }
  1385. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1386. $label .= $obj->code_fournisseur . ' - ';
  1387. }
  1388. $label .= ' ' . $obj->name;
  1389. } else {
  1390. $label = $obj->name;
  1391. }
  1392. if (!empty($obj->name_alias)) {
  1393. $label .= ' (' . $obj->name_alias . ')';
  1394. }
  1395. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1396. $label .= ' - '.$obj->tva_intra;
  1397. }
  1398. $labelhtml = $label;
  1399. if ($showtype) {
  1400. $companytemp->id = $obj->rowid;
  1401. $companytemp->client = $obj->client;
  1402. $companytemp->fournisseur = $obj->fournisseur;
  1403. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1404. if ($tmptype) {
  1405. $labelhtml .= ' ' . $tmptype;
  1406. }
  1407. if ($obj->client || $obj->fournisseur) {
  1408. $label .= ' (';
  1409. }
  1410. if ($obj->client == 1 || $obj->client == 3) {
  1411. $label .= $langs->trans("Customer");
  1412. }
  1413. if ($obj->client == 2 || $obj->client == 3) {
  1414. $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
  1415. }
  1416. if ($obj->fournisseur) {
  1417. $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
  1418. }
  1419. if ($obj->client || $obj->fournisseur) {
  1420. $label .= ')';
  1421. }
  1422. }
  1423. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1424. $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
  1425. if (!empty($obj->country_code)) {
  1426. $s .= ', ' . $langs->trans('Country' . $obj->country_code);
  1427. }
  1428. $label .= $s;
  1429. $labelhtml .= $s;
  1430. }
  1431. if (empty($outputmode)) {
  1432. if (in_array($obj->rowid, $selected)) {
  1433. $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml) . '">' . $label . '</option>';
  1434. } else {
  1435. $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml) . '">' . $label . '</option>';
  1436. }
  1437. } else {
  1438. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
  1439. }
  1440. $i++;
  1441. if (($i % 10) == 0) {
  1442. $out .= "\n";
  1443. }
  1444. }
  1445. }
  1446. $out .= '</select>' . "\n";
  1447. } else {
  1448. dol_print_error($this->db);
  1449. }
  1450. $this->result = array('nbofthirdparties' => $num);
  1451. if ($outputmode) {
  1452. return $outarray;
  1453. }
  1454. return $out;
  1455. }
  1456. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1457. /**
  1458. * Return HTML combo list of absolute discounts
  1459. *
  1460. * @param string $selected Id remise fixe pre-selectionnee
  1461. * @param string $htmlname Nom champ formulaire
  1462. * @param string $filter Criteres optionnels de filtre
  1463. * @param int $socid Id of thirdparty
  1464. * @param int $maxvalue Max value for lines that can be selected
  1465. * @return int Return number of qualifed lines in list
  1466. */
  1467. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1468. {
  1469. // phpcs:enable
  1470. global $langs, $conf;
  1471. // On recherche les remises
  1472. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1473. $sql .= " re.description, re.fk_facture_source";
  1474. $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
  1475. $sql .= " WHERE re.fk_soc = " . (int) $socid;
  1476. $sql .= " AND re.entity = " . $conf->entity;
  1477. if ($filter) {
  1478. $sql .= " AND " . $filter;
  1479. }
  1480. $sql .= " ORDER BY re.description ASC";
  1481. dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
  1482. $resql = $this->db->query($sql);
  1483. if ($resql) {
  1484. print '<select id="select_' . $htmlname . '" class="flat maxwidthonsmartphone" name="' . $htmlname . '">';
  1485. $num = $this->db->num_rows($resql);
  1486. $qualifiedlines = $num;
  1487. $i = 0;
  1488. if ($num) {
  1489. print '<option value="0">&nbsp;</option>';
  1490. while ($i < $num) {
  1491. $obj = $this->db->fetch_object($resql);
  1492. $desc = dol_trunc($obj->description, 40);
  1493. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1494. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1495. }
  1496. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1497. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1498. }
  1499. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1500. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1501. }
  1502. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1503. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1504. }
  1505. $selectstring = '';
  1506. if ($selected > 0 && $selected == $obj->rowid) {
  1507. $selectstring = ' selected';
  1508. }
  1509. $disabled = '';
  1510. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1511. $qualifiedlines--;
  1512. $disabled = ' disabled';
  1513. }
  1514. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1515. $tmpfac = new Facture($this->db);
  1516. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1517. $desc = $desc . ' - ' . $tmpfac->ref;
  1518. }
  1519. }
  1520. print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  1521. $i++;
  1522. }
  1523. }
  1524. print '</select>';
  1525. print ajax_combobox('select_' . $htmlname);
  1526. return $qualifiedlines;
  1527. } else {
  1528. dol_print_error($this->db);
  1529. return -1;
  1530. }
  1531. }
  1532. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1533. /**
  1534. * Return list of all contacts (for a third party or all)
  1535. *
  1536. * @param int $socid Id ot third party or 0 for all
  1537. * @param string $selected Id contact pre-selectionne
  1538. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1539. * @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
  1540. * @param string $exclude List of contacts id to exclude
  1541. * @param string $limitto Disable answers that are not id in this array list
  1542. * @param integer $showfunction Add function into label
  1543. * @param string $morecss Add more class to class style
  1544. * @param integer $showsoc Add company into label
  1545. * @param int $forcecombo Force to use combo box
  1546. * @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')))
  1547. * @param bool $options_only Return options only (for ajax treatment)
  1548. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1549. * @param string $htmlid Html id to use instead of htmlname
  1550. * @return int <0 if KO, Nb of contact in list if OK
  1551. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1552. */
  1553. 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 = '')
  1554. {
  1555. // phpcs:enable
  1556. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1557. return $this->num;
  1558. }
  1559. /**
  1560. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1561. * This also set the number of contacts found into $this->num
  1562. *
  1563. * @since 9.0 Add afterSelectContactOptions hook
  1564. *
  1565. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1566. * @param array|int $selected Array of ID of pre-selected contact id
  1567. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1568. * @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
  1569. * @param string $exclude List of contacts id to exclude
  1570. * @param string $limitto Disable answers that are not id in this array list
  1571. * @param integer $showfunction Add function into label
  1572. * @param string $morecss Add more class to class style
  1573. * @param bool $options_only Return options only (for ajax treatment)
  1574. * @param integer $showsoc Add company into label
  1575. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1576. * @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')))
  1577. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1578. * @param string $htmlid Html id to use instead of htmlname
  1579. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1580. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1581. * @return int|string <0 if KO, HTML with select string if OK.
  1582. */
  1583. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $morecss = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false, $disableifempty = 0)
  1584. {
  1585. global $conf, $langs, $hookmanager, $action;
  1586. $langs->load('companies');
  1587. if (empty($htmlid)) {
  1588. $htmlid = $htmlname;
  1589. }
  1590. $num = 0;
  1591. if ($selected === '') {
  1592. $selected = array();
  1593. } elseif (!is_array($selected)) {
  1594. $selected = array($selected);
  1595. }
  1596. $out = '';
  1597. if (!is_object($hookmanager)) {
  1598. include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  1599. $hookmanager = new HookManager($this->db);
  1600. }
  1601. // We search third parties
  1602. $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";
  1603. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1604. $sql .= ", s.nom as company, s.town AS company_town";
  1605. }
  1606. $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
  1607. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1608. $sql .= " LEFT OUTER JOIN " . $this->db->prefix() . "societe as s ON s.rowid=sp.fk_soc";
  1609. }
  1610. $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
  1611. if ($socid > 0 || $socid == -1) {
  1612. $sql .= " AND sp.fk_soc = " . ((int) $socid);
  1613. }
  1614. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1615. $sql .= " AND sp.statut <> 0";
  1616. }
  1617. // Add where from hooks
  1618. $parameters = array();
  1619. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1620. $sql .= $hookmanager->resPrint;
  1621. $sql .= " ORDER BY sp.lastname ASC";
  1622. dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
  1623. $resql = $this->db->query($sql);
  1624. if ($resql) {
  1625. $num = $this->db->num_rows($resql);
  1626. if ($htmlname != 'none' && !$options_only) {
  1627. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
  1628. }
  1629. if ($showempty && !is_numeric($showempty)) {
  1630. $textforempty = $showempty;
  1631. $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>';
  1632. } else {
  1633. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
  1634. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
  1635. }
  1636. if ($showempty == 2) {
  1637. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
  1638. }
  1639. }
  1640. $i = 0;
  1641. if ($num) {
  1642. include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  1643. $contactstatic = new Contact($this->db);
  1644. while ($i < $num) {
  1645. $obj = $this->db->fetch_object($resql);
  1646. // Set email (or phones) and town extended infos
  1647. $extendedInfos = '';
  1648. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1649. $extendedInfos = array();
  1650. $email = trim($obj->email);
  1651. if (!empty($email)) {
  1652. $extendedInfos[] = $email;
  1653. } else {
  1654. $phone = trim($obj->phone);
  1655. $phone_perso = trim($obj->phone_perso);
  1656. $phone_mobile = trim($obj->phone_mobile);
  1657. if (!empty($phone)) {
  1658. $extendedInfos[] = $phone;
  1659. }
  1660. if (!empty($phone_perso)) {
  1661. $extendedInfos[] = $phone_perso;
  1662. }
  1663. if (!empty($phone_mobile)) {
  1664. $extendedInfos[] = $phone_mobile;
  1665. }
  1666. }
  1667. $contact_town = trim($obj->contact_town);
  1668. $company_town = trim($obj->company_town);
  1669. if (!empty($contact_town)) {
  1670. $extendedInfos[] = $contact_town;
  1671. } elseif (!empty($company_town)) {
  1672. $extendedInfos[] = $company_town;
  1673. }
  1674. $extendedInfos = implode(' - ', $extendedInfos);
  1675. if (!empty($extendedInfos)) {
  1676. $extendedInfos = ' - ' . $extendedInfos;
  1677. }
  1678. }
  1679. $contactstatic->id = $obj->rowid;
  1680. $contactstatic->lastname = $obj->lastname;
  1681. $contactstatic->firstname = $obj->firstname;
  1682. if ($obj->statut == 1) {
  1683. if ($htmlname != 'none') {
  1684. $disabled = 0;
  1685. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1686. $disabled = 1;
  1687. }
  1688. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1689. $disabled = 1;
  1690. }
  1691. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1692. $out .= '<option value="' . $obj->rowid . '"';
  1693. if ($disabled) {
  1694. $out .= ' disabled';
  1695. }
  1696. $out .= ' selected>';
  1697. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1698. if ($showfunction && $obj->poste) {
  1699. $out .= ' (' . $obj->poste . ')';
  1700. }
  1701. if (($showsoc > 0) && $obj->company) {
  1702. $out .= ' - (' . $obj->company . ')';
  1703. }
  1704. $out .= '</option>';
  1705. } else {
  1706. $out .= '<option value="' . $obj->rowid . '"';
  1707. if ($disabled) {
  1708. $out .= ' disabled';
  1709. }
  1710. $out .= '>';
  1711. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1712. if ($showfunction && $obj->poste) {
  1713. $out .= ' (' . $obj->poste . ')';
  1714. }
  1715. if (($showsoc > 0) && $obj->company) {
  1716. $out .= ' - (' . $obj->company . ')';
  1717. }
  1718. $out .= '</option>';
  1719. }
  1720. } else {
  1721. if (in_array($obj->rowid, $selected)) {
  1722. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1723. if ($showfunction && $obj->poste) {
  1724. $out .= ' (' . $obj->poste . ')';
  1725. }
  1726. if (($showsoc > 0) && $obj->company) {
  1727. $out .= ' - (' . $obj->company . ')';
  1728. }
  1729. }
  1730. }
  1731. }
  1732. $i++;
  1733. }
  1734. } else {
  1735. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1736. $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
  1737. $out .= $labeltoshow;
  1738. $out .= '</option>';
  1739. }
  1740. $parameters = array(
  1741. 'socid' => $socid,
  1742. 'htmlname' => $htmlname,
  1743. 'resql' => $resql,
  1744. 'out' => &$out,
  1745. 'showfunction' => $showfunction,
  1746. 'showsoc' => $showsoc,
  1747. );
  1748. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1749. if ($htmlname != 'none' && !$options_only) {
  1750. $out .= '</select>';
  1751. }
  1752. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1753. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1754. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1755. }
  1756. $this->num = $num;
  1757. return $out;
  1758. } else {
  1759. dol_print_error($this->db);
  1760. return -1;
  1761. }
  1762. }
  1763. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1764. /**
  1765. * Return the HTML select list of users
  1766. *
  1767. * @param string $selected Id user preselected
  1768. * @param string $htmlname Field name in form
  1769. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1770. * @param array $exclude Array list of users id to exclude
  1771. * @param int $disabled If select list must be disabled
  1772. * @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
  1773. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1774. * @param string $force_entity '0' or Ids of environment to force
  1775. * @return void
  1776. * @deprecated Use select_dolusers instead
  1777. * @see select_dolusers()
  1778. */
  1779. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1780. {
  1781. // phpcs:enable
  1782. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1783. }
  1784. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1785. /**
  1786. * Return select list of users
  1787. *
  1788. * @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)
  1789. * @param string $htmlname Field name in form
  1790. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1791. * @param array $exclude Array list of users id to exclude
  1792. * @param int $disabled If select list must be disabled
  1793. * @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
  1794. * @param array|string $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1795. * @param string $force_entity '0' or Ids of environment to force
  1796. * @param int $maxlength Maximum length of string into list (0=no limit)
  1797. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1798. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1799. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1800. * @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.
  1801. * @param string $morecss More css
  1802. * @param int $notdisabled Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1803. * @param int $outputmode 0=HTML select string, 1=Array
  1804. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1805. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1806. * @return array|string HTML select string
  1807. * @see select_dolgroups()
  1808. */
  1809. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $notdisabled = 0, $outputmode = 0, $multiple = false, $forcecombo = 0)
  1810. {
  1811. // phpcs:enable
  1812. global $conf, $user, $langs, $hookmanager;
  1813. global $action;
  1814. // If no preselected user defined, we take current user
  1815. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1816. $selected = $user->id;
  1817. }
  1818. if ($selected === '') {
  1819. $selected = array();
  1820. } elseif (!is_array($selected)) {
  1821. $selected = array($selected);
  1822. }
  1823. $excludeUsers = null;
  1824. $includeUsers = null;
  1825. // Permettre l'exclusion d'utilisateurs
  1826. if (is_array($exclude)) {
  1827. $excludeUsers = implode(",", $exclude);
  1828. }
  1829. // Permettre l'inclusion d'utilisateurs
  1830. if (is_array($include)) {
  1831. $includeUsers = implode(",", $include);
  1832. } elseif ($include == 'hierarchy') {
  1833. // Build list includeUsers to have only hierarchy
  1834. $includeUsers = implode(",", $user->getAllChildIds(0));
  1835. } elseif ($include == 'hierarchyme') {
  1836. // Build list includeUsers to have only hierarchy and current user
  1837. $includeUsers = implode(",", $user->getAllChildIds(1));
  1838. }
  1839. $out = '';
  1840. $outarray = array();
  1841. $outarray2 = array();
  1842. // Forge request to select users
  1843. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1844. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1845. $sql .= ", e.label";
  1846. }
  1847. $sql .= " FROM " . $this->db->prefix() . "user as u";
  1848. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1849. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
  1850. if ($force_entity) {
  1851. $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
  1852. } else {
  1853. $sql .= " WHERE u.entity IS NOT NULL";
  1854. }
  1855. } else {
  1856. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1857. $sql .= " LEFT JOIN " . $this->db->prefix() . "usergroup_user as ug";
  1858. $sql .= " ON ug.fk_user = u.rowid";
  1859. $sql .= " WHERE ug.entity = " . $conf->entity;
  1860. } else {
  1861. $sql .= " WHERE u.entity IN (0, " . $conf->entity . ")";
  1862. }
  1863. }
  1864. if (!empty($user->socid)) {
  1865. $sql .= " AND u.fk_soc = " . ((int) $user->socid);
  1866. }
  1867. if (is_array($exclude) && $excludeUsers) {
  1868. $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
  1869. }
  1870. if ($includeUsers) {
  1871. $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
  1872. }
  1873. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $notdisabled) {
  1874. $sql .= " AND u.statut <> 0";
  1875. }
  1876. if (!empty($morefilter)) {
  1877. $sql .= " " . $morefilter;
  1878. }
  1879. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1880. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1881. if (!empty($reshook)) {
  1882. $sql .= $hookmanager->resPrint;
  1883. }
  1884. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1885. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1886. } else {
  1887. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1888. }
  1889. dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
  1890. $resql = $this->db->query($sql);
  1891. if ($resql) {
  1892. $num = $this->db->num_rows($resql);
  1893. $i = 0;
  1894. if ($num) {
  1895. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1896. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  1897. if ($show_empty && !$multiple) {
  1898. $textforempty = ' ';
  1899. if (!empty($conf->use_javascript_ajax)) {
  1900. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1901. }
  1902. if (!is_numeric($show_empty)) {
  1903. $textforempty = $show_empty;
  1904. }
  1905. $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  1906. }
  1907. if ($show_every) {
  1908. $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
  1909. }
  1910. $userstatic = new User($this->db);
  1911. while ($i < $num) {
  1912. $obj = $this->db->fetch_object($resql);
  1913. $userstatic->id = $obj->rowid;
  1914. $userstatic->lastname = $obj->lastname;
  1915. $userstatic->firstname = $obj->firstname;
  1916. $userstatic->photo = $obj->photo;
  1917. $userstatic->statut = $obj->status;
  1918. $userstatic->entity = $obj->entity;
  1919. $userstatic->admin = $obj->admin;
  1920. $disableline = '';
  1921. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1922. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1923. }
  1924. $labeltoshow = '';
  1925. $labeltoshowhtml = '';
  1926. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1927. $fullNameMode = 0;
  1928. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1929. $fullNameMode = 1; //Firstname+lastname
  1930. }
  1931. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1932. $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1933. if (empty($obj->firstname) && empty($obj->lastname)) {
  1934. $labeltoshow .= $obj->login;
  1935. $labeltoshowhtml .= $obj->login;
  1936. }
  1937. // Complete name with a more info string like: ' (info1 - info2 - ...)'
  1938. $moreinfo = '';
  1939. $moreinfohtml = '';
  1940. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1941. $moreinfo .= ($moreinfo ? ' - ' : ' (');
  1942. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
  1943. $moreinfo .= $obj->login;
  1944. $moreinfohtml .= $obj->login;
  1945. }
  1946. if ($showstatus >= 0) {
  1947. if ($obj->status == 1 && $showstatus == 1) {
  1948. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
  1949. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
  1950. }
  1951. if ($obj->status == 0 && $showstatus == 1) {
  1952. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
  1953. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
  1954. }
  1955. }
  1956. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1957. if (!$obj->entity) {
  1958. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
  1959. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
  1960. } else {
  1961. if ($obj->entity != $conf->entity) {
  1962. $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1963. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1964. }
  1965. }
  1966. }
  1967. $moreinfo .= ($moreinfo ? ')' : '');
  1968. $moreinfohtml .= ($moreinfohtml ? ')</span>' : '');
  1969. if ($disableline && $disableline != '1') {
  1970. // Add text from $enableonlytext parameter
  1971. $moreinfo .= ' - ' . $disableline;
  1972. $moreinfohtml .= ' - ' . $disableline;
  1973. }
  1974. $labeltoshow .= $moreinfo;
  1975. $labeltoshowhtml .= $moreinfohtml;
  1976. $out .= '<option value="' . $obj->rowid . '"';
  1977. if ($disableline) {
  1978. $out .= ' disabled';
  1979. }
  1980. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1981. $out .= ' selected';
  1982. }
  1983. $out .= ' data-html="';
  1984. $outhtml = $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
  1985. if ($showstatus >= 0 && $obj->status == 0) {
  1986. $outhtml .= '<strike class="opacitymediumxxx">';
  1987. }
  1988. $outhtml .= $labeltoshowhtml;
  1989. if ($showstatus >= 0 && $obj->status == 0) {
  1990. $outhtml .= '</strike>';
  1991. }
  1992. $out .= dol_escape_htmltag($outhtml);
  1993. $out .= '">';
  1994. $out .= $labeltoshow;
  1995. $out .= '</option>';
  1996. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
  1997. $outarray2[$userstatic->id] = array(
  1998. 'id'=>$userstatic->id,
  1999. 'label'=>$labeltoshow,
  2000. 'labelhtml'=>$labeltoshowhtml
  2001. );
  2002. $i++;
  2003. }
  2004. } else {
  2005. $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
  2006. $out .= '<option value="">' . $langs->trans("None") . '</option>';
  2007. }
  2008. $out .= '</select>';
  2009. if ($num && !$forcecombo) {
  2010. // Enhance with select2
  2011. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2012. $out .= ajax_combobox($htmlname);
  2013. }
  2014. } else {
  2015. dol_print_error($this->db);
  2016. }
  2017. if ($outputmode == 2) {
  2018. return $outarray2;
  2019. } elseif ($outputmode) {
  2020. return $outarray;
  2021. }
  2022. return $out;
  2023. }
  2024. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2025. /**
  2026. * Return select list of users. Selected users are stored into session.
  2027. * List of users are provided into $_SESSION['assignedtouser'].
  2028. *
  2029. * @param string $action Value for $action
  2030. * @param string $htmlname Field name in form
  2031. * @param int $show_empty 0=list without the empty value, 1=add empty value
  2032. * @param array $exclude Array list of users id to exclude
  2033. * @param int $disabled If select list must be disabled
  2034. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  2035. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  2036. * @param int $force_entity '0' or Ids of environment to force
  2037. * @param int $maxlength Maximum length of string into list (0=no limit)
  2038. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  2039. * @param string $morefilter Add more filters into sql request
  2040. * @param int $showproperties Show properties of each attendees
  2041. * @param array $listofuserid Array with properties of each user
  2042. * @param array $listofcontactid Array with properties of each contact
  2043. * @param array $listofotherid Array with properties of each other contact
  2044. * @return string HTML select string
  2045. * @see select_dolgroups()
  2046. */
  2047. public function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array())
  2048. {
  2049. // phpcs:enable
  2050. global $conf, $user, $langs;
  2051. $userstatic = new User($this->db);
  2052. $out = '';
  2053. $assignedtouser = array();
  2054. if (!empty($_SESSION['assignedtouser'])) {
  2055. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  2056. }
  2057. $nbassignetouser = count($assignedtouser);
  2058. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  2059. if ($nbassignetouser) {
  2060. $out .= '<ul class="attendees">';
  2061. }
  2062. $i = 0;
  2063. $ownerid = 0;
  2064. foreach ($assignedtouser as $key => $value) {
  2065. if ($value['id'] == $ownerid) {
  2066. continue;
  2067. }
  2068. $out .= '<li>';
  2069. $userstatic->fetch($value['id']);
  2070. $out .= $userstatic->getNomUrl(-1);
  2071. if ($i == 0) {
  2072. $ownerid = $value['id'];
  2073. $out .= ' (' . $langs->trans("Owner") . ')';
  2074. }
  2075. if ($nbassignetouser > 1 && $action != 'view') {
  2076. $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 . '">';
  2077. }
  2078. // Show my availability
  2079. if ($showproperties) {
  2080. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  2081. $out .= '<div class="myavailability inline-block">';
  2082. $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>';
  2083. $out .= '</div>';
  2084. }
  2085. }
  2086. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2087. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2088. $out .= '</li>';
  2089. $i++;
  2090. }
  2091. if ($nbassignetouser) {
  2092. $out .= '</ul>';
  2093. }
  2094. // Method with no ajax
  2095. if ($action != 'view') {
  2096. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2097. $out .= '<script nonce="' . getNonce() . '" type="text/javascript">jQuery(document).ready(function () {';
  2098. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2099. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2100. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
  2101. $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
  2102. $out .= '});';
  2103. $out .= '})</script>';
  2104. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2105. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
  2106. $out .= '<br>';
  2107. }
  2108. return $out;
  2109. }
  2110. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2111. /**
  2112. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2113. *
  2114. * @param int $selected Preselected products
  2115. * @param string $htmlname Name of HTML select field (must be unique in page).
  2116. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2117. * @param int $limit Limit on number of returned lines
  2118. * @param int $price_level Level of price to show
  2119. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2120. * @param int $finished 2=all, 1=finished, 0=raw material
  2121. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2122. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2123. * @param array $ajaxoptions Options for ajax_autocompleter
  2124. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2125. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2126. * @param int $forcecombo Force to use combo box
  2127. * @param string $morecss Add more css on select
  2128. * @param int $hidepriceinlabel 1=Hide prices in label
  2129. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2130. * 'warehouseopen' = count products from open warehouses,
  2131. * 'warehouseclosed' = count products from closed warehouses,
  2132. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2133. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2134. * @param string $nooutput No print, return the output into a string
  2135. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2136. * @return void|string
  2137. */
  2138. public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 0, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = null, $nooutput = 0, $status_purchase = -1)
  2139. {
  2140. // phpcs:enable
  2141. global $langs, $conf;
  2142. $out = '';
  2143. // check parameters
  2144. $price_level = (!empty($price_level) ? $price_level : 0);
  2145. if (is_null($ajaxoptions)) {
  2146. $ajaxoptions = array();
  2147. }
  2148. if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
  2149. if (isModEnabled("product") && !isModEnabled('service')) {
  2150. $filtertype = '0';
  2151. } elseif (!isModEnabled('product') && isModEnabled("service")) {
  2152. $filtertype = '1';
  2153. }
  2154. }
  2155. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2156. $placeholder = '';
  2157. if ($selected && empty($selected_input_value)) {
  2158. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2159. $producttmpselect = new Product($this->db);
  2160. $producttmpselect->fetch($selected);
  2161. $selected_input_value = $producttmpselect->ref;
  2162. unset($producttmpselect);
  2163. }
  2164. // handle case where product or service module is disabled + no filter specified
  2165. if ($filtertype == '') {
  2166. if (!isModEnabled('product')) { // when product module is disabled, show services only
  2167. $filtertype = 1;
  2168. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2169. $filtertype = 0;
  2170. }
  2171. }
  2172. // mode=1 means customers products
  2173. $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;
  2174. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2175. if (isModEnabled('variants') && is_array($selected_combinations)) {
  2176. // Code to automatically insert with javascript the select of attributes under the select of product
  2177. // when a parent of variant has been selected.
  2178. $out .= '
  2179. <!-- script to auto show attributes select tags if a variant was selected -->
  2180. <script nonce="' . getNonce() . '">
  2181. // auto show attributes fields
  2182. selected = ' . json_encode($selected_combinations) . ';
  2183. combvalues = {};
  2184. jQuery(document).ready(function () {
  2185. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2186. if (jQuery(this).val() == \'free\') {
  2187. jQuery(\'div#attributes_box\').empty();
  2188. }
  2189. });
  2190. jQuery("input#' . $htmlname . '").change(function () {
  2191. if (!jQuery(this).val()) {
  2192. jQuery(\'div#attributes_box\').empty();
  2193. return;
  2194. }
  2195. console.log("A change has started. We get variants fields to inject html select");
  2196. jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
  2197. id: jQuery(this).val()
  2198. }, function (data) {
  2199. jQuery(\'div#attributes_box\').empty();
  2200. jQuery.each(data, function (key, val) {
  2201. combvalues[val.id] = val.values;
  2202. var span = jQuery(document.createElement(\'div\')).css({
  2203. \'display\': \'table-row\'
  2204. });
  2205. span.append(
  2206. jQuery(document.createElement(\'div\')).text(val.label).css({
  2207. \'font-weight\': \'bold\',
  2208. \'display\': \'table-cell\'
  2209. })
  2210. );
  2211. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2212. \'margin-left\': \'15px\',
  2213. \'white-space\': \'pre\'
  2214. }).append(
  2215. jQuery(document.createElement(\'option\')).val(\'\')
  2216. );
  2217. jQuery.each(combvalues[val.id], function (key, val) {
  2218. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2219. if (selected[val.fk_product_attribute] == val.id) {
  2220. tag.attr(\'selected\', \'selected\');
  2221. }
  2222. html.append(tag);
  2223. });
  2224. span.append(html);
  2225. jQuery(\'div#attributes_box\').append(span);
  2226. });
  2227. })
  2228. });
  2229. ' . ($selected ? 'jQuery("input#' . $htmlname . '").change();' : '') . '
  2230. });
  2231. </script>
  2232. ';
  2233. }
  2234. if (empty($hidelabel)) {
  2235. $out .= $langs->trans("RefOrLabel") . ' : ';
  2236. } elseif ($hidelabel > 1) {
  2237. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  2238. if ($hidelabel == 2) {
  2239. $out .= img_picto($langs->trans("Search"), 'search');
  2240. }
  2241. }
  2242. $out .= '<input type="text" class="minwidth100' . ($morecss ? ' ' . $morecss : '') . '" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  2243. if ($hidelabel == 3) {
  2244. $out .= img_picto($langs->trans("Search"), 'search');
  2245. }
  2246. } else {
  2247. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2248. }
  2249. if (empty($nooutput)) {
  2250. print $out;
  2251. } else {
  2252. return $out;
  2253. }
  2254. }
  2255. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2256. /**
  2257. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2258. *
  2259. * @param int $selected Preselected BOM id
  2260. * @param string $htmlname Name of HTML select field (must be unique in page).
  2261. * @param int $limit Limit on number of returned lines
  2262. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2263. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2264. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2265. * @param string $morecss Add more css on select
  2266. * @param string $nooutput No print, return the output into a string
  2267. * @param int $forcecombo Force to use combo box
  2268. * @param array $TProducts Add filter on a defined product
  2269. * @return void|string
  2270. */
  2271. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2272. {
  2273. // phpcs:enable
  2274. global $conf, $user, $langs, $db;
  2275. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2276. $error = 0;
  2277. $out = '';
  2278. if (!$forcecombo) {
  2279. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2280. $events = array();
  2281. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2282. }
  2283. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2284. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2285. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'bom_bom as b';
  2286. $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
  2287. if (!empty($status)) $sql .= ' AND status = ' . (int) $status;
  2288. if (!empty($type)) $sql .= ' AND bomtype = ' . (int) $type;
  2289. if (!empty($TProducts)) $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
  2290. if (!empty($limit)) $sql .= ' LIMIT ' . (int) $limit;
  2291. $resql = $db->query($sql);
  2292. if ($resql) {
  2293. if ($showempty) {
  2294. $out .= '<option value="-1"';
  2295. if (empty($selected)) $out .= ' selected';
  2296. $out .= '>&nbsp;</option>';
  2297. }
  2298. while ($obj = $db->fetch_object($resql)) {
  2299. $product = new Product($db);
  2300. $res = $product->fetch($obj->fk_product);
  2301. $out .= '<option value="' . $obj->rowid . '"';
  2302. if ($obj->rowid == $selected) $out .= 'selected';
  2303. $out .= '>' . $obj->ref . ' - ' . $product->label . ' - ' . $obj->label . '</option>';
  2304. }
  2305. } else {
  2306. $error++;
  2307. dol_print_error($db);
  2308. }
  2309. $out .= '</select>';
  2310. if (empty($nooutput)) {
  2311. print $out;
  2312. } else {
  2313. return $out;
  2314. }
  2315. }
  2316. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2317. /**
  2318. * Return list of products for a customer.
  2319. * Called by select_produits.
  2320. *
  2321. * @param int $selected Preselected product
  2322. * @param string $htmlname Name of select html
  2323. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2324. * @param int $limit Limit on number of returned lines
  2325. * @param int $price_level Level of price to show
  2326. * @param string $filterkey Filter on product
  2327. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2328. * @param int $finished Filter on finished field: 2=No filter
  2329. * @param int $outputmode 0=HTML select string, 1=Array
  2330. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2331. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2332. * @param int $forcecombo Force to use combo box
  2333. * @param string $morecss Add more css on select
  2334. * @param int $hidepriceinlabel 1=Hide prices in label
  2335. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2336. * 'warehouseopen' = count products from open warehouses,
  2337. * 'warehouseclosed' = count products from closed warehouses,
  2338. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2339. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2340. * @return array|string Array of keys for json
  2341. */
  2342. 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)
  2343. {
  2344. // phpcs:enable
  2345. global $langs, $conf;
  2346. global $hookmanager;
  2347. $out = '';
  2348. $outarray = array();
  2349. // Units
  2350. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2351. $langs->load('other');
  2352. }
  2353. $warehouseStatusArray = array();
  2354. if (!empty($warehouseStatus)) {
  2355. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2356. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2357. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2358. }
  2359. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2360. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2361. }
  2362. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2363. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2364. }
  2365. }
  2366. $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";
  2367. if (count($warehouseStatusArray)) {
  2368. $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
  2369. } else {
  2370. $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", 0, "p.stock") . " AS stock";
  2371. }
  2372. $sql = "SELECT ";
  2373. // Add select from hooks
  2374. $parameters = array();
  2375. $reshook = $hookmanager->executeHooks('selectProductsListSelect', $parameters); // Note that $action and $object may have been modified by hook
  2376. if (empty($reshook)) {
  2377. $sql .= $selectFields.$selectFieldsGrouped.$hookmanager->resPrint;
  2378. } else {
  2379. $sql .= $hookmanager->resPrint;
  2380. }
  2381. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2382. //Product category
  2383. $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
  2384. FROM " . $this->db->prefix() . "categorie_product
  2385. WHERE " . $this->db->prefix() . "categorie_product.fk_product=p.rowid
  2386. LIMIT 1
  2387. ) AS categorie_product_id ";
  2388. }
  2389. //Price by customer
  2390. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2391. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2392. $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';
  2393. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2394. }
  2395. // Units
  2396. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2397. $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";
  2398. $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';
  2399. }
  2400. // Multilang : we add translation
  2401. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2402. $sql .= ", pl.label as label_translated";
  2403. $sql .= ", pl.description as description_translated";
  2404. $selectFields .= ", label_translated";
  2405. $selectFields .= ", description_translated";
  2406. }
  2407. // Price by quantity
  2408. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2409. $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
  2410. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2411. $sql .= " AND price_level = " . ((int) $price_level);
  2412. }
  2413. $sql .= " ORDER BY date_price";
  2414. $sql .= " DESC LIMIT 1) as price_rowid";
  2415. $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
  2416. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2417. $sql .= " AND price_level = " . ((int) $price_level);
  2418. }
  2419. $sql .= " ORDER BY date_price";
  2420. $sql .= " DESC LIMIT 1) as price_by_qty";
  2421. $selectFields .= ", price_rowid, price_by_qty";
  2422. }
  2423. $sql .= " FROM ".$this->db->prefix()."product as p";
  2424. // Add from (left join) from hooks
  2425. $parameters = array();
  2426. $reshook = $hookmanager->executeHooks('selectProductsListFrom', $parameters); // Note that $action and $object may have been modified by hook
  2427. $sql .= $hookmanager->resPrint;
  2428. if (count($warehouseStatusArray)) {
  2429. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps on ps.fk_product = p.rowid";
  2430. $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
  2431. $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.
  2432. }
  2433. // include search in supplier ref
  2434. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2435. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2436. }
  2437. //Price by customer
  2438. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2439. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_customer_price as pcp ON pcp.fk_soc=" . ((int) $socid) . " AND pcp.fk_product=p.rowid";
  2440. }
  2441. // Units
  2442. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2443. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  2444. }
  2445. // Multilang : we add translation
  2446. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2447. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid ";
  2448. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2449. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  2450. $soc = new Societe($this->db);
  2451. $result = $soc->fetch($socid);
  2452. if ($result > 0 && !empty($soc->default_lang)) {
  2453. $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
  2454. } else {
  2455. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2456. }
  2457. } else {
  2458. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2459. }
  2460. }
  2461. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2462. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2463. }
  2464. $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
  2465. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2466. $sql .= " AND pac.rowid IS NULL";
  2467. }
  2468. if ($finished == 0) {
  2469. $sql .= " AND p.finished = " . ((int) $finished);
  2470. } elseif ($finished == 1) {
  2471. $sql .= " AND p.finished = " . ((int) $finished);
  2472. if ($status >= 0) {
  2473. $sql .= " AND p.tosell = " . ((int) $status);
  2474. }
  2475. } elseif ($status >= 0) {
  2476. $sql .= " AND p.tosell = " . ((int) $status);
  2477. }
  2478. if ($status_purchase >= 0) {
  2479. $sql .= " AND p.tobuy = " . ((int) $status_purchase);
  2480. }
  2481. // Filter by product type
  2482. if (strval($filtertype) != '') {
  2483. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  2484. } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
  2485. $sql .= " AND p.fk_product_type = 1";
  2486. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2487. $sql .= " AND p.fk_product_type = 0";
  2488. }
  2489. // Add where from hooks
  2490. $parameters = array();
  2491. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2492. $sql .= $hookmanager->resPrint;
  2493. // Add criteria on ref/label
  2494. if ($filterkey != '') {
  2495. $sql .= ' AND (';
  2496. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2497. // For natural search
  2498. $scrit = explode(' ', $filterkey);
  2499. $i = 0;
  2500. if (count($scrit) > 1) {
  2501. $sql .= "(";
  2502. }
  2503. foreach ($scrit as $crit) {
  2504. if ($i > 0) {
  2505. $sql .= " AND ";
  2506. }
  2507. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2508. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2509. $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2510. }
  2511. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2512. $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2513. }
  2514. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2515. $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2516. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2517. $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2518. }
  2519. }
  2520. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2521. $sql .= " OR pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2522. }
  2523. $sql .= ")";
  2524. $i++;
  2525. }
  2526. if (count($scrit) > 1) {
  2527. $sql .= ")";
  2528. }
  2529. if (isModEnabled('barcode')) {
  2530. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  2531. }
  2532. $sql .= ')';
  2533. }
  2534. if (count($warehouseStatusArray)) {
  2535. $sql .= " GROUP BY " . $selectFields;
  2536. }
  2537. //Sort by category
  2538. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2539. $sql .= " ORDER BY categorie_product_id ";
  2540. //ASC OR DESC order
  2541. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2542. } else {
  2543. $sql .= $this->db->order("p.ref");
  2544. }
  2545. $sql .= $this->db->plimit($limit, 0);
  2546. // Build output string
  2547. dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
  2548. $result = $this->db->query($sql);
  2549. if ($result) {
  2550. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2551. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2552. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  2553. $num = $this->db->num_rows($result);
  2554. $events = null;
  2555. if (!$forcecombo) {
  2556. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2557. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2558. }
  2559. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2560. $textifempty = '';
  2561. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2562. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2563. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2564. if ($showempty && !is_numeric($showempty)) {
  2565. $textifempty = $langs->trans($showempty);
  2566. } else {
  2567. $textifempty .= $langs->trans("All");
  2568. }
  2569. } else {
  2570. if ($showempty && !is_numeric($showempty)) {
  2571. $textifempty = $langs->trans($showempty);
  2572. }
  2573. }
  2574. if ($showempty) {
  2575. $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
  2576. }
  2577. $i = 0;
  2578. while ($num && $i < $num) {
  2579. $opt = '';
  2580. $optJson = array();
  2581. $objp = $this->db->fetch_object($result);
  2582. if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1) { // Price by quantity will return many prices for the same product
  2583. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2584. $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
  2585. $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
  2586. $sql .= " ORDER BY quantity ASC";
  2587. dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
  2588. $result2 = $this->db->query($sql);
  2589. if ($result2) {
  2590. $nb_prices = $this->db->num_rows($result2);
  2591. $j = 0;
  2592. while ($nb_prices && $j < $nb_prices) {
  2593. $objp2 = $this->db->fetch_object($result2);
  2594. $objp->price_by_qty_rowid = $objp2->rowid;
  2595. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2596. $objp->price_by_qty_quantity = $objp2->quantity;
  2597. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2598. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2599. // For backward compatibility
  2600. $objp->quantity = $objp2->quantity;
  2601. $objp->price = $objp2->price;
  2602. $objp->unitprice = $objp2->unitprice;
  2603. $objp->remise_percent = $objp2->remise_percent;
  2604. //$objp->tva_tx is not overwritten by $objp2 value
  2605. //$objp->default_vat_code is not overwritten by $objp2 value
  2606. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2607. $j++;
  2608. // Add new entry
  2609. // "key" value of json key array is used by jQuery automatically as selected value
  2610. // "label" value of json key array is used by jQuery automatically as text for combo box
  2611. $out .= $opt;
  2612. array_push($outarray, $optJson);
  2613. }
  2614. }
  2615. } else {
  2616. if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
  2617. $price_product = new Product($this->db);
  2618. $price_product->fetch($objp->rowid, '', '', 1);
  2619. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2620. $priceparser = new PriceParser($this->db);
  2621. $price_result = $priceparser->parseProduct($price_product);
  2622. if ($price_result >= 0) {
  2623. $objp->price = $price_result;
  2624. $objp->unitprice = $price_result;
  2625. //Calculate the VAT
  2626. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2627. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2628. }
  2629. }
  2630. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2631. // Add new entry
  2632. // "key" value of json key array is used by jQuery automatically as selected value
  2633. // "label" value of json key array is used by jQuery automatically as text for combo box
  2634. $out .= $opt;
  2635. array_push($outarray, $optJson);
  2636. }
  2637. $i++;
  2638. }
  2639. $out .= '</select>';
  2640. $this->db->free($result);
  2641. if (empty($outputmode)) {
  2642. return $out;
  2643. }
  2644. return $outarray;
  2645. } else {
  2646. dol_print_error($this->db);
  2647. }
  2648. return '';
  2649. }
  2650. /**
  2651. * Function to forge the string with OPTIONs of SELECT.
  2652. * This define value for &$opt and &$optJson.
  2653. * This function is called by select_produits_list().
  2654. *
  2655. * @param object $objp Resultset of fetch
  2656. * @param string $opt Option (var used for returned value in string option format)
  2657. * @param array $optJson Option (var used for returned value in json format)
  2658. * @param int $price_level Price level
  2659. * @param string $selected Preselected value
  2660. * @param int $hidepriceinlabel Hide price in label
  2661. * @param string $filterkey Filter key to highlight
  2662. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2663. * @return void
  2664. */
  2665. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2666. {
  2667. global $langs, $conf, $user;
  2668. global $hookmanager;
  2669. $outkey = '';
  2670. $outval = '';
  2671. $outref = '';
  2672. $outlabel = '';
  2673. $outlabel_translated = '';
  2674. $outdesc = '';
  2675. $outdesc_translated = '';
  2676. $outbarcode = '';
  2677. $outorigin = '';
  2678. $outtype = '';
  2679. $outprice_ht = '';
  2680. $outprice_ttc = '';
  2681. $outpricebasetype = '';
  2682. $outtva_tx = '';
  2683. $outdefault_vat_code = '';
  2684. $outqty = 1;
  2685. $outdiscount = 0;
  2686. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2687. $label = $objp->label;
  2688. if (!empty($objp->label_translated)) {
  2689. $label = $objp->label_translated;
  2690. }
  2691. if (!empty($filterkey) && $filterkey != '') {
  2692. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  2693. }
  2694. $outkey = $objp->rowid;
  2695. $outref = $objp->ref;
  2696. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2697. $outlabel = $objp->label;
  2698. $outdesc = $objp->description;
  2699. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2700. $outlabel_translated = $objp->label_translated;
  2701. $outdesc_translated = $objp->description_translated;
  2702. }
  2703. $outbarcode = $objp->barcode;
  2704. $outorigin = $objp->fk_country;
  2705. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2706. $outtype = $objp->fk_product_type;
  2707. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2708. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  2709. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2710. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2711. }
  2712. // Units
  2713. $outvalUnits = '';
  2714. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  2715. if (!empty($objp->unit_short)) {
  2716. $outvalUnits .= ' - ' . $objp->unit_short;
  2717. }
  2718. }
  2719. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2720. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2721. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2722. $outvalUnits .= ' - ' . $unitToShow;
  2723. }
  2724. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2725. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  2726. $outvalUnits .= ' - ' . $unitToShow;
  2727. }
  2728. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2729. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2730. $outvalUnits .= ' - ' . $unitToShow;
  2731. }
  2732. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2733. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2734. $outvalUnits .= ' - ' . $unitToShow;
  2735. }
  2736. }
  2737. if ($outdurationvalue && $outdurationunit) {
  2738. $da = array(
  2739. 'h' => $langs->trans('Hour'),
  2740. 'd' => $langs->trans('Day'),
  2741. 'w' => $langs->trans('Week'),
  2742. 'm' => $langs->trans('Month'),
  2743. 'y' => $langs->trans('Year')
  2744. );
  2745. if (isset($da[$outdurationunit])) {
  2746. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  2747. }
  2748. }
  2749. $opt = '<option value="' . $objp->rowid . '"';
  2750. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2751. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2752. $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 . '"';
  2753. }
  2754. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2755. if (!empty($user->rights->stock->lire)) {
  2756. if ($objp->stock > 0) {
  2757. $opt .= ' class="product_line_stock_ok"';
  2758. } elseif ($objp->stock <= 0) {
  2759. $opt .= ' class="product_line_stock_too_low"';
  2760. }
  2761. }
  2762. }
  2763. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2764. $opt .= ' data-labeltrans="' . $outlabel_translated . '"';
  2765. $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
  2766. }
  2767. $opt .= '>';
  2768. $opt .= $objp->ref;
  2769. if (!empty($objp->custref)) {
  2770. $opt .= ' (' . $objp->custref . ')';
  2771. }
  2772. if ($outbarcode) {
  2773. $opt .= ' (' . $outbarcode . ')';
  2774. }
  2775. $opt .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2776. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2777. $opt .= ' (' . getCountry($outorigin, 1) . ')';
  2778. }
  2779. $objRef = $objp->ref;
  2780. if (!empty($objp->custref)) {
  2781. $objRef .= ' (' . $objp->custref . ')';
  2782. }
  2783. if (!empty($filterkey) && $filterkey != '') {
  2784. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  2785. }
  2786. $outval .= $objRef;
  2787. if ($outbarcode) {
  2788. $outval .= ' (' . $outbarcode . ')';
  2789. }
  2790. $outval .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2791. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2792. $outval .= ' (' . getCountry($outorigin, 1) . ')';
  2793. }
  2794. // Units
  2795. $opt .= $outvalUnits;
  2796. $outval .= $outvalUnits;
  2797. $found = 0;
  2798. // Multiprice
  2799. // If we need a particular price level (from 1 to n)
  2800. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2801. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2802. $sql .= " FROM " . $this->db->prefix() . "product_price";
  2803. $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
  2804. $sql .= " AND entity IN (" . getEntity('productprice') . ")";
  2805. $sql .= " AND price_level = " . ((int) $price_level);
  2806. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2807. $sql .= " LIMIT 1";
  2808. dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level, LOG_DEBUG);
  2809. $result2 = $this->db->query($sql);
  2810. if ($result2) {
  2811. $objp2 = $this->db->fetch_object($result2);
  2812. if ($objp2) {
  2813. $found = 1;
  2814. if ($objp2->price_base_type == 'HT') {
  2815. $opt .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2816. $outval .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2817. } else {
  2818. $opt .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2819. $outval .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2820. }
  2821. $outprice_ht = price($objp2->price);
  2822. $outprice_ttc = price($objp2->price_ttc);
  2823. $outpricebasetype = $objp2->price_base_type;
  2824. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2825. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2826. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2827. } else {
  2828. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2829. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2830. }
  2831. }
  2832. } else {
  2833. dol_print_error($this->db);
  2834. }
  2835. }
  2836. // Price by quantity
  2837. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2838. $found = 1;
  2839. $outqty = $objp->quantity;
  2840. $outdiscount = $objp->remise_percent;
  2841. if ($objp->quantity == 1) {
  2842. $opt .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
  2843. $outval .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
  2844. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2845. $outval .= $langs->transnoentities("Unit");
  2846. } else {
  2847. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2848. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2849. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2850. $outval .= $langs->transnoentities("Units");
  2851. }
  2852. $outprice_ht = price($objp->unitprice);
  2853. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2854. $outpricebasetype = $objp->price_base_type;
  2855. $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
  2856. $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
  2857. }
  2858. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2859. $opt .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2860. $outval .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2861. }
  2862. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2863. $opt .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2864. $outval .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2865. }
  2866. // Price by customer
  2867. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2868. if (!empty($objp->idprodcustprice)) {
  2869. $found = 1;
  2870. if ($objp->custprice_base_type == 'HT') {
  2871. $opt .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2872. $outval .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2873. } else {
  2874. $opt .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2875. $outval .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2876. }
  2877. $outprice_ht = price($objp->custprice);
  2878. $outprice_ttc = price($objp->custprice_ttc);
  2879. $outpricebasetype = $objp->custprice_base_type;
  2880. $outtva_tx = $objp->custtva_tx;
  2881. $outdefault_vat_code = $objp->custdefault_vat_code;
  2882. }
  2883. }
  2884. // If level no defined or multiprice not found, we used the default price
  2885. if (empty($hidepriceinlabel) && !$found) {
  2886. if ($objp->price_base_type == 'HT') {
  2887. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2888. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2889. } else {
  2890. $opt .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2891. $outval .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2892. }
  2893. $outprice_ht = price($objp->price);
  2894. $outprice_ttc = price($objp->price_ttc);
  2895. $outpricebasetype = $objp->price_base_type;
  2896. $outtva_tx = $objp->tva_tx;
  2897. $outdefault_vat_code = $objp->default_vat_code;
  2898. }
  2899. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2900. if (!empty($user->rights->stock->lire)) {
  2901. $opt .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  2902. if ($objp->stock > 0) {
  2903. $outval .= ' - <span class="product_line_stock_ok">';
  2904. } elseif ($objp->stock <= 0) {
  2905. $outval .= ' - <span class="product_line_stock_too_low">';
  2906. }
  2907. $outval .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  2908. $outval .= '</span>';
  2909. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2910. $langs->load("stocks");
  2911. $tmpproduct = new Product($this->db);
  2912. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2913. $tmpproduct->load_virtual_stock();
  2914. $virtualstock = $tmpproduct->stock_theorique;
  2915. $opt .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  2916. $outval .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  2917. if ($virtualstock > 0) {
  2918. $outval .= '<span class="product_line_stock_ok">';
  2919. } elseif ($virtualstock <= 0) {
  2920. $outval .= '<span class="product_line_stock_too_low">';
  2921. }
  2922. $outval .= $virtualstock;
  2923. $outval .= '</span>';
  2924. unset($tmpproduct);
  2925. }
  2926. }
  2927. }
  2928. $parameters = array('objp'=>$objp);
  2929. $reshook = $hookmanager->executeHooks('constructProductListOption', $parameters); // Note that $action and $object may have been modified by hook
  2930. if (empty($reshook)) {
  2931. $opt .= $hookmanager->resPrint;
  2932. } else {
  2933. $opt = $hookmanager->resPrint;
  2934. }
  2935. $opt .= "</option>\n";
  2936. $optJson = array(
  2937. 'key' => $outkey,
  2938. 'value' => $outref,
  2939. 'label' => $outval,
  2940. 'label2' => $outlabel,
  2941. 'desc' => $outdesc,
  2942. 'type' => $outtype,
  2943. 'price_ht' => price2num($outprice_ht),
  2944. 'price_ttc' => price2num($outprice_ttc),
  2945. 'price_ht_locale' => price(price2num($outprice_ht)),
  2946. 'price_ttc_locale' => price(price2num($outprice_ttc)),
  2947. 'pricebasetype' => $outpricebasetype,
  2948. 'tva_tx' => $outtva_tx,
  2949. 'default_vat_code' => $outdefault_vat_code,
  2950. 'qty' => $outqty,
  2951. 'discount' => $outdiscount,
  2952. 'duration_value' => $outdurationvalue,
  2953. 'duration_unit' => $outdurationunit,
  2954. 'pbq' => $outpbq,
  2955. 'labeltrans' => $outlabel_translated,
  2956. 'desctrans' => $outdesc_translated,
  2957. 'ref_customer' => $outrefcust
  2958. );
  2959. }
  2960. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2961. /**
  2962. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2963. *
  2964. * @param int $socid Id third party
  2965. * @param string $selected Preselected product
  2966. * @param string $htmlname Name of HTML Select
  2967. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2968. * @param string $filtre For a SQL filter
  2969. * @param array $ajaxoptions Options for ajax_autocompleter
  2970. * @param int $hidelabel Hide label (0=no, 1=yes)
  2971. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2972. * @param string $morecss More CSS
  2973. * @param string $placeholder Placeholder
  2974. * @return void
  2975. */
  2976. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2977. {
  2978. // phpcs:enable
  2979. global $langs, $conf;
  2980. global $price_level, $status, $finished;
  2981. if (!isset($status)) {
  2982. $status = 1;
  2983. }
  2984. $selected_input_value = '';
  2985. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2986. if ($selected > 0) {
  2987. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2988. $producttmpselect = new Product($this->db);
  2989. $producttmpselect->fetch($selected);
  2990. $selected_input_value = $producttmpselect->ref;
  2991. unset($producttmpselect);
  2992. }
  2993. // mode=2 means suppliers products
  2994. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
  2995. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2996. print ($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="minwidth300" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . '>';
  2997. } else {
  2998. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2999. }
  3000. }
  3001. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3002. /**
  3003. * Return list of suppliers products
  3004. *
  3005. * @param int $socid Id of supplier thirdparty (0 = no filter)
  3006. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  3007. * @param string $htmlname Name of HTML select
  3008. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  3009. * @param string $filtre Generic filter. Data must not come from user input.
  3010. * @param string $filterkey Filter of produdts
  3011. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  3012. * @param int $outputmode 0=HTML select string, 1=Array
  3013. * @param int $limit Limit of line number
  3014. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  3015. * @param string $morecss Add more CSS
  3016. * @param int $showstockinlist Show stock information (slower).
  3017. * @param string $placeholder Placeholder
  3018. * @return array|string Array of keys for json or HTML component
  3019. */
  3020. 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 = '')
  3021. {
  3022. // phpcs:enable
  3023. global $langs, $conf, $user;
  3024. global $hookmanager;
  3025. $out = '';
  3026. $outarray = array();
  3027. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  3028. $langs->load('stocks');
  3029. // Units
  3030. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3031. $langs->load('other');
  3032. }
  3033. $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,";
  3034. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  3035. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  3036. $sql .= " pfp.supplier_reputation";
  3037. // if we use supplier description of the products
  3038. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  3039. $sql .= ", pfp.desc_fourn as description";
  3040. } else {
  3041. $sql .= ", p.description";
  3042. }
  3043. // Units
  3044. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3045. $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";
  3046. }
  3047. if (isModEnabled('barcode')) {
  3048. $sql .= ", pfp.barcode";
  3049. }
  3050. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3051. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
  3052. if ($socid > 0) {
  3053. $sql .= " AND pfp.fk_soc = " . ((int) $socid);
  3054. }
  3055. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3056. // Units
  3057. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3058. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  3059. }
  3060. $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
  3061. if ($statut != -1) {
  3062. $sql .= " AND p.tobuy = " . ((int) $statut);
  3063. }
  3064. if (strval($filtertype) != '') {
  3065. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  3066. }
  3067. if (!empty($filtre)) {
  3068. $sql .= " " . $filtre;
  3069. }
  3070. // Add where from hooks
  3071. $parameters = array();
  3072. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3073. $sql .= $hookmanager->resPrint;
  3074. // Add criteria on ref/label
  3075. if ($filterkey != '') {
  3076. $sql .= ' AND (';
  3077. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  3078. // For natural search
  3079. $scrit = explode(' ', $filterkey);
  3080. $i = 0;
  3081. if (count($scrit) > 1) {
  3082. $sql .= "(";
  3083. }
  3084. foreach ($scrit as $crit) {
  3085. if ($i > 0) {
  3086. $sql .= " AND ";
  3087. }
  3088. $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) . "%'";
  3089. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  3090. $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  3091. }
  3092. $sql .= ")";
  3093. $i++;
  3094. }
  3095. if (count($scrit) > 1) {
  3096. $sql .= ")";
  3097. }
  3098. if (isModEnabled('barcode')) {
  3099. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3100. $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3101. }
  3102. $sql .= ')';
  3103. }
  3104. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3105. $sql .= $this->db->plimit($limit, 0);
  3106. // Build output string
  3107. dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
  3108. $result = $this->db->query($sql);
  3109. if ($result) {
  3110. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3111. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  3112. $num = $this->db->num_rows($result);
  3113. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3114. $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
  3115. if (!$selected) {
  3116. $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3117. } else {
  3118. $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3119. }
  3120. $i = 0;
  3121. while ($i < $num) {
  3122. $objp = $this->db->fetch_object($result);
  3123. if (is_null($objp->idprodfournprice)) {
  3124. // There is no supplier price found, we will use the vat rate for sale
  3125. $objp->tva_tx = $objp->tva_tx_sale;
  3126. $objp->default_vat_code = $objp->default_vat_code_sale;
  3127. }
  3128. $outkey = $objp->idprodfournprice; // id in table of price
  3129. if (!$outkey && $alsoproductwithnosupplierprice) {
  3130. $outkey = 'idprod_' . $objp->rowid; // id of product
  3131. }
  3132. $outref = $objp->ref;
  3133. $outbarcode = $objp->barcode;
  3134. $outqty = 1;
  3135. $outdiscount = 0;
  3136. $outtype = $objp->fk_product_type;
  3137. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3138. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  3139. // Units
  3140. $outvalUnits = '';
  3141. if (getDolGlobalInt('PRODUCT_USE_UNITS')) {
  3142. if (!empty($objp->unit_short)) {
  3143. $outvalUnits .= ' - ' . $objp->unit_short;
  3144. }
  3145. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3146. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3147. $outvalUnits .= ' - ' . $unitToShow;
  3148. }
  3149. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3150. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  3151. $outvalUnits .= ' - ' . $unitToShow;
  3152. }
  3153. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3154. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3155. $outvalUnits .= ' - ' . $unitToShow;
  3156. }
  3157. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3158. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3159. $outvalUnits .= ' - ' . $unitToShow;
  3160. }
  3161. if ($outdurationvalue && $outdurationunit) {
  3162. $da = array(
  3163. 'h' => $langs->trans('Hour'),
  3164. 'd' => $langs->trans('Day'),
  3165. 'w' => $langs->trans('Week'),
  3166. 'm' => $langs->trans('Month'),
  3167. 'y' => $langs->trans('Year')
  3168. );
  3169. if (isset($da[$outdurationunit])) {
  3170. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  3171. }
  3172. }
  3173. }
  3174. $objRef = $objp->ref;
  3175. if ($filterkey && $filterkey != '') {
  3176. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  3177. }
  3178. $objRefFourn = $objp->ref_fourn;
  3179. if ($filterkey && $filterkey != '') {
  3180. $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3181. }
  3182. $label = $objp->label;
  3183. if ($filterkey && $filterkey != '') {
  3184. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  3185. }
  3186. $optlabel = $objp->ref;
  3187. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3188. $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
  3189. }
  3190. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3191. $optlabel .= ' (' . $outbarcode . ')';
  3192. }
  3193. $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3194. $outvallabel = $objRef;
  3195. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3196. $outvallabel .= ' (' . $objRefFourn . ')';
  3197. }
  3198. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3199. $outvallabel .= ' (' . $outbarcode . ')';
  3200. }
  3201. $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3202. // Units
  3203. $optlabel .= $outvalUnits;
  3204. $outvallabel .= $outvalUnits;
  3205. if (!empty($objp->idprodfournprice)) {
  3206. $outqty = $objp->quantity;
  3207. $outdiscount = $objp->remise_percent;
  3208. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3209. $prod_supplier = new ProductFournisseur($this->db);
  3210. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3211. $prod_supplier->id = $objp->fk_product;
  3212. $prod_supplier->fourn_qty = $objp->quantity;
  3213. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3214. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3215. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3216. $priceparser = new PriceParser($this->db);
  3217. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3218. if ($price_result >= 0) {
  3219. $objp->fprice = $price_result;
  3220. if ($objp->quantity >= 1) {
  3221. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3222. }
  3223. }
  3224. }
  3225. if ($objp->quantity == 1) {
  3226. $optlabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3227. $outvallabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
  3228. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3229. $outvallabel .= $langs->transnoentities("Unit");
  3230. } else {
  3231. $optlabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  3232. $outvallabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  3233. $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3234. $outvallabel .= ' ' . $langs->transnoentities("Units");
  3235. }
  3236. if ($objp->quantity > 1) {
  3237. $optlabel .= " (" . price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  3238. $outvallabel .= " (" . price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  3239. }
  3240. if ($objp->remise_percent >= 1) {
  3241. $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3242. $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3243. }
  3244. if ($objp->duration) {
  3245. $optlabel .= " - " . $objp->duration;
  3246. $outvallabel .= " - " . $objp->duration;
  3247. }
  3248. if (!$socid) {
  3249. $optlabel .= " - " . dol_trunc($objp->name, 8);
  3250. $outvallabel .= " - " . dol_trunc($objp->name, 8);
  3251. }
  3252. if ($objp->supplier_reputation) {
  3253. //TODO dictionary
  3254. $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
  3255. $optlabel .= " - " . $reputations[$objp->supplier_reputation];
  3256. $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
  3257. }
  3258. } else {
  3259. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3260. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3261. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3262. } else // No supplier price defined for product, even on other suppliers
  3263. {
  3264. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3265. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3266. }
  3267. }
  3268. if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3269. $novirtualstock = ($showstockinlist == 2);
  3270. if (!empty($user->rights->stock->lire)) {
  3271. $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3272. if ($objp->stock > 0) {
  3273. $optlabel .= ' - <span class="product_line_stock_ok">';
  3274. } elseif ($objp->stock <= 0) {
  3275. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3276. }
  3277. $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
  3278. $optlabel .= '</span>';
  3279. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3280. $langs->load("stocks");
  3281. $tmpproduct = new Product($this->db);
  3282. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3283. $tmpproduct->load_virtual_stock();
  3284. $virtualstock = $tmpproduct->stock_theorique;
  3285. $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  3286. $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  3287. if ($virtualstock > 0) {
  3288. $optlabel .= '<span class="product_line_stock_ok">';
  3289. } elseif ($virtualstock <= 0) {
  3290. $optlabel .= '<span class="product_line_stock_too_low">';
  3291. }
  3292. $optlabel .= $virtualstock;
  3293. $optlabel .= '</span>';
  3294. unset($tmpproduct);
  3295. }
  3296. }
  3297. }
  3298. $optstart = '<option value="' . $outkey . '"';
  3299. if ($selected && $selected == $objp->idprodfournprice) {
  3300. $optstart .= ' selected';
  3301. }
  3302. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3303. $optstart .= ' disabled';
  3304. }
  3305. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3306. $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
  3307. $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
  3308. $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
  3309. $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"';
  3310. $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"';
  3311. $optstart .= ' data-discount="' . dol_escape_htmltag($outdiscount) . '"';
  3312. $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"';
  3313. $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"';
  3314. $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
  3315. }
  3316. $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
  3317. $outarrayentry = array(
  3318. 'key' => $outkey,
  3319. 'value' => $outref,
  3320. 'label' => $outvallabel,
  3321. 'qty' => $outqty,
  3322. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3323. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3324. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3325. 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
  3326. 'tva_tx' => price2num($objp->tva_tx),
  3327. 'default_vat_code' => $objp->default_vat_code,
  3328. 'discount' => $outdiscount,
  3329. 'type' => $outtype,
  3330. 'duration_value' => $outdurationvalue,
  3331. 'duration_unit' => $outdurationunit,
  3332. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3333. 'description' => $objp->description
  3334. );
  3335. $parameters = array(
  3336. 'objp' => &$objp,
  3337. 'optstart' => &$optstart,
  3338. 'optlabel' => &$optlabel,
  3339. 'outvallabel' => &$outvallabel,
  3340. 'outarrayentry' => &$outarrayentry
  3341. );
  3342. $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
  3343. // Add new entry
  3344. // "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
  3345. // "label" value of json key array is used by jQuery automatically as text for combo box
  3346. $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";
  3347. array_push(
  3348. $outarray,
  3349. array('key' => $outkey,
  3350. 'value' => $outref,
  3351. 'label' => $outvallabel,
  3352. 'qty' => $outqty,
  3353. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3354. 'price_qty_ht_locale' => price($objp->fprice),
  3355. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3356. 'price_unit_ht_locale' => price($objp->unitprice),
  3357. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3358. 'tva_tx_formated' => price($objp->tva_tx),
  3359. 'tva_tx' => price2num($objp->tva_tx),
  3360. 'default_vat_code' => $objp->default_vat_code,
  3361. 'discount' => $outdiscount,
  3362. 'type' => $outtype,
  3363. 'duration_value' => $outdurationvalue,
  3364. 'duration_unit' => $outdurationunit,
  3365. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3366. 'description' => $objp->description
  3367. )
  3368. );
  3369. // Exemple of var_dump $outarray
  3370. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3371. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3372. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3373. //}
  3374. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3375. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3376. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3377. $i++;
  3378. }
  3379. $out .= '</select>';
  3380. $this->db->free($result);
  3381. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3382. $out .= ajax_combobox($htmlname);
  3383. } else {
  3384. dol_print_error($this->db);
  3385. }
  3386. if (empty($outputmode)) {
  3387. return $out;
  3388. }
  3389. return $outarray;
  3390. }
  3391. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3392. /**
  3393. * Return list of suppliers prices for a product
  3394. *
  3395. * @param int $productid Id of product
  3396. * @param string $htmlname Name of HTML field
  3397. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3398. * @return string
  3399. */
  3400. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3401. {
  3402. // phpcs:enable
  3403. global $langs, $conf;
  3404. $langs->load('stocks');
  3405. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3406. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3407. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3408. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3409. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3410. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3411. $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
  3412. $sql .= " AND p.tobuy = 1";
  3413. $sql .= " AND s.fournisseur = 1";
  3414. $sql .= " AND p.rowid = " . ((int) $productid);
  3415. if (empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED)) {
  3416. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3417. } else {
  3418. $sql .= " ORDER BY pfp.unitprice ASC";
  3419. }
  3420. dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
  3421. $result = $this->db->query($sql);
  3422. if ($result) {
  3423. $num = $this->db->num_rows($result);
  3424. $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3425. if (!$num) {
  3426. $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
  3427. } else {
  3428. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3429. $form .= '<option value="0">&nbsp;</option>';
  3430. $i = 0;
  3431. while ($i < $num) {
  3432. $objp = $this->db->fetch_object($result);
  3433. $opt = '<option value="' . $objp->idprodfournprice . '"';
  3434. //if there is only one supplier, preselect it
  3435. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && !empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED))) {
  3436. $opt .= ' selected';
  3437. }
  3438. $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
  3439. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3440. $prod_supplier = new ProductFournisseur($this->db);
  3441. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3442. $prod_supplier->id = $productid;
  3443. $prod_supplier->fourn_qty = $objp->quantity;
  3444. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3445. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3446. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3447. $priceparser = new PriceParser($this->db);
  3448. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3449. if ($price_result >= 0) {
  3450. $objp->fprice = $price_result;
  3451. if ($objp->quantity >= 1) {
  3452. $objp->unitprice = $objp->fprice / $objp->quantity;
  3453. }
  3454. }
  3455. }
  3456. if ($objp->quantity == 1) {
  3457. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3458. }
  3459. $opt .= $objp->quantity . ' ';
  3460. if ($objp->quantity == 1) {
  3461. $opt .= $langs->trans("Unit");
  3462. } else {
  3463. $opt .= $langs->trans("Units");
  3464. }
  3465. if ($objp->quantity > 1) {
  3466. $opt .= " - ";
  3467. $opt .= price($objp->unitprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit");
  3468. }
  3469. if ($objp->duration) {
  3470. $opt .= " - " . $objp->duration;
  3471. }
  3472. $opt .= "</option>\n";
  3473. $form .= $opt;
  3474. $i++;
  3475. }
  3476. }
  3477. $form .= '</select>';
  3478. $this->db->free($result);
  3479. return $form;
  3480. } else {
  3481. dol_print_error($this->db);
  3482. return '';
  3483. }
  3484. }
  3485. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3486. /**
  3487. * Return list of delivery address
  3488. *
  3489. * @param string $selected Id contact pre-selectionn
  3490. * @param int $socid Id of company
  3491. * @param string $htmlname Name of HTML field
  3492. * @param int $showempty Add an empty field
  3493. * @return integer
  3494. */
  3495. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3496. {
  3497. // phpcs:enable
  3498. // looking for users
  3499. $sql = "SELECT a.rowid, a.label";
  3500. $sql .= " FROM " . $this->db->prefix() . "societe_address as a";
  3501. $sql .= " WHERE a.fk_soc = " . ((int) $socid);
  3502. $sql .= " ORDER BY a.label ASC";
  3503. dol_syslog(get_class($this) . "::select_address", LOG_DEBUG);
  3504. $resql = $this->db->query($sql);
  3505. if ($resql) {
  3506. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3507. if ($showempty) {
  3508. print '<option value="0">&nbsp;</option>';
  3509. }
  3510. $num = $this->db->num_rows($resql);
  3511. $i = 0;
  3512. if ($num) {
  3513. while ($i < $num) {
  3514. $obj = $this->db->fetch_object($resql);
  3515. if ($selected && $selected == $obj->rowid) {
  3516. print '<option value="' . $obj->rowid . '" selected>' . $obj->label . '</option>';
  3517. } else {
  3518. print '<option value="' . $obj->rowid . '">' . $obj->label . '</option>';
  3519. }
  3520. $i++;
  3521. }
  3522. }
  3523. print '</select>';
  3524. return $num;
  3525. } else {
  3526. dol_print_error($this->db);
  3527. return -1;
  3528. }
  3529. }
  3530. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3531. /**
  3532. * Load into cache list of payment terms
  3533. *
  3534. * @return int Nb of lines loaded, <0 if KO
  3535. */
  3536. public function load_cache_conditions_paiements()
  3537. {
  3538. // phpcs:enable
  3539. global $langs;
  3540. $num = count($this->cache_conditions_paiements);
  3541. if ($num > 0) {
  3542. return 0; // Cache already loaded
  3543. }
  3544. dol_syslog(__METHOD__, LOG_DEBUG);
  3545. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3546. $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
  3547. $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
  3548. $sql .= " AND active > 0";
  3549. $sql .= " ORDER BY sortorder";
  3550. $resql = $this->db->query($sql);
  3551. if ($resql) {
  3552. $num = $this->db->num_rows($resql);
  3553. $i = 0;
  3554. while ($i < $num) {
  3555. $obj = $this->db->fetch_object($resql);
  3556. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3557. $label = ($langs->trans("PaymentConditionShort" . $obj->code) != ("PaymentConditionShort" . $obj->code) ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3558. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3559. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3560. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3561. $i++;
  3562. }
  3563. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3564. return $num;
  3565. } else {
  3566. dol_print_error($this->db);
  3567. return -1;
  3568. }
  3569. }
  3570. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3571. /**
  3572. * Load int a cache property th elist of possible delivery delays.
  3573. *
  3574. * @return int Nb of lines loaded, <0 if KO
  3575. */
  3576. public function load_cache_availability()
  3577. {
  3578. // phpcs:enable
  3579. global $langs;
  3580. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3581. if ($num > 0) {
  3582. return 0; // Cache already loaded
  3583. }
  3584. dol_syslog(__METHOD__, LOG_DEBUG);
  3585. $langs->load('propal');
  3586. $sql = "SELECT rowid, code, label, position";
  3587. $sql .= " FROM " . $this->db->prefix() . 'c_availability';
  3588. $sql .= " WHERE active > 0";
  3589. $resql = $this->db->query($sql);
  3590. if ($resql) {
  3591. $num = $this->db->num_rows($resql);
  3592. $i = 0;
  3593. while ($i < $num) {
  3594. $obj = $this->db->fetch_object($resql);
  3595. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3596. $label = ($langs->trans("AvailabilityType" . $obj->code) != ("AvailabilityType" . $obj->code) ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3597. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3598. $this->cache_availability[$obj->rowid]['label'] = $label;
  3599. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3600. $i++;
  3601. }
  3602. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3603. return $num;
  3604. } else {
  3605. dol_print_error($this->db);
  3606. return -1;
  3607. }
  3608. }
  3609. /**
  3610. * Retourne la liste des types de delais de livraison possibles
  3611. *
  3612. * @param int $selected Id du type de delais pre-selectionne
  3613. * @param string $htmlname Nom de la zone select
  3614. * @param string $filtertype To add a filter
  3615. * @param int $addempty Add empty entry
  3616. * @param string $morecss More CSS
  3617. * @return void
  3618. */
  3619. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3620. {
  3621. global $langs, $user;
  3622. $this->load_cache_availability();
  3623. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3624. print '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3625. if ($addempty) {
  3626. print '<option value="0">&nbsp;</option>';
  3627. }
  3628. foreach ($this->cache_availability as $id => $arrayavailability) {
  3629. if ($selected == $id) {
  3630. print '<option value="' . $id . '" selected>';
  3631. } else {
  3632. print '<option value="' . $id . '">';
  3633. }
  3634. print dol_escape_htmltag($arrayavailability['label']);
  3635. print '</option>';
  3636. }
  3637. print '</select>';
  3638. if ($user->admin) {
  3639. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3640. }
  3641. print ajax_combobox($htmlname);
  3642. }
  3643. /**
  3644. * Load into cache cache_demand_reason, array of input reasons
  3645. *
  3646. * @return int Nb of lines loaded, <0 if KO
  3647. */
  3648. public function loadCacheInputReason()
  3649. {
  3650. global $langs;
  3651. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3652. if ($num > 0) {
  3653. return 0; // Cache already loaded
  3654. }
  3655. $sql = "SELECT rowid, code, label";
  3656. $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
  3657. $sql .= " WHERE active > 0";
  3658. $resql = $this->db->query($sql);
  3659. if ($resql) {
  3660. $num = $this->db->num_rows($resql);
  3661. $i = 0;
  3662. $tmparray = array();
  3663. while ($i < $num) {
  3664. $obj = $this->db->fetch_object($resql);
  3665. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3666. $label = ($obj->label != '-' ? $obj->label : '');
  3667. if ($langs->trans("DemandReasonType" . $obj->code) != ("DemandReasonType" . $obj->code)) {
  3668. $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3669. }
  3670. if ($langs->trans($obj->code) != $obj->code) {
  3671. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3672. }
  3673. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3674. $tmparray[$obj->rowid]['code'] = $obj->code;
  3675. $tmparray[$obj->rowid]['label'] = $label;
  3676. $i++;
  3677. }
  3678. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3679. unset($tmparray);
  3680. return $num;
  3681. } else {
  3682. dol_print_error($this->db);
  3683. return -1;
  3684. }
  3685. }
  3686. /**
  3687. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3688. * List found into table c_input_reason loaded by loadCacheInputReason
  3689. *
  3690. * @param int $selected Id or code of type origin to select by default
  3691. * @param string $htmlname Nom de la zone select
  3692. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3693. * @param int $addempty Add an empty entry
  3694. * @param string $morecss Add more css to the HTML select component
  3695. * @param int $notooltip Do not show the tooltip for admin
  3696. * @return void
  3697. */
  3698. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3699. {
  3700. global $langs, $user;
  3701. $this->loadCacheInputReason();
  3702. print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3703. if ($addempty) {
  3704. print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
  3705. }
  3706. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3707. if ($arraydemandreason['code'] == $exclude) {
  3708. continue;
  3709. }
  3710. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3711. print '<option value="' . $arraydemandreason['id'] . '" selected>';
  3712. } else {
  3713. print '<option value="' . $arraydemandreason['id'] . '">';
  3714. }
  3715. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3716. print $langs->trans($label);
  3717. print '</option>';
  3718. }
  3719. print '</select>';
  3720. if ($user->admin && empty($notooltip)) {
  3721. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3722. }
  3723. print ajax_combobox('select_' . $htmlname);
  3724. }
  3725. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3726. /**
  3727. * Charge dans cache la liste des types de paiements possibles
  3728. *
  3729. * @return int Nb of lines loaded, <0 if KO
  3730. */
  3731. public function load_cache_types_paiements()
  3732. {
  3733. // phpcs:enable
  3734. global $langs;
  3735. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3736. if ($num > 0) {
  3737. return $num; // Cache already loaded
  3738. }
  3739. dol_syslog(__METHOD__, LOG_DEBUG);
  3740. $this->cache_types_paiements = array();
  3741. $sql = "SELECT id, code, libelle as label, type, active";
  3742. $sql .= " FROM " . $this->db->prefix() . "c_paiement";
  3743. $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
  3744. $resql = $this->db->query($sql);
  3745. if ($resql) {
  3746. $num = $this->db->num_rows($resql);
  3747. $i = 0;
  3748. while ($i < $num) {
  3749. $obj = $this->db->fetch_object($resql);
  3750. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3751. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != ("PaymentTypeShort" . $obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3752. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3753. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3754. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3755. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3756. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3757. $i++;
  3758. }
  3759. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3760. return $num;
  3761. } else {
  3762. dol_print_error($this->db);
  3763. return -1;
  3764. }
  3765. }
  3766. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3767. /**
  3768. * print list of payment modes.
  3769. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3770. * See instead to force the default value by the caller.
  3771. *
  3772. * @param int $selected Id of payment term to preselect by default
  3773. * @param string $htmlname Nom de la zone select
  3774. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3775. * @param int $addempty Add an empty entry
  3776. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3777. * @param string $morecss Add more CSS on select tag
  3778. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3779. * 0 : use default deposit percentage from entry
  3780. * > 0 : force deposit percentage (for example, from company object)
  3781. * @return void
  3782. * @deprecated
  3783. */
  3784. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3785. {
  3786. // phpcs:enable
  3787. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
  3788. }
  3789. /**
  3790. * Return list of payment modes.
  3791. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3792. * See instead to force the default value by the caller.
  3793. *
  3794. * @param int $selected Id of payment term to preselect by default
  3795. * @param string $htmlname Nom de la zone select
  3796. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3797. * @param int $addempty Add an empty entry
  3798. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3799. * @param string $morecss Add more CSS on select tag
  3800. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3801. * 0 : use default deposit percentage from entry
  3802. * > 0 : force deposit percentage (for example, from company object)
  3803. * @return string String for the HTML select component
  3804. */
  3805. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3806. {
  3807. global $langs, $user, $conf;
  3808. $out = '';
  3809. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3810. $this->load_cache_conditions_paiements();
  3811. // Set default value if not already set by caller
  3812. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3813. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3814. }
  3815. $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3816. if ($addempty) {
  3817. $out .= '<option value="0">&nbsp;</option>';
  3818. }
  3819. $selectedDepositPercent = null;
  3820. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3821. if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
  3822. continue;
  3823. }
  3824. if ($selected == $id) {
  3825. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3826. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3827. } else {
  3828. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3829. }
  3830. $label = $arrayconditions['label'];
  3831. if (!empty($arrayconditions['deposit_percent'])) {
  3832. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3833. }
  3834. $out .= $label;
  3835. $out .= '</option>';
  3836. }
  3837. $out .= '</select>';
  3838. if ($user->admin && empty($noinfoadmin)) {
  3839. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3840. }
  3841. $out .= ajax_combobox($htmlname);
  3842. if ($deposit_percent >= 0) {
  3843. $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3844. $out .= $langs->trans('DepositPercent') . ' : ';
  3845. $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . $deposit_percent . '" />';
  3846. $out .= '</span>';
  3847. $out .= '
  3848. <script nonce="' . getNonce() . '">
  3849. $(document).ready(function () {
  3850. $("#' . $htmlname . '").change(function () {
  3851. let $selected = $(this).find("option:selected");
  3852. let depositPercent = $selected.attr("data-deposit_percent");
  3853. if (depositPercent.length > 0) {
  3854. $("#' . $htmlname . '_deposit_percent_container").show().find("#' . $htmlname . '_deposit_percent").val(depositPercent);
  3855. } else {
  3856. $("#' . $htmlname . '_deposit_percent_container").hide();
  3857. }
  3858. return true;
  3859. });
  3860. });
  3861. </script>';
  3862. }
  3863. return $out;
  3864. }
  3865. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3866. /**
  3867. * Return list of payment methods
  3868. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3869. *
  3870. * @param string $selected Id or code or preselected payment mode
  3871. * @param string $htmlname Name of select field
  3872. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3873. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3874. * @param int $empty 1=can be empty, 0 otherwise
  3875. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3876. * @param int $maxlength Max length of label
  3877. * @param int $active Active or not, -1 = all
  3878. * @param string $morecss Add more CSS on select tag
  3879. * @param int $nooutput 1=Return string, do not send to output
  3880. * @return string|void String for the HTML select component
  3881. */
  3882. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3883. {
  3884. // phpcs:enable
  3885. global $langs, $user, $conf;
  3886. $out = '';
  3887. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
  3888. $filterarray = array();
  3889. if ($filtertype == 'CRDT') {
  3890. $filterarray = array(0, 2, 3);
  3891. } elseif ($filtertype == 'DBIT') {
  3892. $filterarray = array(1, 2, 3);
  3893. } elseif ($filtertype != '' && $filtertype != '-1') {
  3894. $filterarray = explode(',', $filtertype);
  3895. }
  3896. $this->load_cache_types_paiements();
  3897. // Set default value if not already set by caller
  3898. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3899. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3900. }
  3901. $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3902. if ($empty) {
  3903. $out .= '<option value="">&nbsp;</option>';
  3904. }
  3905. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3906. // If not good status
  3907. if ($active >= 0 && $arraytypes['active'] != $active) {
  3908. continue;
  3909. }
  3910. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3911. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3912. continue;
  3913. }
  3914. // We discard empty line if showempty is on because an empty line has already been output.
  3915. if ($empty && empty($arraytypes['code'])) {
  3916. continue;
  3917. }
  3918. if ($format == 0) {
  3919. $out .= '<option value="' . $id . '"';
  3920. } elseif ($format == 1) {
  3921. $out .= '<option value="' . $arraytypes['code'] . '"';
  3922. } elseif ($format == 2) {
  3923. $out .= '<option value="' . $arraytypes['code'] . '"';
  3924. } elseif ($format == 3) {
  3925. $out .= '<option value="' . $id . '"';
  3926. }
  3927. // Print attribute selected or not
  3928. if ($format == 1 || $format == 2) {
  3929. if ($selected == $arraytypes['code']) {
  3930. $out .= ' selected';
  3931. }
  3932. } else {
  3933. if ($selected == $id) {
  3934. $out .= ' selected';
  3935. }
  3936. }
  3937. $out .= '>';
  3938. $value = '';
  3939. if ($format == 0) {
  3940. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3941. } elseif ($format == 1) {
  3942. $value = $arraytypes['code'];
  3943. } elseif ($format == 2) {
  3944. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3945. } elseif ($format == 3) {
  3946. $value = $arraytypes['code'];
  3947. }
  3948. $out .= $value ? $value : '&nbsp;';
  3949. $out .= '</option>';
  3950. }
  3951. $out .= '</select>';
  3952. if ($user->admin && !$noadmininfo) {
  3953. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3954. }
  3955. $out .= ajax_combobox('select' . $htmlname);
  3956. if (empty($nooutput)) {
  3957. print $out;
  3958. } else {
  3959. return $out;
  3960. }
  3961. }
  3962. /**
  3963. * Selection HT or TTC
  3964. *
  3965. * @param string $selected Id pre-selectionne
  3966. * @param string $htmlname Nom de la zone select
  3967. * @param string $addjscombo Add js combo
  3968. * @return string Code of HTML select to chose tax or not
  3969. */
  3970. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3971. {
  3972. global $langs;
  3973. $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3974. $options = array(
  3975. 'HT' => $langs->trans("HT"),
  3976. 'TTC' => $langs->trans("TTC")
  3977. );
  3978. foreach ($options as $id => $value) {
  3979. if ($selected == $id) {
  3980. $return .= '<option value="' . $id . '" selected>' . $value;
  3981. } else {
  3982. $return .= '<option value="' . $id . '">' . $value;
  3983. }
  3984. $return .= '</option>';
  3985. }
  3986. $return .= '</select>';
  3987. if ($addjscombo) {
  3988. $return .= ajax_combobox('select_' . $htmlname);
  3989. }
  3990. return $return;
  3991. }
  3992. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3993. /**
  3994. * Load in cache list of transport mode
  3995. *
  3996. * @return int Nb of lines loaded, <0 if KO
  3997. */
  3998. public function load_cache_transport_mode()
  3999. {
  4000. // phpcs:enable
  4001. global $langs;
  4002. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  4003. if ($num > 0) {
  4004. return $num; // Cache already loaded
  4005. }
  4006. dol_syslog(__METHOD__, LOG_DEBUG);
  4007. $this->cache_transport_mode = array();
  4008. $sql = "SELECT rowid, code, label, active";
  4009. $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
  4010. $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
  4011. $resql = $this->db->query($sql);
  4012. if ($resql) {
  4013. $num = $this->db->num_rows($resql);
  4014. $i = 0;
  4015. while ($i < $num) {
  4016. $obj = $this->db->fetch_object($resql);
  4017. // If traduction exist, we use it else we take the default label
  4018. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != ("PaymentTypeShort" . $obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  4019. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  4020. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  4021. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  4022. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  4023. $i++;
  4024. }
  4025. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  4026. return $num;
  4027. } else {
  4028. dol_print_error($this->db);
  4029. return -1;
  4030. }
  4031. }
  4032. /**
  4033. * Return list of transport mode for intracomm report
  4034. *
  4035. * @param string $selected Id of the transport mode pre-selected
  4036. * @param string $htmlname Name of the select field
  4037. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  4038. * @param int $empty 1=can be empty, 0 else
  4039. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  4040. * @param int $maxlength Max length of label
  4041. * @param int $active Active or not, -1 = all
  4042. * @param string $morecss Add more CSS on select tag
  4043. * @return void
  4044. */
  4045. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  4046. {
  4047. global $langs, $user;
  4048. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
  4049. $this->load_cache_transport_mode();
  4050. print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  4051. if ($empty) {
  4052. print '<option value="">&nbsp;</option>';
  4053. }
  4054. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  4055. // If not good status
  4056. if ($active >= 0 && $arraytypes['active'] != $active) {
  4057. continue;
  4058. }
  4059. // We discard empty line if showempty is on because an empty line has already been output.
  4060. if ($empty && empty($arraytypes['code'])) {
  4061. continue;
  4062. }
  4063. if ($format == 0) {
  4064. print '<option value="' . $id . '"';
  4065. } elseif ($format == 1) {
  4066. print '<option value="' . $arraytypes['code'] . '"';
  4067. } elseif ($format == 2) {
  4068. print '<option value="' . $arraytypes['code'] . '"';
  4069. } elseif ($format == 3) {
  4070. print '<option value="' . $id . '"';
  4071. }
  4072. // If text is selected, we compare with code, else with id
  4073. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  4074. print ' selected';
  4075. } elseif ($selected == $id) {
  4076. print ' selected';
  4077. }
  4078. print '>';
  4079. $value = '';
  4080. if ($format == 0) {
  4081. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4082. } elseif ($format == 1) {
  4083. $value = $arraytypes['code'];
  4084. } elseif ($format == 2) {
  4085. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4086. } elseif ($format == 3) {
  4087. $value = $arraytypes['code'];
  4088. }
  4089. print $value ? $value : '&nbsp;';
  4090. print '</option>';
  4091. }
  4092. print '</select>';
  4093. if ($user->admin && !$noadmininfo) {
  4094. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4095. }
  4096. }
  4097. /**
  4098. * Return a HTML select list of shipping mode
  4099. *
  4100. * @param string $selected Id shipping mode pre-selected
  4101. * @param string $htmlname Name of select zone
  4102. * @param string $filtre To filter list. This parameter must not come from input of users
  4103. * @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.
  4104. * @param string $moreattrib To add more attribute on select
  4105. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  4106. * @param string $morecss More CSS
  4107. * @return void
  4108. */
  4109. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  4110. {
  4111. global $langs, $conf, $user;
  4112. $langs->load("admin");
  4113. $langs->load("deliveries");
  4114. $sql = "SELECT rowid, code, libelle as label";
  4115. $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
  4116. $sql .= " WHERE active > 0";
  4117. if ($filtre) {
  4118. $sql .= " AND " . $filtre;
  4119. }
  4120. $sql .= " ORDER BY libelle ASC";
  4121. dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
  4122. $result = $this->db->query($sql);
  4123. if ($result) {
  4124. $num = $this->db->num_rows($result);
  4125. $i = 0;
  4126. if ($num) {
  4127. print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4128. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4129. print '<option value="-1">&nbsp;</option>';
  4130. }
  4131. while ($i < $num) {
  4132. $obj = $this->db->fetch_object($result);
  4133. if ($selected == $obj->rowid) {
  4134. print '<option value="' . $obj->rowid . '" selected>';
  4135. } else {
  4136. print '<option value="' . $obj->rowid . '">';
  4137. }
  4138. print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
  4139. print '</option>';
  4140. $i++;
  4141. }
  4142. print "</select>";
  4143. if ($user->admin && empty($noinfoadmin)) {
  4144. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4145. }
  4146. print ajax_combobox('select' . $htmlname);
  4147. } else {
  4148. print $langs->trans("NoShippingMethodDefined");
  4149. }
  4150. } else {
  4151. dol_print_error($this->db);
  4152. }
  4153. }
  4154. /**
  4155. * Display form to select shipping mode
  4156. *
  4157. * @param string $page Page
  4158. * @param int $selected Id of shipping mode
  4159. * @param string $htmlname Name of select html field
  4160. * @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.
  4161. * @return void
  4162. */
  4163. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4164. {
  4165. global $langs;
  4166. $langs->load("deliveries");
  4167. if ($htmlname != "none") {
  4168. print '<form method="POST" action="' . $page . '">';
  4169. print '<input type="hidden" name="action" value="setshippingmethod">';
  4170. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4171. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4172. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  4173. print '</form>';
  4174. } else {
  4175. if ($selected) {
  4176. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4177. print $langs->trans("SendingMethod" . strtoupper($code));
  4178. } else {
  4179. print "&nbsp;";
  4180. }
  4181. }
  4182. }
  4183. /**
  4184. * Creates HTML last in cycle situation invoices selector
  4185. *
  4186. * @param string $selected Preselected ID
  4187. * @param int $socid Company ID
  4188. *
  4189. * @return string HTML select
  4190. */
  4191. public function selectSituationInvoices($selected = '', $socid = 0)
  4192. {
  4193. global $langs;
  4194. $langs->load('bills');
  4195. $opt = '<option value="" selected></option>';
  4196. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4197. $sql .= ' FROM ' . $this->db->prefix() . 'facture';
  4198. $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
  4199. $sql .= ' AND situation_counter >= 1';
  4200. $sql .= ' AND fk_soc = ' . (int) $socid;
  4201. $sql .= ' AND type <> 2';
  4202. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4203. $resql = $this->db->query($sql);
  4204. if ($resql && $this->db->num_rows($resql) > 0) {
  4205. // Last seen cycle
  4206. $ref = 0;
  4207. while ($obj = $this->db->fetch_object($resql)) {
  4208. //Same cycle ?
  4209. if ($obj->situation_cycle_ref != $ref) {
  4210. // Just seen this cycle
  4211. $ref = $obj->situation_cycle_ref;
  4212. //not final ?
  4213. if ($obj->situation_final != 1) {
  4214. //Not prov?
  4215. if (substr($obj->ref, 1, 4) != 'PROV') {
  4216. if ($selected == $obj->rowid) {
  4217. $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
  4218. } else {
  4219. $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
  4220. }
  4221. }
  4222. }
  4223. }
  4224. }
  4225. } else {
  4226. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  4227. }
  4228. if ($opt == '<option value ="" selected></option>') {
  4229. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  4230. }
  4231. return $opt;
  4232. }
  4233. /**
  4234. * Creates HTML units selector (code => label)
  4235. *
  4236. * @param string $selected Preselected Unit ID
  4237. * @param string $htmlname Select name
  4238. * @param int $showempty Add a nempty line
  4239. * @param string $unit_type Restrict to one given unit type
  4240. * @return string HTML select
  4241. */
  4242. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4243. {
  4244. global $langs;
  4245. $langs->load('products');
  4246. $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
  4247. $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
  4248. $sql .= ' WHERE active > 0';
  4249. if (!empty($unit_type)) {
  4250. $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
  4251. }
  4252. $sql .= " ORDER BY sortorder";
  4253. $resql = $this->db->query($sql);
  4254. if ($resql && $this->db->num_rows($resql) > 0) {
  4255. if ($showempty) {
  4256. $return .= '<option value="none"></option>';
  4257. }
  4258. while ($res = $this->db->fetch_object($resql)) {
  4259. $unitLabel = $res->label;
  4260. if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
  4261. $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
  4262. }
  4263. if ($selected == $res->rowid) {
  4264. $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
  4265. } else {
  4266. $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
  4267. }
  4268. }
  4269. $return .= '</select>';
  4270. }
  4271. return $return;
  4272. }
  4273. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4274. /**
  4275. * Return a HTML select list of bank accounts
  4276. *
  4277. * @param string $selected Id account pre-selected
  4278. * @param string $htmlname Name of select zone
  4279. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4280. * @param string $filtre To filter list. This parameter must not come from input of users
  4281. * @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.
  4282. * @param string $moreattrib To add more attribute on select
  4283. * @param int $showcurrency Show currency in label
  4284. * @param string $morecss More CSS
  4285. * @param int $nooutput 1=Return string, do not send to output
  4286. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4287. */
  4288. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4289. {
  4290. // phpcs:enable
  4291. global $langs, $conf;
  4292. $out = '';
  4293. $langs->load("admin");
  4294. $num = 0;
  4295. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4296. $sql .= " FROM " . $this->db->prefix() . "bank_account";
  4297. $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
  4298. if ($status != 2) {
  4299. $sql .= " AND clos = " . (int) $status;
  4300. }
  4301. if ($filtre) {
  4302. $sql .= " AND " . $filtre;
  4303. }
  4304. $sql .= " ORDER BY label";
  4305. dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
  4306. $result = $this->db->query($sql);
  4307. if ($result) {
  4308. $num = $this->db->num_rows($result);
  4309. $i = 0;
  4310. if ($num) {
  4311. $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4312. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4313. $out .= '<option value="-1">&nbsp;</option>';
  4314. }
  4315. while ($i < $num) {
  4316. $obj = $this->db->fetch_object($result);
  4317. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4318. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" selected>';
  4319. } else {
  4320. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '">';
  4321. }
  4322. $out .= trim($obj->label);
  4323. if ($showcurrency) {
  4324. $out .= ' (' . $obj->currency_code . ')';
  4325. }
  4326. if ($status == 2 && $obj->status == 1) {
  4327. $out .= ' (' . $langs->trans("Closed") . ')';
  4328. }
  4329. $out .= '</option>';
  4330. $i++;
  4331. }
  4332. $out .= "</select>";
  4333. $out .= ajax_combobox('select' . $htmlname);
  4334. } else {
  4335. if ($status == 0) {
  4336. $out .= '<span class="opacitymedium">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
  4337. } else {
  4338. $out .= '<span class="opacitymedium">' . $langs->trans("NoBankAccountFound") . '</span>';
  4339. }
  4340. }
  4341. } else {
  4342. dol_print_error($this->db);
  4343. }
  4344. // Output or return
  4345. if (empty($nooutput)) {
  4346. print $out;
  4347. } else {
  4348. return $out;
  4349. }
  4350. return $num;
  4351. }
  4352. /**
  4353. * Return a HTML select list of establishment
  4354. *
  4355. * @param string $selected Id establishment pre-selected
  4356. * @param string $htmlname Name of select zone
  4357. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4358. * @param string $filtre To filter list. This parameter must not come from input of users
  4359. * @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.
  4360. * @param string $moreattrib To add more attribute on select
  4361. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4362. */
  4363. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4364. {
  4365. global $langs, $conf;
  4366. $langs->load("admin");
  4367. $num = 0;
  4368. $sql = "SELECT rowid, name, fk_country, status, entity";
  4369. $sql .= " FROM " . $this->db->prefix() . "establishment";
  4370. $sql .= " WHERE 1=1";
  4371. if ($status != 2) {
  4372. $sql .= " AND status = " . (int) $status;
  4373. }
  4374. if ($filtre) {
  4375. $sql .= " AND " . $filtre;
  4376. }
  4377. $sql .= " ORDER BY name";
  4378. dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
  4379. $result = $this->db->query($sql);
  4380. if ($result) {
  4381. $num = $this->db->num_rows($result);
  4382. $i = 0;
  4383. if ($num) {
  4384. print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4385. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4386. print '<option value="-1">&nbsp;</option>';
  4387. }
  4388. while ($i < $num) {
  4389. $obj = $this->db->fetch_object($result);
  4390. if ($selected == $obj->rowid) {
  4391. print '<option value="' . $obj->rowid . '" selected>';
  4392. } else {
  4393. print '<option value="' . $obj->rowid . '">';
  4394. }
  4395. print trim($obj->name);
  4396. if ($status == 2 && $obj->status == 1) {
  4397. print ' (' . $langs->trans("Closed") . ')';
  4398. }
  4399. print '</option>';
  4400. $i++;
  4401. }
  4402. print "</select>";
  4403. } else {
  4404. if ($status == 0) {
  4405. print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
  4406. } else {
  4407. print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
  4408. }
  4409. }
  4410. return $num;
  4411. } else {
  4412. dol_print_error($this->db);
  4413. return -1;
  4414. }
  4415. }
  4416. /**
  4417. * Display form to select bank account
  4418. *
  4419. * @param string $page Page
  4420. * @param int $selected Id of bank account
  4421. * @param string $htmlname Name of select html field
  4422. * @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.
  4423. * @return void
  4424. */
  4425. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4426. {
  4427. global $langs;
  4428. if ($htmlname != "none") {
  4429. print '<form method="POST" action="' . $page . '">';
  4430. print '<input type="hidden" name="action" value="setbankaccount">';
  4431. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4432. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4433. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4434. if ($nbaccountfound > 0) {
  4435. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  4436. }
  4437. print '</form>';
  4438. } else {
  4439. $langs->load('banks');
  4440. if ($selected) {
  4441. require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
  4442. $bankstatic = new Account($this->db);
  4443. $result = $bankstatic->fetch($selected);
  4444. if ($result) {
  4445. print $bankstatic->getNomUrl(1);
  4446. }
  4447. } else {
  4448. print "&nbsp;";
  4449. }
  4450. }
  4451. }
  4452. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4453. /**
  4454. * Return list of categories having choosed type
  4455. *
  4456. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4457. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4458. * @param string $htmlname HTML field name
  4459. * @param int $maxlength Maximum length for labels
  4460. * @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.
  4461. * $markafterid can be an :
  4462. * - int (id of category)
  4463. * - string (categories ids seprated by comma)
  4464. * - array (list of categories ids)
  4465. * @param int $outputmode 0=HTML select string, 1=Array, 2=Array extended
  4466. * @param int $include [=0] Removed or 1=Keep only
  4467. * @param string $morecss More CSS
  4468. * @return string|array
  4469. * @see select_categories()
  4470. */
  4471. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4472. {
  4473. // phpcs:enable
  4474. global $conf, $langs;
  4475. $langs->load("categories");
  4476. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  4477. // For backward compatibility
  4478. if (is_numeric($type)) {
  4479. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4480. }
  4481. if ($type === Categorie::TYPE_BANK_LINE) {
  4482. // TODO Move this into common category feature
  4483. $cate_arbo = array();
  4484. $sql = "SELECT c.label, c.rowid";
  4485. $sql .= " FROM " . $this->db->prefix() . "bank_categ as c";
  4486. $sql .= " WHERE entity = " . $conf->entity;
  4487. $sql .= " ORDER BY c.label";
  4488. $result = $this->db->query($sql);
  4489. if ($result) {
  4490. $num = $this->db->num_rows($result);
  4491. $i = 0;
  4492. while ($i < $num) {
  4493. $objp = $this->db->fetch_object($result);
  4494. if ($objp) {
  4495. $cate_arbo[$objp->rowid] = array('id' => $objp->rowid, 'fulllabel' => $objp->label, 'color' => '', 'picto' => 'category');
  4496. }
  4497. $i++;
  4498. }
  4499. $this->db->free($result);
  4500. } else {
  4501. dol_print_error($this->db);
  4502. }
  4503. } else {
  4504. $cat = new Categorie($this->db);
  4505. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4506. }
  4507. $outarray = array();
  4508. $output = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  4509. if (is_array($cate_arbo)) {
  4510. if (!count($cate_arbo)) {
  4511. $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
  4512. } else {
  4513. $output .= '<option value="-1">&nbsp;</option>';
  4514. foreach ($cate_arbo as $key => $value) {
  4515. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4516. $add = 'selected ';
  4517. } else {
  4518. $add = '';
  4519. }
  4520. $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
  4521. $output .= ' data-html="' . dol_escape_htmltag(img_picto('', 'category', 'class="pictofixedwidth" style="color: #' . $cate_arbo[$key]['color'] . '"') . dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle')) . '"';
  4522. $output .= '>';
  4523. $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4524. $output .= '</option>';
  4525. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4526. }
  4527. }
  4528. }
  4529. $output .= '</select>';
  4530. $output .= "\n";
  4531. if ($outputmode == 2) {
  4532. return $cate_arbo;
  4533. } elseif ($outputmode) {
  4534. return $outarray;
  4535. }
  4536. return $output;
  4537. }
  4538. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4539. /**
  4540. * Show a confirmation HTML form or AJAX popup
  4541. *
  4542. * @param string $page Url of page to call if confirmation is OK
  4543. * @param string $title Title
  4544. * @param string $question Question
  4545. * @param string $action Action
  4546. * @param array $formquestion An array with forms complementary inputs
  4547. * @param string $selectedchoice "" or "no" or "yes"
  4548. * @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
  4549. * @param int $height Force height of box
  4550. * @param int $width Force width of box
  4551. * @return void
  4552. * @deprecated
  4553. * @see formconfirm()
  4554. */
  4555. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4556. {
  4557. // phpcs:enable
  4558. dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4559. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4560. }
  4561. /**
  4562. * Show a confirmation HTML form or AJAX popup.
  4563. * Easiest way to use this is with useajax=1.
  4564. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4565. * just after calling this method. For example:
  4566. * print '<script nonce="'.getNonce().'" type="text/javascript">'."\n";
  4567. * print 'jQuery(document).ready(function() {'."\n";
  4568. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4569. * print '});'."\n";
  4570. * print '</script>'."\n";
  4571. *
  4572. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4573. * @param string $title Title
  4574. * @param string $question Question
  4575. * @param string $action Action
  4576. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...'))
  4577. * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss',
  4578. * 'other', 'onecolumn' or 'hidden'...
  4579. * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0
  4580. * @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
  4581. * @param int|string $height Force height of box (0 = auto)
  4582. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4583. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4584. * @param string $labelbuttonyes Label for Yes
  4585. * @param string $labelbuttonno Label for No
  4586. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4587. */
  4588. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4589. {
  4590. global $langs, $conf;
  4591. $more = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
  4592. $formconfirm = '';
  4593. $inputok = array();
  4594. $inputko = array();
  4595. // Clean parameters
  4596. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4597. if ($conf->browser->layout == 'phone') {
  4598. $width = '95%';
  4599. }
  4600. // Set height automatically if not defined
  4601. if (empty($height)) {
  4602. $height = 220;
  4603. if (is_array($formquestion) && count($formquestion) > 2) {
  4604. $height += ((count($formquestion) - 2) * 24);
  4605. }
  4606. }
  4607. if (is_array($formquestion) && !empty($formquestion)) {
  4608. // First add hidden fields and value
  4609. foreach ($formquestion as $key => $input) {
  4610. if (is_array($input) && !empty($input)) {
  4611. if ($input['type'] == 'hidden') {
  4612. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4613. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4614. $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";
  4615. }
  4616. }
  4617. }
  4618. // Now add questions
  4619. $moreonecolumn = '';
  4620. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
  4621. foreach ($formquestion as $key => $input) {
  4622. if (is_array($input) && !empty($input)) {
  4623. $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
  4624. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4625. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4626. if ($input['type'] == 'text') {
  4627. $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";
  4628. } elseif ($input['type'] == 'password') {
  4629. $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";
  4630. } elseif ($input['type'] == 'textarea') {
  4631. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4632. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4633. $more .= $input['value'];
  4634. $more .= '</textarea>';
  4635. $more .= '</div></div>'."\n";*/
  4636. $moreonecolumn .= '<div class="margintoponly">';
  4637. $moreonecolumn .= $input['label'] . '<br>';
  4638. $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
  4639. $moreonecolumn .= $input['value'];
  4640. $moreonecolumn .= '</textarea>';
  4641. $moreonecolumn .= '</div>';
  4642. } elseif (in_array($input['type'], ['select', 'multiselect'])) {
  4643. if (empty($morecss)) {
  4644. $morecss = 'minwidth100';
  4645. }
  4646. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4647. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4648. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4649. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4650. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4651. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4652. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4653. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
  4654. if (!empty($input['label'])) {
  4655. $more .= $input['label'] . '</div><div class="tagtd left">';
  4656. }
  4657. if ($input['type'] == 'select') {
  4658. $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);
  4659. } else {
  4660. $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);
  4661. }
  4662. $more .= '</div></div>' . "\n";
  4663. } elseif ($input['type'] == 'checkbox') {
  4664. $more .= '<div class="tagtr">';
  4665. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '"><label for="' . dol_escape_htmltag($input['name']) . '">' . $input['label'] . '</label></div><div class="tagtd">';
  4666. $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
  4667. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4668. $more .= ' checked';
  4669. }
  4670. if (is_bool($input['value']) && $input['value']) {
  4671. $more .= ' checked';
  4672. }
  4673. if (isset($input['disabled'])) {
  4674. $more .= ' disabled';
  4675. }
  4676. $more .= ' /></div>';
  4677. $more .= '</div>' . "\n";
  4678. } elseif ($input['type'] == 'radio') {
  4679. $i = 0;
  4680. foreach ($input['values'] as $selkey => $selval) {
  4681. $more .= '<div class="tagtr">';
  4682. if (isset($input['label'])) {
  4683. if ($i == 0) {
  4684. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4685. } else {
  4686. $more .= '<div clas="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
  4687. }
  4688. }
  4689. $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;
  4690. if (!empty($input['disabled'])) {
  4691. $more .= ' disabled';
  4692. }
  4693. if (isset($input['default']) && $input['default'] === $selkey) {
  4694. $more .= ' checked="checked"';
  4695. }
  4696. $more .= ' /> ';
  4697. $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
  4698. $more .= '</div></div>' . "\n";
  4699. $i++;
  4700. }
  4701. } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
  4702. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4703. $more .= '<div class="tagtd">';
  4704. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4705. $h = $m = 0;
  4706. if ($input['type'] == 'datetime') {
  4707. $h = isset($input['hours']) ? $input['hours'] : 1;
  4708. $m = isset($input['minutes']) ? $input['minutes'] : 1;
  4709. }
  4710. $more .= $this->selectDate($input['value'], $input['name'], $h, $m, 0, '', 1, $addnowlink);
  4711. $more .= '</div></div>'."\n";
  4712. $formquestion[] = array('name'=>$input['name'].'day');
  4713. $formquestion[] = array('name'=>$input['name'].'month');
  4714. $formquestion[] = array('name'=>$input['name'].'year');
  4715. $formquestion[] = array('name'=>$input['name'].'hour');
  4716. $formquestion[] = array('name'=>$input['name'].'min');
  4717. } elseif ($input['type'] == 'other') { // can be 1 column or 2 depending if label is set or not
  4718. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4719. if (!empty($input['label'])) {
  4720. $more .= $input['label'] . '</div><div class="tagtd">';
  4721. }
  4722. $more .= $input['value'];
  4723. $more .= '</div></div>' . "\n";
  4724. } elseif ($input['type'] == 'onecolumn') {
  4725. $moreonecolumn .= '<div class="margintoponly">';
  4726. $moreonecolumn .= $input['value'];
  4727. $moreonecolumn .= '</div>' . "\n";
  4728. } elseif ($input['type'] == 'hidden') {
  4729. // Do nothing more, already added by a previous loop
  4730. } elseif ($input['type'] == 'separator') {
  4731. $more .= '<br>';
  4732. } else {
  4733. $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
  4734. }
  4735. }
  4736. }
  4737. $more .= '</div>' . "\n";
  4738. $more .= $moreonecolumn;
  4739. }
  4740. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4741. // 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
  4742. // See page product/card.php for example
  4743. if (!empty($conf->dol_use_jmobile)) {
  4744. $useajax = 0;
  4745. }
  4746. if (empty($conf->use_javascript_ajax)) {
  4747. $useajax = 0;
  4748. }
  4749. if ($useajax) {
  4750. $autoOpen = true;
  4751. $dialogconfirm = 'dialog-confirm';
  4752. $button = '';
  4753. if (!is_numeric($useajax)) {
  4754. $button = $useajax;
  4755. $useajax = 1;
  4756. $autoOpen = false;
  4757. $dialogconfirm .= '-' . $button;
  4758. }
  4759. $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
  4760. $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
  4761. // Add input fields into list of fields to read during submit (inputok and inputko)
  4762. if (is_array($formquestion)) {
  4763. foreach ($formquestion as $key => $input) {
  4764. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4765. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4766. if (is_array($input) && isset($input['name'])) {
  4767. if (strpos($input['name'], ',') > 0) {
  4768. $inputok = array_merge($inputok, explode(',', $input['name']));
  4769. } else {
  4770. array_push($inputok, $input['name']);
  4771. }
  4772. }
  4773. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4774. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4775. array_push($inputko, $input['name']);
  4776. }
  4777. }
  4778. }
  4779. // Show JQuery confirm box.
  4780. $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
  4781. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4782. $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
  4783. }
  4784. if (!empty($more)) {
  4785. $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
  4786. }
  4787. $formconfirm .= ($question ? '<div class="confirmmessage">' . img_help('', '') . ' ' . $question . '</div>' : '');
  4788. $formconfirm .= '</div>' . "\n";
  4789. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
  4790. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  4791. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4792. $formconfirm .= 'jQuery(document).ready(function() {
  4793. $(function() {
  4794. $( "#' . $dialogconfirm . '" ).dialog(
  4795. {
  4796. autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
  4797. if ($newselectedchoice == 'no') {
  4798. $formconfirm .= '
  4799. open: function() {
  4800. $(this).parent().find("button.ui-button:eq(2)").focus();
  4801. },';
  4802. }
  4803. $jsforcursor = '';
  4804. if ($useajax == 1) {
  4805. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
  4806. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
  4807. }
  4808. $postconfirmas = 'GET';
  4809. $formconfirm .= '
  4810. resizable: false,
  4811. height: "' . $height . '",
  4812. width: "' . $width . '",
  4813. modal: true,
  4814. closeOnEscape: false,
  4815. buttons: {
  4816. "' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '": function() {
  4817. var options = "token=' . urlencode(newToken()) . '";
  4818. var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
  4819. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4820. var pageyes = "' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '";
  4821. if (inputok.length > 0) {
  4822. $.each(inputok, function(i, inputname) {
  4823. var more = "";
  4824. var inputvalue;
  4825. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4826. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4827. } else {
  4828. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4829. inputvalue = $("#" + inputname + more).val();
  4830. }
  4831. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4832. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4833. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4834. });
  4835. }
  4836. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
  4837. if (pageyes.length > 0) {';
  4838. if ($postconfirmas == 'GET') {
  4839. $formconfirm .= 'location.href = urljump;';
  4840. } else {
  4841. $formconfirm .= $jsforcursor;
  4842. $formconfirm .= 'var post = $.post(
  4843. pageyes,
  4844. options,
  4845. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4846. );';
  4847. }
  4848. $formconfirm .= '
  4849. console.log("after post ok");
  4850. }
  4851. $(this).dialog("close");
  4852. },
  4853. "' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '": function() {
  4854. var options = "token=' . urlencode(newToken()) . '";
  4855. var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
  4856. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4857. var pageno="' . dol_escape_js(!empty($pageno) ? $pageno : '') . '";
  4858. if (inputko.length > 0) {
  4859. $.each(inputko, function(i, inputname) {
  4860. var more = "";
  4861. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4862. var inputvalue = $("#" + inputname + more).val();
  4863. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4864. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4865. });
  4866. }
  4867. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
  4868. //alert(urljump);
  4869. if (pageno.length > 0) {';
  4870. if ($postconfirmas == 'GET') {
  4871. $formconfirm .= 'location.href = urljump;';
  4872. } else {
  4873. $formconfirm .= $jsforcursor;
  4874. $formconfirm .= 'var post = $.post(
  4875. pageno,
  4876. options,
  4877. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4878. );';
  4879. }
  4880. $formconfirm .= '
  4881. console.log("after post ko");
  4882. }
  4883. $(this).dialog("close");
  4884. }
  4885. }
  4886. }
  4887. );
  4888. var button = "' . $button . '";
  4889. if (button.length > 0) {
  4890. $( "#" + button ).click(function() {
  4891. $("#' . $dialogconfirm . '").dialog("open");
  4892. });
  4893. }
  4894. });
  4895. });
  4896. </script>';
  4897. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4898. } else {
  4899. $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
  4900. if (empty($disableformtag)) {
  4901. $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftroright">' . "\n";
  4902. }
  4903. $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
  4904. $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
  4905. $formconfirm .= '<table class="valid centpercent">' . "\n";
  4906. // Line title
  4907. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4908. $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
  4909. $formconfirm .= '</td></tr>' . "\n";
  4910. // Line text
  4911. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4912. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . $formquestion['text'] . '</td></tr>' . "\n";
  4913. }
  4914. // Line form fields
  4915. if ($more) {
  4916. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . "\n";
  4917. $formconfirm .= $more;
  4918. $formconfirm .= '</td></tr>' . "\n";
  4919. }
  4920. // Line with question
  4921. $formconfirm .= '<tr class="valid">';
  4922. $formconfirm .= '<td class="valid">' . $question . '</td>';
  4923. $formconfirm .= '<td class="valid center">';
  4924. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  4925. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
  4926. $formconfirm .= '</td>';
  4927. $formconfirm .= '</tr>' . "\n";
  4928. $formconfirm .= '</table>' . "\n";
  4929. if (empty($disableformtag)) {
  4930. $formconfirm .= "</form>\n";
  4931. }
  4932. $formconfirm .= '<br>';
  4933. if (!empty($conf->use_javascript_ajax)) {
  4934. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4935. $formconfirm .= '<script nonce="' . getNonce() . '" type="text/javascript">' . "\n";
  4936. $formconfirm .= '
  4937. $(document).ready(function () {
  4938. $(".confirmvalidatebutton").on("click", function() {
  4939. console.log("We click on button");
  4940. $(this).attr("disabled", "disabled");
  4941. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4942. //console.log($(this).closest("form"));
  4943. $(this).closest("form").submit();
  4944. });
  4945. });
  4946. ';
  4947. $formconfirm .= '</script>' . "\n";
  4948. }
  4949. $formconfirm .= "<!-- end formconfirm -->\n";
  4950. }
  4951. return $formconfirm;
  4952. }
  4953. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4954. /**
  4955. * Show a form to select a project
  4956. *
  4957. * @param int $page Page
  4958. * @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)
  4959. * @param int $selected Id pre-selected project
  4960. * @param string $htmlname Name of select field
  4961. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4962. * @param int $maxlength Max length
  4963. * @param int $forcefocus Force focus on field (works with javascript only)
  4964. * @param int $nooutput No print is done. String is returned.
  4965. * @param string $textifnoproject Text to show if no project
  4966. * @param string $morecss More CSS
  4967. * @return string Return html content
  4968. */
  4969. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
  4970. {
  4971. // phpcs:enable
  4972. global $langs;
  4973. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  4974. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  4975. $out = '';
  4976. $formproject = new FormProjets($this->db);
  4977. $langs->load("project");
  4978. if ($htmlname != "none") {
  4979. $out .= '<form method="post" action="' . $page . '">';
  4980. $out .= '<input type="hidden" name="action" value="classin">';
  4981. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  4982. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
  4983. $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  4984. $out .= '</form>';
  4985. } else {
  4986. $out .= '<span class="project_head_block">';
  4987. if ($selected) {
  4988. $projet = new Project($this->db);
  4989. $projet->fetch($selected);
  4990. $out .= $projet->getNomUrl(0, '', 1);
  4991. } else {
  4992. $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
  4993. }
  4994. $out .= '</span>';
  4995. }
  4996. if (empty($nooutput)) {
  4997. print $out;
  4998. return '';
  4999. }
  5000. return $out;
  5001. }
  5002. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5003. /**
  5004. * Show a form to select payment conditions
  5005. *
  5006. * @param int $page Page
  5007. * @param string $selected Id condition pre-selectionne
  5008. * @param string $htmlname Name of select html field
  5009. * @param int $addempty Add empty entry
  5010. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5011. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  5012. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  5013. * 0 : use default deposit percentage from entry
  5014. * > 0 : force deposit percentage (for example, from company object)
  5015. * @param int $nooutput No print is done. String is returned.
  5016. * @return string HTML output or ''
  5017. */
  5018. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
  5019. {
  5020. // phpcs:enable
  5021. global $langs;
  5022. $out = '';
  5023. if ($htmlname != "none") {
  5024. $out .= '<form method="POST" action="' . $page . '">';
  5025. $out .= '<input type="hidden" name="action" value="setconditions">';
  5026. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5027. if ($type) {
  5028. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5029. }
  5030. $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  5031. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5032. $out .= '</form>';
  5033. } else {
  5034. if ($selected) {
  5035. $this->load_cache_conditions_paiements();
  5036. if (isset($this->cache_conditions_paiements[$selected])) {
  5037. $label = $this->cache_conditions_paiements[$selected]['label'];
  5038. if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  5039. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  5040. }
  5041. $out .= $label;
  5042. } else {
  5043. $langs->load('errors');
  5044. $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
  5045. }
  5046. } else {
  5047. $out .= '&nbsp;';
  5048. }
  5049. }
  5050. if (empty($nooutput)) {
  5051. print $out;
  5052. return '';
  5053. }
  5054. return $out;
  5055. }
  5056. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5057. /**
  5058. * Show a form to select a delivery delay
  5059. *
  5060. * @param int $page Page
  5061. * @param string $selected Id condition pre-selectionne
  5062. * @param string $htmlname Name of select html field
  5063. * @param int $addempty Add an empty entry
  5064. * @return void
  5065. */
  5066. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  5067. {
  5068. // phpcs:enable
  5069. global $langs;
  5070. if ($htmlname != "none") {
  5071. print '<form method="post" action="' . $page . '">';
  5072. print '<input type="hidden" name="action" value="setavailability">';
  5073. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5074. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  5075. print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5076. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
  5077. print '</form>';
  5078. } else {
  5079. if ($selected) {
  5080. $this->load_cache_availability();
  5081. print $this->cache_availability[$selected]['label'];
  5082. } else {
  5083. print "&nbsp;";
  5084. }
  5085. }
  5086. }
  5087. /**
  5088. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  5089. * List found into table c_input_reason loaded by loadCacheInputReason
  5090. *
  5091. * @param string $page Page
  5092. * @param string $selected Id condition pre-selectionne
  5093. * @param string $htmlname Name of select html field
  5094. * @param int $addempty Add empty entry
  5095. * @return void
  5096. */
  5097. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  5098. {
  5099. global $langs;
  5100. if ($htmlname != "none") {
  5101. print '<form method="post" action="' . $page . '">';
  5102. print '<input type="hidden" name="action" value="setdemandreason">';
  5103. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5104. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  5105. print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5106. print '</form>';
  5107. } else {
  5108. if ($selected) {
  5109. $this->loadCacheInputReason();
  5110. foreach ($this->cache_demand_reason as $key => $val) {
  5111. if ($val['id'] == $selected) {
  5112. print $val['label'];
  5113. break;
  5114. }
  5115. }
  5116. } else {
  5117. print "&nbsp;";
  5118. }
  5119. }
  5120. }
  5121. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5122. /**
  5123. * Show a form + html select a date
  5124. *
  5125. * @param string $page Page
  5126. * @param string $selected Date preselected
  5127. * @param string $htmlname Html name of date input fields or 'none'
  5128. * @param int $displayhour Display hour selector
  5129. * @param int $displaymin Display minutes selector
  5130. * @param int $nooutput 1=No print output, return string
  5131. * @param string $type 'direct-debit' or 'bank-transfer'
  5132. * @return string
  5133. * @see selectDate()
  5134. */
  5135. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  5136. {
  5137. // phpcs:enable
  5138. global $langs;
  5139. $ret = '';
  5140. if ($htmlname != "none") {
  5141. $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5142. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5143. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5144. if ($type) {
  5145. $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5146. }
  5147. $ret .= '<table class="nobordernopadding">';
  5148. $ret .= '<tr><td>';
  5149. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
  5150. $ret .= '</td>';
  5151. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5152. $ret .= '</tr></table></form>';
  5153. } else {
  5154. if ($displayhour) {
  5155. $ret .= dol_print_date($selected, 'dayhour');
  5156. } else {
  5157. $ret .= dol_print_date($selected, 'day');
  5158. }
  5159. }
  5160. if (empty($nooutput)) {
  5161. print $ret;
  5162. }
  5163. return $ret;
  5164. }
  5165. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5166. /**
  5167. * Show a select form to choose a user
  5168. *
  5169. * @param string $page Page
  5170. * @param string $selected Id of user preselected
  5171. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  5172. * @param array $exclude List of users id to exclude
  5173. * @param array $include List of users id to include
  5174. * @return void
  5175. */
  5176. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  5177. {
  5178. // phpcs:enable
  5179. global $langs;
  5180. if ($htmlname != "none") {
  5181. print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5182. print '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5183. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5184. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5185. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5186. print '</form>';
  5187. } else {
  5188. if ($selected) {
  5189. require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
  5190. $theuser = new User($this->db);
  5191. $theuser->fetch($selected);
  5192. print $theuser->getNomUrl(1);
  5193. } else {
  5194. print "&nbsp;";
  5195. }
  5196. }
  5197. }
  5198. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5199. /**
  5200. * Show form with payment mode
  5201. *
  5202. * @param string $page Page
  5203. * @param int $selected Id mode pre-selectionne
  5204. * @param string $htmlname Name of select html field
  5205. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5206. * @param int $active Active or not, -1 = all
  5207. * @param int $addempty 1=Add empty entry
  5208. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5209. * @param int $nooutput 1=Return string, no output
  5210. * @return string HTML output or ''
  5211. */
  5212. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
  5213. {
  5214. // phpcs:enable
  5215. global $langs;
  5216. $out = '';
  5217. if ($htmlname != "none") {
  5218. $out .= '<form method="POST" action="' . $page . '">';
  5219. $out .= '<input type="hidden" name="action" value="setmode">';
  5220. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5221. if ($type) {
  5222. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5223. }
  5224. $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5225. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5226. $out .= '</form>';
  5227. } else {
  5228. if ($selected) {
  5229. $this->load_cache_types_paiements();
  5230. $out .= $this->cache_types_paiements[$selected]['label'];
  5231. } else {
  5232. $out .= "&nbsp;";
  5233. }
  5234. }
  5235. if ($nooutput) {
  5236. return $out;
  5237. } else {
  5238. print $out;
  5239. }
  5240. return '';
  5241. }
  5242. /**
  5243. * Show form with transport mode
  5244. *
  5245. * @param string $page Page
  5246. * @param int $selected Id mode pre-select
  5247. * @param string $htmlname Name of select html field
  5248. * @param int $active Active or not, -1 = all
  5249. * @param int $addempty 1=Add empty entry
  5250. * @return void
  5251. */
  5252. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5253. {
  5254. global $langs;
  5255. if ($htmlname != "none") {
  5256. print '<form method="POST" action="' . $page . '">';
  5257. print '<input type="hidden" name="action" value="settransportmode">';
  5258. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5259. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5260. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5261. print '</form>';
  5262. } else {
  5263. if ($selected) {
  5264. $this->load_cache_transport_mode();
  5265. print $this->cache_transport_mode[$selected]['label'];
  5266. } else {
  5267. print "&nbsp;";
  5268. }
  5269. }
  5270. }
  5271. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5272. /**
  5273. * Show form with multicurrency code
  5274. *
  5275. * @param string $page Page
  5276. * @param string $selected code pre-selectionne
  5277. * @param string $htmlname Name of select html field
  5278. * @return void
  5279. */
  5280. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5281. {
  5282. // phpcs:enable
  5283. global $langs;
  5284. if ($htmlname != "none") {
  5285. print '<form method="POST" action="' . $page . '">';
  5286. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5287. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5288. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5289. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5290. print '</form>';
  5291. } else {
  5292. dol_include_once('/core/lib/company.lib.php');
  5293. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5294. }
  5295. }
  5296. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5297. /**
  5298. * Show form with multicurrency rate
  5299. *
  5300. * @param string $page Page
  5301. * @param double $rate Current rate
  5302. * @param string $htmlname Name of select html field
  5303. * @param string $currency Currency code to explain the rate
  5304. * @return void
  5305. */
  5306. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5307. {
  5308. // phpcs:enable
  5309. global $langs, $mysoc, $conf;
  5310. if ($htmlname != "none") {
  5311. print '<form method="POST" action="' . $page . '">';
  5312. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5313. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5314. print '<input type="text" class="maxwidth100" name="' . $htmlname . '" value="' . (!empty($rate) ? price(price2num($rate, 'CU')) : 1) . '" /> ';
  5315. print '<select name="calculation_mode">';
  5316. print '<option value="1">Change ' . $langs->trans("PriceUHT") . ' of lines</option>';
  5317. print '<option value="2">Change ' . $langs->trans("PriceUHTCurrency") . ' of lines</option>';
  5318. print '</select> ';
  5319. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5320. print '</form>';
  5321. } else {
  5322. if (!empty($rate)) {
  5323. print price($rate, 1, $langs, 1, 0);
  5324. if ($currency && $rate != 1) {
  5325. print ' &nbsp; (' . price($rate, 1, $langs, 1, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')';
  5326. }
  5327. } else {
  5328. print 1;
  5329. }
  5330. }
  5331. }
  5332. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5333. /**
  5334. * Show a select box with available absolute discounts
  5335. *
  5336. * @param string $page Page URL where form is shown
  5337. * @param int $selected Value pre-selected
  5338. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5339. * @param int $socid Third party id
  5340. * @param float $amount Total amount available
  5341. * @param string $filter SQL filter on discounts
  5342. * @param int $maxvalue Max value for lines that can be selected
  5343. * @param string $more More string to add
  5344. * @param int $hidelist 1=Hide list
  5345. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5346. * @return void
  5347. */
  5348. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5349. {
  5350. // phpcs:enable
  5351. global $conf, $langs;
  5352. if ($htmlname != "none") {
  5353. print '<form method="post" action="' . $page . '">';
  5354. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5355. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5356. print '<div class="inline-block">';
  5357. if (!empty($discount_type)) {
  5358. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5359. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5360. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5361. } else {
  5362. $translationKey = 'HasCreditNoteFromSupplier';
  5363. }
  5364. } else {
  5365. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5366. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5367. } else {
  5368. $translationKey = 'HasCreditNoteFromSupplier';
  5369. }
  5370. }
  5371. } else {
  5372. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5373. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5374. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5375. } else {
  5376. $translationKey = 'CompanyHasCreditNote';
  5377. }
  5378. } else {
  5379. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5380. $translationKey = 'CompanyHasAbsoluteDiscount';
  5381. } else {
  5382. $translationKey = 'CompanyHasCreditNote';
  5383. }
  5384. }
  5385. }
  5386. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5387. if (empty($hidelist)) {
  5388. print ' ';
  5389. }
  5390. print '</div>';
  5391. if (empty($hidelist)) {
  5392. print '<div class="inline-block" style="padding-right: 10px">';
  5393. $newfilter = 'discount_type=' . intval($discount_type);
  5394. if (!empty($discount_type)) {
  5395. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5396. } else {
  5397. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5398. }
  5399. if ($filter) {
  5400. $newfilter .= ' AND (' . $filter . ')';
  5401. }
  5402. // output the combo of discounts
  5403. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5404. if ($nbqualifiedlines > 0) {
  5405. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
  5406. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5407. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5408. }
  5409. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5410. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5411. }
  5412. print '>';
  5413. }
  5414. print '</div>';
  5415. }
  5416. if ($more) {
  5417. print '<div class="inline-block">';
  5418. print $more;
  5419. print '</div>';
  5420. }
  5421. print '</form>';
  5422. } else {
  5423. if ($selected) {
  5424. print $selected;
  5425. } else {
  5426. print "0";
  5427. }
  5428. }
  5429. }
  5430. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5431. /**
  5432. * Show forms to select a contact
  5433. *
  5434. * @param string $page Page
  5435. * @param Societe $societe Filter on third party
  5436. * @param int $selected Id contact pre-selectionne
  5437. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5438. * @return void
  5439. */
  5440. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5441. {
  5442. // phpcs:enable
  5443. global $langs, $conf;
  5444. if ($htmlname != "none") {
  5445. print '<form method="post" action="' . $page . '">';
  5446. print '<input type="hidden" name="action" value="set_contact">';
  5447. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5448. print '<table class="nobordernopadding">';
  5449. print '<tr><td>';
  5450. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5451. $num = $this->num;
  5452. if ($num == 0) {
  5453. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5454. print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&amp;action=create&amp;backtoreferer=1">' . $addcontact . '</a>';
  5455. }
  5456. print '</td>';
  5457. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5458. print '</tr></table></form>';
  5459. } else {
  5460. if ($selected) {
  5461. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  5462. $contact = new Contact($this->db);
  5463. $contact->fetch($selected);
  5464. print $contact->getFullName($langs);
  5465. } else {
  5466. print "&nbsp;";
  5467. }
  5468. }
  5469. }
  5470. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5471. /**
  5472. * Output html select to select thirdparty
  5473. *
  5474. * @param string $page Page
  5475. * @param string $selected Id preselected
  5476. * @param string $htmlname Name of HTML select
  5477. * @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.
  5478. * @param int $showempty Add an empty field
  5479. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5480. * @param int $forcecombo Force to use combo box
  5481. * @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')))
  5482. * @param int $nooutput No print output. Return it only.
  5483. * @param array $excludeids Exclude IDs from the select combo
  5484. * @param string $textifnothirdparty Text to show if no thirdparty
  5485. * @return string HTML output or ''
  5486. */
  5487. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
  5488. {
  5489. // phpcs:enable
  5490. global $langs;
  5491. $out = '';
  5492. if ($htmlname != "none") {
  5493. $out .= '<form method="post" action="' . $page . '">';
  5494. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5495. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5496. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5497. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5498. $out .= '</form>';
  5499. } else {
  5500. if ($selected) {
  5501. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  5502. $soc = new Societe($this->db);
  5503. $soc->fetch($selected);
  5504. $out .= $soc->getNomUrl(0, '');
  5505. } else {
  5506. $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
  5507. }
  5508. }
  5509. if ($nooutput) {
  5510. return $out;
  5511. } else {
  5512. print $out;
  5513. }
  5514. return '';
  5515. }
  5516. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5517. /**
  5518. * Retourne la liste des devises, dans la langue de l'utilisateur
  5519. *
  5520. * @param string $selected preselected currency code
  5521. * @param string $htmlname name of HTML select list
  5522. * @deprecated
  5523. * @return void
  5524. */
  5525. public function select_currency($selected = '', $htmlname = 'currency_id')
  5526. {
  5527. // phpcs:enable
  5528. print $this->selectCurrency($selected, $htmlname);
  5529. }
  5530. /**
  5531. * Retourne la liste des devises, dans la langue de l'utilisateur
  5532. *
  5533. * @param string $selected preselected currency code
  5534. * @param string $htmlname name of HTML select list
  5535. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5536. * @param string $useempty '1'=Allow empty value
  5537. * @return string
  5538. */
  5539. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5540. {
  5541. global $conf, $langs, $user;
  5542. $langs->loadCacheCurrencies('');
  5543. $out = '';
  5544. if ($selected == 'euro' || $selected == 'euros') {
  5545. $selected = 'EUR'; // Pour compatibilite
  5546. }
  5547. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
  5548. if ($useempty) {
  5549. $out .= '<option value="-1" selected></option>';
  5550. }
  5551. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5552. $labeltoshow = $currency['label'];
  5553. if ($mode == 1) {
  5554. $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
  5555. } else {
  5556. $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
  5557. }
  5558. if ($selected && $selected == $code_iso) {
  5559. $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5560. } else {
  5561. $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5562. }
  5563. $out .= $labeltoshow;
  5564. $out .= '</option>';
  5565. }
  5566. $out .= '</select>';
  5567. if ($user->admin) {
  5568. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5569. }
  5570. // Make select dynamic
  5571. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5572. $out .= ajax_combobox($htmlname);
  5573. return $out;
  5574. }
  5575. /**
  5576. * Return array of currencies in user language
  5577. *
  5578. * @param string $selected Preselected currency code
  5579. * @param string $htmlname Name of HTML select list
  5580. * @param integer $useempty 1=Add empty line
  5581. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5582. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5583. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5584. * @param string $morecss More css
  5585. * @return string
  5586. */
  5587. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5588. {
  5589. global $conf, $langs;
  5590. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5591. $TCurrency = array();
  5592. $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
  5593. $sql .= " WHERE entity IN ('" . getEntity('mutlicurrency') . "')";
  5594. if ($filter) {
  5595. $sql .= " AND " . $filter;
  5596. }
  5597. $resql = $this->db->query($sql);
  5598. if ($resql) {
  5599. while ($obj = $this->db->fetch_object($resql)) {
  5600. $TCurrency[$obj->code] = $obj->code;
  5601. }
  5602. }
  5603. $out = '';
  5604. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  5605. if ($useempty) {
  5606. $out .= '<option value="">&nbsp;</option>';
  5607. }
  5608. // If company current currency not in table, we add it into list. Should always be available.
  5609. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5610. $TCurrency[$conf->currency] = $conf->currency;
  5611. }
  5612. if (count($TCurrency) > 0) {
  5613. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5614. if (isset($TCurrency[$code_iso])) {
  5615. if (!empty($selected) && $selected == $code_iso) {
  5616. $out .= '<option value="' . $code_iso . '" selected="selected">';
  5617. } else {
  5618. $out .= '<option value="' . $code_iso . '">';
  5619. }
  5620. $out .= $currency['label'];
  5621. $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
  5622. $out .= '</option>';
  5623. }
  5624. }
  5625. }
  5626. $out .= '</select>';
  5627. // Make select dynamic
  5628. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5629. $out .= ajax_combobox($htmlname);
  5630. return $out;
  5631. }
  5632. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5633. /**
  5634. * Load into the cache vat rates of a country
  5635. *
  5636. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5637. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5638. */
  5639. public function load_cache_vatrates($country_code)
  5640. {
  5641. // phpcs:enable
  5642. global $langs, $user;
  5643. $num = count($this->cache_vatrates);
  5644. if ($num > 0) {
  5645. return $num; // Cache already loaded
  5646. }
  5647. dol_syslog(__METHOD__, LOG_DEBUG);
  5648. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5649. $sql .= " FROM " . $this->db->prefix() . "c_tva as t, " . $this->db->prefix() . "c_country as c";
  5650. $sql .= " WHERE t.fk_pays = c.rowid";
  5651. $sql .= " AND t.active > 0";
  5652. $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
  5653. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5654. $resql = $this->db->query($sql);
  5655. if ($resql) {
  5656. $num = $this->db->num_rows($resql);
  5657. if ($num) {
  5658. for ($i = 0; $i < $num; $i++) {
  5659. $obj = $this->db->fetch_object($resql);
  5660. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5661. $this->cache_vatrates[$i]['code'] = $obj->code;
  5662. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5663. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5664. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5665. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5666. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5667. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5668. $this->cache_vatrates[$i]['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
  5669. $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
  5670. $positiverates = '';
  5671. if ($obj->taux) {
  5672. $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
  5673. }
  5674. if ($obj->localtax1) {
  5675. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
  5676. }
  5677. if ($obj->localtax2) {
  5678. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
  5679. }
  5680. if (empty($positiverates)) {
  5681. $positiverates = '0';
  5682. }
  5683. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
  5684. }
  5685. return $num;
  5686. } else {
  5687. $this->error = '<span class="error">';
  5688. $this->error .= $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code);
  5689. $reg = array();
  5690. if (!empty($user) && $user->admin && preg_match('/\'(..)\'/', $country_code, $reg)) {
  5691. $langs->load("errors");
  5692. $new_country_code = $reg[1];
  5693. $country_id = dol_getIdFromCode($this->db, $new_country_code, 'c_pays', 'code', 'rowid');
  5694. $this->error .= '<br>'.$langs->trans("ErrorFixThisHere", DOL_URL_ROOT.'/admin/dict.php?id=10'.($country_id > 0 ? '&countryidforinsert='.$country_id : ''));
  5695. }
  5696. $this->error .= '</span>';
  5697. return -1;
  5698. }
  5699. } else {
  5700. $this->error = '<span class="error">' . $this->db->error() . '</span>';
  5701. return -2;
  5702. }
  5703. }
  5704. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5705. /**
  5706. * Output an HTML select vat rate.
  5707. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5708. *
  5709. * @param string $htmlname Name of HTML select field
  5710. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5711. * @param Societe $societe_vendeuse Thirdparty seller
  5712. * @param Societe $societe_acheteuse Thirdparty buyer
  5713. * @param int $idprod Id product. O if unknown of NA.
  5714. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5715. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5716. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5717. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5718. * 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.
  5719. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5720. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5721. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5722. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5723. * @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
  5724. * @return string
  5725. */
  5726. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5727. {
  5728. // phpcs:enable
  5729. global $langs, $conf, $mysoc;
  5730. $langs->load('errors');
  5731. $return = '';
  5732. // Define defaultnpr, defaultttx and defaultcode
  5733. $defaultnpr = ($info_bits & 0x01);
  5734. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5735. $defaulttx = str_replace('*', '', $selectedrate);
  5736. $defaultcode = '';
  5737. $reg = array();
  5738. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5739. $defaultcode = $reg[1];
  5740. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5741. }
  5742. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5743. // Check parameters
  5744. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5745. if ($societe_vendeuse->id == $mysoc->id) {
  5746. $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
  5747. } else {
  5748. $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
  5749. }
  5750. return $return;
  5751. }
  5752. //var_dump($societe_acheteuse);
  5753. //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";
  5754. //exit;
  5755. // Define list of countries to use to search VAT rates to show
  5756. // First we defined code_country to use to find list
  5757. if (is_object($societe_vendeuse)) {
  5758. $code_country = "'" . $societe_vendeuse->country_code . "'";
  5759. } else {
  5760. $code_country = "'" . $mysoc->country_code . "'"; // Pour compatibilite ascendente
  5761. }
  5762. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5763. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  5764. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5765. // We also add the buyer country code
  5766. if (is_numeric($type)) {
  5767. if ($type == 1) { // We know product is a service
  5768. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5769. }
  5770. } elseif (!$idprod) { // We don't know type of product
  5771. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5772. } else {
  5773. $prodstatic = new Product($this->db);
  5774. $prodstatic->fetch($idprod);
  5775. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5776. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5777. }
  5778. }
  5779. }
  5780. }
  5781. // Now we get list
  5782. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5783. if ($num > 0) {
  5784. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5785. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5786. $tmpthirdparty = new Societe($this->db);
  5787. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5788. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5789. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5790. $defaultcode = $reg[1];
  5791. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5792. }
  5793. if (empty($defaulttx)) {
  5794. $defaultnpr = 0;
  5795. }
  5796. }
  5797. // If we fails to find a default vat rate, we take the last one in list
  5798. // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
  5799. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5800. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5801. // We take the last one found in list
  5802. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5803. } else {
  5804. // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
  5805. $defaulttx = '';
  5806. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5807. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5808. }
  5809. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5810. $defaultcode = $reg[1];
  5811. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5812. }
  5813. }
  5814. }
  5815. // Disabled if seller is not subject to VAT
  5816. $disabled = false;
  5817. $title = '';
  5818. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5819. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5820. // of using supplier invoices (this is a very bad idea !)
  5821. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5822. $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
  5823. $disabled = true;
  5824. }
  5825. }
  5826. if (!$options_only) {
  5827. $return .= '<select class="flat minwidth50imp maxwidth100" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
  5828. }
  5829. $selectedfound = false;
  5830. foreach ($this->cache_vatrates as $rate) {
  5831. // Keep only 0 if seller is not subject to VAT
  5832. if ($disabled && $rate['txtva'] != 0) {
  5833. continue;
  5834. }
  5835. // Define key to use into select list
  5836. $key = $rate['txtva'];
  5837. $key .= $rate['nprtva'] ? '*' : '';
  5838. if ($mode > 0 && $rate['code']) {
  5839. $key .= ' (' . $rate['code'] . ')';
  5840. }
  5841. if ($mode < 0) {
  5842. $key = $rate['rowid'];
  5843. }
  5844. $return .= '<option value="' . $key . '"';
  5845. if (!$selectedfound) {
  5846. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5847. if ($defaultcode == $rate['code']) {
  5848. $return .= ' selected';
  5849. $selectedfound = true;
  5850. }
  5851. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5852. $return .= ' selected';
  5853. $selectedfound = true;
  5854. }
  5855. }
  5856. $return .= '>';
  5857. // Show label of VAT
  5858. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5859. // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
  5860. $return .= $rate['labelpositiverates'];
  5861. } else {
  5862. // Simple label
  5863. $return .= vatrate($rate['label']);
  5864. }
  5865. //$return.=($rate['code']?' '.$rate['code']:'');
  5866. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5867. $return .= '</option>';
  5868. }
  5869. if (!$options_only) {
  5870. $return .= '</select>';
  5871. //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
  5872. }
  5873. } else {
  5874. $return .= $this->error;
  5875. }
  5876. $this->num = $num;
  5877. return $return;
  5878. }
  5879. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5880. /**
  5881. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5882. * Fields are preselected with :
  5883. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5884. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5885. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5886. *
  5887. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5888. * @param string $prefix Prefix for fields name
  5889. * @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
  5890. * @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
  5891. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5892. * @param string $form_name Not used
  5893. * @param int $d 1=Show days, month, years
  5894. * @param int $addnowlink Add a link "Now"
  5895. * @param int $nooutput Do not output html string but return it
  5896. * @param int $disabled Disable input fields
  5897. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5898. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5899. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5900. * @return string '' or HTML component string if nooutput is 1
  5901. * @deprecated
  5902. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5903. */
  5904. public function select_date($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $nooutput = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '')
  5905. {
  5906. // phpcs:enable
  5907. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5908. if (!empty($nooutput)) {
  5909. return $retstring;
  5910. }
  5911. print $retstring;
  5912. return '';
  5913. }
  5914. /**
  5915. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5916. * Fields are preselected with :
  5917. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5918. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5919. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5920. *
  5921. * @param integer $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5922. * @param integer $set_time_end Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
  5923. * @param string $prefix Prefix for fields name
  5924. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5925. * @param string $forcenewline Force new line between the 2 dates.
  5926. * @return string Html for selectDate
  5927. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5928. */
  5929. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5930. {
  5931. global $langs;
  5932. $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5933. if ($forcenewline) {
  5934. $ret .= '<br>';
  5935. }
  5936. $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5937. return $ret;
  5938. }
  5939. /**
  5940. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5941. * Fields are preselected with :
  5942. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5943. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5944. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5945. *
  5946. * @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).
  5947. * @param string $prefix Prefix for fields name
  5948. * @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
  5949. * @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
  5950. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5951. * @param string $form_name Not used
  5952. * @param int $d 1=Show days, month, years
  5953. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5954. * @param int $disabled Disable input fields
  5955. * @param int $fullday When a checkbox with id #fullday is checked, hours are set with 00:00 (if value if 'fulldaystart') or 23:59 (if value is 'fulldayend')
  5956. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5957. * @param datetime|string|array $adddateof Add a link "Date of ..." using the following date. Must be array(array('adddateof'=>..., 'labeladddateof'=>...))
  5958. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5959. * @param int $stepminutes Specify step for minutes between 1 and 30
  5960. * @param string $labeladddateof Label to use for the $adddateof parameter. Deprecated. Used only when $adddateof is not an array.
  5961. * @param string $placeholder Placeholder
  5962. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5963. * @return string Html for selectDate
  5964. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5965. */
  5966. 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')
  5967. {
  5968. global $conf, $langs;
  5969. if ($gm === 'auto') {
  5970. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5971. }
  5972. $retstring = '';
  5973. if ($prefix == '') {
  5974. $prefix = 're';
  5975. }
  5976. if ($h == '') {
  5977. $h = 0;
  5978. }
  5979. if ($m == '') {
  5980. $m = 0;
  5981. }
  5982. $emptydate = 0;
  5983. $emptyhours = 0;
  5984. if ($stepminutes <= 0 || $stepminutes > 30) {
  5985. $stepminutes = 1;
  5986. }
  5987. if ($empty == 1) {
  5988. $emptydate = 1;
  5989. $emptyhours = 1;
  5990. }
  5991. if ($empty == 2) {
  5992. $emptydate = 0;
  5993. $emptyhours = 1;
  5994. }
  5995. $orig_set_time = $set_time;
  5996. if ($set_time === '' && $emptydate == 0) {
  5997. include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  5998. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5999. $set_time = dol_now($gm);
  6000. } else {
  6001. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  6002. }
  6003. }
  6004. // Analysis of the pre-selection date
  6005. $reg = array();
  6006. $shour = '';
  6007. $smin = '';
  6008. $ssec = '';
  6009. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  6010. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  6011. $syear = (!empty($reg[1]) ? $reg[1] : '');
  6012. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  6013. $sday = (!empty($reg[3]) ? $reg[3] : '');
  6014. $shour = (!empty($reg[4]) ? $reg[4] : '');
  6015. $smin = (!empty($reg[5]) ? $reg[5] : '');
  6016. } elseif (strval($set_time) != '' && $set_time != -1) {
  6017. // set_time est un timestamps (0 possible)
  6018. $syear = dol_print_date($set_time, "%Y", $gm);
  6019. $smonth = dol_print_date($set_time, "%m", $gm);
  6020. $sday = dol_print_date($set_time, "%d", $gm);
  6021. if ($orig_set_time != '') {
  6022. $shour = dol_print_date($set_time, "%H", $gm);
  6023. $smin = dol_print_date($set_time, "%M", $gm);
  6024. $ssec = dol_print_date($set_time, "%S", $gm);
  6025. }
  6026. } else {
  6027. // Date est '' ou vaut -1
  6028. $syear = '';
  6029. $smonth = '';
  6030. $sday = '';
  6031. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  6032. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  6033. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  6034. }
  6035. if ($h == 3) {
  6036. $shour = '';
  6037. }
  6038. if ($m == 3) {
  6039. $smin = '';
  6040. }
  6041. $nowgmt = dol_now('gmt');
  6042. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  6043. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  6044. $usecalendar = 'combo';
  6045. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  6046. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  6047. }
  6048. if ($d) {
  6049. // Show date with popup
  6050. if ($usecalendar != 'combo') {
  6051. $formated_date = '';
  6052. //print "e".$set_time." t ".$conf->format_date_short;
  6053. if (strval($set_time) != '' && $set_time != -1) {
  6054. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  6055. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6056. }
  6057. // Calendrier popup version eldy
  6058. if ($usecalendar == "eldy") {
  6059. // Input area to enter date manually
  6060. $retstring .= '<input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate" maxlength="11" value="' . $formated_date . '"';
  6061. $retstring .= ($disabled ? ' disabled' : '');
  6062. $retstring .= ' onChange="dpChangeDay(\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6063. $retstring .= '>';
  6064. // Icon calendar
  6065. $retstringbuttom = '';
  6066. if (!$disabled) {
  6067. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
  6068. $base = DOL_URL_ROOT . '/core/';
  6069. $retstringbuttom .= ' onClick="showDP(\'' . $base . '\',\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\',\'' . $langs->defaultlang . '\');"';
  6070. $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"') . '</button>';
  6071. } else {
  6072. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6073. }
  6074. $retstring = $retstringbuttom . $retstring;
  6075. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6076. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6077. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6078. } elseif ($usecalendar == 'jquery') {
  6079. if (!$disabled) {
  6080. // Output javascript for datepicker
  6081. $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (date('Y') - 100));
  6082. $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (date('Y') + 100));
  6083. $retstring .= '<script nonce="' . getNonce() . '" type="text/javascript">';
  6084. $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
  6085. dateFormat: '" . $langs->trans("FormatDateShortJQueryInput") . "',
  6086. autoclose: true,
  6087. todayHighlight: true,
  6088. yearRange: '" . $minYear . ":" . $maxYear . "',";
  6089. if (!empty($conf->dol_use_jmobile)) {
  6090. $retstring .= "
  6091. beforeShow: function (input, datePicker) {
  6092. input.disabled = true;
  6093. },
  6094. onClose: function (dateText, datePicker) {
  6095. this.disabled = false;
  6096. },
  6097. ";
  6098. }
  6099. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  6100. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  6101. $retstring .= "
  6102. showOn: 'button', /* both has problem with autocompletion */
  6103. buttonImage: '" . DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png',
  6104. buttonImageOnly: true";
  6105. }
  6106. $retstring .= "
  6107. }) });";
  6108. $retstring .= "</script>";
  6109. }
  6110. // Zone de saisie manuelle de la date
  6111. $retstring .= '<div class="nowraponall inline-block divfordateinput">';
  6112. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  6113. $retstring .= ($disabled ? ' disabled' : '');
  6114. $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
  6115. $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6116. $retstring .= '>';
  6117. // Icone calendrier
  6118. if (!$disabled) {
  6119. /* Not required. Managed by option buttonImage of jquery
  6120. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  6121. $retstring.='<script nonce="'.getNonce().'" type="text/javascript">';
  6122. $retstring.="jQuery(document).ready(function() {";
  6123. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  6124. $retstring.=" jQuery('#".$prefix."').focus();";
  6125. $retstring.=' });';
  6126. $retstring.='});';
  6127. $retstring.="</script>";*/
  6128. } else {
  6129. $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6130. $retsring = $retstringbutton . $retstring;
  6131. }
  6132. $retstring .= '</div>';
  6133. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6134. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6135. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6136. } else {
  6137. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  6138. }
  6139. } else {
  6140. // Show date with combo selects
  6141. // Day
  6142. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
  6143. if ($emptydate || $set_time == -1) {
  6144. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6145. }
  6146. for ($day = 1; $day <= 31; $day++) {
  6147. $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
  6148. }
  6149. $retstring .= "</select>";
  6150. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
  6151. if ($emptydate || $set_time == -1) {
  6152. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6153. }
  6154. // Month
  6155. for ($month = 1; $month <= 12; $month++) {
  6156. $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
  6157. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  6158. $retstring .= "</option>";
  6159. }
  6160. $retstring .= "</select>";
  6161. // Year
  6162. if ($emptydate || $set_time == -1) {
  6163. $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 . '">';
  6164. } else {
  6165. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
  6166. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  6167. $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
  6168. }
  6169. $retstring .= "</select>\n";
  6170. }
  6171. }
  6172. }
  6173. if ($d && $h) {
  6174. $retstring .= ($h == 2 ? '<br>' : ' ');
  6175. $retstring .= '<span class="nowraponall">';
  6176. }
  6177. if ($h) {
  6178. $hourstart = 0;
  6179. $hourend = 24;
  6180. if ($openinghours != '') {
  6181. $openinghours = explode(',', $openinghours);
  6182. $hourstart = $openinghours[0];
  6183. $hourend = $openinghours[1];
  6184. if ($hourend < $hourstart) {
  6185. $hourend = $hourstart;
  6186. }
  6187. }
  6188. // Show hour
  6189. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
  6190. if ($emptyhours) {
  6191. $retstring .= '<option value="-1">&nbsp;</option>';
  6192. }
  6193. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  6194. if (strlen($hour) < 2) {
  6195. $hour = "0" . $hour;
  6196. }
  6197. $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
  6198. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  6199. $retstring .= '</option>';
  6200. }
  6201. $retstring .= '</select>';
  6202. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  6203. if ($m) {
  6204. $retstring .= ":";
  6205. }
  6206. }
  6207. if ($m) {
  6208. // Show minutes
  6209. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
  6210. if ($emptyhours) {
  6211. $retstring .= '<option value="-1">&nbsp;</option>';
  6212. }
  6213. for ($min = 0; $min < 60; $min += $stepminutes) {
  6214. if (strlen($min) < 2) {
  6215. $min = "0" . $min;
  6216. }
  6217. $retstring .= '<option value="' . $min . '"' . (($min == $smin) ? ' selected' : '') . '>' . $min . (empty($conf->dol_optimize_smallscreen) ? '' : '') . '</option>';
  6218. }
  6219. $retstring .= '</select>';
  6220. $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
  6221. }
  6222. if ($d && $h) {
  6223. $retstring .= '</span>';
  6224. }
  6225. // Add a "Now" link
  6226. if (!empty($conf->use_javascript_ajax) && $addnowlink) {
  6227. // Script which will be inserted in the onClick of the "Now" link
  6228. $reset_scripts = "";
  6229. if ($addnowlink == 2) { // local computer time
  6230. // pad add leading 0 on numbers
  6231. $reset_scripts .= "Number.prototype.pad = function(size) {
  6232. var s = String(this);
  6233. while (s.length < (size || 2)) {s = '0' + s;}
  6234. return s;
  6235. };
  6236. var d = new Date();";
  6237. }
  6238. // Generate the date part, depending on the use or not of the javascript calendar
  6239. if ($addnowlink == 1) { // server time expressed in user time setup
  6240. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6241. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6242. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6243. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6244. } elseif ($addnowlink == 2) {
  6245. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6246. * This break application for foreign languages.
  6247. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6248. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6249. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6250. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6251. */
  6252. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6253. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6254. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6255. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6256. }
  6257. /*if ($usecalendar == "eldy")
  6258. {
  6259. $base=DOL_URL_ROOT.'/core/';
  6260. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6261. }
  6262. else
  6263. {
  6264. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6265. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6266. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6267. }*/
  6268. // Update the hour part
  6269. if ($h) {
  6270. if ($fullday) {
  6271. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6272. }
  6273. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6274. if ($addnowlink == 1) {
  6275. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6276. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6277. } elseif ($addnowlink == 2) {
  6278. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
  6279. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6280. }
  6281. if ($fullday) {
  6282. $reset_scripts .= ' } ';
  6283. }
  6284. }
  6285. // Update the minute part
  6286. if ($m) {
  6287. if ($fullday) {
  6288. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6289. }
  6290. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6291. if ($addnowlink == 1) {
  6292. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6293. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6294. } elseif ($addnowlink == 2) {
  6295. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
  6296. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6297. }
  6298. if ($fullday) {
  6299. $reset_scripts .= ' } ';
  6300. }
  6301. }
  6302. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6303. if ($reset_scripts && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6304. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
  6305. $retstring .= $langs->trans("Now");
  6306. $retstring .= '</button> ';
  6307. }
  6308. }
  6309. // Add a "Plus one hour" link
  6310. if ($conf->use_javascript_ajax && $addplusone) {
  6311. // Script which will be inserted in the onClick of the "Add plusone" link
  6312. $reset_scripts = "";
  6313. // Generate the date part, depending on the use or not of the javascript calendar
  6314. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
  6315. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6316. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6317. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6318. // Update the hour part
  6319. if ($h) {
  6320. if ($fullday) {
  6321. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6322. }
  6323. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6324. if ($fullday) {
  6325. $reset_scripts .= ' } ';
  6326. }
  6327. }
  6328. // Update the minute part
  6329. if ($m) {
  6330. if ($fullday) {
  6331. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6332. }
  6333. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6334. if ($fullday) {
  6335. $reset_scripts .= ' } ';
  6336. }
  6337. }
  6338. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6339. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6340. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
  6341. $retstring .= $langs->trans("DateStartPlusOne");
  6342. $retstring .= '</button> ';
  6343. }
  6344. }
  6345. // Add a link to set data
  6346. if ($conf->use_javascript_ajax && !empty($adddateof)) {
  6347. if (!is_array($adddateof)) {
  6348. $arrayofdateof = array(array('adddateof'=>$adddateof, 'labeladddateof'=>$labeladddateof));
  6349. } else {
  6350. $arrayofdateof = $adddateof;
  6351. }
  6352. foreach ($arrayofdateof as $valuedateof) {
  6353. $tmpadddateof = $valuedateof['adddateof'];
  6354. $tmplabeladddateof = $valuedateof['labeladddateof'];
  6355. $tmparray = dol_getdate($tmpadddateof);
  6356. if (empty($tmplabeladddateof)) {
  6357. $tmplabeladddateof = $langs->trans("DateInvoice");
  6358. }
  6359. $reset_scripts = 'console.log(\'Click on now link\'); ';
  6360. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($tmpadddateof, 'dayinputnoreduce').'\');';
  6361. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
  6362. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
  6363. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
  6364. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$tmplabeladddateof.'</button>';
  6365. }
  6366. }
  6367. return $retstring;
  6368. }
  6369. /**
  6370. * selectTypeDuration
  6371. *
  6372. * @param string $prefix Prefix
  6373. * @param string $selected Selected duration type
  6374. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6375. * @return string HTML select string
  6376. */
  6377. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6378. {
  6379. global $langs;
  6380. $TDurationTypes = array(
  6381. 'y' => $langs->trans('Years'),
  6382. 'm' => $langs->trans('Month'),
  6383. 'w' => $langs->trans('Weeks'),
  6384. 'd' => $langs->trans('Days'),
  6385. 'h' => $langs->trans('Hours'),
  6386. 'i' => $langs->trans('Minutes')
  6387. );
  6388. // Removed undesired duration types
  6389. foreach ($excludetypes as $value) {
  6390. unset($TDurationTypes[$value]);
  6391. }
  6392. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
  6393. foreach ($TDurationTypes as $key => $typeduration) {
  6394. $retstring .= '<option value="' . $key . '"';
  6395. if ($key == $selected) {
  6396. $retstring .= " selected";
  6397. }
  6398. $retstring .= ">" . $typeduration . "</option>";
  6399. }
  6400. $retstring .= "</select>";
  6401. $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
  6402. return $retstring;
  6403. }
  6404. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6405. /**
  6406. * Function to show a form to select a duration on a page
  6407. *
  6408. * @param string $prefix Prefix for input fields
  6409. * @param int $iSecond Default preselected duration (number of seconds or '')
  6410. * @param int $disabled Disable the combo box
  6411. * @param string $typehour If 'select' then input hour and input min is a combo,
  6412. * If 'text' input hour is in text and input min is a text,
  6413. * If 'textselect' input hour is in text and input min is a combo
  6414. * @param integer $minunderhours If 1, show minutes selection under the hours
  6415. * @param int $nooutput Do not output html string but return it
  6416. * @return string HTML component
  6417. */
  6418. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6419. {
  6420. // phpcs:enable
  6421. global $langs;
  6422. $retstring = '<span class="nowraponall">';
  6423. $hourSelected = '';
  6424. $minSelected = '';
  6425. // Hours
  6426. if ($iSecond != '') {
  6427. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6428. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6429. $minSelected = convertSecondToTime($iSecond, 'min');
  6430. }
  6431. if ($typehour == 'select') {
  6432. $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
  6433. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6434. $retstring .= '<option value="' . $hour . '"';
  6435. if (is_numeric($hourSelected) && $hourSelected == $hour) {
  6436. $retstring .= " selected";
  6437. }
  6438. $retstring .= ">" . $hour . "</option>";
  6439. }
  6440. $retstring .= "</select>";
  6441. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6442. $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour right" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
  6443. } else {
  6444. return 'BadValueForParameterTypeHour';
  6445. }
  6446. if ($typehour != 'text') {
  6447. $retstring .= ' ' . $langs->trans('HourShort');
  6448. } else {
  6449. $retstring .= '<span class="">:</span>';
  6450. }
  6451. // Minutes
  6452. if ($minunderhours) {
  6453. $retstring .= '<br>';
  6454. } else {
  6455. if ($typehour != 'text') {
  6456. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6457. }
  6458. }
  6459. if ($typehour == 'select' || $typehour == 'textselect') {
  6460. $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
  6461. for ($min = 0; $min <= 55; $min = $min + 5) {
  6462. $retstring .= '<option value="' . $min . '"';
  6463. if (is_numeric($minSelected) && $minSelected == $min) {
  6464. $retstring .= ' selected';
  6465. }
  6466. $retstring .= '>' . $min . '</option>';
  6467. }
  6468. $retstring .= "</select>";
  6469. } elseif ($typehour == 'text') {
  6470. $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute right" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
  6471. }
  6472. if ($typehour != 'text') {
  6473. $retstring .= ' ' . $langs->trans('MinuteShort');
  6474. }
  6475. $retstring .= "</span>";
  6476. if (!empty($nooutput)) {
  6477. return $retstring;
  6478. }
  6479. print $retstring;
  6480. return '';
  6481. }
  6482. /**
  6483. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6484. *
  6485. * @param int $selected Preselected tickets
  6486. * @param string $htmlname Name of HTML select field (must be unique in page).
  6487. * @param string $filtertype To add a filter
  6488. * @param int $limit Limit on number of returned lines
  6489. * @param int $status Ticket status
  6490. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6491. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6492. * @param array $ajaxoptions Options for ajax_autocompleter
  6493. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6494. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6495. * @param int $forcecombo Force to use combo box
  6496. * @param string $morecss Add more css on select
  6497. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6498. * @param string $nooutput No print, return the output into a string
  6499. * @return string
  6500. */
  6501. 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)
  6502. {
  6503. global $langs, $conf;
  6504. $out = '';
  6505. // check parameters
  6506. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6507. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6508. $placeholder = '';
  6509. if ($selected && empty($selected_input_value)) {
  6510. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6511. $tickettmpselect = new Ticket($this->db);
  6512. $tickettmpselect->fetch($selected);
  6513. $selected_input_value = $tickettmpselect->ref;
  6514. unset($tickettmpselect);
  6515. }
  6516. $urloption = '';
  6517. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6518. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6519. elseif ($hidelabel > 1) {
  6520. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6521. if ($hidelabel == 2) {
  6522. $out .= img_picto($langs->trans("Search"), 'search');
  6523. }
  6524. }
  6525. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6526. if ($hidelabel == 3) {
  6527. $out .= img_picto($langs->trans("Search"), 'search');
  6528. }
  6529. } else {
  6530. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6531. }
  6532. if (empty($nooutput)) {
  6533. print $out;
  6534. } else {
  6535. return $out;
  6536. }
  6537. return '';
  6538. }
  6539. /**
  6540. * Return list of tickets.
  6541. * Called by selectTickets.
  6542. *
  6543. * @param int $selected Preselected ticket
  6544. * @param string $htmlname Name of select html
  6545. * @param string $filtertype Filter on ticket type
  6546. * @param int $limit Limit on number of returned lines
  6547. * @param string $filterkey Filter on ticket ref or subject
  6548. * @param int $status Ticket status
  6549. * @param int $outputmode 0=HTML select string, 1=Array
  6550. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6551. * @param int $forcecombo Force to use combo box
  6552. * @param string $morecss Add more css on select
  6553. * @return array|string Array of keys for json or HTML component
  6554. */
  6555. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6556. {
  6557. global $langs, $conf;
  6558. $out = '';
  6559. $outarray = array();
  6560. $selectFields = " p.rowid, p.ref, p.message";
  6561. $sql = "SELECT ";
  6562. $sql .= $selectFields;
  6563. $sql .= " FROM " . $this->db->prefix() . "ticket as p";
  6564. $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
  6565. // Add criteria on ref/label
  6566. if ($filterkey != '') {
  6567. $sql .= ' AND (';
  6568. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6569. // For natural search
  6570. $scrit = explode(' ', $filterkey);
  6571. $i = 0;
  6572. if (count($scrit) > 1) $sql .= "(";
  6573. foreach ($scrit as $crit) {
  6574. if ($i > 0) $sql .= " AND ";
  6575. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6576. $sql .= ")";
  6577. $i++;
  6578. }
  6579. if (count($scrit) > 1) $sql .= ")";
  6580. $sql .= ')';
  6581. }
  6582. $sql .= $this->db->plimit($limit, 0);
  6583. // Build output string
  6584. dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
  6585. $result = $this->db->query($sql);
  6586. if ($result) {
  6587. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6588. require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
  6589. $num = $this->db->num_rows($result);
  6590. $events = null;
  6591. if (!$forcecombo) {
  6592. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6593. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6594. }
  6595. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6596. $textifempty = '';
  6597. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6598. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6599. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6600. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6601. else $textifempty .= $langs->trans("All");
  6602. } else {
  6603. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6604. }
  6605. if ($showempty) $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6606. $i = 0;
  6607. while ($num && $i < $num) {
  6608. $opt = '';
  6609. $optJson = array();
  6610. $objp = $this->db->fetch_object($result);
  6611. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6612. // Add new entry
  6613. // "key" value of json key array is used by jQuery automatically as selected value
  6614. // "label" value of json key array is used by jQuery automatically as text for combo box
  6615. $out .= $opt;
  6616. array_push($outarray, $optJson);
  6617. $i++;
  6618. }
  6619. $out .= '</select>';
  6620. $this->db->free($result);
  6621. if (empty($outputmode)) {
  6622. return $out;
  6623. }
  6624. return $outarray;
  6625. } else {
  6626. dol_print_error($this->db);
  6627. }
  6628. return array();
  6629. }
  6630. /**
  6631. * constructTicketListOption.
  6632. * This define value for &$opt and &$optJson.
  6633. *
  6634. * @param object $objp Result set of fetch
  6635. * @param string $opt Option (var used for returned value in string option format)
  6636. * @param array $optJson Option (var used for returned value in json format)
  6637. * @param string $selected Preselected value
  6638. * @param string $filterkey Filter key to highlight
  6639. * @return void
  6640. */
  6641. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6642. {
  6643. $outkey = '';
  6644. $outref = '';
  6645. $outtype = '';
  6646. $outkey = $objp->rowid;
  6647. $outref = $objp->ref;
  6648. $outtype = $objp->fk_product_type;
  6649. $opt = '<option value="' . $objp->rowid . '"';
  6650. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6651. $opt .= '>';
  6652. $opt .= $objp->ref;
  6653. $objRef = $objp->ref;
  6654. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6655. $opt .= "</option>\n";
  6656. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6657. }
  6658. /**
  6659. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6660. *
  6661. * @param int $selected Preselected tickets
  6662. * @param string $htmlname Name of HTML select field (must be unique in page).
  6663. * @param string $filtertype To add a filter
  6664. * @param int $limit Limit on number of returned lines
  6665. * @param int $status Ticket status
  6666. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6667. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6668. * @param array $ajaxoptions Options for ajax_autocompleter
  6669. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6670. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6671. * @param int $forcecombo Force to use combo box
  6672. * @param string $morecss Add more css on select
  6673. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6674. * @param string $nooutput No print, return the output into a string
  6675. * @return string
  6676. */
  6677. 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)
  6678. {
  6679. global $langs, $conf;
  6680. $out = '';
  6681. // check parameters
  6682. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6683. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6684. $placeholder = '';
  6685. if ($selected && empty($selected_input_value)) {
  6686. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6687. $projecttmpselect = new Project($this->db);
  6688. $projecttmpselect->fetch($selected);
  6689. $selected_input_value = $projecttmpselect->ref;
  6690. unset($projecttmpselect);
  6691. }
  6692. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6693. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6694. elseif ($hidelabel > 1) {
  6695. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6696. if ($hidelabel == 2) {
  6697. $out .= img_picto($langs->trans("Search"), 'search');
  6698. }
  6699. }
  6700. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6701. if ($hidelabel == 3) {
  6702. $out .= img_picto($langs->trans("Search"), 'search');
  6703. }
  6704. } else {
  6705. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6706. }
  6707. if (empty($nooutput)) {
  6708. print $out;
  6709. } else {
  6710. return $out;
  6711. }
  6712. return '';
  6713. }
  6714. /**
  6715. * Return list of projects.
  6716. * Called by selectProjects.
  6717. *
  6718. * @param int $selected Preselected project
  6719. * @param string $htmlname Name of select html
  6720. * @param string $filtertype Filter on project type
  6721. * @param int $limit Limit on number of returned lines
  6722. * @param string $filterkey Filter on project ref or subject
  6723. * @param int $status Ticket status
  6724. * @param int $outputmode 0=HTML select string, 1=Array
  6725. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6726. * @param int $forcecombo Force to use combo box
  6727. * @param string $morecss Add more css on select
  6728. * @return array|string Array of keys for json or HTML component
  6729. */
  6730. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6731. {
  6732. global $langs, $conf;
  6733. $out = '';
  6734. $outarray = array();
  6735. $selectFields = " p.rowid, p.ref";
  6736. $sql = "SELECT ";
  6737. $sql .= $selectFields;
  6738. $sql .= " FROM " . $this->db->prefix() . "projet as p";
  6739. $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
  6740. // Add criteria on ref/label
  6741. if ($filterkey != '') {
  6742. $sql .= ' AND (';
  6743. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6744. // For natural search
  6745. $scrit = explode(' ', $filterkey);
  6746. $i = 0;
  6747. if (count($scrit) > 1) $sql .= "(";
  6748. foreach ($scrit as $crit) {
  6749. if ($i > 0) $sql .= " AND ";
  6750. $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6751. $sql .= "";
  6752. $i++;
  6753. }
  6754. if (count($scrit) > 1) $sql .= ")";
  6755. $sql .= ')';
  6756. }
  6757. $sql .= $this->db->plimit($limit, 0);
  6758. // Build output string
  6759. dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
  6760. $result = $this->db->query($sql);
  6761. if ($result) {
  6762. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6763. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  6764. $num = $this->db->num_rows($result);
  6765. $events = null;
  6766. if (!$forcecombo) {
  6767. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6768. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6769. }
  6770. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6771. $textifempty = '';
  6772. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6773. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6774. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6775. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6776. else $textifempty .= $langs->trans("All");
  6777. } else {
  6778. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6779. }
  6780. if ($showempty) $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6781. $i = 0;
  6782. while ($num && $i < $num) {
  6783. $opt = '';
  6784. $optJson = array();
  6785. $objp = $this->db->fetch_object($result);
  6786. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6787. // Add new entry
  6788. // "key" value of json key array is used by jQuery automatically as selected value
  6789. // "label" value of json key array is used by jQuery automatically as text for combo box
  6790. $out .= $opt;
  6791. array_push($outarray, $optJson);
  6792. $i++;
  6793. }
  6794. $out .= '</select>';
  6795. $this->db->free($result);
  6796. if (empty($outputmode)) {
  6797. return $out;
  6798. }
  6799. return $outarray;
  6800. } else {
  6801. dol_print_error($this->db);
  6802. }
  6803. return array();
  6804. }
  6805. /**
  6806. * constructProjectListOption.
  6807. * This define value for &$opt and &$optJson.
  6808. *
  6809. * @param object $objp Result set of fetch
  6810. * @param string $opt Option (var used for returned value in string option format)
  6811. * @param array $optJson Option (var used for returned value in json format)
  6812. * @param string $selected Preselected value
  6813. * @param string $filterkey Filter key to highlight
  6814. * @return void
  6815. */
  6816. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6817. {
  6818. $outkey = '';
  6819. $outref = '';
  6820. $outtype = '';
  6821. $label = $objp->label;
  6822. $outkey = $objp->rowid;
  6823. $outref = $objp->ref;
  6824. $outlabel = $objp->label;
  6825. $outtype = $objp->fk_product_type;
  6826. $opt = '<option value="' . $objp->rowid . '"';
  6827. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6828. $opt .= '>';
  6829. $opt .= $objp->ref;
  6830. $objRef = $objp->ref;
  6831. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6832. $opt .= "</option>\n";
  6833. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6834. }
  6835. /**
  6836. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6837. *
  6838. * @param int $selected Preselected tickets
  6839. * @param string $htmlname Name of HTML select field (must be unique in page).
  6840. * @param string $filtertype To add a filter
  6841. * @param int $limit Limit on number of returned lines
  6842. * @param int $status Ticket status
  6843. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6844. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6845. * @param array $ajaxoptions Options for ajax_autocompleter
  6846. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6847. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6848. * @param int $forcecombo Force to use combo box
  6849. * @param string $morecss Add more css on select
  6850. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6851. * @param string $nooutput No print, return the output into a string
  6852. * @return string
  6853. */
  6854. 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)
  6855. {
  6856. global $langs, $conf;
  6857. $out = '';
  6858. // check parameters
  6859. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6860. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6861. $placeholder = '';
  6862. $urloption = '';
  6863. if ($selected && empty($selected_input_value)) {
  6864. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  6865. $adherenttmpselect = new Adherent($this->db);
  6866. $adherenttmpselect->fetch($selected);
  6867. $selected_input_value = $adherenttmpselect->ref;
  6868. unset($adherenttmpselect);
  6869. }
  6870. $urloption = '';
  6871. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6872. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6873. elseif ($hidelabel > 1) {
  6874. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6875. if ($hidelabel == 2) {
  6876. $out .= img_picto($langs->trans("Search"), 'search');
  6877. }
  6878. }
  6879. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6880. if ($hidelabel == 3) {
  6881. $out .= img_picto($langs->trans("Search"), 'search');
  6882. }
  6883. } else {
  6884. $filterkey = '';
  6885. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6886. }
  6887. if (empty($nooutput)) {
  6888. print $out;
  6889. } else {
  6890. return $out;
  6891. }
  6892. return '';
  6893. }
  6894. /**
  6895. * Return list of adherents.
  6896. * Called by selectMembers.
  6897. *
  6898. * @param int $selected Preselected adherent
  6899. * @param string $htmlname Name of select html
  6900. * @param string $filtertype Filter on adherent type
  6901. * @param int $limit Limit on number of returned lines
  6902. * @param string $filterkey Filter on member status
  6903. * @param int $status Member status
  6904. * @param int $outputmode 0=HTML select string, 1=Array
  6905. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6906. * @param int $forcecombo Force to use combo box
  6907. * @param string $morecss Add more css on select
  6908. * @return array|string Array of keys for json or HTML string component
  6909. */
  6910. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6911. {
  6912. global $langs, $conf;
  6913. $out = '';
  6914. $outarray = array();
  6915. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname, p.fk_adherent_type";
  6916. $sql = "SELECT ";
  6917. $sql .= $selectFields;
  6918. $sql .= " FROM " . $this->db->prefix() . "adherent as p";
  6919. $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
  6920. // Add criteria on ref/label
  6921. if ($filterkey != '') {
  6922. $sql .= ' AND (';
  6923. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6924. // For natural search
  6925. $scrit = explode(' ', $filterkey);
  6926. $i = 0;
  6927. if (count($scrit) > 1) $sql .= "(";
  6928. foreach ($scrit as $crit) {
  6929. if ($i > 0) $sql .= " AND ";
  6930. $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6931. $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  6932. $i++;
  6933. }
  6934. if (count($scrit) > 1) $sql .= ")";
  6935. $sql .= ')';
  6936. }
  6937. if ($status != -1) {
  6938. $sql .= ' AND statut = ' . ((int) $status);
  6939. }
  6940. $sql .= $this->db->plimit($limit, 0);
  6941. // Build output string
  6942. dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
  6943. $result = $this->db->query($sql);
  6944. if ($result) {
  6945. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  6946. require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
  6947. $num = $this->db->num_rows($result);
  6948. $events = null;
  6949. if (!$forcecombo) {
  6950. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6951. $out .= ajax_combobox($htmlname, $events, !empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT) ? $conf->global->PROJECT_USE_SEARCH_TO_SELECT : '');
  6952. }
  6953. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6954. $textifempty = '';
  6955. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6956. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6957. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6958. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6959. else $textifempty .= $langs->trans("All");
  6960. } else {
  6961. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6962. }
  6963. if ($showempty) {
  6964. $out .= '<option value="-1" selected>' . $textifempty . '</option>';
  6965. }
  6966. $i = 0;
  6967. while ($num && $i < $num) {
  6968. $opt = '';
  6969. $optJson = array();
  6970. $objp = $this->db->fetch_object($result);
  6971. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6972. // Add new entry
  6973. // "key" value of json key array is used by jQuery automatically as selected value
  6974. // "label" value of json key array is used by jQuery automatically as text for combo box
  6975. $out .= $opt;
  6976. array_push($outarray, $optJson);
  6977. $i++;
  6978. }
  6979. $out .= '</select>';
  6980. $this->db->free($result);
  6981. if (empty($outputmode)) {
  6982. return $out;
  6983. }
  6984. return $outarray;
  6985. } else {
  6986. dol_print_error($this->db);
  6987. }
  6988. return array();
  6989. }
  6990. /**
  6991. * constructMemberListOption.
  6992. * This define value for &$opt and &$optJson.
  6993. *
  6994. * @param object $objp Result set of fetch
  6995. * @param string $opt Option (var used for returned value in string option format)
  6996. * @param array $optJson Option (var used for returned value in json format)
  6997. * @param string $selected Preselected value
  6998. * @param string $filterkey Filter key to highlight
  6999. * @return void
  7000. */
  7001. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  7002. {
  7003. $outkey = '';
  7004. $outlabel = '';
  7005. $outtype = '';
  7006. $outkey = $objp->rowid;
  7007. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  7008. $outtype = $objp->fk_adherent_type;
  7009. $opt = '<option value="' . $objp->rowid . '"';
  7010. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  7011. $opt .= '>';
  7012. if (!empty($filterkey) && $filterkey != '') {
  7013. $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
  7014. }
  7015. $opt .= $outlabel;
  7016. $opt .= "</option>\n";
  7017. $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
  7018. }
  7019. /**
  7020. * Generic method to select a component from a combo list.
  7021. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  7022. * This is the generic method that will replace all specific existing methods.
  7023. *
  7024. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  7025. * @param string $htmlname Name of HTML select component
  7026. * @param int $preselectedvalue Preselected value (ID of element)
  7027. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7028. * @param string $searchkey Search criteria
  7029. * @param string $placeholder Place holder
  7030. * @param string $morecss More CSS
  7031. * @param string $moreparams More params provided to ajax call
  7032. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7033. * @param int $disabled 1=Html component is disabled
  7034. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  7035. * @return string Return HTML string
  7036. * @see selectForFormsList(), select_thirdparty_list()
  7037. */
  7038. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  7039. {
  7040. global $conf, $user;
  7041. $objecttmp = null;
  7042. // Example of value for $objectdec:
  7043. // Bom:bom/class/bom.class.php:0:t.status=1
  7044. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  7045. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  7046. $InfoFieldList = explode(":", $objectdesc, 4);
  7047. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  7048. $reg = array();
  7049. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  7050. $InfoFieldList[4] = $reg[1]; // take the sort field
  7051. }
  7052. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  7053. $classname = $InfoFieldList[0];
  7054. $classpath = $InfoFieldList[1];
  7055. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  7056. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  7057. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  7058. if (!empty($classpath)) {
  7059. dol_include_once($classpath);
  7060. if ($classname && class_exists($classname)) {
  7061. $objecttmp = new $classname($this->db);
  7062. // Make some replacement
  7063. $sharedentities = getEntity(strtolower($classname));
  7064. $filter = str_replace(
  7065. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  7066. array($conf->entity, $sharedentities, $user->id),
  7067. $filter
  7068. );
  7069. }
  7070. }
  7071. if (!is_object($objecttmp)) {
  7072. dol_syslog('Error bad setup of type for field ' . join(',', $InfoFieldList), LOG_WARNING);
  7073. return 'Error bad setup of type for field ' . join(',', $InfoFieldList);
  7074. }
  7075. //var_dump($filter);
  7076. $prefixforautocompletemode = $objecttmp->element;
  7077. if ($prefixforautocompletemode == 'societe') {
  7078. $prefixforautocompletemode = 'company';
  7079. }
  7080. if ($prefixforautocompletemode == 'product') {
  7081. $prefixforautocompletemode = 'produit';
  7082. }
  7083. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7084. dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
  7085. $out = '';
  7086. if (!empty($conf->use_javascript_ajax) && getDolGlobalString($confkeyforautocompletemode) && !$forcecombo) {
  7087. // No immediate load of all database
  7088. $placeholder = '';
  7089. if ($preselectedvalue && empty($selected_input_value)) {
  7090. $objecttmp->fetch($preselectedvalue);
  7091. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  7092. //unset($objecttmp);
  7093. }
  7094. $objectdesc = $classname . ':' . $classpath . ':' . $addcreatebuttonornot . ':' . $filter;
  7095. $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
  7096. // No immediate load of all database
  7097. $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdesc) . '&filter=' . urlencode($filter) . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
  7098. // Activate the auto complete using ajax call.
  7099. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  7100. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  7101. $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) . '"' : '') . ' />';
  7102. } else {
  7103. // Immediate load of table record.
  7104. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
  7105. }
  7106. return $out;
  7107. }
  7108. /**
  7109. * Output html form to select an object.
  7110. * Note, this function is called by selectForForms or by ajax selectobject.php
  7111. *
  7112. * @param Object $objecttmp Object to knwo the table to scan for combo.
  7113. * @param string $htmlname Name of HTML select component
  7114. * @param int $preselectedvalue Preselected value (ID of element)
  7115. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  7116. * @param string $searchkey Search value
  7117. * @param string $placeholder Place holder
  7118. * @param string $morecss More CSS
  7119. * @param string $moreparams More params provided to ajax call
  7120. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7121. * @param int $outputmode 0=HTML select string, 1=Array
  7122. * @param int $disabled 1=Html component is disabled
  7123. * @param string $sortfield Sort field
  7124. * @param string $filter Add more filter
  7125. * @return string|array Return HTML string
  7126. * @see selectForForms()
  7127. */
  7128. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '')
  7129. {
  7130. global $conf, $langs, $user, $hookmanager;
  7131. //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
  7132. $prefixforautocompletemode = $objecttmp->element;
  7133. if ($prefixforautocompletemode == 'societe') {
  7134. $prefixforautocompletemode = 'company';
  7135. }
  7136. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7137. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  7138. $tmpfieldstoshow = '';
  7139. foreach ($objecttmp->fields as $key => $val) {
  7140. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  7141. continue;
  7142. }
  7143. if (!empty($val['showoncombobox'])) {
  7144. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
  7145. }
  7146. }
  7147. if ($tmpfieldstoshow) {
  7148. $fieldstoshow = $tmpfieldstoshow;
  7149. }
  7150. } else {
  7151. // For backward compatibility
  7152. $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'showoncombobox' => 1);
  7153. }
  7154. if (empty($fieldstoshow)) {
  7155. if (isset($objecttmp->fields['ref'])) {
  7156. $fieldstoshow = 't.ref';
  7157. } else {
  7158. $langs->load("errors");
  7159. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  7160. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  7161. }
  7162. }
  7163. $out = '';
  7164. $outarray = array();
  7165. $tmparray = array();
  7166. $num = 0;
  7167. // Search data
  7168. $sql = "SELECT t.rowid, " . $fieldstoshow . " FROM " . $this->db->prefix() . $objecttmp->table_element . " as t";
  7169. if (isset($objecttmp->ismultientitymanaged)) {
  7170. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7171. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  7172. $sql .= " INNER JOIN " . $this->db->prefix() . $tmparray[1] . " as parenttable ON parenttable.rowid = t." . $tmparray[0];
  7173. }
  7174. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7175. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7176. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  7177. }
  7178. }
  7179. }
  7180. // Add where from hooks
  7181. $parameters = array(
  7182. 'object' => $objecttmp,
  7183. 'htmlname' => $htmlname,
  7184. 'filter' => $filter,
  7185. 'searchkey' => $searchkey
  7186. );
  7187. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  7188. if (!empty($hookmanager->resPrint)) {
  7189. $sql .= $hookmanager->resPrint;
  7190. } else {
  7191. $sql .= " WHERE 1=1";
  7192. if (isset($objecttmp->ismultientitymanaged)) {
  7193. if ($objecttmp->ismultientitymanaged == 1) {
  7194. $sql .= " AND t.entity IN (" . getEntity($objecttmp->table_element) . ")";
  7195. }
  7196. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7197. $sql .= " AND parenttable.entity = t." . $tmparray[0];
  7198. }
  7199. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  7200. if ($objecttmp->element == 'societe') {
  7201. $sql .= " AND t.rowid = " . ((int) $user->socid);
  7202. } else {
  7203. $sql .= " AND t.fk_soc = " . ((int) $user->socid);
  7204. }
  7205. }
  7206. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7207. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7208. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  7209. }
  7210. }
  7211. }
  7212. if ($searchkey != '') {
  7213. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  7214. }
  7215. if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  7216. $errormessage = '';
  7217. $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
  7218. if ($errormessage) {
  7219. return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
  7220. }
  7221. }
  7222. }
  7223. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7224. //$sql.=$this->db->plimit($limit, 0);
  7225. //print $sql;
  7226. // Build output string
  7227. $resql = $this->db->query($sql);
  7228. if ($resql) {
  7229. // Construct $out and $outarray
  7230. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
  7231. // 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
  7232. $textifempty = '&nbsp;';
  7233. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7234. if (!empty($conf->global->$confkeyforautocompletemode)) {
  7235. if ($showempty && !is_numeric($showempty)) {
  7236. $textifempty = $langs->trans($showempty);
  7237. } else {
  7238. $textifempty .= $langs->trans("All");
  7239. }
  7240. }
  7241. if ($showempty) {
  7242. $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
  7243. }
  7244. $num = $this->db->num_rows($resql);
  7245. $i = 0;
  7246. if ($num) {
  7247. while ($i < $num) {
  7248. $obj = $this->db->fetch_object($resql);
  7249. $label = '';
  7250. $tmparray = explode(',', $fieldstoshow);
  7251. $oldvalueforshowoncombobox = 0;
  7252. foreach ($tmparray as $key => $val) {
  7253. $val = preg_replace('/t\./', '', $val);
  7254. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7255. $label .= $obj->$val;
  7256. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  7257. }
  7258. if (empty($outputmode)) {
  7259. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7260. $out .= '<option value="' . $obj->rowid . '" selected>' . $label . '</option>';
  7261. } else {
  7262. $out .= '<option value="' . $obj->rowid . '">' . $label . '</option>';
  7263. }
  7264. } else {
  7265. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
  7266. }
  7267. $i++;
  7268. if (($i % 10) == 0) {
  7269. $out .= "\n";
  7270. }
  7271. }
  7272. }
  7273. $out .= '</select>' . "\n";
  7274. if (!$forcecombo) {
  7275. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7276. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  7277. }
  7278. } else {
  7279. dol_print_error($this->db);
  7280. }
  7281. $this->result = array('nbofelement' => $num);
  7282. if ($outputmode) {
  7283. return $outarray;
  7284. }
  7285. return $out;
  7286. }
  7287. /**
  7288. * Return a HTML select string, built from an array of key+value.
  7289. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7290. *
  7291. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7292. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7293. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7294. * @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.
  7295. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7296. * @param int $value_as_key 1 to use value as key
  7297. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7298. * @param int $translate 1=Translate and encode value
  7299. * @param int $maxlen Length maximum for labels
  7300. * @param int $disabled Html select box is disabled
  7301. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7302. * @param string $morecss Add more class to css styles
  7303. * @param int $addjscombo Add js combo
  7304. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7305. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7306. * @param int $nohtmlescape No html escaping.
  7307. * @return string HTML select string.
  7308. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7309. */
  7310. 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)
  7311. {
  7312. global $conf, $langs;
  7313. // Do we want a multiselect ?
  7314. //$jsbeautify = 0;
  7315. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7316. $jsbeautify = 1;
  7317. if ($value_as_key) {
  7318. $array = array_combine($array, $array);
  7319. }
  7320. $out = '';
  7321. if ($addjscombo < 0) {
  7322. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7323. $addjscombo = 1;
  7324. } else {
  7325. $addjscombo = 0;
  7326. }
  7327. }
  7328. $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
  7329. $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . '"';
  7330. $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
  7331. $out .= '>';
  7332. if ($show_empty) {
  7333. $textforempty = ' ';
  7334. if (!empty($conf->use_javascript_ajax)) {
  7335. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7336. }
  7337. if (!is_numeric($show_empty)) {
  7338. $textforempty = $show_empty;
  7339. }
  7340. $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  7341. }
  7342. if (is_array($array)) {
  7343. // Translate
  7344. if ($translate) {
  7345. foreach ($array as $key => $value) {
  7346. if (!is_array($value)) {
  7347. $array[$key] = $langs->trans($value);
  7348. } else {
  7349. $array[$key]['label'] = $langs->trans($value['label']);
  7350. }
  7351. }
  7352. }
  7353. // Sort
  7354. if ($sort == 'ASC') {
  7355. asort($array);
  7356. } elseif ($sort == 'DESC') {
  7357. arsort($array);
  7358. }
  7359. foreach ($array as $key => $tmpvalue) {
  7360. if (is_array($tmpvalue)) {
  7361. $value = $tmpvalue['label'];
  7362. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7363. $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
  7364. } else {
  7365. $value = $tmpvalue;
  7366. $disabled = '';
  7367. $style = '';
  7368. }
  7369. if (!empty($disablebademail)) {
  7370. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7371. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7372. $disabled = ' disabled';
  7373. $style = ' class="warning"';
  7374. }
  7375. }
  7376. if ($key_in_label) {
  7377. if (empty($nohtmlescape)) {
  7378. $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
  7379. } else {
  7380. $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
  7381. }
  7382. } else {
  7383. if (empty($nohtmlescape)) {
  7384. $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
  7385. } else {
  7386. $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
  7387. }
  7388. if ($value == '' || $value == '-') {
  7389. $selectOptionValue = '&nbsp;';
  7390. }
  7391. }
  7392. $out .= '<option value="' . $key . '"';
  7393. $out .= $style . $disabled;
  7394. if (is_array($id)) {
  7395. if (in_array($key, $id) && !$disabled) {
  7396. $out .= ' selected'; // To preselect a value
  7397. }
  7398. } else {
  7399. $id = (string) $id; // if $id = 0, then $id = '0'
  7400. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7401. $out .= ' selected'; // To preselect a value
  7402. }
  7403. }
  7404. if ($nohtmlescape) {
  7405. $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
  7406. }
  7407. if (is_array($tmpvalue)) {
  7408. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7409. if (preg_match('/^data-/', $keyforvalue)) {
  7410. $out .= ' '.$keyforvalue.'="'.dol_escape_htmltag($valueforvalue).'"';
  7411. }
  7412. }
  7413. }
  7414. $out .= '>';
  7415. //var_dump($selectOptionValue);
  7416. $out .= $selectOptionValue;
  7417. $out .= "</option>\n";
  7418. }
  7419. }
  7420. $out .= "</select>";
  7421. // Add code for jquery to use multiselect
  7422. if ($addjscombo && $jsbeautify) {
  7423. // Enhance with select2
  7424. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7425. $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', ($show_empty < 0 ? (string) $show_empty : '-1'), $morecss);
  7426. }
  7427. return $out;
  7428. }
  7429. /**
  7430. * 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.
  7431. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7432. *
  7433. * @param string $htmlname Name of html select area
  7434. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7435. * @param string $id Preselected key
  7436. * @param string $moreparam Add more parameters onto the select tag
  7437. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7438. * @param int $disabled Html select box is disabled
  7439. * @param int $minimumInputLength Minimum Input Length
  7440. * @param string $morecss Add more class to css styles
  7441. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7442. * @param string $placeholder String to use as placeholder
  7443. * @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)
  7444. * @return string HTML select string
  7445. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7446. */
  7447. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7448. {
  7449. global $conf, $langs;
  7450. global $delayedhtmlcontent; // Will be used later outside of this function
  7451. // TODO Use an internal dolibarr component instead of select2
  7452. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7453. return '';
  7454. }
  7455. $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
  7456. $outdelayed = '';
  7457. if (!empty($conf->use_javascript_ajax)) {
  7458. $tmpplugin = 'select2';
  7459. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7460. <script nonce="' . getNonce() . '">
  7461. $(document).ready(function () {
  7462. ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
  7463. $(".' . $htmlname . '").select2({
  7464. ajax: {
  7465. dir: "ltr",
  7466. url: "' . $url . '",
  7467. dataType: \'json\',
  7468. delay: 250,
  7469. data: function (params) {
  7470. return {
  7471. q: params.term, // search term
  7472. page: params.page
  7473. }
  7474. },
  7475. processResults: function (data) {
  7476. // parse the results into the format expected by Select2.
  7477. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7478. //console.log(data);
  7479. saveRemoteData = data;
  7480. /* format json result for select2 */
  7481. result = []
  7482. $.each( data, function( key, value ) {
  7483. result.push({id: key, text: value.text});
  7484. });
  7485. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7486. //console.log(result);
  7487. return {results: result, more: false}
  7488. },
  7489. cache: true
  7490. },
  7491. language: select2arrayoflanguage,
  7492. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7493. placeholder: "' . dol_escape_js($placeholder) . '",
  7494. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7495. minimumInputLength: ' . ((int) $minimumInputLength) . ',
  7496. formatResult: function (result, container, query, escapeMarkup) {
  7497. return escapeMarkup(result.text);
  7498. },
  7499. });
  7500. ' . ($callurlonselect ? '
  7501. /* Code to execute a GET when we select a value */
  7502. $(".' . $htmlname . '").change(function() {
  7503. var selected = $(".' . $htmlname . '").val();
  7504. console.log("We select in selectArrayAjax the entry "+selected)
  7505. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7506. $.each( saveRemoteData, function( key, value ) {
  7507. if (key == selected)
  7508. {
  7509. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7510. location.assign(value.url);
  7511. }
  7512. });
  7513. });' : '') . '
  7514. });
  7515. </script>';
  7516. }
  7517. if ($acceptdelayedhtml) {
  7518. $delayedhtmlcontent .= $outdelayed;
  7519. } else {
  7520. $out .= $outdelayed;
  7521. }
  7522. return $out;
  7523. }
  7524. /**
  7525. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7526. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7527. *
  7528. * @param string $htmlname Name of html select area
  7529. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7530. * @param string $id Preselected key
  7531. * @param string $moreparam Add more parameters onto the select tag
  7532. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7533. * @param int $disabled Html select box is disabled
  7534. * @param int $minimumInputLength Minimum Input Length
  7535. * @param string $morecss Add more class to css styles
  7536. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7537. * @param string $placeholder String to use as placeholder
  7538. * @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)
  7539. * @param string $textfortitle Text to show on title.
  7540. * @return string HTML select string
  7541. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7542. */
  7543. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0, $textfortitle = '')
  7544. {
  7545. global $conf, $langs;
  7546. global $delayedhtmlcontent; // Will be used later outside of this function
  7547. // TODO Use an internal dolibarr component instead of select2
  7548. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7549. return '';
  7550. }
  7551. $out = '<select type="text"'.($textfortitle? ' title="'.dol_escape_htmltag($textfortitle).'"' : '').' id="'.$htmlname.'" class="'.$htmlname.($morecss ? ' ' . $morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.'"><option></option></select>';
  7552. $formattedarrayresult = array();
  7553. foreach ($array as $key => $value) {
  7554. $o = new stdClass();
  7555. $o->id = $key;
  7556. $o->text = $value['text'];
  7557. $o->url = $value['url'];
  7558. $formattedarrayresult[] = $o;
  7559. }
  7560. $outdelayed = '';
  7561. if (!empty($conf->use_javascript_ajax)) {
  7562. $tmpplugin = 'select2';
  7563. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7564. <script nonce="' . getNonce() . '">
  7565. $(document).ready(function () {
  7566. var data = ' . json_encode($formattedarrayresult) . ';
  7567. ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
  7568. $(".' . $htmlname . '").select2({
  7569. data: data,
  7570. language: select2arrayoflanguage,
  7571. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7572. placeholder: "' . dol_escape_js($placeholder) . '",
  7573. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7574. minimumInputLength: ' . $minimumInputLength . ',
  7575. formatResult: function (result, container, query, escapeMarkup) {
  7576. return escapeMarkup(result.text);
  7577. },
  7578. matcher: function (params, data) {
  7579. if(! data.id) return null;';
  7580. if ($callurlonselect) {
  7581. // We forge the url with 'sall='
  7582. $outdelayed .= '
  7583. var urlBase = data.url;
  7584. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7585. /* console.log("params.term="+params.term); */
  7586. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7587. saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7588. }
  7589. if (!$disableFiltering) {
  7590. $outdelayed .= '
  7591. if(data.text.match(new RegExp(params.term))) {
  7592. return data;
  7593. }
  7594. return null;';
  7595. } else {
  7596. $outdelayed .= '
  7597. return data;';
  7598. }
  7599. $outdelayed .= '
  7600. }
  7601. });
  7602. ' . ($callurlonselect ? '
  7603. /* Code to execute a GET when we select a value */
  7604. $(".' . $htmlname . '").change(function() {
  7605. var selected = $(".' . $htmlname . '").val();
  7606. console.log("We select "+selected)
  7607. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7608. $.each( saveRemoteData, function( key, value ) {
  7609. if (key == selected)
  7610. {
  7611. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7612. location.assign(value.url);
  7613. }
  7614. });
  7615. });' : '') . '
  7616. });
  7617. </script>';
  7618. }
  7619. if ($acceptdelayedhtml) {
  7620. $delayedhtmlcontent .= $outdelayed;
  7621. } else {
  7622. $out .= $outdelayed;
  7623. }
  7624. return $out;
  7625. }
  7626. /**
  7627. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7628. *
  7629. * @param string $htmlname Name of select
  7630. * @param array $array Array(key=>value) or Array(key=>array('id'=> , 'label'=> , 'color'=> , 'picto'=> , 'labelhtml'=> ))
  7631. * @param array $selected Array of keys preselected
  7632. * @param int $key_in_label 1 to show key like in "[key] value"
  7633. * @param int $value_as_key 1 to use value as key
  7634. * @param string $morecss Add more css style
  7635. * @param int $translate Translate and encode value
  7636. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7637. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7638. * @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.
  7639. * @param string $placeholder String to use as placeholder
  7640. * @param int $addjscombo Add js combo
  7641. * @return string HTML multiselect string
  7642. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7643. */
  7644. 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)
  7645. {
  7646. global $conf, $langs;
  7647. $out = '';
  7648. if ($addjscombo < 0) {
  7649. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7650. $addjscombo = 1;
  7651. } else {
  7652. $addjscombo = 0;
  7653. }
  7654. }
  7655. $useenhancedmultiselect = 0;
  7656. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7657. $useenhancedmultiselect = 1;
  7658. }
  7659. // Output select component
  7660. $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";
  7661. if (is_array($array) && !empty($array)) {
  7662. if ($value_as_key) {
  7663. $array = array_combine($array, $array);
  7664. }
  7665. if (!empty($array)) {
  7666. foreach ($array as $key => $value) {
  7667. $tmpkey = $key;
  7668. $tmpvalue = $value;
  7669. $tmpcolor = '';
  7670. $tmppicto = '';
  7671. $tmplabelhtml = '';
  7672. if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
  7673. $tmpkey = $value['id'];
  7674. $tmpvalue = $value['label'];
  7675. $tmpcolor = $value['color'];
  7676. $tmppicto = $value['picto'];
  7677. $tmplabelhtml = !empty($value['labelhtml']) ? $value['labelhtml'] : '';
  7678. }
  7679. $newval = ($translate ? $langs->trans($tmpvalue) : $tmpvalue);
  7680. $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
  7681. $out .= '<option value="' . $tmpkey . '"';
  7682. if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
  7683. $out .= ' selected';
  7684. }
  7685. if (!empty($tmplabelhtml)) {
  7686. $out .= ' data-html="' . dol_escape_htmltag($tmplabelhtml) . '"';
  7687. } else {
  7688. $out .= ' data-html="' . dol_escape_htmltag(($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval) . '"';
  7689. }
  7690. $out .= '>';
  7691. $out .= dol_htmlentitiesbr($newval);
  7692. $out .= '</option>' . "\n";
  7693. }
  7694. }
  7695. }
  7696. $out .= '</select>' . "\n";
  7697. // Add code for jquery to use multiselect
  7698. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7699. $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
  7700. $out .= "\n" . '<script nonce="' . getNonce() . '">' . "\n";
  7701. if ($addjscombo == 1) {
  7702. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7703. $out .= 'function formatResult(record, container) {' . "\n";
  7704. $out .= ' if ($(record.element).attr("data-html") != undefined) return htmlEntityDecodeJs($(record.element).attr("data-html")); // If property html set, we decode html entities and use this' . "\n";
  7705. $out .= ' return record.text;';
  7706. $out .= '}' . "\n";
  7707. $out .= 'function formatSelection(record) {' . "\n";
  7708. if ($elemtype == 'category') {
  7709. $out .= 'return \'<span><img src="' . DOL_URL_ROOT . '/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7710. } else {
  7711. $out .= 'return record.text;';
  7712. }
  7713. $out .= '}' . "\n";
  7714. $out .= '$(document).ready(function () {
  7715. $(\'#' . $htmlname . '\').' . $tmpplugin . '({';
  7716. if ($placeholder) {
  7717. $out .= '
  7718. placeholder: {
  7719. id: \'-1\',
  7720. text: \'' . dol_escape_js($placeholder) . '\'
  7721. },';
  7722. }
  7723. $out .= ' dir: \'ltr\',
  7724. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag (ko with multiselect) */
  7725. dropdownCssClass: \'' . $morecss . '\', /* Line to add class on the new <span class="select2-selection...> tag (ok with multiselect) */
  7726. // Specify format function for dropdown item
  7727. formatResult: formatResult,
  7728. templateResult: formatResult, /* For 4.0 */
  7729. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7730. // Specify format function for selected item
  7731. formatSelection: formatSelection,
  7732. templateSelection: formatSelection /* For 4.0 */
  7733. });
  7734. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7735. the size only if component is not hidden by default on load */
  7736. $(\'#' . $htmlname . ' + .select2\').addClass(\'' . $morecss . '\');
  7737. });' . "\n";
  7738. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7739. // Add other js lib
  7740. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7741. // ...
  7742. $out .= 'console.log(\'addjscombo=2 for htmlname=' . $htmlname . '\');';
  7743. $out .= '$(document).ready(function () {
  7744. $(\'#' . $htmlname . '\').multiSelect({
  7745. containerHTML: \'<div class="multi-select-container">\',
  7746. menuHTML: \'<div class="multi-select-menu">\',
  7747. buttonHTML: \'<span class="multi-select-button ' . $morecss . '">\',
  7748. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7749. activeClass: \'multi-select-container--open\',
  7750. noneText: \'' . $placeholder . '\'
  7751. });
  7752. })';
  7753. }
  7754. $out .= '</script>';
  7755. }
  7756. return $out;
  7757. }
  7758. /**
  7759. * 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.
  7760. *
  7761. * @param string $htmlname Name of HTML field
  7762. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7763. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7764. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7765. * @return string HTML multiselect string
  7766. * @see selectarray()
  7767. */
  7768. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7769. {
  7770. global $conf, $langs, $user, $extrafields;
  7771. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7772. return '';
  7773. }
  7774. if (empty($array)) {
  7775. return '';
  7776. }
  7777. $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
  7778. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7779. $tmparray = explode(',', $user->conf->$tmpvar);
  7780. foreach ($array as $key => $val) {
  7781. //var_dump($key);
  7782. //var_dump($tmparray);
  7783. if (in_array($key, $tmparray)) {
  7784. $array[$key]['checked'] = 1;
  7785. } else {
  7786. $array[$key]['checked'] = 0;
  7787. }
  7788. }
  7789. } else { // There is no list of fields already customized for user
  7790. foreach ($array as $key => $val) {
  7791. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7792. $array[$key]['checked'] = 0;
  7793. }
  7794. }
  7795. }
  7796. $listoffieldsforselection = '';
  7797. $listcheckedstring = '';
  7798. foreach ($array as $key => $val) {
  7799. // var_dump($val);
  7800. // var_dump(array_key_exists('enabled', $val));
  7801. // var_dump(!$val['enabled']);
  7802. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7803. unset($array[$key]); // We don't want this field
  7804. continue;
  7805. }
  7806. if (!empty($val['type']) && $val['type'] == 'separate') {
  7807. // Field remains in array but we don't add it into $listoffieldsforselection
  7808. //$listoffieldsforselection .= '<li>-----</li>';
  7809. continue;
  7810. }
  7811. if ($val['label']) {
  7812. if (!empty($val['langfile']) && is_object($langs)) {
  7813. $langs->load($val['langfile']);
  7814. }
  7815. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7816. $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>';
  7817. $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
  7818. }
  7819. }
  7820. $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
  7821. <dl class="dropdown">
  7822. <dt>
  7823. <a href="#' . $htmlname . '">
  7824. ' . img_picto('', 'list') . '
  7825. </a>
  7826. <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
  7827. </dt>
  7828. <dd class="dropdowndd">
  7829. <div class="multiselectcheckbox'.$htmlname.'">
  7830. <ul class="'.$htmlname.($pos == '1' ? 'left' : '').'">
  7831. <li><input class="inputsearch_dropdownselectedfields width90p minwidth200imp" style="width:90%;" type="text" placeholder="'.$langs->trans('Search').'"></li>
  7832. '.$listoffieldsforselection.'
  7833. </ul>
  7834. </div>
  7835. </dd>
  7836. </dl>
  7837. <script nonce="' . getNonce() . '" type="text/javascript">
  7838. jQuery(document).ready(function () {
  7839. $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on(\'click\', function () {
  7840. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7841. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7842. var title = $(this).val() + ",";
  7843. if ($(this).is(\':checked\')) {
  7844. $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
  7845. }
  7846. else {
  7847. $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
  7848. }
  7849. // Now, we submit page
  7850. //$(this).parents(\'form:first\').submit();
  7851. });
  7852. $("input.inputsearch_dropdownselectedfields").on("keyup", function() {
  7853. var value = $(this).val().toLowerCase();
  7854. $(\'.multiselectcheckbox'.$htmlname.' li > label\').filter(function() {
  7855. $(this).parent().toggle($(this).text().toLowerCase().indexOf(value) > -1)
  7856. });
  7857. });
  7858. });
  7859. </script>
  7860. ';
  7861. return $out;
  7862. }
  7863. /**
  7864. * Render list of categories linked to object with id $id and type $type
  7865. *
  7866. * @param int $id Id of object
  7867. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7868. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7869. * @param int $nolink 1=Do not add html links
  7870. * @return string String with categories
  7871. */
  7872. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7873. {
  7874. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  7875. $cat = new Categorie($this->db);
  7876. $categories = $cat->containing($id, $type);
  7877. if ($rendermode == 1) {
  7878. $toprint = array();
  7879. foreach ($categories as $c) {
  7880. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7881. foreach ($ways as $way) {
  7882. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>';
  7883. }
  7884. }
  7885. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  7886. }
  7887. if ($rendermode == 0) {
  7888. $arrayselected = array();
  7889. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7890. foreach ($categories as $c) {
  7891. $arrayselected[] = $c->id;
  7892. }
  7893. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7894. }
  7895. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7896. }
  7897. /**
  7898. * Show linked object block.
  7899. *
  7900. * @param CommonObject $object Object we want to show links to
  7901. * @param string $morehtmlright More html to show on right of title
  7902. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7903. * @param string $title Title
  7904. * @return int <0 if KO, >=0 if OK
  7905. */
  7906. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false, $title = 'RelatedObjects')
  7907. {
  7908. global $conf, $langs, $hookmanager;
  7909. global $bc, $action;
  7910. $object->fetchObjectLinked();
  7911. // Bypass the default method
  7912. $hookmanager->initHooks(array('commonobject'));
  7913. $parameters = array(
  7914. 'morehtmlright' => $morehtmlright,
  7915. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7916. );
  7917. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7918. $nbofdifferenttypes = count($object->linkedObjects);
  7919. if (empty($reshook)) {
  7920. print '<!-- showLinkedObjectBlock -->';
  7921. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7922. print '<div class="div-table-responsive-no-min">';
  7923. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
  7924. print '<tr class="liste_titre">';
  7925. print '<td>' . $langs->trans("Type") . '</td>';
  7926. print '<td>' . $langs->trans("Ref") . '</td>';
  7927. print '<td class="center"></td>';
  7928. print '<td class="center">' . $langs->trans("Date") . '</td>';
  7929. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  7930. print '<td class="right">' . $langs->trans("Status") . '</td>';
  7931. print '<td></td>';
  7932. print '</tr>';
  7933. $nboftypesoutput = 0;
  7934. foreach ($object->linkedObjects as $objecttype => $objects) {
  7935. $tplpath = $element = $subelement = $objecttype;
  7936. // to display inport button on tpl
  7937. $showImportButton = false;
  7938. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7939. $showImportButton = true;
  7940. }
  7941. $regs = array();
  7942. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7943. $element = $regs[1];
  7944. $subelement = $regs[2];
  7945. $tplpath = $element . '/' . $subelement;
  7946. }
  7947. $tplname = 'linkedobjectblock';
  7948. // To work with non standard path
  7949. if ($objecttype == 'facture') {
  7950. $tplpath = 'compta/' . $element;
  7951. if (!isModEnabled('facture')) {
  7952. continue; // Do not show if module disabled
  7953. }
  7954. } elseif ($objecttype == 'facturerec') {
  7955. $tplpath = 'compta/facture';
  7956. $tplname = 'linkedobjectblockForRec';
  7957. if (!isModEnabled('facture')) {
  7958. continue; // Do not show if module disabled
  7959. }
  7960. } elseif ($objecttype == 'propal') {
  7961. $tplpath = 'comm/' . $element;
  7962. if (!isModEnabled('propal')) {
  7963. continue; // Do not show if module disabled
  7964. }
  7965. } elseif ($objecttype == 'supplier_proposal') {
  7966. if (!isModEnabled('supplier_proposal')) {
  7967. continue; // Do not show if module disabled
  7968. }
  7969. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
  7970. $tplpath = 'expedition';
  7971. if (!isModEnabled('expedition')) {
  7972. continue; // Do not show if module disabled
  7973. }
  7974. } elseif ($objecttype == 'reception') {
  7975. $tplpath = 'reception';
  7976. if (!isModEnabled('reception')) {
  7977. continue; // Do not show if module disabled
  7978. }
  7979. } elseif ($objecttype == 'delivery') {
  7980. $tplpath = 'delivery';
  7981. if (!isModEnabled('expedition')) {
  7982. continue; // Do not show if module disabled
  7983. }
  7984. } elseif ($objecttype == 'ficheinter') {
  7985. $tplpath = 'fichinter';
  7986. if (!isModEnabled('ficheinter')) {
  7987. continue; // Do not show if module disabled
  7988. }
  7989. } elseif ($objecttype == 'invoice_supplier') {
  7990. $tplpath = 'fourn/facture';
  7991. } elseif ($objecttype == 'order_supplier') {
  7992. $tplpath = 'fourn/commande';
  7993. } elseif ($objecttype == 'expensereport') {
  7994. $tplpath = 'expensereport';
  7995. } elseif ($objecttype == 'subscription') {
  7996. $tplpath = 'adherents';
  7997. } elseif ($objecttype == 'conferenceorbooth') {
  7998. $tplpath = 'eventorganization';
  7999. } elseif ($objecttype == 'conferenceorboothattendee') {
  8000. $tplpath = 'eventorganization';
  8001. } elseif ($objecttype == 'mo') {
  8002. $tplpath = 'mrp';
  8003. if (!isModEnabled('mrp')) {
  8004. continue; // Do not show if module disabled
  8005. }
  8006. }
  8007. global $linkedObjectBlock;
  8008. $linkedObjectBlock = $objects;
  8009. // Output template part (modules that overwrite templates must declare this into descriptor)
  8010. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
  8011. foreach ($dirtpls as $reldir) {
  8012. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  8013. global $noMoreLinkedObjectBlockAfter;
  8014. $noMoreLinkedObjectBlockAfter = 1;
  8015. }
  8016. $res = @include dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
  8017. if ($res) {
  8018. $nboftypesoutput++;
  8019. break;
  8020. }
  8021. }
  8022. }
  8023. if (!$nboftypesoutput) {
  8024. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
  8025. }
  8026. print '</table>';
  8027. if (!empty($compatibleImportElementsList)) {
  8028. $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
  8029. }
  8030. print '</div>';
  8031. }
  8032. return $nbofdifferenttypes;
  8033. }
  8034. /**
  8035. * Show block with links to link to other objects.
  8036. *
  8037. * @param CommonObject $object Object we want to show links to
  8038. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  8039. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  8040. * @return string HTML block
  8041. */
  8042. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  8043. {
  8044. global $conf, $langs, $hookmanager;
  8045. global $action;
  8046. $linktoelem = '';
  8047. $linktoelemlist = '';
  8048. $listofidcompanytoscan = '';
  8049. if (!is_object($object->thirdparty)) {
  8050. $object->fetch_thirdparty();
  8051. }
  8052. $possiblelinks = array();
  8053. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  8054. $listofidcompanytoscan = $object->thirdparty->id;
  8055. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  8056. $listofidcompanytoscan .= ',' . $object->thirdparty->parent;
  8057. }
  8058. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  8059. include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  8060. $tmpproject = new Project($this->db);
  8061. $tmpproject->fetch($object->fk_project);
  8062. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  8063. $listofidcompanytoscan .= ',' . $tmpproject->socid;
  8064. }
  8065. unset($tmpproject);
  8066. }
  8067. $possiblelinks = array(
  8068. 'propal' => array(
  8069. 'enabled' => isModEnabled('propal'),
  8070. 'perms' => 1,
  8071. 'label' => 'LinkToProposal',
  8072. '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') . ')'),
  8073. 'shipping' => array(
  8074. 'enabled' => isModEnabled('expedition'),
  8075. 'perms' => 1,
  8076. 'label' => 'LinkToExpedition',
  8077. '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') . ')'),
  8078. 'order' => array(
  8079. 'enabled' => isModEnabled('commande'),
  8080. 'perms' => 1,
  8081. 'label' => 'LinkToOrder',
  8082. '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') . ')'),
  8083. 'invoice' => array(
  8084. 'enabled' => isModEnabled('facture'),
  8085. 'perms' => 1,
  8086. 'label' => 'LinkToInvoice',
  8087. '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') . ')'),
  8088. 'invoice_template' => array(
  8089. 'enabled' => isModEnabled('facture'),
  8090. 'perms' => 1,
  8091. 'label' => 'LinkToTemplateInvoice',
  8092. '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') . ')'),
  8093. 'contrat' => array(
  8094. 'enabled' => isModEnabled('contrat'),
  8095. 'perms' => 1,
  8096. 'label' => 'LinkToContract',
  8097. '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
  8098. 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'
  8099. ),
  8100. 'fichinter' => array(
  8101. 'enabled' => isModEnabled('ficheinter'),
  8102. 'perms' => 1,
  8103. 'label' => 'LinkToIntervention',
  8104. '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') . ')'),
  8105. 'supplier_proposal' => array(
  8106. 'enabled' => (isModEnabled('supplier_proposal') ? $conf->supplier_proposal->enabled : 0),
  8107. 'perms' => 1,
  8108. 'label' => 'LinkToSupplierProposal',
  8109. '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') . ')'),
  8110. 'order_supplier' => array(
  8111. 'enabled' => (isModEnabled("supplier_order") ? $conf->supplier_order->enabled : 0),
  8112. 'perms' => 1,
  8113. 'label' => 'LinkToSupplierOrder',
  8114. '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') . ')'),
  8115. 'invoice_supplier' => array(
  8116. 'enabled' => (isModEnabled("supplier_invoice") ? $conf->supplier_invoice->enabled : 0),
  8117. 'perms' => 1, 'label' => 'LinkToSupplierInvoice',
  8118. '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') . ')'),
  8119. 'ticket' => array(
  8120. 'enabled' => isModEnabled('ticket'),
  8121. 'perms' => 1,
  8122. 'label' => 'LinkToTicket',
  8123. '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') . ')'),
  8124. 'mo' => array(
  8125. 'enabled' => isModEnabled('mrp'),
  8126. 'perms' => 1,
  8127. 'label' => 'LinkToMo',
  8128. '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') . ')')
  8129. );
  8130. }
  8131. if ($object->table_element == 'commande_fournisseur') {
  8132. $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').')';
  8133. } elseif ($object->table_element == 'mrp_mo') {
  8134. $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').')';
  8135. }
  8136. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  8137. // Can complete the possiblelink array
  8138. $hookmanager->initHooks(array('commonobject'));
  8139. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  8140. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8141. }
  8142. if (empty($reshook)) {
  8143. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8144. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  8145. }
  8146. } elseif ($reshook > 0) {
  8147. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8148. $possiblelinks = $hookmanager->resArray;
  8149. }
  8150. }
  8151. foreach ($possiblelinks as $key => $possiblelink) {
  8152. $num = 0;
  8153. if (empty($possiblelink['enabled'])) {
  8154. continue;
  8155. }
  8156. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  8157. print '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
  8158. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8159. print '<br>'."\n";
  8160. print '<!-- form to add a link from anywhere -->'."\n";
  8161. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  8162. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8163. print '<input type="hidden" name="action" value="addlinkbyref">';
  8164. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8165. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8166. print '<table class="noborder">';
  8167. print '<tr>';
  8168. //print '<td>' . $langs->trans("Ref") . '</td>';
  8169. print '<td class="center"><input type="text" placeholder="'.dol_escape_htmltag($langs->trans("Ref")).'" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;';
  8170. print '<input type="submit" class="button small valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
  8171. print '<input type="submit" class="button small" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  8172. print '</tr>';
  8173. print '</table>';
  8174. print '</form>';
  8175. }
  8176. $sql = $possiblelink['sql'];
  8177. $resqllist = $this->db->query($sql);
  8178. if ($resqllist) {
  8179. $num = $this->db->num_rows($resqllist);
  8180. $i = 0;
  8181. print '<br>';
  8182. print '<!-- form to add a link from object to same thirdparty -->'."\n";
  8183. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
  8184. print '<input type="hidden" name="action" value="addlink">';
  8185. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8186. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8187. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8188. print '<table class="noborder">';
  8189. print '<tr class="liste_titre">';
  8190. print '<td class="nowrap"></td>';
  8191. print '<td class="center">' . $langs->trans("Ref") . '</td>';
  8192. print '<td class="left">' . $langs->trans("RefCustomer") . '</td>';
  8193. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  8194. print '<td class="left">' . $langs->trans("Company") . '</td>';
  8195. print '</tr>';
  8196. while ($i < $num) {
  8197. $objp = $this->db->fetch_object($resqllist);
  8198. print '<tr class="oddeven">';
  8199. print '<td class="left">';
  8200. print '<input type="radio" name="idtolinkto" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
  8201. print '</td>';
  8202. print '<td class="center"><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
  8203. print '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
  8204. print '<td class="right">';
  8205. if ($possiblelink['label'] == 'LinkToContract') {
  8206. $form = new Form($this->db);
  8207. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
  8208. }
  8209. print '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
  8210. print '</td>';
  8211. print '<td>' . $objp->name . '</td>';
  8212. print '</tr>';
  8213. $i++;
  8214. }
  8215. print '</table>';
  8216. print '<div class="center">';
  8217. if ($num) {
  8218. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly small" value="' . $langs->trans('ToLink') . '">';
  8219. }
  8220. if (empty($conf->use_javascript_ajax)) {
  8221. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly small" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8222. } else {
  8223. 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>';
  8224. }
  8225. print '</form>';
  8226. $this->db->free($resqllist);
  8227. } else {
  8228. dol_print_error($this->db);
  8229. }
  8230. print '</div>';
  8231. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  8232. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8233. $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $num . ')</a></li>';
  8234. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  8235. } else {
  8236. $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  8237. }
  8238. }
  8239. }
  8240. if ($linktoelemlist) {
  8241. $linktoelem = '
  8242. <dl class="dropdown" id="linktoobjectname">
  8243. ';
  8244. if (!empty($conf->use_javascript_ajax)) {
  8245. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
  8246. }
  8247. $linktoelem .= '<dd>
  8248. <div class="multiselectlinkto">
  8249. <ul class="ulselectedfields">' . $linktoelemlist . '
  8250. </ul>
  8251. </div>
  8252. </dd>
  8253. </dl>';
  8254. } else {
  8255. $linktoelem = '';
  8256. }
  8257. if (!empty($conf->use_javascript_ajax)) {
  8258. print '<!-- Add js to show linkto box -->
  8259. <script nonce="' . getNonce() . '">
  8260. jQuery(document).ready(function() {
  8261. jQuery(".linkto").click(function() {
  8262. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  8263. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  8264. });
  8265. });
  8266. </script>
  8267. ';
  8268. }
  8269. return $linktoelem;
  8270. }
  8271. /**
  8272. * Return an html string with a select combo box to choose yes or no
  8273. *
  8274. * @param string $htmlname Name of html select field
  8275. * @param string $value Pre-selected value
  8276. * @param int $option 0 return yes/no, 1 return 1/0
  8277. * @param bool $disabled true or false
  8278. * @param int $useempty 1=Add empty line
  8279. * @param int $addjscombo 1=Add js beautifier on combo box
  8280. * @param string $morecss More CSS
  8281. * @param string $labelyes Label for Yes
  8282. * @param string $labelno Label for No
  8283. * @return string See option
  8284. */
  8285. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8286. {
  8287. global $langs;
  8288. $yes = "yes";
  8289. $no = "no";
  8290. if ($option) {
  8291. $yes = "1";
  8292. $no = "0";
  8293. }
  8294. $disabled = ($disabled ? ' disabled' : '');
  8295. $resultyesno = '<select class="flat width75' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
  8296. if ($useempty) {
  8297. $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8298. }
  8299. if (("$value" == 'yes') || ($value == 1)) {
  8300. $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
  8301. $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
  8302. } else {
  8303. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8304. $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
  8305. $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
  8306. }
  8307. $resultyesno .= '</select>' . "\n";
  8308. if ($addjscombo) {
  8309. $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
  8310. }
  8311. return $resultyesno;
  8312. }
  8313. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8314. /**
  8315. * Return list of export templates
  8316. *
  8317. * @param string $selected Id modele pre-selectionne
  8318. * @param string $htmlname Name of HTML select
  8319. * @param string $type Type of searched templates
  8320. * @param int $useempty Affiche valeur vide dans liste
  8321. * @return void
  8322. */
  8323. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8324. {
  8325. // phpcs:enable
  8326. $sql = "SELECT rowid, label";
  8327. $sql .= " FROM " . $this->db->prefix() . "export_model";
  8328. $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
  8329. $sql .= " ORDER BY rowid";
  8330. $result = $this->db->query($sql);
  8331. if ($result) {
  8332. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  8333. if ($useempty) {
  8334. print '<option value="-1">&nbsp;</option>';
  8335. }
  8336. $num = $this->db->num_rows($result);
  8337. $i = 0;
  8338. while ($i < $num) {
  8339. $obj = $this->db->fetch_object($result);
  8340. if ($selected == $obj->rowid) {
  8341. print '<option value="' . $obj->rowid . '" selected>';
  8342. } else {
  8343. print '<option value="' . $obj->rowid . '">';
  8344. }
  8345. print $obj->label;
  8346. print '</option>';
  8347. $i++;
  8348. }
  8349. print "</select>";
  8350. } else {
  8351. dol_print_error($this->db);
  8352. }
  8353. }
  8354. /**
  8355. * Return a HTML area with the reference of object and a navigation bar for a business object
  8356. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8357. *
  8358. * @param object $object Object to show.
  8359. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8360. * @param string $morehtml More html content to output just before the nav bar.
  8361. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8362. * @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.
  8363. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8364. * @param string $morehtmlref More html to show after ref.
  8365. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8366. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8367. * @param string $morehtmlleft More html code to show before ref.
  8368. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8369. * @param string $morehtmlright More html code to show after ref.
  8370. * @return string Portion HTML with ref + navigation buttons
  8371. */
  8372. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8373. {
  8374. global $conf, $langs, $hookmanager, $extralanguages;
  8375. $ret = '';
  8376. if (empty($fieldid)) {
  8377. $fieldid = 'rowid';
  8378. }
  8379. if (empty($fieldref)) {
  8380. $fieldref = 'ref';
  8381. }
  8382. // Preparing gender's display if there is one
  8383. $addgendertxt = '';
  8384. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8385. $addgendertxt = ' ';
  8386. switch ($object->gender) {
  8387. case 'man':
  8388. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8389. break;
  8390. case 'woman':
  8391. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8392. break;
  8393. case 'other':
  8394. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8395. break;
  8396. }
  8397. }
  8398. /*
  8399. $addadmin = '';
  8400. if (property_exists($object, 'admin')) {
  8401. if (isModEnabled('multicompany') && !empty($object->admin) && empty($object->entity)) {
  8402. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8403. } elseif (!empty($object->admin)) {
  8404. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8405. }
  8406. }*/
  8407. // Add where from hooks
  8408. if (is_object($hookmanager)) {
  8409. $parameters = array('showrefnav' => true);
  8410. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8411. $object->next_prev_filter .= $hookmanager->resPrint;
  8412. }
  8413. $previous_ref = $next_ref = '';
  8414. if ($shownav) {
  8415. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8416. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8417. $navurl = $_SERVER["PHP_SELF"];
  8418. // Special case for project/task page
  8419. if ($paramid == 'project_ref') {
  8420. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8421. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8422. $paramid = 'ref';
  8423. }
  8424. }
  8425. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8426. // accesskey is for Mac: CTRL + key for all browsers
  8427. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8428. if ($conf->browser->name == 'chrome') {
  8429. $stringforfirstkey .= ' ALT +';
  8430. } elseif ($conf->browser->name == 'firefox') {
  8431. $stringforfirstkey .= ' ALT + SHIFT +';
  8432. } else {
  8433. $stringforfirstkey .= ' CTL +';
  8434. }
  8435. $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>';
  8436. $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>';
  8437. }
  8438. //print "xx".$previous_ref."x".$next_ref;
  8439. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8440. // Right part of banner
  8441. if ($morehtmlright) {
  8442. $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
  8443. }
  8444. if ($previous_ref || $next_ref || $morehtml) {
  8445. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8446. }
  8447. if ($morehtml) {
  8448. $ret .= '<li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
  8449. }
  8450. if ($shownav && ($previous_ref || $next_ref)) {
  8451. $ret .= '<li class="pagination">' . $previous_ref . '</li>';
  8452. $ret .= '<li class="pagination">' . $next_ref . '</li>';
  8453. }
  8454. if ($previous_ref || $next_ref || $morehtml) {
  8455. $ret .= '</ul></div>';
  8456. }
  8457. $parameters = array();
  8458. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8459. if (empty($reshook)) {
  8460. $morehtmlstatus .= $hookmanager->resPrint;
  8461. } else {
  8462. $morehtmlstatus = $hookmanager->resPrint;
  8463. }
  8464. if ($morehtmlstatus) {
  8465. $ret .= '<div class="statusref">' . $morehtmlstatus . '</div>';
  8466. }
  8467. $parameters = array();
  8468. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8469. if (empty($reshook)) {
  8470. $morehtmlref .= $hookmanager->resPrint;
  8471. } elseif ($reshook > 0) {
  8472. $morehtmlref = $hookmanager->resPrint;
  8473. }
  8474. // Left part of banner
  8475. if ($morehtmlleft) {
  8476. if ($conf->browser->layout == 'phone') {
  8477. $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>';
  8478. } else {
  8479. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
  8480. }
  8481. }
  8482. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8483. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
  8484. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8485. if ($object->element == 'societe') {
  8486. $ret .= dol_htmlentities($object->name);
  8487. // List of extra languages
  8488. $arrayoflangcode = array();
  8489. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8490. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8491. }
  8492. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8493. if (!is_object($extralanguages)) {
  8494. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  8495. $extralanguages = new ExtraLanguages($this->db);
  8496. }
  8497. $extralanguages->fetch_name_extralanguages('societe');
  8498. if (!empty($extralanguages->attributes['societe']['name'])) {
  8499. $object->fetchValuesForExtraLanguages();
  8500. $htmltext = '';
  8501. // If there is extra languages
  8502. foreach ($arrayoflangcode as $extralangcode) {
  8503. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8504. if ($object->array_languages['name'][$extralangcode]) {
  8505. $htmltext .= $object->array_languages['name'][$extralangcode];
  8506. } else {
  8507. $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
  8508. }
  8509. }
  8510. $ret .= '<!-- Show translations of name -->' . "\n";
  8511. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8512. }
  8513. }
  8514. } elseif ($object->element == 'member') {
  8515. $ret .= $object->ref . '<br>';
  8516. $fullname = $object->getFullName($langs);
  8517. if ($object->morphy == 'mor' && $object->societe) {
  8518. $ret .= dol_htmlentities($object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '');
  8519. } else {
  8520. $ret .= dol_htmlentities($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities($object->societe) . ')' : '');
  8521. }
  8522. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8523. $ret .= dol_htmlentities($object->getFullName($langs)) . $addgendertxt;
  8524. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8525. $ret .= $object->ref . '<br>' . $object->label;
  8526. } elseif (in_array($object->element, array('adherent_type'))) {
  8527. $ret .= $object->label;
  8528. } elseif ($object->element == 'ecm_directories') {
  8529. $ret .= '';
  8530. } elseif ($fieldref != 'none') {
  8531. $ret .= dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "");
  8532. }
  8533. if ($morehtmlref) {
  8534. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8535. if (substr($morehtmlref, 0, 4) != '<div') {
  8536. $ret .= ' ';
  8537. }
  8538. $ret .= $morehtmlref;
  8539. }
  8540. $ret .= '</div>';
  8541. $ret .= '</div><!-- End banner content -->';
  8542. return $ret;
  8543. }
  8544. /**
  8545. * Return HTML code to output a barcode
  8546. *
  8547. * @param Object $object Object containing data to retrieve file name
  8548. * @param int $width Width of photo
  8549. * @param string $morecss More CSS on img of barcode
  8550. * @return string HTML code to output barcode
  8551. */
  8552. public function showbarcode(&$object, $width = 100, $morecss = '')
  8553. {
  8554. global $conf;
  8555. //Check if barcode is filled in the card
  8556. if (empty($object->barcode)) {
  8557. return '';
  8558. }
  8559. // Complete object if not complete
  8560. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8561. $result = $object->fetch_barcode();
  8562. //Check if fetch_barcode() failed
  8563. if ($result < 1) {
  8564. return '<!-- ErrorFetchBarcode -->';
  8565. }
  8566. }
  8567. // Barcode image
  8568. $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
  8569. $out = '<!-- url barcode = ' . $url . ' -->';
  8570. $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
  8571. return $out;
  8572. }
  8573. /**
  8574. * Return HTML code to output a photo
  8575. *
  8576. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8577. * @param object $object Object containing data to retrieve file name
  8578. * @param int $width Width of photo
  8579. * @param int $height Height of photo (auto if 0)
  8580. * @param int $caneditfield Add edit fields
  8581. * @param string $cssclass CSS name to use on img for photo
  8582. * @param string $imagesize 'mini', 'small' or '' (original)
  8583. * @param int $addlinktofullsize Add link to fullsize image
  8584. * @param int $cache 1=Accept to use image in cache
  8585. * @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 ''.
  8586. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8587. * @return string HTML code to output photo
  8588. */
  8589. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8590. {
  8591. global $conf, $langs;
  8592. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8593. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8594. $ret = '';
  8595. $dir = '';
  8596. $file = '';
  8597. $originalfile = '';
  8598. $altfile = '';
  8599. $email = '';
  8600. $capture = '';
  8601. if ($modulepart == 'societe') {
  8602. $dir = $conf->societe->multidir_output[$entity];
  8603. if (!empty($object->logo)) {
  8604. if (dolIsAllowedForPreview($object->logo)) {
  8605. if ((string) $imagesize == 'mini') {
  8606. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8607. } elseif ((string) $imagesize == 'small') {
  8608. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
  8609. } else {
  8610. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8611. }
  8612. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8613. }
  8614. }
  8615. $email = $object->email;
  8616. } elseif ($modulepart == 'contact') {
  8617. $dir = $conf->societe->multidir_output[$entity] . '/contact';
  8618. if (!empty($object->photo)) {
  8619. if (dolIsAllowedForPreview($object->photo)) {
  8620. if ((string) $imagesize == 'mini') {
  8621. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8622. } elseif ((string) $imagesize == 'small') {
  8623. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8624. } else {
  8625. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8626. }
  8627. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8628. }
  8629. }
  8630. $email = $object->email;
  8631. $capture = 'user';
  8632. } elseif ($modulepart == 'userphoto') {
  8633. $dir = $conf->user->dir_output;
  8634. if (!empty($object->photo)) {
  8635. if (dolIsAllowedForPreview($object->photo)) {
  8636. if ((string) $imagesize == 'mini') {
  8637. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8638. } elseif ((string) $imagesize == 'small') {
  8639. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8640. } else {
  8641. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8642. }
  8643. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8644. }
  8645. }
  8646. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8647. $altfile = $object->id . ".jpg"; // For backward compatibility
  8648. }
  8649. $email = $object->email;
  8650. $capture = 'user';
  8651. } elseif ($modulepart == 'memberphoto') {
  8652. $dir = $conf->adherent->dir_output;
  8653. if (!empty($object->photo)) {
  8654. if (dolIsAllowedForPreview($object->photo)) {
  8655. if ((string) $imagesize == 'mini') {
  8656. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8657. } elseif ((string) $imagesize == 'small') {
  8658. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8659. } else {
  8660. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8661. }
  8662. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8663. }
  8664. }
  8665. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8666. $altfile = $object->id . ".jpg"; // For backward compatibility
  8667. }
  8668. $email = $object->email;
  8669. $capture = 'user';
  8670. } else {
  8671. // Generic case to show photos
  8672. $dir = $conf->$modulepart->dir_output;
  8673. if (!empty($object->photo)) {
  8674. if (dolIsAllowedForPreview($object->photo)) {
  8675. if ((string) $imagesize == 'mini') {
  8676. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8677. } elseif ((string) $imagesize == 'small') {
  8678. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8679. } else {
  8680. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8681. }
  8682. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8683. }
  8684. }
  8685. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8686. $altfile = $object->id . ".jpg"; // For backward compatibility
  8687. }
  8688. $email = $object->email;
  8689. }
  8690. if ($forcecapture) {
  8691. $capture = $forcecapture;
  8692. }
  8693. if ($dir) {
  8694. if ($file && file_exists($dir . "/" . $file)) {
  8695. if ($addlinktofullsize) {
  8696. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8697. if ($urladvanced) {
  8698. $ret .= '<a href="' . $urladvanced . '">';
  8699. } else {
  8700. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8701. }
  8702. }
  8703. $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 . '">';
  8704. if ($addlinktofullsize) {
  8705. $ret .= '</a>';
  8706. }
  8707. } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
  8708. if ($addlinktofullsize) {
  8709. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8710. if ($urladvanced) {
  8711. $ret .= '<a href="' . $urladvanced . '">';
  8712. } else {
  8713. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8714. }
  8715. }
  8716. $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 . '">';
  8717. if ($addlinktofullsize) {
  8718. $ret .= '</a>';
  8719. }
  8720. } else {
  8721. $nophoto = '/public/theme/common/nophoto.png';
  8722. $defaultimg = 'identicon'; // For gravatar
  8723. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8724. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8725. $nophoto = 'company';
  8726. } else {
  8727. $nophoto = '/public/theme/common/user_anonymous.png';
  8728. if (!empty($object->gender) && $object->gender == 'man') {
  8729. $nophoto = '/public/theme/common/user_man.png';
  8730. }
  8731. if (!empty($object->gender) && $object->gender == 'woman') {
  8732. $nophoto = '/public/theme/common/user_woman.png';
  8733. }
  8734. }
  8735. }
  8736. if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
  8737. // see https://gravatar.com/site/implement/images/php/
  8738. $ret .= '<!-- Put link to gravatar -->';
  8739. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" title="' . $email . ' Gravatar avatar" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s=' . $width . '&d=' . $defaultimg . '">'; // gravatar need md5 hash
  8740. } else {
  8741. if ($nophoto == 'company') {
  8742. $ret .= '<div class="divforspanimg photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
  8743. $ret .= '<div class="difforspanimgright"></div>';
  8744. } else {
  8745. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
  8746. }
  8747. }
  8748. }
  8749. if ($caneditfield) {
  8750. if ($object->photo) {
  8751. $ret .= "<br>\n";
  8752. }
  8753. $ret .= '<table class="nobordernopadding centpercent">';
  8754. if ($object->photo) {
  8755. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
  8756. }
  8757. $ret .= '<tr><td class="tdoverflow">';
  8758. $maxfilesizearray = getMaxFileSizeArray();
  8759. $maxmin = $maxfilesizearray['maxmin'];
  8760. if ($maxmin > 0) {
  8761. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
  8762. }
  8763. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . $capture . '"' : '') . '>';
  8764. $ret .= '</td></tr>';
  8765. $ret .= '</table>';
  8766. }
  8767. } else {
  8768. dol_print_error('', 'Call of showphoto with wrong parameters modulepart=' . $modulepart);
  8769. }
  8770. return $ret;
  8771. }
  8772. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8773. /**
  8774. * Return select list of groups
  8775. *
  8776. * @param string|object $selected Id group or group preselected
  8777. * @param string $htmlname Field name in form
  8778. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8779. * @param string|array $exclude Array list of groups id to exclude
  8780. * @param int $disabled If select list must be disabled
  8781. * @param string|array $include Array list of groups id to include
  8782. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8783. * @param string $force_entity '0' or Ids of environment to force
  8784. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8785. * @param string $morecss More css to add to html component
  8786. * @return string
  8787. * @see select_dolusers()
  8788. */
  8789. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8790. {
  8791. // phpcs:enable
  8792. global $conf, $user, $langs;
  8793. // Permettre l'exclusion de groupes
  8794. $excludeGroups = null;
  8795. if (is_array($exclude)) {
  8796. $excludeGroups = implode(",", $exclude);
  8797. }
  8798. // Permettre l'inclusion de groupes
  8799. $includeGroups = null;
  8800. if (is_array($include)) {
  8801. $includeGroups = implode(",", $include);
  8802. }
  8803. if (!is_array($selected)) {
  8804. $selected = array($selected);
  8805. }
  8806. $out = '';
  8807. // On recherche les groupes
  8808. $sql = "SELECT ug.rowid, ug.nom as name";
  8809. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8810. $sql .= ", e.label";
  8811. }
  8812. $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
  8813. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8814. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
  8815. if ($force_entity) {
  8816. $sql .= " WHERE ug.entity IN (0, " . $force_entity . ")";
  8817. } else {
  8818. $sql .= " WHERE ug.entity IS NOT NULL";
  8819. }
  8820. } else {
  8821. $sql .= " WHERE ug.entity IN (0, " . $conf->entity . ")";
  8822. }
  8823. if (is_array($exclude) && $excludeGroups) {
  8824. $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
  8825. }
  8826. if (is_array($include) && $includeGroups) {
  8827. $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
  8828. }
  8829. $sql .= " ORDER BY ug.nom ASC";
  8830. dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
  8831. $resql = $this->db->query($sql);
  8832. if ($resql) {
  8833. // Enhance with select2
  8834. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  8835. $out .= '<select class="flat minwidth200' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  8836. $num = $this->db->num_rows($resql);
  8837. $i = 0;
  8838. if ($num) {
  8839. if ($show_empty && !$multiple) {
  8840. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8841. }
  8842. while ($i < $num) {
  8843. $obj = $this->db->fetch_object($resql);
  8844. $disableline = 0;
  8845. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8846. $disableline = 1;
  8847. }
  8848. $out .= '<option value="' . $obj->rowid . '"';
  8849. if ($disableline) {
  8850. $out .= ' disabled';
  8851. }
  8852. 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))) {
  8853. $out .= ' selected';
  8854. }
  8855. $out .= '>';
  8856. $out .= $obj->name;
  8857. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8858. $out .= " (" . $obj->label . ")";
  8859. }
  8860. $out .= '</option>';
  8861. $i++;
  8862. }
  8863. } else {
  8864. if ($show_empty) {
  8865. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
  8866. }
  8867. $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
  8868. }
  8869. $out .= '</select>';
  8870. $out .= ajax_combobox($htmlname);
  8871. } else {
  8872. dol_print_error($this->db);
  8873. }
  8874. return $out;
  8875. }
  8876. /**
  8877. * Return HTML to show the search and clear seach button
  8878. *
  8879. * @param string $pos Position of colon on the list. Value 'left' or 'right'
  8880. * @return string
  8881. */
  8882. public function showFilterButtons($pos = '')
  8883. {
  8884. $out = '<div class="nowraponall">';
  8885. if ($pos == 'left') {
  8886. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8887. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8888. } else {
  8889. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8890. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8891. }
  8892. $out .= '</div>';
  8893. return $out;
  8894. }
  8895. /**
  8896. * Return HTML to show the search and clear search button
  8897. *
  8898. * @param string $cssclass CSS class
  8899. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8900. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8901. * @return string
  8902. */
  8903. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8904. {
  8905. global $conf, $langs;
  8906. $out = '';
  8907. if (!empty($conf->use_javascript_ajax)) {
  8908. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
  8909. }
  8910. $out .= '<script nonce="' . getNonce() . '">
  8911. $(document).ready(function() {
  8912. $("#' . $cssclass . 's").click(function() {
  8913. if($(this).is(\':checked\')){
  8914. console.log("We check all ' . $cssclass . ' and trigger the change method");
  8915. $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
  8916. }
  8917. else
  8918. {
  8919. console.log("We uncheck all");
  8920. $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
  8921. }' . "\n";
  8922. if ($calljsfunction) {
  8923. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8924. }
  8925. $out .= ' });
  8926. $(".' . $cssclass . '").change(function() {
  8927. $(this).closest("tr").toggleClass("highlight", this.checked);
  8928. });
  8929. });
  8930. </script>';
  8931. return $out;
  8932. }
  8933. /**
  8934. * Return HTML to show the search and clear seach button
  8935. *
  8936. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8937. * @param string $cssclass CSS class
  8938. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8939. * @param string $massactionname Mass action name
  8940. * @return string
  8941. */
  8942. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8943. {
  8944. $out = $this->showFilterButtons();
  8945. if ($addcheckuncheckall) {
  8946. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8947. }
  8948. return $out;
  8949. }
  8950. /**
  8951. * Return HTML to show the select of expense categories
  8952. *
  8953. * @param string $selected preselected category
  8954. * @param string $htmlname name of HTML select list
  8955. * @param integer $useempty 1=Add empty line
  8956. * @param array $excludeid id to exclude
  8957. * @param string $target htmlname of target select to bind event
  8958. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8959. * @param array $params param to give
  8960. * @param int $info_admin Show the tooltip help picto to setup list
  8961. * @return string
  8962. */
  8963. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8964. {
  8965. global $langs, $user;
  8966. $out = '';
  8967. $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
  8968. $sql .= " AND entity IN (0," . getEntity('exp_tax_cat') . ")";
  8969. if (!empty($excludeid)) {
  8970. $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
  8971. }
  8972. $sql .= " ORDER BY label";
  8973. $resql = $this->db->query($sql);
  8974. if ($resql) {
  8975. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
  8976. if ($useempty) {
  8977. $out .= '<option value="0">&nbsp;</option>';
  8978. }
  8979. while ($obj = $this->db->fetch_object($resql)) {
  8980. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
  8981. }
  8982. $out .= '</select>';
  8983. $out .= ajax_combobox('select_' . $htmlname);
  8984. if (!empty($htmlname) && $user->admin && $info_admin) {
  8985. $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8986. }
  8987. if (!empty($target)) {
  8988. $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8989. $resql = $this->db->query($sql);
  8990. if ($resql) {
  8991. if ($this->db->num_rows($resql) > 0) {
  8992. $obj = $this->db->fetch_object($resql);
  8993. $out .= '<script nonce="' . getNonce() . '">
  8994. $(function() {
  8995. $("select[name=' . $target . ']").on("change", function() {
  8996. var current_val = $(this).val();
  8997. if (current_val == ' . $obj->id . ') {';
  8998. if (!empty($default_selected) || !empty($selected)) {
  8999. $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
  9000. }
  9001. $out .= '
  9002. $("select[name=' . $htmlname . ']").change();
  9003. }
  9004. });
  9005. $("select[name=' . $htmlname . ']").change(function() {
  9006. if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
  9007. // get price of kilometer to fill the unit price
  9008. $.ajax({
  9009. method: "POST",
  9010. dataType: "json",
  9011. data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
  9012. url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . join('&', $params)) . '",
  9013. }).done(function( data, textStatus, jqXHR ) {
  9014. console.log(data);
  9015. if (typeof data.up != "undefined") {
  9016. $("input[name=value_unit]").val(data.up);
  9017. $("select[name=' . $htmlname . ']").attr("title", data.title);
  9018. } else {
  9019. $("input[name=value_unit]").val("");
  9020. $("select[name=' . $htmlname . ']").attr("title", "");
  9021. }
  9022. });
  9023. }
  9024. });
  9025. });
  9026. </script>';
  9027. }
  9028. }
  9029. }
  9030. } else {
  9031. dol_print_error($this->db);
  9032. }
  9033. return $out;
  9034. }
  9035. /**
  9036. * Return HTML to show the select ranges of expense range
  9037. *
  9038. * @param string $selected preselected category
  9039. * @param string $htmlname name of HTML select list
  9040. * @param integer $useempty 1=Add empty line
  9041. * @return string
  9042. */
  9043. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  9044. {
  9045. global $conf, $langs;
  9046. $out = '';
  9047. $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
  9048. $sql .= " WHERE entity = " . $conf->entity . " AND active = 1";
  9049. $resql = $this->db->query($sql);
  9050. if ($resql) {
  9051. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9052. if ($useempty) {
  9053. $out .= '<option value="0"></option>';
  9054. }
  9055. while ($obj = $this->db->fetch_object($resql)) {
  9056. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
  9057. }
  9058. $out .= '</select>';
  9059. } else {
  9060. dol_print_error($this->db);
  9061. }
  9062. return $out;
  9063. }
  9064. /**
  9065. * Return HTML to show a select of expense
  9066. *
  9067. * @param string $selected preselected category
  9068. * @param string $htmlname name of HTML select list
  9069. * @param integer $useempty 1=Add empty choice
  9070. * @param integer $allchoice 1=Add all choice
  9071. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  9072. * @return string
  9073. */
  9074. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  9075. {
  9076. global $langs;
  9077. $out = '';
  9078. $sql = "SELECT id, code, label FROM " . $this->db->prefix() . "c_type_fees";
  9079. $sql .= " WHERE active = 1";
  9080. $resql = $this->db->query($sql);
  9081. if ($resql) {
  9082. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  9083. if ($useempty) {
  9084. $out .= '<option value="0"></option>';
  9085. }
  9086. if ($allchoice) {
  9087. $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
  9088. }
  9089. $field = 'code';
  9090. if ($useid) {
  9091. $field = 'id';
  9092. }
  9093. while ($obj = $this->db->fetch_object($resql)) {
  9094. $key = $langs->trans($obj->code);
  9095. $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
  9096. }
  9097. $out .= '</select>';
  9098. } else {
  9099. dol_print_error($this->db);
  9100. }
  9101. return $out;
  9102. }
  9103. /**
  9104. * Output a combo list with invoices qualified for a third party
  9105. *
  9106. * @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)
  9107. * @param int $selected Id invoice preselected
  9108. * @param string $htmlname Name of HTML select
  9109. * @param int $maxlength Maximum length of label
  9110. * @param int $option_only Return only html options lines without the select tag
  9111. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9112. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  9113. * @param int $forcefocus Force focus on field (works with javascript only)
  9114. * @param int $disabled Disabled
  9115. * @param string $morecss More css added to the select component
  9116. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  9117. * @param string $showproject 'all' = Show project info, ''=Hide project info
  9118. * @param User $usertofilter User object to use for filtering
  9119. * @return string HTML Select Invoice
  9120. */
  9121. 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)
  9122. {
  9123. global $user, $conf, $langs;
  9124. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  9125. if (is_null($usertofilter)) {
  9126. $usertofilter = $user;
  9127. }
  9128. $out = '';
  9129. $hideunselectables = false;
  9130. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  9131. $hideunselectables = true;
  9132. }
  9133. if (empty($projectsListId)) {
  9134. if (empty($usertofilter->rights->projet->all->lire)) {
  9135. $projectstatic = new Project($this->db);
  9136. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  9137. }
  9138. }
  9139. // Search all projects
  9140. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  9141. p.title, p.fk_soc, p.fk_statut, p.public,";
  9142. $sql .= ' s.nom as name';
  9143. $sql .= ' FROM ' . $this->db->prefix() . 'projet as p';
  9144. $sql .= ' LEFT JOIN ' . $this->db->prefix() . 'societe as s ON s.rowid = p.fk_soc,';
  9145. $sql .= ' ' . $this->db->prefix() . 'facture as f';
  9146. $sql .= " WHERE p.entity IN (" . getEntity('project') . ")";
  9147. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  9148. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  9149. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  9150. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  9151. $sql .= " ORDER BY p.ref, f.ref ASC";
  9152. $resql = $this->db->query($sql);
  9153. if ($resql) {
  9154. // Use select2 selector
  9155. if (!empty($conf->use_javascript_ajax)) {
  9156. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9157. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9158. $out .= $comboenhancement;
  9159. $morecss = 'minwidth200imp maxwidth500';
  9160. }
  9161. if (empty($option_only)) {
  9162. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9163. }
  9164. if (!empty($show_empty)) {
  9165. $out .= '<option value="0" class="optiongrey">';
  9166. if (!is_numeric($show_empty)) {
  9167. $out .= $show_empty;
  9168. } else {
  9169. $out .= '&nbsp;';
  9170. }
  9171. $out .= '</option>';
  9172. }
  9173. $num = $this->db->num_rows($resql);
  9174. $i = 0;
  9175. if ($num) {
  9176. while ($i < $num) {
  9177. $obj = $this->db->fetch_object($resql);
  9178. // 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.
  9179. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  9180. // Do nothing
  9181. } else {
  9182. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  9183. $i++;
  9184. continue;
  9185. }
  9186. $labeltoshow = '';
  9187. if ($showproject == 'all') {
  9188. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  9189. if ($obj->name) {
  9190. $labeltoshow .= ' - ' . $obj->name; // Soc name
  9191. }
  9192. $disabled = 0;
  9193. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  9194. $disabled = 1;
  9195. $labeltoshow .= ' - ' . $langs->trans("Draft");
  9196. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  9197. if ($discard_closed == 2) {
  9198. $disabled = 1;
  9199. }
  9200. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9201. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  9202. $disabled = 1;
  9203. $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
  9204. }
  9205. }
  9206. if (!empty($selected) && $selected == $obj->rowid) {
  9207. $out .= '<option value="' . $obj->rowid . '" selected';
  9208. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9209. $out .= '>' . $labeltoshow . '</option>';
  9210. } else {
  9211. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  9212. $resultat = '';
  9213. } else {
  9214. $resultat = '<option value="' . $obj->rowid . '"';
  9215. if ($disabled) {
  9216. $resultat .= ' disabled';
  9217. }
  9218. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  9219. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  9220. $resultat .= '>';
  9221. $resultat .= $labeltoshow;
  9222. $resultat .= '</option>';
  9223. }
  9224. $out .= $resultat;
  9225. }
  9226. }
  9227. $i++;
  9228. }
  9229. }
  9230. if (empty($option_only)) {
  9231. $out .= '</select>';
  9232. }
  9233. $this->db->free($resql);
  9234. return $out;
  9235. } else {
  9236. dol_print_error($this->db);
  9237. return '';
  9238. }
  9239. }
  9240. /**
  9241. * Output a combo list with invoices qualified for a third party
  9242. *
  9243. * @param int $selected Id invoice preselected
  9244. * @param string $htmlname Name of HTML select
  9245. * @param int $maxlength Maximum length of label
  9246. * @param int $option_only Return only html options lines without the select tag
  9247. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9248. * @param int $forcefocus Force focus on field (works with javascript only)
  9249. * @param int $disabled Disabled
  9250. * @param string $morecss More css added to the select component
  9251. * @return int Nbr of project if OK, <0 if KO
  9252. */
  9253. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  9254. {
  9255. global $user, $conf, $langs;
  9256. $out = '';
  9257. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  9258. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  9259. //$sql.= ', el.fk_source';
  9260. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  9261. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  9262. $sql .= " ORDER BY f.titre ASC";
  9263. $resql = $this->db->query($sql);
  9264. if ($resql) {
  9265. // Use select2 selector
  9266. if (!empty($conf->use_javascript_ajax)) {
  9267. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9268. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9269. $out .= $comboenhancement;
  9270. $morecss = 'minwidth200imp maxwidth500';
  9271. }
  9272. if (empty($option_only)) {
  9273. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9274. }
  9275. if (!empty($show_empty)) {
  9276. $out .= '<option value="0" class="optiongrey">';
  9277. if (!is_numeric($show_empty)) {
  9278. $out .= $show_empty;
  9279. } else {
  9280. $out .= '&nbsp;';
  9281. }
  9282. $out .= '</option>';
  9283. }
  9284. $num = $this->db->num_rows($resql);
  9285. if ($num) {
  9286. while ($obj = $this->db->fetch_object($resql)) {
  9287. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9288. $disabled = 0;
  9289. if (!empty($obj->suspended)) {
  9290. $disabled = 1;
  9291. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9292. }
  9293. if (!empty($selected) && $selected == $obj->rowid) {
  9294. $out .= '<option value="' . $obj->rowid . '" selected';
  9295. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9296. $out .= '>' . $labeltoshow . '</option>';
  9297. } else {
  9298. if ($disabled && ($selected != $obj->rowid)) {
  9299. $resultat = '';
  9300. } else {
  9301. $resultat = '<option value="' . $obj->rowid . '"';
  9302. if ($disabled) {
  9303. $resultat .= ' disabled';
  9304. }
  9305. $resultat .= '>';
  9306. $resultat .= $labeltoshow;
  9307. $resultat .= '</option>';
  9308. }
  9309. $out .= $resultat;
  9310. }
  9311. }
  9312. }
  9313. if (empty($option_only)) {
  9314. $out .= '</select>';
  9315. }
  9316. print $out;
  9317. $this->db->free($resql);
  9318. return $num;
  9319. } else {
  9320. $this->errors[] = $this->db->lasterror;
  9321. return -1;
  9322. }
  9323. }
  9324. /**
  9325. * Output the component to make advanced search criteries
  9326. *
  9327. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9328. * @param array $search_component_params Array of selected search criterias
  9329. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9330. * @param string $search_component_params_hidden String with $search_component_params criterias
  9331. * @return string HTML component for advanced search
  9332. */
  9333. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9334. {
  9335. global $langs;
  9336. if ($search_component_params_hidden != '' && !preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9337. $search_component_params_hidden = '(' . $search_component_params_hidden . ')';
  9338. }
  9339. $ret = '';
  9340. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9341. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9342. $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
  9343. $ret .= '</a>';
  9344. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9345. // Show select fields as tags.
  9346. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9347. if ($search_component_params_hidden) {
  9348. // Split the criteria on each AND
  9349. //var_dump($search_component_params_hidden);
  9350. $nbofchars = dol_strlen($search_component_params_hidden);
  9351. $arrayofandtags = array();
  9352. $i = 0; $s = '';
  9353. $countparenthesis = 0;
  9354. while ($i < $nbofchars) {
  9355. $char = dol_substr($search_component_params_hidden, $i, 1);
  9356. if ($char == '(') {
  9357. $countparenthesis++;
  9358. } elseif ($char == ')') {
  9359. $countparenthesis--;
  9360. }
  9361. if ($countparenthesis == 0) {
  9362. $char2 = dol_substr($search_component_params_hidden, $i+1, 1);
  9363. $char3 = dol_substr($search_component_params_hidden, $i+2, 1);
  9364. if ($char == 'A' && $char2 == 'N' && $char3 == 'D') {
  9365. // We found a AND
  9366. $arrayofandtags[] = trim($s);
  9367. $s = '';
  9368. $i+=2;
  9369. } else {
  9370. $s .= $char;
  9371. }
  9372. } else {
  9373. $s .= $char;
  9374. }
  9375. $i++;
  9376. }
  9377. if ($s) {
  9378. $arrayofandtags[] = trim($s);
  9379. }
  9380. // Show each AND part
  9381. foreach ($arrayofandtags as $tmpkey => $tmpval) {
  9382. $errormessage = '';
  9383. $searchtags = forgeSQLFromUniversalSearchCriteria($tmpval, $errormessage, 1, 1);
  9384. if ($errormessage) {
  9385. $this->error = 'ERROR in parsing search string: '.$errormessage;
  9386. }
  9387. // Remove first and last parenthesis but only if first is the opening and last the closing of the same group
  9388. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  9389. $searchtags = removeGlobalParenthesis($searchtags);
  9390. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch" data-ufilterid="'.($tmpkey+1).'" data-ufilter="'.dol_escape_htmltag($tmpval).'">';
  9391. $ret .= '<span class="tagsearchdelete select2-selection__choice__remove" data-ufilterid="'.($tmpkey+1).'">x</span> ';
  9392. $ret .= dol_escape_htmltag($searchtags);
  9393. $ret .= '</span>';
  9394. }
  9395. }
  9396. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9397. //$ret .= search_component_params
  9398. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9399. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9400. $show_search_component_params_hidden = 1;
  9401. if ($show_search_component_params_hidden) {
  9402. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9403. }
  9404. $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%')) -->";
  9405. $ret .= '<input type="hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
  9406. // $ret .= "<!-- sql= ".forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage)." -->";
  9407. // For compatibility with forms that show themself the search criteria in addition of this component, we output these fields
  9408. foreach ($arrayofcriterias as $criterias) {
  9409. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9410. if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9411. continue;
  9412. }
  9413. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9414. continue;
  9415. }
  9416. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9417. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
  9418. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
  9419. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
  9420. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
  9421. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
  9422. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
  9423. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
  9424. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
  9425. } else {
  9426. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
  9427. }
  9428. }
  9429. }
  9430. $ret .= '</div>';
  9431. $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";
  9432. $ret .= '<input type="text" placeholder="' . $langs->trans("Search") . '" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9433. $ret .= '</div>';
  9434. $ret .= '</div>';
  9435. $ret .= '<script>
  9436. jQuery(".tagsearchdelete").click(function() {
  9437. var filterid = $(this).parents().data("ufilterid");
  9438. console.log("We click to delete a criteria nb "+filterid);
  9439. // TODO Update the search_component_params_hidden with all data-ufilter except the one delete and post page
  9440. });
  9441. </script>
  9442. ';
  9443. return $ret;
  9444. }
  9445. /**
  9446. * selectModelMail
  9447. *
  9448. * @param string $prefix Prefix
  9449. * @param string $modelType Model type
  9450. * @param int $default 1=Show also Default mail template
  9451. * @param int $addjscombo Add js combobox
  9452. * @return string HTML select string
  9453. */
  9454. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9455. {
  9456. global $langs, $user;
  9457. $retstring = '';
  9458. $TModels = array();
  9459. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  9460. $formmail = new FormMail($this->db);
  9461. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9462. if ($default) {
  9463. $TModels[0] = $langs->trans('DefaultMailModel');
  9464. }
  9465. if ($result > 0) {
  9466. foreach ($formmail->lines_model as $model) {
  9467. $TModels[$model->id] = $model->label;
  9468. }
  9469. }
  9470. $retstring .= '<select class="flat" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
  9471. foreach ($TModels as $id_model => $label_model) {
  9472. $retstring .= '<option value="' . $id_model . '"';
  9473. $retstring .= ">" . $label_model . "</option>";
  9474. }
  9475. $retstring .= "</select>";
  9476. if ($addjscombo) {
  9477. $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
  9478. }
  9479. return $retstring;
  9480. }
  9481. /**
  9482. * Output the buttons to submit a creation/edit form
  9483. *
  9484. * @param string $save_label Alternative label for save button
  9485. * @param string $cancel_label Alternative label for cancel button
  9486. * @param array $morebuttons Add additional buttons between save and cancel
  9487. * @param bool $withoutdiv Option to remove enclosing centered div
  9488. * @param string $morecss More CSS
  9489. * @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.
  9490. * @return string Html code with the buttons
  9491. */
  9492. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9493. {
  9494. global $langs;
  9495. $buttons = array();
  9496. $save = array(
  9497. 'name' => 'save',
  9498. 'label_key' => $save_label,
  9499. );
  9500. if ($save_label == 'Create' || $save_label == 'Add') {
  9501. $save['name'] = 'add';
  9502. } elseif ($save_label == 'Modify') {
  9503. $save['name'] = 'edit';
  9504. }
  9505. $cancel = array(
  9506. 'name' => 'cancel',
  9507. 'label_key' => 'Cancel',
  9508. );
  9509. !empty($save_label) ? $buttons[] = $save : '';
  9510. if (!empty($morebuttons)) {
  9511. $buttons[] = $morebuttons;
  9512. }
  9513. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9514. $retstring = $withoutdiv ? '' : '<div class="center">';
  9515. foreach ($buttons as $button) {
  9516. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9517. $retstring .= '<input type="submit" class="button button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->trans($button['label_key'])) . '">';
  9518. }
  9519. $retstring .= $withoutdiv ? '' : '</div>';
  9520. if ($dol_openinpopup) {
  9521. $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . $dol_openinpopup . ' context, so we enable the close of dialog on cancel -->' . "\n";
  9522. $retstring .= '<script nonce="' . getNonce() . '">';
  9523. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9524. e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . $dol_openinpopup . '\');
  9525. window.parent.jQuery(\'#idfordialog' . $dol_openinpopup . '\').dialog(\'close\');
  9526. });';
  9527. $retstring .= '</script>';
  9528. }
  9529. return $retstring;
  9530. }
  9531. }