html.form.class.php 444 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517
  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. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. */
  38. /**
  39. * \file htdocs/core/class/html.form.class.php
  40. * \ingroup core
  41. * \brief File of class with all html predefined components
  42. */
  43. /**
  44. * Class to manage generation of HTML components
  45. * Only common components must be here.
  46. *
  47. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  48. */
  49. class Form
  50. {
  51. /**
  52. * @var DoliDB Database handler.
  53. */
  54. public $db;
  55. /**
  56. * @var string Error code (or message)
  57. */
  58. public $error = '';
  59. /**
  60. * @var string[] Array of error strings
  61. */
  62. public $errors = array();
  63. public $num;
  64. // Cache arrays
  65. public $cache_types_paiements = array();
  66. public $cache_conditions_paiements = array();
  67. public $cache_transport_mode = array();
  68. public $cache_availability = array();
  69. public $cache_demand_reason = array();
  70. public $cache_types_fees = array();
  71. public $cache_vatrates = array();
  72. /**
  73. * Constructor
  74. *
  75. * @param DoliDB $db Database handler
  76. */
  77. public function __construct($db)
  78. {
  79. $this->db = $db;
  80. }
  81. /**
  82. * Output key field for an editable field
  83. *
  84. * @param string $text Text of label or key to translate
  85. * @param string $htmlname Name of select field ('edit' prefix will be added)
  86. * @param string $preselected Value to show/edit (not used in this function)
  87. * @param object $object Object
  88. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  89. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'checkbox:ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
  90. * @param string $moreparam More param to add on a href URL.
  91. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  92. * @param int $notabletag 1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
  93. * @param string $paramid Key of parameter for id ('id', 'socid')
  94. * @param string $help Tooltip help
  95. * @return string HTML edit field
  96. */
  97. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  98. {
  99. global $conf, $langs;
  100. $ret = '';
  101. // TODO change for compatibility
  102. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata)) {
  103. if (!empty($perm)) {
  104. $tmp = explode(':', $typeofdata);
  105. $ret .= '<div class="editkey_' . $tmp[0] . (!empty($tmp[1]) ? ' ' . $tmp[1] : '') . '" id="' . $htmlname . '">';
  106. if ($fieldrequired) {
  107. $ret .= '<span class="fieldrequired">';
  108. }
  109. if ($help) {
  110. $ret .= $this->textwithpicto($langs->trans($text), $help);
  111. } else {
  112. $ret .= $langs->trans($text);
  113. }
  114. if ($fieldrequired) {
  115. $ret .= '</span>';
  116. }
  117. $ret .= '</div>' . "\n";
  118. } else {
  119. if ($fieldrequired) {
  120. $ret .= '<span class="fieldrequired">';
  121. }
  122. if ($help) {
  123. $ret .= $this->textwithpicto($langs->trans($text), $help);
  124. } else {
  125. $ret .= $langs->trans($text);
  126. }
  127. if ($fieldrequired) {
  128. $ret .= '</span>';
  129. }
  130. }
  131. } else {
  132. if (empty($notabletag) && $perm) {
  133. $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  134. }
  135. if ($fieldrequired) {
  136. $ret .= '<span class="fieldrequired">';
  137. }
  138. if ($help) {
  139. $ret .= $this->textwithpicto($langs->trans($text), $help);
  140. } else {
  141. $ret .= $langs->trans($text);
  142. }
  143. if ($fieldrequired) {
  144. $ret .= '</span>';
  145. }
  146. if (!empty($notabletag)) {
  147. $ret .= ' ';
  148. }
  149. if (empty($notabletag) && $perm) {
  150. $ret .= '</td>';
  151. }
  152. if (empty($notabletag) && $perm) {
  153. $ret .= '<td class="right">';
  154. }
  155. if ($htmlname && GETPOST('action', 'aZ09') != 'edit' . $htmlname && $perm) {
  156. $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>';
  157. }
  158. if (!empty($notabletag) && $notabletag == 1) {
  159. $ret .= ' : ';
  160. }
  161. if (!empty($notabletag) && $notabletag == 3) {
  162. $ret .= ' ';
  163. }
  164. if (empty($notabletag) && $perm) {
  165. $ret .= '</td>';
  166. }
  167. if (empty($notabletag) && $perm) {
  168. $ret .= '</tr></table>';
  169. }
  170. }
  171. return $ret;
  172. }
  173. /**
  174. * Output value of a field for an editable field
  175. *
  176. * @param string $text Text of label (not used in this function)
  177. * @param string $htmlname Name of select field
  178. * @param string $value Value to show/edit
  179. * @param object $object Object
  180. * @param boolean $perm Permission to allow button to edit parameter
  181. * @param string $typeofdata Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select;xkey:xval,ykey:yval,...')
  182. * @param string $editvalue When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of numeric value). Use '' to use same than $value
  183. * @param object $extObject External object
  184. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  185. * @param string $moreparam More param to add on the form action href URL
  186. * @param int $notabletag Do no output table tags
  187. * @param string $formatfunc Call a specific function to output field in view mode (For example: 'dol_print_email')
  188. * @param string $paramid Key of parameter for id ('id', 'socid')
  189. * @param string $gm 'auto' or 'tzuser' or 'tzserver' (when $typeofdata is a date)
  190. * @return string HTML edit field
  191. */
  192. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id', $gm = 'auto')
  193. {
  194. global $conf, $langs;
  195. $ret = '';
  196. // Check parameters
  197. if (empty($typeofdata)) {
  198. return 'ErrorBadParameter typeofdata is empty';
  199. }
  200. // Clean paramater $typeofdata
  201. if ($typeofdata == 'datetime') {
  202. $typeofdata = 'dayhour';
  203. }
  204. $reg = array();
  205. if (preg_match('/^(\w+)\((\d+)\)$/', $typeofdata, $reg)) {
  206. if ($reg[1] == 'varchar') {
  207. $typeofdata = 'string';
  208. } elseif ($reg[1] == 'int') {
  209. $typeofdata = 'numeric';
  210. } else {
  211. return 'ErrorBadParameter ' . $typeofdata;
  212. }
  213. }
  214. // When option to edit inline is activated
  215. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  216. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  217. } else {
  218. $editmode = (GETPOST('action', 'aZ09') == 'edit' . $htmlname);
  219. if ($editmode) {
  220. $ret .= "\n";
  221. $ret .= '<form method="post" action="' . $_SERVER["PHP_SELF"] . ($moreparam ? '?' . $moreparam : '') . '">';
  222. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  223. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  224. $ret .= '<input type="hidden" name="' . $paramid . '" value="' . $object->id . '">';
  225. if (empty($notabletag)) {
  226. $ret .= '<table class="nobordernopadding centpercent">';
  227. }
  228. if (empty($notabletag)) {
  229. $ret .= '<tr><td>';
  230. }
  231. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  232. $tmp = explode(':', $typeofdata);
  233. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($editvalue ? $editvalue : $value) . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  234. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  235. $tmp = explode(':', $typeofdata);
  236. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  237. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $valuetoshow . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  238. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  239. $tmp = explode(':', $typeofdata);
  240. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  241. $ret .= '<input type="text" id="' . $htmlname . '" name="' . $htmlname . '" value="' . ($valuetoshow != '' ? price($valuetoshow) : '') . '"' . (empty($tmp[1]) ? '' : ' size="' . $tmp[1] . '"') . ' autofocus>';
  242. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  243. $tmp = explode(':', $typeofdata);
  244. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
  245. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  246. $tmp = explode(':', $typeofdata);
  247. $cols = (empty($tmp[2]) ? '' : $tmp[2]);
  248. $morealt = '';
  249. if (preg_match('/%/', $cols)) {
  250. $morealt = ' style="width: ' . $cols . '"';
  251. $cols = '';
  252. }
  253. $valuetoshow = ($editvalue ? $editvalue : $value);
  254. $ret .= '<textarea id="' . $htmlname . '" name="' . $htmlname . '" wrap="soft" rows="' . (empty($tmp[1]) ? '20' : $tmp[1]) . '"' . ($cols ? ' cols="' . $cols . '"' : 'class="quatrevingtpercent"') . $morealt . '" autofocus>';
  255. // textarea convert automatically entities chars into simple chars.
  256. // 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.
  257. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  258. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  259. $ret .= '</textarea>';
  260. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  261. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form' . $htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  262. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  263. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form' . $htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  264. } elseif (preg_match('/^select;/', $typeofdata)) {
  265. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  266. $arraylist = array();
  267. foreach ($arraydata as $val) {
  268. $tmp = explode(':', $val);
  269. $tmpkey = str_replace('|', ':', $tmp[0]);
  270. $arraylist[$tmpkey] = $tmp[1];
  271. }
  272. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  273. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  274. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  275. require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
  276. $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]));
  277. $ret .= $doleditor->Create(1);
  278. }
  279. if (empty($notabletag)) {
  280. $ret .= '</td>';
  281. }
  282. // Button save-cancel
  283. if (empty($notabletag)) {
  284. $ret .= '<td class="left">';
  285. }
  286. //else $ret.='<div class="clearboth"></div>';
  287. $ret .= '<input type="submit" class="smallpaddingimp button' . (empty($notabletag) ? '' : ' ') . '" name="modify" value="' . $langs->trans("Modify") . '">';
  288. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  289. $ret .= '<br>' . "\n";
  290. }
  291. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel' . (empty($notabletag) ? '' : ' ') . '" name="cancel" value="' . $langs->trans("Cancel") . '">';
  292. if (empty($notabletag)) {
  293. $ret .= '</td>';
  294. }
  295. if (empty($notabletag)) {
  296. $ret .= '</tr></table>' . "\n";
  297. }
  298. $ret .= '</form>' . "\n";
  299. } else {
  300. if (preg_match('/^(email)/', $typeofdata)) {
  301. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  302. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  303. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  304. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  305. $tmp = explode(':', $typeofdata);
  306. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  307. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  308. $ret .= dol_htmlentitiesbr($value);
  309. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  310. $ret .= dol_string_onlythesehtmltags($value);
  311. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  312. $ret .= dol_string_onlythesehtmltags($value);
  313. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  314. $ret .= '<span class="valuedate">' . dol_print_date($value, 'day', $gm) . '</span>';
  315. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  316. $ret .= '<span class="valuedate">' . dol_print_date($value, 'dayhour', $gm) . '</span>';
  317. } elseif (preg_match('/^select;/', $typeofdata)) {
  318. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  319. $arraylist = array();
  320. foreach ($arraydata as $val) {
  321. $tmp = explode(':', $val);
  322. $arraylist[$tmp[0]] = $tmp[1];
  323. }
  324. $ret .= $arraylist[$value];
  325. if ($htmlname == 'fk_product_type') {
  326. if ($value == 0) {
  327. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  328. } else {
  329. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"') . $ret;
  330. }
  331. }
  332. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  333. $tmpcontent = dol_htmlentitiesbr($value);
  334. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  335. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  336. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  337. $tmpcontent = $firstline . ((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  338. }
  339. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  340. // clean data from some dangerous html
  341. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  342. } else {
  343. $ret .= dol_escape_htmltag($value);
  344. }
  345. if ($formatfunc && method_exists($object, $formatfunc)) {
  346. $ret = $object->$formatfunc($ret);
  347. }
  348. }
  349. }
  350. return $ret;
  351. }
  352. /**
  353. * Output edit in place form
  354. *
  355. * @param string $fieldname Name of the field
  356. * @param object $object Object
  357. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  358. * @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]'...)
  359. * @param string $check Same coe than $check parameter of GETPOST()
  360. * @param string $morecss More CSS
  361. * @return string HTML code for the edit of alternative language
  362. */
  363. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  364. {
  365. global $conf, $langs, $extralanguages;
  366. $result = '';
  367. // List of extra languages
  368. $arrayoflangcode = array();
  369. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  370. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  371. }
  372. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  373. if (!is_object($extralanguages)) {
  374. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  375. $extralanguages = new ExtraLanguages($this->db);
  376. }
  377. $extralanguages->fetch_name_extralanguages('societe');
  378. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  379. return ''; // No extralang field to show
  380. }
  381. $result .= '<!-- Widget for translation -->' . "\n";
  382. $result .= '<div class="inline-block paddingleft image-' . $object->element . '-' . $fieldname . '">';
  383. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  384. $result .= $s;
  385. $result .= '</div>';
  386. $result .= '<div class="inline-block hidden field-' . $object->element . '-' . $fieldname . '">';
  387. $resultforextrlang = '';
  388. foreach ($arrayoflangcode as $langcode) {
  389. $valuetoshow = GETPOSTISSET('field-' . $object->element . "-" . $fieldname . "-" . $langcode) ? GETPOST('field-' . $object->element . '-' . $fieldname . "-" . $langcode, $check) : '';
  390. if (empty($valuetoshow)) {
  391. $object->fetchValuesForExtraLanguages();
  392. //var_dump($object->array_languages);
  393. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  394. }
  395. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  396. $resultforextrlang .= $s;
  397. // TODO Use the showInputField() method of ExtraLanguages object
  398. if ($typeofdata == 'textarea') {
  399. $resultforextrlang .= '<textarea name="field-' . $object->element . "-" . $fieldname . "-" . $langcode . '" id="' . $fieldname . "-" . $langcode . '" class="' . $morecss . '" rows="' . ROWS_2 . '" wrap="soft">';
  400. $resultforextrlang .= $valuetoshow;
  401. $resultforextrlang .= '</textarea>';
  402. } else {
  403. $resultforextrlang .= '<input type="text" class="inputfieldforlang ' . ($morecss ? ' ' . $morecss : '') . '" name="field-' . $object->element . '-' . $fieldname . '-' . $langcode . '" value="' . $valuetoshow . '">';
  404. }
  405. }
  406. $result .= $resultforextrlang;
  407. $result .= '</div>';
  408. $result .= '<script>$(".image-' . $object->element . '-' . $fieldname . '").click(function() { console.log("Toggle lang widget"); jQuery(".field-' . $object->element . '-' . $fieldname . '").toggle(); });</script>';
  409. }
  410. return $result;
  411. }
  412. /**
  413. * Output edit in place form
  414. *
  415. * @param object $object Object
  416. * @param string $value Value to show/edit
  417. * @param string $htmlname DIV ID (field name)
  418. * @param int $condition Condition to edit
  419. * @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')
  420. * @param string $editvalue When in edit mode, use this value as $value instead of value
  421. * @param object $extObject External object
  422. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  423. * @return string HTML edit in place
  424. */
  425. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  426. {
  427. global $conf;
  428. $out = '';
  429. // Check parameters
  430. if (preg_match('/^text/', $inputType)) {
  431. $value = dol_nl2br($value);
  432. } elseif (preg_match('/^numeric/', $inputType)) {
  433. $value = price($value);
  434. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  435. $value = dol_print_date($value, 'day');
  436. }
  437. if ($condition) {
  438. $element = false;
  439. $table_element = false;
  440. $fk_element = false;
  441. $loadmethod = false;
  442. $savemethod = false;
  443. $ext_element = false;
  444. $button_only = false;
  445. $inputOption = '';
  446. $rows = '';
  447. $cols = '';
  448. if (is_object($object)) {
  449. $element = $object->element;
  450. $table_element = $object->table_element;
  451. $fk_element = $object->id;
  452. }
  453. if (is_object($extObject)) {
  454. $ext_element = $extObject->element;
  455. }
  456. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  457. $tmp = explode(':', $inputType);
  458. $inputType = $tmp[0];
  459. if (!empty($tmp[1])) {
  460. $inputOption = $tmp[1];
  461. }
  462. if (!empty($tmp[2])) {
  463. $savemethod = $tmp[2];
  464. }
  465. $out .= '<input id="width_' . $htmlname . '" value="' . $inputOption . '" type="hidden"/>' . "\n";
  466. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  467. $tmp = explode(':', $inputType);
  468. $inputType = $tmp[0];
  469. if (!empty($tmp[1])) {
  470. $inputOption = $tmp[1];
  471. }
  472. if (!empty($tmp[2])) {
  473. $savemethod = $tmp[2];
  474. }
  475. $out .= '<input id="timestamp" type="hidden"/>' . "\n"; // Use for timestamp format
  476. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  477. $tmp = explode(':', $inputType);
  478. $inputType = $tmp[0];
  479. $loadmethod = $tmp[1];
  480. if (!empty($tmp[2])) {
  481. $savemethod = $tmp[2];
  482. }
  483. if (!empty($tmp[3])) {
  484. $button_only = true;
  485. }
  486. } elseif (preg_match('/^textarea/', $inputType)) {
  487. $tmp = explode(':', $inputType);
  488. $inputType = $tmp[0];
  489. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  490. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  491. } elseif (preg_match('/^ckeditor/', $inputType)) {
  492. $tmp = explode(':', $inputType);
  493. $inputType = $tmp[0];
  494. $toolbar = $tmp[1];
  495. if (!empty($tmp[2])) {
  496. $width = $tmp[2];
  497. }
  498. if (!empty($tmp[3])) {
  499. $heigth = $tmp[3];
  500. }
  501. if (!empty($tmp[4])) {
  502. $savemethod = $tmp[4];
  503. }
  504. if (isModEnabled('fckeditor')) {
  505. $out .= '<input id="ckeditor_toolbar" value="' . $toolbar . '" type="hidden"/>' . "\n";
  506. } else {
  507. $inputType = 'textarea';
  508. }
  509. }
  510. $out .= '<input id="element_' . $htmlname . '" value="' . $element . '" type="hidden"/>' . "\n";
  511. $out .= '<input id="table_element_' . $htmlname . '" value="' . $table_element . '" type="hidden"/>' . "\n";
  512. $out .= '<input id="fk_element_' . $htmlname . '" value="' . $fk_element . '" type="hidden"/>' . "\n";
  513. $out .= '<input id="loadmethod_' . $htmlname . '" value="' . $loadmethod . '" type="hidden"/>' . "\n";
  514. if (!empty($savemethod)) {
  515. $out .= '<input id="savemethod_' . $htmlname . '" value="' . $savemethod . '" type="hidden"/>' . "\n";
  516. }
  517. if (!empty($ext_element)) {
  518. $out .= '<input id="ext_element_' . $htmlname . '" value="' . $ext_element . '" type="hidden"/>' . "\n";
  519. }
  520. if (!empty($custommsg)) {
  521. if (is_array($custommsg)) {
  522. if (!empty($custommsg['success'])) {
  523. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg['success'] . '" type="hidden"/>' . "\n";
  524. }
  525. if (!empty($custommsg['error'])) {
  526. $out .= '<input id="errormsg_' . $htmlname . '" value="' . $custommsg['error'] . '" type="hidden"/>' . "\n";
  527. }
  528. } else {
  529. $out .= '<input id="successmsg_' . $htmlname . '" value="' . $custommsg . '" type="hidden"/>' . "\n";
  530. }
  531. }
  532. if ($inputType == 'textarea') {
  533. $out .= '<input id="textarea_' . $htmlname . '_rows" value="' . $rows . '" type="hidden"/>' . "\n";
  534. $out .= '<input id="textarea_' . $htmlname . '_cols" value="' . $cols . '" type="hidden"/>' . "\n";
  535. }
  536. $out .= '<span id="viewval_' . $htmlname . '" class="viewval_' . $inputType . ($button_only ? ' inactive' : ' active') . '">' . $value . '</span>' . "\n";
  537. $out .= '<span id="editval_' . $htmlname . '" class="editval_' . $inputType . ($button_only ? ' inactive' : ' active') . ' hideobject">' . (!empty($editvalue) ? $editvalue : $value) . '</span>' . "\n";
  538. } else {
  539. $out = $value;
  540. }
  541. return $out;
  542. }
  543. /**
  544. * Show a text and picto with tooltip on text or picto.
  545. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  546. *
  547. * @param string $text Text to show
  548. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  549. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  550. * @param int $direction -1=image is before, 0=no image, 1=image is after
  551. * @param string $img Html code for image (use img_xxx() function to get it)
  552. * @param string $extracss Add a CSS style to td tags
  553. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  554. * @param string $incbefore Include code before the text
  555. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  556. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  557. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  558. * @return string Code html du tooltip (texte+picto)
  559. * @see textwithpicto() Use thisfunction if you can.
  560. */
  561. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  562. {
  563. if ($incbefore) {
  564. $text = $incbefore . $text;
  565. }
  566. if (!$htmltext) {
  567. return $text;
  568. }
  569. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  570. $tag = 'td';
  571. if ($notabs == 2) {
  572. $tag = 'div';
  573. }
  574. if ($notabs == 3) {
  575. $tag = 'span';
  576. }
  577. // Sanitize tooltip
  578. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  579. $extrastyle = '';
  580. if ($direction < 0) {
  581. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  582. $extrastyle = 'padding: 0px; padding-left: 3px;';
  583. }
  584. if ($direction > 0) {
  585. $extracss = ($extracss ? $extracss . ' ' : '') . ($notabs != 3 ? 'inline-block' : '');
  586. $extrastyle = 'padding: 0px; padding-right: 3px;';
  587. }
  588. $classfortooltip = 'classfortooltip';
  589. $s = '';
  590. $textfordialog = '';
  591. if ($tooltiptrigger == '') {
  592. $htmltext = str_replace('"', '&quot;', $htmltext);
  593. } else {
  594. $classfortooltip = 'classfortooltiponclick';
  595. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_' . $tooltiptrigger . '" class="classfortooltiponclicktext">' . $htmltext . '</div>';
  596. }
  597. if ($tooltipon == 2 || $tooltipon == 3) {
  598. $paramfortooltipimg = ' class="' . $classfortooltip . ($notabs != 3 ? ' inline-block' : '') . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '"';
  599. if ($tooltiptrigger == '') {
  600. $paramfortooltipimg .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on img tag to store tooltip
  601. } else {
  602. $paramfortooltipimg .= ' dolid="' . $tooltiptrigger . '"';
  603. }
  604. } else {
  605. $paramfortooltipimg = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  606. }
  607. if ($tooltipon == 1 || $tooltipon == 3) {
  608. $paramfortooltiptd = ' class="' . ($tooltipon == 3 ? 'cursorpointer ' : '') . $classfortooltip . ' inline-block' . ($extracss ? ' ' . $extracss : '') . '" style="padding: 0px;' . ($extrastyle ? ' ' . $extrastyle : '') . '" ';
  609. if ($tooltiptrigger == '') {
  610. $paramfortooltiptd .= ' title="' . ($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)) . '"'; // Attribut to put on td tag to store tooltip
  611. } else {
  612. $paramfortooltiptd .= ' dolid="' . $tooltiptrigger . '"';
  613. }
  614. } else {
  615. $paramfortooltiptd = ($extracss ? ' class="' . $extracss . '"' : '') . ($extrastyle ? ' style="' . $extrastyle . '"' : ''); // Attribut to put on td text tag
  616. }
  617. if (empty($notabs)) {
  618. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  619. } elseif ($notabs == 2) {
  620. $s .= '<div class="inline-block' . ($forcenowrap ? ' nowrap' : '') . '">';
  621. }
  622. // Define value if value is before
  623. if ($direction < 0) {
  624. $s .= '<' . $tag . $paramfortooltipimg;
  625. if ($tag == 'td') {
  626. $s .= ' class="valigntop" width="14"';
  627. }
  628. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  629. }
  630. // Use another method to help avoid having a space in value in order to use this value with jquery
  631. // Define label
  632. if ((string) $text != '') {
  633. $s .= '<' . $tag . $paramfortooltiptd . '>' . $text . '</' . $tag . '>';
  634. }
  635. // Define value if value is after
  636. if ($direction > 0) {
  637. $s .= '<' . $tag . $paramfortooltipimg;
  638. if ($tag == 'td') {
  639. $s .= ' class="valignmiddle" width="14"';
  640. }
  641. $s .= '>' . $textfordialog . $img . '</' . $tag . '>';
  642. }
  643. if (empty($notabs)) {
  644. $s .= '</tr></table>';
  645. } elseif ($notabs == 2) {
  646. $s .= '</div>';
  647. }
  648. return $s;
  649. }
  650. /**
  651. * Show a text with a picto and a tooltip on picto
  652. *
  653. * @param string $text Text to show
  654. * @param string $htmltext Content of tooltip
  655. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  656. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  657. * @param string $extracss Add a CSS style to td, div or span tag
  658. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  659. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  660. * @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')
  661. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  662. * @return string HTML code of text, picto, tooltip
  663. */
  664. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  665. {
  666. global $conf, $langs;
  667. //For backwards compatibility
  668. if ($type == '0') {
  669. $type = 'info';
  670. } elseif ($type == '1') {
  671. $type = 'help';
  672. }
  673. if (preg_match('/onsmartphone$/', $tooltiptrigger) && empty($conf->dol_no_mouse_hover)) {
  674. $tooltiptrigger = preg_replace('/^.*onsmartphone$/', '', $tooltiptrigger);
  675. }
  676. $alt = '';
  677. if ($tooltiptrigger) {
  678. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  679. }
  680. // If info or help with no javascript, show only text
  681. if (empty($conf->use_javascript_ajax)) {
  682. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  683. return $text;
  684. } else {
  685. $alt = $htmltext;
  686. $htmltext = '';
  687. }
  688. }
  689. // If info or help with smartphone, show only text (tooltip hover can't works)
  690. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  691. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  692. return $text;
  693. }
  694. }
  695. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  696. //if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
  697. //{
  698. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  699. //}
  700. $img = '';
  701. if ($type == 'info') {
  702. $img = img_help(0, $alt);
  703. } elseif ($type == 'help') {
  704. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  705. } elseif ($type == 'helpclickable') {
  706. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  707. } elseif ($type == 'superadmin') {
  708. $img = img_picto($alt, 'redstar');
  709. } elseif ($type == 'admin') {
  710. $img = img_picto($alt, 'star');
  711. } elseif ($type == 'warning') {
  712. $img = img_warning($alt);
  713. } elseif ($type != 'none') {
  714. $img = img_picto($alt, $type); // $type can be an image path
  715. }
  716. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  717. }
  718. /**
  719. * Generate select HTML to choose massaction
  720. *
  721. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  722. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  723. * @param int $alwaysvisible 1=select button always visible
  724. * @param string $name Name for massaction
  725. * @param string $cssclass CSS class used to check for select
  726. * @return string|void Select list
  727. */
  728. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  729. {
  730. global $conf, $langs, $hookmanager;
  731. $disabled = 0;
  732. $ret = '<div class="centpercent center">';
  733. $ret .= '<select class="flat' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'select valignmiddle alignstart" id="' . $name . '" name="' . $name . '"' . ($disabled ? ' disabled="disabled"' : '') . '>';
  734. // 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.
  735. $parameters = array();
  736. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  737. // check if there is a mass action
  738. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  739. return;
  740. }
  741. if (empty($reshook)) {
  742. $ret .= '<option value="0"' . ($disabled ? ' disabled="disabled"' : '') . '>-- ' . $langs->trans("SelectAction") . ' --</option>';
  743. foreach ($arrayofaction as $code => $label) {
  744. $ret .= '<option value="' . $code . '"' . ($disabled ? ' disabled="disabled"' : '') . ' data-html="' . dol_escape_htmltag($label) . '">' . $label . '</option>';
  745. }
  746. }
  747. $ret .= $hookmanager->resPrint;
  748. $ret .= '</select>';
  749. if (empty($conf->dol_optimize_smallscreen)) {
  750. $ret .= ajax_combobox('.' . $name . 'select');
  751. }
  752. // 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
  753. $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.
  754. $ret .= '<input type="submit" disabled name="confirmmassaction"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display: none"') . ' class="button smallpaddingimp' . (empty($conf->use_javascript_ajax) ? '' : ' hideobject') . ' ' . $name . ' ' . $name . 'confirmed" value="' . dol_escape_htmltag($langs->trans("Confirm")) . '">';
  755. $ret .= '</div>';
  756. if (!empty($conf->use_javascript_ajax)) {
  757. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  758. <script>
  759. 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 */
  760. {
  761. atleastoneselected=0;
  762. jQuery("."+cssclass).each(function( index ) {
  763. /* console.log( index + ": " + $( this ).text() ); */
  764. if ($(this).is(\':checked\')) atleastoneselected++;
  765. });
  766. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  767. if (atleastoneselected || ' . $alwaysvisible . ')
  768. {
  769. jQuery("."+name).show();
  770. ' . ($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("' . $selected . '").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '') . '
  771. ' . ($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '') . '
  772. }
  773. else
  774. {
  775. jQuery("."+name).hide();
  776. jQuery("."+name+"other").hide();
  777. }
  778. }
  779. jQuery(document).ready(function () {
  780. initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
  781. jQuery(".' . $cssclass . '").click(function() {
  782. initCheckForSelect(1, "' . $name . '", "' . $cssclass . '");
  783. });
  784. jQuery(".' . $name . 'select").change(function() {
  785. var massaction = $( this ).val();
  786. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  787. if (massaction == "builddoc")
  788. {
  789. urlform = urlform + "#show_files";
  790. }
  791. $( this ).closest("form").attr("action", urlform);
  792. console.log("we select a mass action name=' . $name . ' massaction="+massaction+" - "+urlform);
  793. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  794. if ($(this).val() != \'0\')
  795. {
  796. jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
  797. jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
  798. jQuery(".' . $name . '"+massaction).show();
  799. }
  800. else
  801. {
  802. jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
  803. jQuery(".' . $name . 'other").hide(); /* To disable any div open */
  804. }
  805. });
  806. });
  807. </script>
  808. ';
  809. }
  810. return $ret;
  811. }
  812. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  813. /**
  814. * Return combo list of activated countries, into language of user
  815. *
  816. * @param string $selected Id or Code or Label of preselected country
  817. * @param string $htmlname Name of html select object
  818. * @param string $htmloption More html options on select object
  819. * @param integer $maxlength Max length for labels (0=no limit)
  820. * @param string $morecss More css class
  821. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  822. * @param int|string $showempty Show empty choice
  823. * @param int $disablefavorites 1=Disable favorites,
  824. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  825. * @param array $exclude_country_code Array of country code (iso2) to exclude
  826. * @param int $hideflags Hide flags
  827. * @return string HTML string with select
  828. */
  829. 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)
  830. {
  831. // phpcs:enable
  832. global $conf, $langs, $mysoc;
  833. $langs->load("dict");
  834. $out = '';
  835. $countryArray = array();
  836. $favorite = array();
  837. $label = array();
  838. $atleastonefavorite = 0;
  839. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  840. $sql .= " FROM " . $this->db->prefix() . "c_country";
  841. $sql .= " WHERE active > 0";
  842. //$sql.= " ORDER BY code ASC";
  843. dol_syslog(get_class($this) . "::select_country", LOG_DEBUG);
  844. $resql = $this->db->query($sql);
  845. if ($resql) {
  846. $out .= '<select id="select' . $htmlname . '" class="flat maxwidth200onsmartphone selectcountry' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" ' . $htmloption . '>';
  847. $num = $this->db->num_rows($resql);
  848. $i = 0;
  849. if ($num) {
  850. while ($i < $num) {
  851. $obj = $this->db->fetch_object($resql);
  852. $countryArray[$i]['rowid'] = $obj->rowid;
  853. $countryArray[$i]['code_iso'] = $obj->code_iso;
  854. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  855. $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 : ''));
  856. $countryArray[$i]['favorite'] = $obj->favorite;
  857. $countryArray[$i]['eec'] = $obj->eec;
  858. $favorite[$i] = $obj->favorite;
  859. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  860. $i++;
  861. }
  862. if (empty($disablefavorites)) {
  863. $array1_sort_order = SORT_DESC;
  864. $array2_sort_order = SORT_ASC;
  865. array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
  866. } else {
  867. $countryArray = dol_sort_array($countryArray, 'label');
  868. }
  869. if ($showempty) {
  870. if (is_numeric($showempty)) {
  871. $out .= '<option value="">&nbsp;</option>' . "\n";
  872. } else {
  873. $out .= '<option value="">' . $langs->trans($showempty) . '</option>' . "\n";
  874. }
  875. }
  876. if ($addspecialentries) { // Add dedicated entries for groups of countries
  877. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  878. $out .= '<option value="special_allnotme"' . ($selected == 'special_allnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  879. $out .= '<option value="special_eec"' . ($selected == 'special_eec' ? ' selected' : '') . '>' . $langs->trans("CountriesInEEC") . '</option>';
  880. if ($mysoc->isInEEC()) {
  881. $out .= '<option value="special_eecnotme"' . ($selected == 'special_eecnotme' ? ' selected' : '') . '>' . $langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country" . $mysoc->country_code)) . '</option>';
  882. }
  883. $out .= '<option value="special_noteec"' . ($selected == 'special_noteec' ? ' selected' : '') . '>' . $langs->trans("CountriesNotInEEC") . '</option>';
  884. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  885. }
  886. foreach ($countryArray as $row) {
  887. //if (empty($showempty) && empty($row['rowid'])) continue;
  888. if (empty($row['rowid'])) {
  889. continue;
  890. }
  891. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  892. continue; // exclude some countries
  893. }
  894. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  895. $atleastonefavorite++;
  896. }
  897. if (empty($row['favorite']) && $atleastonefavorite) {
  898. $atleastonefavorite = 0;
  899. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  900. }
  901. $labeltoshow = '';
  902. if ($row['label']) {
  903. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  904. } else {
  905. $labeltoshow .= '&nbsp;';
  906. }
  907. if ($row['code_iso']) {
  908. $labeltoshow .= ' <span class="opacitymedium">(' . $row['code_iso'] . ')</span>';
  909. if (empty($hideflags)) {
  910. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  911. $labeltoshow = $tmpflag . ' ' . $labeltoshow;
  912. }
  913. }
  914. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  915. $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']) . '">';
  916. } else {
  917. $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']) . '">';
  918. }
  919. $out .= $labeltoshow;
  920. $out .= '</option>' . "\n";
  921. }
  922. }
  923. $out .= '</select>';
  924. } else {
  925. dol_print_error($this->db);
  926. }
  927. // Make select dynamic
  928. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  929. $out .= ajax_combobox('select' . $htmlname, array(), 0, 0, 'resolve');
  930. return $out;
  931. }
  932. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  933. /**
  934. * Return select list of incoterms
  935. *
  936. * @param string $selected Id or Code of preselected incoterm
  937. * @param string $location_incoterms Value of input location
  938. * @param string $page Defined the form action
  939. * @param string $htmlname Name of html select object
  940. * @param string $htmloption Options html on select object
  941. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  942. * @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')))
  943. * @param array $disableautocomplete Disable autocomplete
  944. * @return string HTML string with select and input
  945. */
  946. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  947. {
  948. // phpcs:enable
  949. global $conf, $langs;
  950. $langs->load("dict");
  951. $out = '';
  952. $moreattrib = '';
  953. $incotermArray = array();
  954. $sql = "SELECT rowid, code";
  955. $sql .= " FROM " . $this->db->prefix() . "c_incoterms";
  956. $sql .= " WHERE active > 0";
  957. $sql .= " ORDER BY code ASC";
  958. dol_syslog(get_class($this) . "::select_incoterm", LOG_DEBUG);
  959. $resql = $this->db->query($sql);
  960. if ($resql) {
  961. if ($conf->use_javascript_ajax && !$forcecombo) {
  962. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  963. $out .= ajax_combobox($htmlname, $events);
  964. }
  965. if (!empty($page)) {
  966. $out .= '<form method="post" action="' . $page . '">';
  967. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  968. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  969. }
  970. $out .= '<select id="' . $htmlname . '" class="flat selectincoterm width75" name="' . $htmlname . '" ' . $htmloption . '>';
  971. $out .= '<option value="0">&nbsp;</option>';
  972. $num = $this->db->num_rows($resql);
  973. $i = 0;
  974. if ($num) {
  975. while ($i < $num) {
  976. $obj = $this->db->fetch_object($resql);
  977. $incotermArray[$i]['rowid'] = $obj->rowid;
  978. $incotermArray[$i]['code'] = $obj->code;
  979. $i++;
  980. }
  981. foreach ($incotermArray as $row) {
  982. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  983. $out .= '<option value="' . $row['rowid'] . '" selected>';
  984. } else {
  985. $out .= '<option value="' . $row['rowid'] . '">';
  986. }
  987. if ($row['code']) {
  988. $out .= $row['code'];
  989. }
  990. $out .= '</option>';
  991. }
  992. }
  993. $out .= '</select>';
  994. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  995. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT . '/core/ajax/locationincoterms.php') . "\n";
  996. $moreattrib .= ' autocomplete="off"';
  997. }
  998. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="' . $location_incoterms . '">' . "\n";
  999. if (!empty($page)) {
  1000. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="' . $langs->trans("Modify") . '"></form>';
  1001. }
  1002. } else {
  1003. dol_print_error($this->db);
  1004. }
  1005. return $out;
  1006. }
  1007. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1008. /**
  1009. * Return list of types of lines (product or service)
  1010. * Example: 0=product, 1=service, 9=other (for external module)
  1011. *
  1012. * @param string $selected Preselected type
  1013. * @param string $htmlname Name of field in html form
  1014. * @param int $showempty Add an empty field
  1015. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  1016. * @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')
  1017. * @return void
  1018. */
  1019. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  1020. {
  1021. // phpcs:enable
  1022. global $langs, $conf;
  1023. // If product & services are enabled or both disabled.
  1024. if (
  1025. $forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
  1026. || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))
  1027. ) {
  1028. if (empty($hidetext)) {
  1029. print $langs->trans("Type") . ': ';
  1030. }
  1031. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  1032. if ($showempty) {
  1033. print '<option value="-1"';
  1034. if ($selected == -1) {
  1035. print ' selected';
  1036. }
  1037. print '>&nbsp;</option>';
  1038. }
  1039. print '<option value="0"';
  1040. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1041. print ' selected';
  1042. }
  1043. print '>' . $langs->trans("Product");
  1044. print '<option value="1"';
  1045. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1046. print ' selected';
  1047. }
  1048. print '>' . $langs->trans("Service");
  1049. print '</select>';
  1050. print ajax_combobox('select_' . $htmlname);
  1051. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1052. }
  1053. if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
  1054. print $langs->trans("Service");
  1055. print '<input type="hidden" name="' . $htmlname . '" value="1">';
  1056. }
  1057. if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
  1058. print $langs->trans("Product");
  1059. print '<input type="hidden" name="' . $htmlname . '" value="0">';
  1060. }
  1061. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1062. 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
  1063. }
  1064. }
  1065. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1066. /**
  1067. * Load into cache cache_types_fees, array of types of fees
  1068. *
  1069. * @return int Nb of lines loaded, <0 if KO
  1070. */
  1071. public function load_cache_types_fees()
  1072. {
  1073. // phpcs:enable
  1074. global $langs;
  1075. $num = count($this->cache_types_fees);
  1076. if ($num > 0) {
  1077. return 0; // Cache already loaded
  1078. }
  1079. dol_syslog(__METHOD__, LOG_DEBUG);
  1080. $langs->load("trips");
  1081. $sql = "SELECT c.code, c.label";
  1082. $sql .= " FROM " . $this->db->prefix() . "c_type_fees as c";
  1083. $sql .= " WHERE active > 0";
  1084. $resql = $this->db->query($sql);
  1085. if ($resql) {
  1086. $num = $this->db->num_rows($resql);
  1087. $i = 0;
  1088. while ($i < $num) {
  1089. $obj = $this->db->fetch_object($resql);
  1090. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1091. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1092. $this->cache_types_fees[$obj->code] = $label;
  1093. $i++;
  1094. }
  1095. asort($this->cache_types_fees);
  1096. return $num;
  1097. } else {
  1098. dol_print_error($this->db);
  1099. return -1;
  1100. }
  1101. }
  1102. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1103. /**
  1104. * Return list of types of notes
  1105. *
  1106. * @param string $selected Preselected type
  1107. * @param string $htmlname Name of field in form
  1108. * @param int $showempty Add an empty field
  1109. * @return void
  1110. */
  1111. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1112. {
  1113. // phpcs:enable
  1114. global $user, $langs;
  1115. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  1116. $this->load_cache_types_fees();
  1117. print '<select id="select_' . $htmlname . '" class="flat" name="' . $htmlname . '">';
  1118. if ($showempty) {
  1119. print '<option value="-1"';
  1120. if ($selected == -1) {
  1121. print ' selected';
  1122. }
  1123. print '>&nbsp;</option>';
  1124. }
  1125. foreach ($this->cache_types_fees as $key => $value) {
  1126. print '<option value="' . $key . '"';
  1127. if ($key == $selected) {
  1128. print ' selected';
  1129. }
  1130. print '>';
  1131. print $value;
  1132. print '</option>';
  1133. }
  1134. print '</select>';
  1135. if ($user->admin) {
  1136. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1137. }
  1138. }
  1139. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1140. /**
  1141. * Output html form to select a third party
  1142. *
  1143. * @param string $selected Preselected type
  1144. * @param string $htmlname Name of field in form
  1145. * @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)')
  1146. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1147. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1148. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1149. * @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')))
  1150. * @param int $limit Maximum number of elements
  1151. * @param string $morecss Add more css styles to the SELECT component
  1152. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1153. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1154. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1155. * @param array $ajaxoptions Options for ajax_autocompleter
  1156. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1157. * @param array $excludeids Exclude IDs from the select combo
  1158. * @param int $showcode Show code
  1159. * @return string HTML string with select box for thirdparty.
  1160. */
  1161. 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)
  1162. {
  1163. // phpcs:enable
  1164. global $conf, $user, $langs;
  1165. $out = '';
  1166. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1167. if (is_null($ajaxoptions)) {
  1168. $ajaxoptions = array();
  1169. }
  1170. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1171. // No immediate load of all database
  1172. $placeholder = '';
  1173. if ($selected && empty($selected_input_value)) {
  1174. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  1175. $societetmp = new Societe($this->db);
  1176. $societetmp->fetch($selected);
  1177. $selected_input_value = $societetmp->name;
  1178. unset($societetmp);
  1179. }
  1180. // mode 1
  1181. $urloption = 'htmlname=' . urlencode(str_replace('.', '_', $htmlname)) . '&outjson=1&filter=' . urlencode($filter) . (empty($excludeids) ? '' : '&excludeids=' . join(',', $excludeids)) . ($showtype ? '&showtype=' . urlencode($showtype) : '') . ($showcode ? '&showcode=' . urlencode($showcode) : '');
  1182. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1183. if (empty($hidelabel)) {
  1184. print $langs->trans("RefOrLabel") . ' : ';
  1185. } elseif ($hidelabel > 1) {
  1186. $placeholder = $langs->trans("RefOrLabel");
  1187. if ($hidelabel == 2) {
  1188. $out .= img_picto($langs->trans("Search"), 'search');
  1189. }
  1190. }
  1191. $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' : '') . ' />';
  1192. if ($hidelabel == 3) {
  1193. $out .= img_picto($langs->trans("Search"), 'search');
  1194. }
  1195. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1196. } else {
  1197. // Immediate load of all database
  1198. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1199. }
  1200. return $out;
  1201. }
  1202. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1203. /**
  1204. * Output html form to select a third party.
  1205. * 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.
  1206. *
  1207. * @param string $selected Preselected type
  1208. * @param string $htmlname Name of field in form
  1209. * @param string $filter Optional filters criteras (example: 's.rowid NOT IN (x)', 's.client IN (1,3)'). Do not use a filter coming from input of users.
  1210. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1211. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1212. * @param int $forcecombo Force to use standard HTML select component without beautification
  1213. * @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')))
  1214. * @param string $filterkey Filter on key value
  1215. * @param int $outputmode 0=HTML select string, 1=Array
  1216. * @param int $limit Limit number of answers
  1217. * @param string $morecss Add more css styles to the SELECT component
  1218. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1219. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1220. * @param array $excludeids Exclude IDs from the select combo
  1221. * @param int $showcode Show code in list
  1222. * @return string HTML string with
  1223. */
  1224. 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)
  1225. {
  1226. // phpcs:enable
  1227. global $conf, $user, $langs;
  1228. global $hookmanager;
  1229. $out = '';
  1230. $num = 0;
  1231. $outarray = array();
  1232. if ($selected === '') {
  1233. $selected = array();
  1234. } elseif (!is_array($selected)) {
  1235. $selected = array($selected);
  1236. }
  1237. // Clean $filter that may contains sql conditions so sql code
  1238. if (function_exists('testSqlAndScriptInject')) {
  1239. if (testSqlAndScriptInject($filter, 3) > 0) {
  1240. $filter = '';
  1241. }
  1242. }
  1243. // We search companies
  1244. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1245. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1246. $sql .= ", s.address, s.zip, s.town";
  1247. $sql .= ", dictp.code as country_code";
  1248. }
  1249. $sql .= " FROM " . $this->db->prefix() . "societe as s";
  1250. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1251. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_country as dictp ON dictp.rowid = s.fk_pays";
  1252. }
  1253. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1254. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  1255. }
  1256. $sql .= " WHERE s.entity IN (" . getEntity('societe') . ")";
  1257. if (!empty($user->socid)) {
  1258. $sql .= " AND s.rowid = " . ((int) $user->socid);
  1259. }
  1260. if ($filter) {
  1261. $sql .= " AND (" . $filter . ")";
  1262. }
  1263. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1264. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  1265. }
  1266. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1267. $sql .= " AND s.status <> 0";
  1268. }
  1269. if (!empty($excludeids)) {
  1270. $sql .= " AND s.rowid NOT IN (" . $this->db->sanitize(join(',', $excludeids)) . ")";
  1271. }
  1272. // Add where from hooks
  1273. $parameters = array();
  1274. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1275. $sql .= $hookmanager->resPrint;
  1276. // Add criteria
  1277. if ($filterkey && $filterkey != '') {
  1278. $sql .= " AND (";
  1279. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1280. // For natural search
  1281. $scrit = explode(' ', $filterkey);
  1282. $i = 0;
  1283. if (count($scrit) > 1) {
  1284. $sql .= "(";
  1285. }
  1286. foreach ($scrit as $crit) {
  1287. if ($i > 0) {
  1288. $sql .= " AND ";
  1289. }
  1290. $sql .= "(s.nom LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  1291. $i++;
  1292. }
  1293. if (count($scrit) > 1) {
  1294. $sql .= ")";
  1295. }
  1296. if (isModEnabled('barcode')) {
  1297. $sql .= " OR s.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1298. }
  1299. $sql .= " OR s.code_client LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.code_fournisseur LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1300. $sql .= " OR s.name_alias LIKE '" . $this->db->escape($prefix . $filterkey) . "%' OR s.tva_intra LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  1301. $sql .= ")";
  1302. }
  1303. $sql .= $this->db->order("nom", "ASC");
  1304. $sql .= $this->db->plimit($limit, 0);
  1305. // Build output string
  1306. dol_syslog(get_class($this) . "::select_thirdparty_list", LOG_DEBUG);
  1307. $resql = $this->db->query($sql);
  1308. if ($resql) {
  1309. if (!$forcecombo) {
  1310. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1311. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1312. }
  1313. // Construct $out and $outarray
  1314. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($moreparam ? ' ' . $moreparam : '') . ' name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . '>' . "\n";
  1315. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1316. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1317. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1318. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1319. if ($showempty && !is_numeric($showempty)) {
  1320. $textifempty = $langs->trans($showempty);
  1321. } else {
  1322. $textifempty .= $langs->trans("All");
  1323. }
  1324. }
  1325. if ($showempty) {
  1326. $out .= '<option value="-1" data-html="' . dol_escape_htmltag('<span class="opacitymedium">' . ($textifempty ? $textifempty : '&nbsp;') . '</span>') . '">' . $textifempty . '</option>' . "\n";
  1327. }
  1328. $companytemp = new Societe($this->db);
  1329. $num = $this->db->num_rows($resql);
  1330. $i = 0;
  1331. if ($num) {
  1332. while ($i < $num) {
  1333. $obj = $this->db->fetch_object($resql);
  1334. $label = '';
  1335. if ($showcode || !empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) {
  1336. if (($obj->client) && (!empty($obj->code_client))) {
  1337. $label = $obj->code_client . ' - ';
  1338. }
  1339. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1340. $label .= $obj->code_fournisseur . ' - ';
  1341. }
  1342. $label .= ' ' . $obj->name;
  1343. } else {
  1344. $label = $obj->name;
  1345. }
  1346. if (!empty($obj->name_alias)) {
  1347. $label .= ' (' . $obj->name_alias . ')';
  1348. }
  1349. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1350. $label .= ' - ' . $obj->tva_intra;
  1351. }
  1352. $labelhtml = $label;
  1353. if ($showtype) {
  1354. $companytemp->id = $obj->rowid;
  1355. $companytemp->client = $obj->client;
  1356. $companytemp->fournisseur = $obj->fournisseur;
  1357. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1358. if ($tmptype) {
  1359. $labelhtml .= ' ' . $tmptype;
  1360. }
  1361. if ($obj->client || $obj->fournisseur) {
  1362. $label .= ' (';
  1363. }
  1364. if ($obj->client == 1 || $obj->client == 3) {
  1365. $label .= $langs->trans("Customer");
  1366. }
  1367. if ($obj->client == 2 || $obj->client == 3) {
  1368. $label .= ($obj->client == 3 ? ', ' : '') . $langs->trans("Prospect");
  1369. }
  1370. if ($obj->fournisseur) {
  1371. $label .= ($obj->client ? ', ' : '') . $langs->trans("Supplier");
  1372. }
  1373. if ($obj->client || $obj->fournisseur) {
  1374. $label .= ')';
  1375. }
  1376. }
  1377. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1378. $s = ($obj->address ? ' - ' . $obj->address : '') . ($obj->zip ? ' - ' . $obj->zip : '') . ($obj->town ? ' ' . $obj->town : '');
  1379. if (!empty($obj->country_code)) {
  1380. $s .= ', ' . $langs->trans('Country' . $obj->country_code);
  1381. }
  1382. $label .= $s;
  1383. $labelhtml .= $s;
  1384. }
  1385. if (empty($outputmode)) {
  1386. if (in_array($obj->rowid, $selected)) {
  1387. $out .= '<option value="' . $obj->rowid . '" selected data-html="' . dol_escape_htmltag($labelhtml) . '">' . $label . '</option>';
  1388. } else {
  1389. $out .= '<option value="' . $obj->rowid . '" data-html="' . dol_escape_htmltag($labelhtml) . '">' . $label . '</option>';
  1390. }
  1391. } else {
  1392. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label, 'labelhtml' => $labelhtml));
  1393. }
  1394. $i++;
  1395. if (($i % 10) == 0) {
  1396. $out .= "\n";
  1397. }
  1398. }
  1399. }
  1400. $out .= '</select>' . "\n";
  1401. } else {
  1402. dol_print_error($this->db);
  1403. }
  1404. $this->result = array('nbofthirdparties' => $num);
  1405. if ($outputmode) {
  1406. return $outarray;
  1407. }
  1408. return $out;
  1409. }
  1410. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1411. /**
  1412. * Return HTML combo list of absolute discounts
  1413. *
  1414. * @param string $selected Id remise fixe pre-selectionnee
  1415. * @param string $htmlname Nom champ formulaire
  1416. * @param string $filter Criteres optionnels de filtre
  1417. * @param int $socid Id of thirdparty
  1418. * @param int $maxvalue Max value for lines that can be selected
  1419. * @return int Return number of qualifed lines in list
  1420. */
  1421. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1422. {
  1423. // phpcs:enable
  1424. global $langs, $conf;
  1425. // On recherche les remises
  1426. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1427. $sql .= " re.description, re.fk_facture_source";
  1428. $sql .= " FROM " . $this->db->prefix() . "societe_remise_except as re";
  1429. $sql .= " WHERE re.fk_soc = " . (int) $socid;
  1430. $sql .= " AND re.entity = " . $conf->entity;
  1431. if ($filter) {
  1432. $sql .= " AND " . $filter;
  1433. }
  1434. $sql .= " ORDER BY re.description ASC";
  1435. dol_syslog(get_class($this) . "::select_remises", LOG_DEBUG);
  1436. $resql = $this->db->query($sql);
  1437. if ($resql) {
  1438. print '<select id="select_' . $htmlname . '" class="flat maxwidthonsmartphone" name="' . $htmlname . '">';
  1439. $num = $this->db->num_rows($resql);
  1440. $qualifiedlines = $num;
  1441. $i = 0;
  1442. if ($num) {
  1443. print '<option value="0">&nbsp;</option>';
  1444. while ($i < $num) {
  1445. $obj = $this->db->fetch_object($resql);
  1446. $desc = dol_trunc($obj->description, 40);
  1447. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1448. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1449. }
  1450. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1451. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1452. }
  1453. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1454. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1455. }
  1456. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1457. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1458. }
  1459. $selectstring = '';
  1460. if ($selected > 0 && $selected == $obj->rowid) {
  1461. $selectstring = ' selected';
  1462. }
  1463. $disabled = '';
  1464. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1465. $qualifiedlines--;
  1466. $disabled = ' disabled';
  1467. }
  1468. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1469. $tmpfac = new Facture($this->db);
  1470. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1471. $desc = $desc . ' - ' . $tmpfac->ref;
  1472. }
  1473. }
  1474. print '<option value="' . $obj->rowid . '"' . $selectstring . $disabled . '>' . $desc . ' (' . price($obj->amount_ht) . ' ' . $langs->trans("HT") . ' - ' . price($obj->amount_ttc) . ' ' . $langs->trans("TTC") . ')</option>';
  1475. $i++;
  1476. }
  1477. }
  1478. print '</select>';
  1479. print ajax_combobox('select_' . $htmlname);
  1480. return $qualifiedlines;
  1481. } else {
  1482. dol_print_error($this->db);
  1483. return -1;
  1484. }
  1485. }
  1486. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1487. /**
  1488. * Return list of all contacts (for a third party or all)
  1489. *
  1490. * @param int $socid Id ot third party or 0 for all
  1491. * @param string $selected Id contact pre-selectionne
  1492. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1493. * @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
  1494. * @param string $exclude List of contacts id to exclude
  1495. * @param string $limitto Disable answers that are not id in this array list
  1496. * @param integer $showfunction Add function into label
  1497. * @param string $morecss Add more class to class style
  1498. * @param integer $showsoc Add company into label
  1499. * @param int $forcecombo Force to use combo box
  1500. * @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')))
  1501. * @param bool $options_only Return options only (for ajax treatment)
  1502. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1503. * @param string $htmlid Html id to use instead of htmlname
  1504. * @return int <0 if KO, Nb of contact in list if OK
  1505. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1506. */
  1507. 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 = '')
  1508. {
  1509. // phpcs:enable
  1510. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1511. return $this->num;
  1512. }
  1513. /**
  1514. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1515. * This also set the number of contacts found into $this->num
  1516. *
  1517. * @since 9.0 Add afterSelectContactOptions hook
  1518. *
  1519. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1520. * @param array|int $selected Array of ID of pre-selected contact id
  1521. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1522. * @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
  1523. * @param string $exclude List of contacts id to exclude
  1524. * @param string $limitto Disable answers that are not id in this array list
  1525. * @param integer $showfunction Add function into label
  1526. * @param string $morecss Add more class to class style
  1527. * @param bool $options_only Return options only (for ajax treatment)
  1528. * @param integer $showsoc Add company into label
  1529. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1530. * @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')))
  1531. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1532. * @param string $htmlid Html id to use instead of htmlname
  1533. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1534. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1535. * @return int|string <0 if KO, HTML with select string if OK.
  1536. */
  1537. 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)
  1538. {
  1539. global $conf, $langs, $hookmanager, $action;
  1540. $langs->load('companies');
  1541. if (empty($htmlid)) {
  1542. $htmlid = $htmlname;
  1543. }
  1544. $num = 0;
  1545. if ($selected === '') {
  1546. $selected = array();
  1547. } elseif (!is_array($selected)) {
  1548. $selected = array($selected);
  1549. }
  1550. $out = '';
  1551. if (!is_object($hookmanager)) {
  1552. include_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  1553. $hookmanager = new HookManager($this->db);
  1554. }
  1555. // We search third parties
  1556. $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";
  1557. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1558. $sql .= ", s.nom as company, s.town AS company_town";
  1559. }
  1560. $sql .= " FROM " . $this->db->prefix() . "socpeople as sp";
  1561. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1562. $sql .= " LEFT OUTER JOIN " . $this->db->prefix() . "societe as s ON s.rowid=sp.fk_soc";
  1563. }
  1564. $sql .= " WHERE sp.entity IN (" . getEntity('contact') . ")";
  1565. if ($socid > 0 || $socid == -1) {
  1566. $sql .= " AND sp.fk_soc = " . ((int) $socid);
  1567. }
  1568. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1569. $sql .= " AND sp.statut <> 0";
  1570. }
  1571. // Add where from hooks
  1572. $parameters = array();
  1573. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1574. $sql .= $hookmanager->resPrint;
  1575. $sql .= " ORDER BY sp.lastname ASC";
  1576. dol_syslog(get_class($this) . "::selectcontacts", LOG_DEBUG);
  1577. $resql = $this->db->query($sql);
  1578. if ($resql) {
  1579. $num = $this->db->num_rows($resql);
  1580. if ($htmlname != 'none' && !$options_only) {
  1581. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlid . '" name="' . $htmlname . (($num || empty($disableifempty)) ? '' : ' disabled') . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . (!empty($moreparam) ? $moreparam : '') . '>';
  1582. }
  1583. if ($showempty && ! is_numeric($showempty)) {
  1584. $textforempty = $showempty;
  1585. $out .= '<option class="optiongrey" value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>' . $textforempty . '</option>';
  1586. } else {
  1587. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1588. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>&nbsp;</option>';
  1589. }
  1590. if ($showempty == 2) {
  1591. $out .= '<option value="0"' . (in_array(0, $selected) ? ' selected' : '') . '>-- ' . $langs->trans("Internal") . ' --</option>';
  1592. }
  1593. }
  1594. $i = 0;
  1595. if ($num) {
  1596. include_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  1597. $contactstatic = new Contact($this->db);
  1598. while ($i < $num) {
  1599. $obj = $this->db->fetch_object($resql);
  1600. // Set email (or phones) and town extended infos
  1601. $extendedInfos = '';
  1602. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1603. $extendedInfos = array();
  1604. $email = trim($obj->email);
  1605. if (!empty($email)) {
  1606. $extendedInfos[] = $email;
  1607. } else {
  1608. $phone = trim($obj->phone);
  1609. $phone_perso = trim($obj->phone_perso);
  1610. $phone_mobile = trim($obj->phone_mobile);
  1611. if (!empty($phone)) {
  1612. $extendedInfos[] = $phone;
  1613. }
  1614. if (!empty($phone_perso)) {
  1615. $extendedInfos[] = $phone_perso;
  1616. }
  1617. if (!empty($phone_mobile)) {
  1618. $extendedInfos[] = $phone_mobile;
  1619. }
  1620. }
  1621. $contact_town = trim($obj->contact_town);
  1622. $company_town = trim($obj->company_town);
  1623. if (!empty($contact_town)) {
  1624. $extendedInfos[] = $contact_town;
  1625. } elseif (!empty($company_town)) {
  1626. $extendedInfos[] = $company_town;
  1627. }
  1628. $extendedInfos = implode(' - ', $extendedInfos);
  1629. if (!empty($extendedInfos)) {
  1630. $extendedInfos = ' - ' . $extendedInfos;
  1631. }
  1632. }
  1633. $contactstatic->id = $obj->rowid;
  1634. $contactstatic->lastname = $obj->lastname;
  1635. $contactstatic->firstname = $obj->firstname;
  1636. if ($obj->statut == 1) {
  1637. if ($htmlname != 'none') {
  1638. $disabled = 0;
  1639. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1640. $disabled = 1;
  1641. }
  1642. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1643. $disabled = 1;
  1644. }
  1645. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1646. $out .= '<option value="' . $obj->rowid . '"';
  1647. if ($disabled) {
  1648. $out .= ' disabled';
  1649. }
  1650. $out .= ' selected>';
  1651. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1652. if ($showfunction && $obj->poste) {
  1653. $out .= ' (' . $obj->poste . ')';
  1654. }
  1655. if (($showsoc > 0) && $obj->company) {
  1656. $out .= ' - (' . $obj->company . ')';
  1657. }
  1658. $out .= '</option>';
  1659. } else {
  1660. $out .= '<option value="' . $obj->rowid . '"';
  1661. if ($disabled) {
  1662. $out .= ' disabled';
  1663. }
  1664. $out .= '>';
  1665. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1666. if ($showfunction && $obj->poste) {
  1667. $out .= ' (' . $obj->poste . ')';
  1668. }
  1669. if (($showsoc > 0) && $obj->company) {
  1670. $out .= ' - (' . $obj->company . ')';
  1671. }
  1672. $out .= '</option>';
  1673. }
  1674. } else {
  1675. if (in_array($obj->rowid, $selected)) {
  1676. $out .= $contactstatic->getFullName($langs) . $extendedInfos;
  1677. if ($showfunction && $obj->poste) {
  1678. $out .= ' (' . $obj->poste . ')';
  1679. }
  1680. if (($showsoc > 0) && $obj->company) {
  1681. $out .= ' - (' . $obj->company . ')';
  1682. }
  1683. }
  1684. }
  1685. }
  1686. $i++;
  1687. }
  1688. } else {
  1689. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1690. $out .= '<option class="disabled" value="-1"' . (($showempty == 2 || $multiple) ? '' : ' selected') . ' disabled="disabled">';
  1691. $out .= $labeltoshow;
  1692. $out .= '</option>';
  1693. }
  1694. $parameters = array(
  1695. 'socid' => $socid,
  1696. 'htmlname' => $htmlname,
  1697. 'resql' => $resql,
  1698. 'out' => &$out,
  1699. 'showfunction' => $showfunction,
  1700. 'showsoc' => $showsoc,
  1701. );
  1702. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1703. if ($htmlname != 'none' && !$options_only) {
  1704. $out .= '</select>';
  1705. }
  1706. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1707. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1708. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1709. }
  1710. $this->num = $num;
  1711. return $out;
  1712. } else {
  1713. dol_print_error($this->db);
  1714. return -1;
  1715. }
  1716. }
  1717. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1718. /**
  1719. * Return the HTML select list of users
  1720. *
  1721. * @param string $selected Id user preselected
  1722. * @param string $htmlname Field name in form
  1723. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1724. * @param array $exclude Array list of users id to exclude
  1725. * @param int $disabled If select list must be disabled
  1726. * @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
  1727. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1728. * @param string $force_entity '0' or Ids of environment to force
  1729. * @return void
  1730. * @deprecated Use select_dolusers instead
  1731. * @see select_dolusers()
  1732. */
  1733. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1734. {
  1735. // phpcs:enable
  1736. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1737. }
  1738. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1739. /**
  1740. * Return select list of users
  1741. *
  1742. * @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)
  1743. * @param string $htmlname Field name in form
  1744. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1745. * @param array $exclude Array list of users id to exclude
  1746. * @param int $disabled If select list must be disabled
  1747. * @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
  1748. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1749. * @param string $force_entity '0' or Ids of environment to force
  1750. * @param int $maxlength Maximum length of string into list (0=no limit)
  1751. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1752. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1753. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1754. * @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.
  1755. * @param string $morecss More css
  1756. * @param int $notdisabled Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1757. * @param int $outputmode 0=HTML select string, 1=Array
  1758. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1759. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1760. * @return string HTML select string
  1761. * @see select_dolgroups()
  1762. */
  1763. 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)
  1764. {
  1765. // phpcs:enable
  1766. global $conf, $user, $langs, $hookmanager;
  1767. global $action;
  1768. // If no preselected user defined, we take current user
  1769. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1770. $selected = $user->id;
  1771. }
  1772. if ($selected === '') {
  1773. $selected = array();
  1774. } elseif (!is_array($selected)) {
  1775. $selected = array($selected);
  1776. }
  1777. $excludeUsers = null;
  1778. $includeUsers = null;
  1779. // Permettre l'exclusion d'utilisateurs
  1780. if (is_array($exclude)) {
  1781. $excludeUsers = implode(",", $exclude);
  1782. }
  1783. // Permettre l'inclusion d'utilisateurs
  1784. if (is_array($include)) {
  1785. $includeUsers = implode(",", $include);
  1786. } elseif ($include == 'hierarchy') {
  1787. // Build list includeUsers to have only hierarchy
  1788. $includeUsers = implode(",", $user->getAllChildIds(0));
  1789. } elseif ($include == 'hierarchyme') {
  1790. // Build list includeUsers to have only hierarchy and current user
  1791. $includeUsers = implode(",", $user->getAllChildIds(1));
  1792. }
  1793. $out = '';
  1794. $outarray = array();
  1795. // Forge request to select users
  1796. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1797. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1798. $sql .= ", e.label";
  1799. }
  1800. $sql .= " FROM " . $this->db->prefix() . "user as u";
  1801. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1802. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid = u.entity";
  1803. if ($force_entity) {
  1804. $sql .= " WHERE u.entity IN (0, " . $this->db->sanitize($force_entity) . ")";
  1805. } else {
  1806. $sql .= " WHERE u.entity IS NOT NULL";
  1807. }
  1808. } else {
  1809. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1810. $sql .= " LEFT JOIN " . $this->db->prefix() . "usergroup_user as ug";
  1811. $sql .= " ON ug.fk_user = u.rowid";
  1812. $sql .= " WHERE ug.entity = " . $conf->entity;
  1813. } else {
  1814. $sql .= " WHERE u.entity IN (0, " . $conf->entity . ")";
  1815. }
  1816. }
  1817. if (!empty($user->socid)) {
  1818. $sql .= " AND u.fk_soc = " . ((int) $user->socid);
  1819. }
  1820. if (is_array($exclude) && $excludeUsers) {
  1821. $sql .= " AND u.rowid NOT IN (" . $this->db->sanitize($excludeUsers) . ")";
  1822. }
  1823. if ($includeUsers) {
  1824. $sql .= " AND u.rowid IN (" . $this->db->sanitize($includeUsers) . ")";
  1825. }
  1826. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $notdisabled) {
  1827. $sql .= " AND u.statut <> 0";
  1828. }
  1829. if (!empty($morefilter)) {
  1830. $sql .= " " . $morefilter;
  1831. }
  1832. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1833. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1834. if (!empty($reshook)) {
  1835. $sql .= $hookmanager->resPrint;
  1836. }
  1837. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1838. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1839. } else {
  1840. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1841. }
  1842. dol_syslog(get_class($this) . "::select_dolusers", LOG_DEBUG);
  1843. $resql = $this->db->query($sql);
  1844. if ($resql) {
  1845. $num = $this->db->num_rows($resql);
  1846. $i = 0;
  1847. if ($num) {
  1848. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1849. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : ' minwidth200') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  1850. if ($show_empty && !$multiple) {
  1851. $textforempty = ' ';
  1852. if (!empty($conf->use_javascript_ajax)) {
  1853. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1854. }
  1855. if (!is_numeric($show_empty)) {
  1856. $textforempty = $show_empty;
  1857. }
  1858. $out .= '<option class="optiongrey" value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ((empty($selected) || in_array(-1, $selected)) ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  1859. }
  1860. if ($show_every) {
  1861. $out .= '<option value="-2"' . ((in_array(-2, $selected)) ? ' selected' : '') . '>-- ' . $langs->trans("Everybody") . ' --</option>' . "\n";
  1862. }
  1863. $userstatic = new User($this->db);
  1864. while ($i < $num) {
  1865. $obj = $this->db->fetch_object($resql);
  1866. $userstatic->id = $obj->rowid;
  1867. $userstatic->lastname = $obj->lastname;
  1868. $userstatic->firstname = $obj->firstname;
  1869. $userstatic->photo = $obj->photo;
  1870. $userstatic->statut = $obj->status;
  1871. $userstatic->entity = $obj->entity;
  1872. $userstatic->admin = $obj->admin;
  1873. $disableline = '';
  1874. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1875. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1876. }
  1877. $labeltoshow = '';
  1878. $labeltoshowhtml = '';
  1879. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1880. $fullNameMode = 0;
  1881. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1882. $fullNameMode = 1; //Firstname+lastname
  1883. }
  1884. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1885. $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1886. if (empty($obj->firstname) && empty($obj->lastname)) {
  1887. $labeltoshow .= $obj->login;
  1888. $labeltoshowhtml .= $obj->login;
  1889. }
  1890. // Complete name with a more info string like: ' (info1 - info2 - ...)'
  1891. $moreinfo = '';
  1892. $moreinfohtml = '';
  1893. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1894. $moreinfo .= ($moreinfo ? ' - ' : ' (');
  1895. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
  1896. $moreinfo .= $obj->login;
  1897. $moreinfohtml .= $obj->login;
  1898. }
  1899. if ($showstatus >= 0) {
  1900. if ($obj->status == 1 && $showstatus == 1) {
  1901. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Enabled');
  1902. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Enabled');
  1903. }
  1904. if ($obj->status == 0 && $showstatus == 1) {
  1905. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans('Disabled');
  1906. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans('Disabled');
  1907. }
  1908. }
  1909. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1910. if (!$obj->entity) {
  1911. $moreinfo .= ($moreinfo ? ' - ' : ' (') . $langs->trans("AllEntities");
  1912. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . $langs->trans("AllEntities");
  1913. } else {
  1914. if ($obj->entity != $conf->entity) {
  1915. $moreinfo .= ($moreinfo ? ' - ' : ' (') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1916. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(') . ($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1917. }
  1918. }
  1919. }
  1920. $moreinfo .= ($moreinfo ? ')' : '');
  1921. $moreinfohtml .= ($moreinfohtml ? ')' : '');
  1922. if ($disableline && $disableline != '1') {
  1923. // Add text from $enableonlytext parameter
  1924. $moreinfo .= ' - ' . $disableline;
  1925. $moreinfohtml .= ' - ' . $disableline;
  1926. }
  1927. $labeltoshow .= $moreinfo;
  1928. $labeltoshowhtml .= $moreinfohtml;
  1929. $out .= '<option value="' . $obj->rowid . '"';
  1930. if ($disableline) {
  1931. $out .= ' disabled';
  1932. }
  1933. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1934. $out .= ' selected';
  1935. }
  1936. $out .= ' data-html="';
  1937. $outhtml = '';
  1938. // if (!empty($obj->photo)) {
  1939. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1) . ' ';
  1940. // }
  1941. if ($showstatus >= 0 && $obj->status == 0) {
  1942. $outhtml .= '<strike class="opacitymediumxxx">';
  1943. }
  1944. $outhtml .= $labeltoshowhtml;
  1945. if ($showstatus >= 0 && $obj->status == 0) {
  1946. $outhtml .= '</strike>';
  1947. }
  1948. $out .= dol_escape_htmltag($outhtml);
  1949. $out .= '">';
  1950. $out .= $labeltoshow;
  1951. $out .= '</option>';
  1952. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength) . $moreinfo;
  1953. $i++;
  1954. }
  1955. } else {
  1956. $out .= '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '" disabled>';
  1957. $out .= '<option value="">' . $langs->trans("None") . '</option>';
  1958. }
  1959. $out .= '</select>';
  1960. if ($num && !$forcecombo) {
  1961. // Enhance with select2
  1962. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1963. $out .= ajax_combobox($htmlname);
  1964. }
  1965. } else {
  1966. dol_print_error($this->db);
  1967. }
  1968. if ($outputmode) {
  1969. return $outarray;
  1970. }
  1971. return $out;
  1972. }
  1973. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1974. /**
  1975. * Return select list of users. Selected users are stored into session.
  1976. * List of users are provided into $_SESSION['assignedtouser'].
  1977. *
  1978. * @param string $action Value for $action
  1979. * @param string $htmlname Field name in form
  1980. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1981. * @param array $exclude Array list of users id to exclude
  1982. * @param int $disabled If select list must be disabled
  1983. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1984. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1985. * @param int $force_entity '0' or Ids of environment to force
  1986. * @param int $maxlength Maximum length of string into list (0=no limit)
  1987. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1988. * @param string $morefilter Add more filters into sql request
  1989. * @param int $showproperties Show properties of each attendees
  1990. * @param array $listofuserid Array with properties of each user
  1991. * @param array $listofcontactid Array with properties of each contact
  1992. * @param array $listofotherid Array with properties of each other contact
  1993. * @return string HTML select string
  1994. * @see select_dolgroups()
  1995. */
  1996. 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())
  1997. {
  1998. // phpcs:enable
  1999. global $conf, $user, $langs;
  2000. $userstatic = new User($this->db);
  2001. $out = '';
  2002. $assignedtouser = array();
  2003. if (!empty($_SESSION['assignedtouser'])) {
  2004. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  2005. }
  2006. $nbassignetouser = count($assignedtouser);
  2007. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  2008. if ($nbassignetouser) {
  2009. $out .= '<ul class="attendees">';
  2010. }
  2011. $i = 0;
  2012. $ownerid = 0;
  2013. foreach ($assignedtouser as $key => $value) {
  2014. if ($value['id'] == $ownerid) {
  2015. continue;
  2016. }
  2017. $out .= '<li>';
  2018. $userstatic->fetch($value['id']);
  2019. $out .= $userstatic->getNomUrl(-1);
  2020. if ($i == 0) {
  2021. $ownerid = $value['id'];
  2022. $out .= ' (' . $langs->trans("Owner") . ')';
  2023. }
  2024. if ($nbassignetouser > 1 && $action != 'view') {
  2025. $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 . '">';
  2026. }
  2027. // Show my availability
  2028. if ($showproperties) {
  2029. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  2030. $out .= '<div class="myavailability inline-block">';
  2031. $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>';
  2032. $out .= '</div>';
  2033. }
  2034. }
  2035. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2036. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2037. $out .= '</li>';
  2038. $i++;
  2039. }
  2040. if ($nbassignetouser) {
  2041. $out .= '</ul>';
  2042. }
  2043. // Method with no ajax
  2044. if ($action != 'view') {
  2045. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2046. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  2047. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2048. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2049. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#' . $action . 'assignedtouser").attr("disabled", false); }';
  2050. $out .= ' else { jQuery("#' . $action . 'assignedtouser").attr("disabled", true); }';
  2051. $out .= '});';
  2052. $out .= '})</script>';
  2053. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2054. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="' . $action . 'assignedtouser" name="' . $action . 'assignedtouser" value="' . dol_escape_htmltag($langs->trans("Add")) . '">';
  2055. $out .= '<br>';
  2056. }
  2057. return $out;
  2058. }
  2059. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2060. /**
  2061. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2062. *
  2063. * @param int $selected Preselected products
  2064. * @param string $htmlname Name of HTML select field (must be unique in page).
  2065. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2066. * @param int $limit Limit on number of returned lines
  2067. * @param int $price_level Level of price to show
  2068. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2069. * @param int $finished 2=all, 1=finished, 0=raw material
  2070. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2071. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2072. * @param array $ajaxoptions Options for ajax_autocompleter
  2073. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2074. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2075. * @param int $forcecombo Force to use combo box
  2076. * @param string $morecss Add more css on select
  2077. * @param int $hidepriceinlabel 1=Hide prices in label
  2078. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2079. * 'warehouseopen' = count products from open warehouses,
  2080. * 'warehouseclosed' = count products from closed warehouses,
  2081. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2082. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2083. * @param string $nooutput No print, return the output into a string
  2084. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2085. * @return void|string
  2086. */
  2087. 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)
  2088. {
  2089. // phpcs:enable
  2090. global $langs, $conf;
  2091. $out = '';
  2092. // check parameters
  2093. $price_level = (!empty($price_level) ? $price_level : 0);
  2094. if (is_null($ajaxoptions)) {
  2095. $ajaxoptions = array();
  2096. }
  2097. if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
  2098. if (isModEnabled("product") && !isModEnabled('service')) {
  2099. $filtertype = '0';
  2100. } elseif (!isModEnabled('product') && isModEnabled("service")) {
  2101. $filtertype = '1';
  2102. }
  2103. }
  2104. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2105. $placeholder = '';
  2106. if ($selected && empty($selected_input_value)) {
  2107. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2108. $producttmpselect = new Product($this->db);
  2109. $producttmpselect->fetch($selected);
  2110. $selected_input_value = $producttmpselect->ref;
  2111. unset($producttmpselect);
  2112. }
  2113. // handle case where product or service module is disabled + no filter specified
  2114. if ($filtertype == '') {
  2115. if (!isModEnabled('product')) { // when product module is disabled, show services only
  2116. $filtertype = 1;
  2117. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2118. $filtertype = 0;
  2119. }
  2120. }
  2121. // mode=1 means customers products
  2122. $urloption = 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=1&status=' . $status . '&status_purchase=' . $status_purchase . '&finished=' . $finished . '&hidepriceinlabel=' . $hidepriceinlabel . '&warehousestatus=' . $warehouseStatus;
  2123. //Price by customer
  2124. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2125. $urloption .= '&socid=' . $socid;
  2126. }
  2127. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2128. if (isModEnabled('variants') && is_array($selected_combinations)) {
  2129. // Code to automatically insert with javascript the select of attributes under the select of product
  2130. // when a parent of variant has been selected.
  2131. $out .= '
  2132. <!-- script to auto show attributes select tags if a variant was selected -->
  2133. <script>
  2134. // auto show attributes fields
  2135. selected = ' . json_encode($selected_combinations) . ';
  2136. combvalues = {};
  2137. jQuery(document).ready(function () {
  2138. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2139. if (jQuery(this).val() == \'free\') {
  2140. jQuery(\'div#attributes_box\').empty();
  2141. }
  2142. });
  2143. jQuery("input#' . $htmlname . '").change(function () {
  2144. if (!jQuery(this).val()) {
  2145. jQuery(\'div#attributes_box\').empty();
  2146. return;
  2147. }
  2148. console.log("A change has started. We get variants fields to inject html select");
  2149. jQuery.getJSON("' . DOL_URL_ROOT . '/variants/ajax/getCombinations.php", {
  2150. id: jQuery(this).val()
  2151. }, function (data) {
  2152. jQuery(\'div#attributes_box\').empty();
  2153. jQuery.each(data, function (key, val) {
  2154. combvalues[val.id] = val.values;
  2155. var span = jQuery(document.createElement(\'div\')).css({
  2156. \'display\': \'table-row\'
  2157. });
  2158. span.append(
  2159. jQuery(document.createElement(\'div\')).text(val.label).css({
  2160. \'font-weight\': \'bold\',
  2161. \'display\': \'table-cell\'
  2162. })
  2163. );
  2164. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2165. \'margin-left\': \'15px\',
  2166. \'white-space\': \'pre\'
  2167. }).append(
  2168. jQuery(document.createElement(\'option\')).val(\'\')
  2169. );
  2170. jQuery.each(combvalues[val.id], function (key, val) {
  2171. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2172. if (selected[val.fk_product_attribute] == val.id) {
  2173. tag.attr(\'selected\', \'selected\');
  2174. }
  2175. html.append(tag);
  2176. });
  2177. span.append(html);
  2178. jQuery(\'div#attributes_box\').append(span);
  2179. });
  2180. })
  2181. });
  2182. ' . ($selected ? 'jQuery("input#' . $htmlname . '").change();' : '') . '
  2183. });
  2184. </script>
  2185. ';
  2186. }
  2187. if (empty($hidelabel)) {
  2188. $out .= $langs->trans("RefOrLabel") . ' : ';
  2189. } elseif ($hidelabel > 1) {
  2190. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  2191. if ($hidelabel == 2) {
  2192. $out .= img_picto($langs->trans("Search"), 'search');
  2193. }
  2194. }
  2195. $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' : '') . ' />';
  2196. if ($hidelabel == 3) {
  2197. $out .= img_picto($langs->trans("Search"), 'search');
  2198. }
  2199. } else {
  2200. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2201. }
  2202. if (empty($nooutput)) {
  2203. print $out;
  2204. } else {
  2205. return $out;
  2206. }
  2207. }
  2208. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2209. /**
  2210. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2211. *
  2212. * @param int $selected Preselected BOM id
  2213. * @param string $htmlname Name of HTML select field (must be unique in page).
  2214. * @param int $limit Limit on number of returned lines
  2215. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2216. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2217. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2218. * @param string $morecss Add more css on select
  2219. * @param string $nooutput No print, return the output into a string
  2220. * @param int $forcecombo Force to use combo box
  2221. * @param array $TProducts Add filter on a defined product
  2222. * @return void|string
  2223. */
  2224. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2225. {
  2226. // phpcs:enable
  2227. global $conf, $user, $langs, $db;
  2228. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2229. $error = 0;
  2230. $out = '';
  2231. if (!$forcecombo) {
  2232. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2233. $events = array();
  2234. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2235. }
  2236. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2237. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2238. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'bom_bom as b';
  2239. $sql .= ' WHERE b.entity IN (' . getEntity('bom') . ')';
  2240. if (!empty($status)) $sql .= ' AND status = ' . (int) $status;
  2241. if (!empty($type)) $sql .= ' AND bomtype = ' . (int) $type;
  2242. if (!empty($TProducts)) $sql .= ' AND fk_product IN (' . $this->db->sanitize(implode(',', $TProducts)) . ')';
  2243. if (!empty($limit)) $sql .= ' LIMIT ' . (int) $limit;
  2244. $resql = $db->query($sql);
  2245. if ($resql) {
  2246. if ($showempty) {
  2247. $out .= '<option value="-1"';
  2248. if (empty($selected)) $out .= ' selected';
  2249. $out .= '>&nbsp;</option>';
  2250. }
  2251. while ($obj = $db->fetch_object($resql)) {
  2252. $product = new Product($db);
  2253. $res = $product->fetch($obj->fk_product);
  2254. $out .= '<option value="' . $obj->rowid . '"';
  2255. if ($obj->rowid == $selected) $out .= 'selected';
  2256. $out .= '>' . $obj->ref . ' - ' . $product->label . ' - ' . $obj->label . '</option>';
  2257. }
  2258. } else {
  2259. $error++;
  2260. dol_print_error($db);
  2261. }
  2262. if (empty($nooutput)) {
  2263. print $out;
  2264. } else {
  2265. return $out;
  2266. }
  2267. }
  2268. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2269. /**
  2270. * Return list of products for a customer.
  2271. * Called by select_produits.
  2272. *
  2273. * @param int $selected Preselected product
  2274. * @param string $htmlname Name of select html
  2275. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2276. * @param int $limit Limit on number of returned lines
  2277. * @param int $price_level Level of price to show
  2278. * @param string $filterkey Filter on product
  2279. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2280. * @param int $finished Filter on finished field: 2=No filter
  2281. * @param int $outputmode 0=HTML select string, 1=Array
  2282. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2283. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2284. * @param int $forcecombo Force to use combo box
  2285. * @param string $morecss Add more css on select
  2286. * @param int $hidepriceinlabel 1=Hide prices in label
  2287. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2288. * 'warehouseopen' = count products from open warehouses,
  2289. * 'warehouseclosed' = count products from closed warehouses,
  2290. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2291. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2292. * @return array Array of keys for json
  2293. */
  2294. 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)
  2295. {
  2296. // phpcs:enable
  2297. global $langs, $conf;
  2298. global $hookmanager;
  2299. $out = '';
  2300. $outarray = array();
  2301. // Units
  2302. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2303. $langs->load('other');
  2304. }
  2305. $warehouseStatusArray = array();
  2306. if (!empty($warehouseStatus)) {
  2307. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  2308. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2309. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2310. }
  2311. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2312. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2313. }
  2314. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2315. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2316. }
  2317. }
  2318. $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";
  2319. if (count($warehouseStatusArray)) {
  2320. $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
  2321. } else {
  2322. $selectFieldsGrouped = ", " . $this->db->ifsql("p.stock IS NULL", 0, "p.stock") . " AS stock";
  2323. }
  2324. $sql = "SELECT ";
  2325. $sql .= $selectFields . $selectFieldsGrouped;
  2326. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2327. //Product category
  2328. $sql .= ", (SELECT " . $this->db->prefix() . "categorie_product.fk_categorie
  2329. FROM " . $this->db->prefix() . "categorie_product
  2330. WHERE " . $this->db->prefix() . "categorie_product.fk_product=p.rowid
  2331. LIMIT 1
  2332. ) AS categorie_product_id ";
  2333. }
  2334. //Price by customer
  2335. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2336. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2337. $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';
  2338. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2339. }
  2340. // Units
  2341. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2342. $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";
  2343. $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';
  2344. }
  2345. // Multilang : we add translation
  2346. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2347. $sql .= ", pl.label as label_translated";
  2348. $sql .= ", pl.description as description_translated";
  2349. $selectFields .= ", label_translated";
  2350. $selectFields .= ", description_translated";
  2351. }
  2352. // Price by quantity
  2353. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2354. $sql .= ", (SELECT pp.rowid FROM " . $this->db->prefix() . "product_price as pp WHERE pp.fk_product = p.rowid";
  2355. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2356. $sql .= " AND price_level = " . ((int) $price_level);
  2357. }
  2358. $sql .= " ORDER BY date_price";
  2359. $sql .= " DESC LIMIT 1) as price_rowid";
  2360. $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
  2361. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2362. $sql .= " AND price_level = " . ((int) $price_level);
  2363. }
  2364. $sql .= " ORDER BY date_price";
  2365. $sql .= " DESC LIMIT 1) as price_by_qty";
  2366. $selectFields .= ", price_rowid, price_by_qty";
  2367. }
  2368. $sql .= " FROM " . $this->db->prefix() . "product as p";
  2369. if (count($warehouseStatusArray)) {
  2370. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as ps on ps.fk_product = p.rowid";
  2371. $sql .= " LEFT JOIN " . $this->db->prefix() . "entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (" . getEntity('stock') . ")";
  2372. $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.
  2373. }
  2374. // include search in supplier ref
  2375. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2376. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2377. }
  2378. //Price by customer
  2379. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2380. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_customer_price as pcp ON pcp.fk_soc=" . ((int) $socid) . " AND pcp.fk_product=p.rowid";
  2381. }
  2382. // Units
  2383. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2384. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  2385. }
  2386. // Multilang : we add translation
  2387. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2388. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_lang as pl ON pl.fk_product = p.rowid ";
  2389. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2390. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  2391. $soc = new Societe($this->db);
  2392. $result = $soc->fetch($socid);
  2393. if ($result > 0 && !empty($soc->default_lang)) {
  2394. $sql .= " AND pl.lang = '" . $this->db->escape($soc->default_lang) . "'";
  2395. } else {
  2396. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2397. }
  2398. } else {
  2399. $sql .= " AND pl.lang = '" . $this->db->escape($langs->getDefaultLang()) . "'";
  2400. }
  2401. }
  2402. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2403. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2404. }
  2405. $sql .= ' WHERE p.entity IN (' . getEntity('product') . ')';
  2406. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2407. $sql .= " AND pac.rowid IS NULL";
  2408. }
  2409. if ($finished == 0) {
  2410. $sql .= " AND p.finished = " . ((int) $finished);
  2411. } elseif ($finished == 1) {
  2412. $sql .= " AND p.finished = " . ((int) $finished);
  2413. if ($status >= 0) {
  2414. $sql .= " AND p.tosell = " . ((int) $status);
  2415. }
  2416. } elseif ($status >= 0) {
  2417. $sql .= " AND p.tosell = " . ((int) $status);
  2418. }
  2419. if ($status_purchase >= 0) {
  2420. $sql .= " AND p.tobuy = " . ((int) $status_purchase);
  2421. }
  2422. // Filter by product type
  2423. if (strval($filtertype) != '') {
  2424. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  2425. } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
  2426. $sql .= " AND p.fk_product_type = 1";
  2427. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2428. $sql .= " AND p.fk_product_type = 0";
  2429. }
  2430. // Add where from hooks
  2431. $parameters = array();
  2432. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2433. $sql .= $hookmanager->resPrint;
  2434. // Add criteria on ref/label
  2435. if ($filterkey != '') {
  2436. $sql .= ' AND (';
  2437. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2438. // For natural search
  2439. $scrit = explode(' ', $filterkey);
  2440. $i = 0;
  2441. if (count($scrit) > 1) {
  2442. $sql .= "(";
  2443. }
  2444. foreach ($scrit as $crit) {
  2445. if ($i > 0) {
  2446. $sql .= " AND ";
  2447. }
  2448. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2449. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2450. $sql .= " OR pl.label LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2451. }
  2452. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2453. $sql .= " OR pcp.ref_customer LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2454. }
  2455. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2456. $sql .= " OR p.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2457. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2458. $sql .= " OR pl.description LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2459. }
  2460. }
  2461. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2462. $sql .= " OR pfp.ref_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  2463. }
  2464. $sql .= ")";
  2465. $i++;
  2466. }
  2467. if (count($scrit) > 1) {
  2468. $sql .= ")";
  2469. }
  2470. if (isModEnabled('barcode')) {
  2471. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  2472. }
  2473. $sql .= ')';
  2474. }
  2475. if (count($warehouseStatusArray)) {
  2476. $sql .= " GROUP BY " . $selectFields;
  2477. }
  2478. //Sort by category
  2479. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2480. $sql .= " ORDER BY categorie_product_id ";
  2481. //ASC OR DESC order
  2482. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2483. } else {
  2484. $sql .= $this->db->order("p.ref");
  2485. }
  2486. $sql .= $this->db->plimit($limit, 0);
  2487. // Build output string
  2488. dol_syslog(get_class($this) . "::select_produits_list search products", LOG_DEBUG);
  2489. $result = $this->db->query($sql);
  2490. if ($result) {
  2491. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2492. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2493. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  2494. $num = $this->db->num_rows($result);
  2495. $events = null;
  2496. if (!$forcecombo) {
  2497. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  2498. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2499. }
  2500. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  2501. $textifempty = '';
  2502. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2503. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2504. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2505. if ($showempty && !is_numeric($showempty)) {
  2506. $textifempty = $langs->trans($showempty);
  2507. } else {
  2508. $textifempty .= $langs->trans("All");
  2509. }
  2510. } else {
  2511. if ($showempty && !is_numeric($showempty)) {
  2512. $textifempty = $langs->trans($showempty);
  2513. }
  2514. }
  2515. if ($showempty) {
  2516. $out .= '<option value="-1" selected>' . ($textifempty ? $textifempty : '&nbsp;') . '</option>';
  2517. }
  2518. $i = 0;
  2519. while ($num && $i < $num) {
  2520. $opt = '';
  2521. $optJson = array();
  2522. $objp = $this->db->fetch_object($result);
  2523. 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
  2524. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2525. $sql .= " FROM " . $this->db->prefix() . "product_price_by_qty";
  2526. $sql .= " WHERE fk_product_price = " . ((int) $objp->price_rowid);
  2527. $sql .= " ORDER BY quantity ASC";
  2528. dol_syslog(get_class($this) . "::select_produits_list search prices by qty", LOG_DEBUG);
  2529. $result2 = $this->db->query($sql);
  2530. if ($result2) {
  2531. $nb_prices = $this->db->num_rows($result2);
  2532. $j = 0;
  2533. while ($nb_prices && $j < $nb_prices) {
  2534. $objp2 = $this->db->fetch_object($result2);
  2535. $objp->price_by_qty_rowid = $objp2->rowid;
  2536. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2537. $objp->price_by_qty_quantity = $objp2->quantity;
  2538. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2539. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2540. // For backward compatibility
  2541. $objp->quantity = $objp2->quantity;
  2542. $objp->price = $objp2->price;
  2543. $objp->unitprice = $objp2->unitprice;
  2544. $objp->remise_percent = $objp2->remise_percent;
  2545. //$objp->tva_tx is not overwritten by $objp2 value
  2546. //$objp->default_vat_code is not overwritten by $objp2 value
  2547. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2548. $j++;
  2549. // Add new entry
  2550. // "key" value of json key array is used by jQuery automatically as selected value
  2551. // "label" value of json key array is used by jQuery automatically as text for combo box
  2552. $out .= $opt;
  2553. array_push($outarray, $optJson);
  2554. }
  2555. }
  2556. } else {
  2557. if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
  2558. $price_product = new Product($this->db);
  2559. $price_product->fetch($objp->rowid, '', '', 1);
  2560. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  2561. $priceparser = new PriceParser($this->db);
  2562. $price_result = $priceparser->parseProduct($price_product);
  2563. if ($price_result >= 0) {
  2564. $objp->price = $price_result;
  2565. $objp->unitprice = $price_result;
  2566. //Calculate the VAT
  2567. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2568. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2569. }
  2570. }
  2571. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2572. // Add new entry
  2573. // "key" value of json key array is used by jQuery automatically as selected value
  2574. // "label" value of json key array is used by jQuery automatically as text for combo box
  2575. $out .= $opt;
  2576. array_push($outarray, $optJson);
  2577. }
  2578. $i++;
  2579. }
  2580. $out .= '</select>';
  2581. $this->db->free($result);
  2582. if (empty($outputmode)) {
  2583. return $out;
  2584. }
  2585. return $outarray;
  2586. } else {
  2587. dol_print_error($this->db);
  2588. }
  2589. }
  2590. /**
  2591. * Function to forge the string with OPTIONs of SELECT.
  2592. * This define value for &$opt and &$optJson.
  2593. * This function is called by select_produits_list().
  2594. *
  2595. * @param object $objp Resultset of fetch
  2596. * @param string $opt Option (var used for returned value in string option format)
  2597. * @param string $optJson Option (var used for returned value in json format)
  2598. * @param int $price_level Price level
  2599. * @param string $selected Preselected value
  2600. * @param int $hidepriceinlabel Hide price in label
  2601. * @param string $filterkey Filter key to highlight
  2602. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2603. * @return void
  2604. */
  2605. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2606. {
  2607. global $langs, $conf, $user;
  2608. $outkey = '';
  2609. $outval = '';
  2610. $outref = '';
  2611. $outlabel = '';
  2612. $outlabel_translated = '';
  2613. $outdesc = '';
  2614. $outdesc_translated = '';
  2615. $outbarcode = '';
  2616. $outorigin = '';
  2617. $outtype = '';
  2618. $outprice_ht = '';
  2619. $outprice_ttc = '';
  2620. $outpricebasetype = '';
  2621. $outtva_tx = '';
  2622. $outdefault_vat_code = '';
  2623. $outqty = 1;
  2624. $outdiscount = 0;
  2625. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2626. $label = $objp->label;
  2627. if (!empty($objp->label_translated)) {
  2628. $label = $objp->label_translated;
  2629. }
  2630. if (!empty($filterkey) && $filterkey != '') {
  2631. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  2632. }
  2633. $outkey = $objp->rowid;
  2634. $outref = $objp->ref;
  2635. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2636. $outlabel = $objp->label;
  2637. $outdesc = $objp->description;
  2638. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2639. $outlabel_translated = $objp->label_translated;
  2640. $outdesc_translated = $objp->description_translated;
  2641. }
  2642. $outbarcode = $objp->barcode;
  2643. $outorigin = $objp->fk_country;
  2644. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2645. $outtype = $objp->fk_product_type;
  2646. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2647. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  2648. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2649. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  2650. }
  2651. // Units
  2652. $outvalUnits = '';
  2653. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2654. if (!empty($objp->unit_short)) {
  2655. $outvalUnits .= ' - ' . $objp->unit_short;
  2656. }
  2657. }
  2658. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2659. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2660. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2661. $outvalUnits .= ' - ' . $unitToShow;
  2662. }
  2663. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2664. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  2665. $outvalUnits .= ' - ' . $unitToShow;
  2666. }
  2667. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2668. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2669. $outvalUnits .= ' - ' . $unitToShow;
  2670. }
  2671. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2672. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2673. $outvalUnits .= ' - ' . $unitToShow;
  2674. }
  2675. }
  2676. if ($outdurationvalue && $outdurationunit) {
  2677. $da = array(
  2678. 'h' => $langs->trans('Hour'),
  2679. 'd' => $langs->trans('Day'),
  2680. 'w' => $langs->trans('Week'),
  2681. 'm' => $langs->trans('Month'),
  2682. 'y' => $langs->trans('Year')
  2683. );
  2684. if (isset($da[$outdurationunit])) {
  2685. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  2686. }
  2687. }
  2688. $opt = '<option value="' . $objp->rowid . '"';
  2689. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2690. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2691. $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 . '"';
  2692. }
  2693. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2694. if (!empty($user->rights->stock->lire)) {
  2695. if ($objp->stock > 0) {
  2696. $opt .= ' class="product_line_stock_ok"';
  2697. } elseif ($objp->stock <= 0) {
  2698. $opt .= ' class="product_line_stock_too_low"';
  2699. }
  2700. }
  2701. }
  2702. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2703. $opt .= ' data-labeltrans="' . $outlabel_translated . '"';
  2704. $opt .= ' data-desctrans="' . dol_escape_htmltag($outdesc_translated) . '"';
  2705. }
  2706. $opt .= '>';
  2707. $opt .= $objp->ref;
  2708. if (!empty($objp->custref)) {
  2709. $opt .= ' (' . $objp->custref . ')';
  2710. }
  2711. if ($outbarcode) {
  2712. $opt .= ' (' . $outbarcode . ')';
  2713. }
  2714. $opt .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2715. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2716. $opt .= ' (' . getCountry($outorigin, 1) . ')';
  2717. }
  2718. $objRef = $objp->ref;
  2719. if (!empty($objp->custref)) {
  2720. $objRef .= ' (' . $objp->custref . ')';
  2721. }
  2722. if (!empty($filterkey) && $filterkey != '') {
  2723. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  2724. }
  2725. $outval .= $objRef;
  2726. if ($outbarcode) {
  2727. $outval .= ' (' . $outbarcode . ')';
  2728. }
  2729. $outval .= ' - ' . dol_trunc($label, $maxlengtharticle);
  2730. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2731. $outval .= ' (' . getCountry($outorigin, 1) . ')';
  2732. }
  2733. // Units
  2734. $opt .= $outvalUnits;
  2735. $outval .= $outvalUnits;
  2736. $found = 0;
  2737. // Multiprice
  2738. // If we need a particular price level (from 1 to n)
  2739. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2740. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2741. $sql .= " FROM " . $this->db->prefix() . "product_price";
  2742. $sql .= " WHERE fk_product = " . ((int) $objp->rowid);
  2743. $sql .= " AND entity IN (" . getEntity('productprice') . ")";
  2744. $sql .= " AND price_level = " . ((int) $price_level);
  2745. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2746. $sql .= " LIMIT 1";
  2747. dol_syslog(get_class($this) . '::constructProductListOption search price for product ' . $objp->rowid . ' AND level ' . $price_level . '', LOG_DEBUG);
  2748. $result2 = $this->db->query($sql);
  2749. if ($result2) {
  2750. $objp2 = $this->db->fetch_object($result2);
  2751. if ($objp2) {
  2752. $found = 1;
  2753. if ($objp2->price_base_type == 'HT') {
  2754. $opt .= ' - ' . price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2755. $outval .= ' - ' . price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2756. } else {
  2757. $opt .= ' - ' . price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2758. $outval .= ' - ' . price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2759. }
  2760. $outprice_ht = price($objp2->price);
  2761. $outprice_ttc = price($objp2->price_ttc);
  2762. $outpricebasetype = $objp2->price_base_type;
  2763. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2764. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2765. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2766. } else {
  2767. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2768. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2769. }
  2770. }
  2771. } else {
  2772. dol_print_error($this->db);
  2773. }
  2774. }
  2775. // Price by quantity
  2776. 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))) {
  2777. $found = 1;
  2778. $outqty = $objp->quantity;
  2779. $outdiscount = $objp->remise_percent;
  2780. if ($objp->quantity == 1) {
  2781. $opt .= ' - ' . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/";
  2782. $outval .= ' - ' . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/";
  2783. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2784. $outval .= $langs->transnoentities("Unit");
  2785. } else {
  2786. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2787. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $objp->quantity;
  2788. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2789. $outval .= $langs->transnoentities("Units");
  2790. }
  2791. $outprice_ht = price($objp->unitprice);
  2792. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2793. $outpricebasetype = $objp->price_base_type;
  2794. $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
  2795. $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
  2796. }
  2797. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2798. $opt .= " (" . price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->trans("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2799. $outval .= " (" . price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency) . "/" . $langs->transnoentities("Unit") . ")"; // Do not use strtolower because it breaks utf8 encoding
  2800. }
  2801. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2802. $opt .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2803. $outval .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  2804. }
  2805. // Price by customer
  2806. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2807. if (!empty($objp->idprodcustprice)) {
  2808. $found = 1;
  2809. if ($objp->custprice_base_type == 'HT') {
  2810. $opt .= ' - ' . price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2811. $outval .= ' - ' . price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2812. } else {
  2813. $opt .= ' - ' . price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2814. $outval .= ' - ' . price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2815. }
  2816. $outprice_ht = price($objp->custprice);
  2817. $outprice_ttc = price($objp->custprice_ttc);
  2818. $outpricebasetype = $objp->custprice_base_type;
  2819. $outtva_tx = $objp->custtva_tx;
  2820. $outdefault_vat_code = $objp->custdefault_vat_code;
  2821. }
  2822. }
  2823. // If level no defined or multiprice not found, we used the default price
  2824. if (empty($hidepriceinlabel) && !$found) {
  2825. if ($objp->price_base_type == 'HT') {
  2826. $opt .= ' - ' . price($objp->price, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("HT");
  2827. $outval .= ' - ' . price($objp->price, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("HT");
  2828. } else {
  2829. $opt .= ' - ' . price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->trans("TTC");
  2830. $outval .= ' - ' . price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency) . ' ' . $langs->transnoentities("TTC");
  2831. }
  2832. $outprice_ht = price($objp->price);
  2833. $outprice_ttc = price($objp->price_ttc);
  2834. $outpricebasetype = $objp->price_base_type;
  2835. $outtva_tx = $objp->tva_tx;
  2836. $outdefault_vat_code = $objp->default_vat_code;
  2837. }
  2838. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2839. if (!empty($user->rights->stock->lire)) {
  2840. $opt .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  2841. if ($objp->stock > 0) {
  2842. $outval .= ' - <span class="product_line_stock_ok">';
  2843. } elseif ($objp->stock <= 0) {
  2844. $outval .= ' - <span class="product_line_stock_too_low">';
  2845. }
  2846. $outval .= $langs->transnoentities("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  2847. $outval .= '</span>';
  2848. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2849. $langs->load("stocks");
  2850. $tmpproduct = new Product($this->db);
  2851. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2852. $tmpproduct->load_virtual_stock();
  2853. $virtualstock = $tmpproduct->stock_theorique;
  2854. $opt .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  2855. $outval .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  2856. if ($virtualstock > 0) {
  2857. $outval .= '<span class="product_line_stock_ok">';
  2858. } elseif ($virtualstock <= 0) {
  2859. $outval .= '<span class="product_line_stock_too_low">';
  2860. }
  2861. $outval .= $virtualstock;
  2862. $outval .= '</span>';
  2863. unset($tmpproduct);
  2864. }
  2865. }
  2866. }
  2867. $opt .= "</option>\n";
  2868. $optJson = array(
  2869. 'key' => $outkey,
  2870. 'value' => $outref,
  2871. 'label' => $outval,
  2872. 'label2' => $outlabel,
  2873. 'desc' => $outdesc,
  2874. 'type' => $outtype,
  2875. 'price_ht' => price2num($outprice_ht),
  2876. 'price_ttc' => price2num($outprice_ttc),
  2877. 'price_ht_locale' => price(price2num($outprice_ht)),
  2878. 'price_ttc_locale' => price(price2num($outprice_ttc)),
  2879. 'pricebasetype' => $outpricebasetype,
  2880. 'tva_tx' => $outtva_tx,
  2881. 'default_vat_code' => $outdefault_vat_code,
  2882. 'qty' => $outqty,
  2883. 'discount' => $outdiscount,
  2884. 'duration_value' => $outdurationvalue,
  2885. 'duration_unit' => $outdurationunit,
  2886. 'pbq' => $outpbq,
  2887. 'labeltrans' => $outlabel_translated,
  2888. 'desctrans' => $outdesc_translated,
  2889. 'ref_customer' => $outrefcust
  2890. );
  2891. }
  2892. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2893. /**
  2894. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2895. *
  2896. * @param int $socid Id third party
  2897. * @param string $selected Preselected product
  2898. * @param string $htmlname Name of HTML Select
  2899. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2900. * @param string $filtre For a SQL filter
  2901. * @param array $ajaxoptions Options for ajax_autocompleter
  2902. * @param int $hidelabel Hide label (0=no, 1=yes)
  2903. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2904. * @param string $morecss More CSS
  2905. * @param string $placeholder Placeholder
  2906. * @return void
  2907. */
  2908. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2909. {
  2910. // phpcs:enable
  2911. global $langs, $conf;
  2912. global $price_level, $status, $finished;
  2913. if (!isset($status)) {
  2914. $status = 1;
  2915. }
  2916. $selected_input_value = '';
  2917. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2918. if ($selected > 0) {
  2919. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  2920. $producttmpselect = new Product($this->db);
  2921. $producttmpselect->fetch($selected);
  2922. $selected_input_value = $producttmpselect->ref;
  2923. unset($producttmpselect);
  2924. }
  2925. // mode=2 means suppliers products
  2926. $urloption = ($socid > 0 ? 'socid=' . $socid . '&' : '') . 'htmlname=' . $htmlname . '&outjson=1&price_level=' . $price_level . '&type=' . $filtertype . '&mode=2&status=' . $status . '&finished=' . $finished . '&alsoproductwithnosupplierprice=' . $alsoproductwithnosupplierprice;
  2927. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2928. print ($hidelabel ? '' : $langs->trans("RefOrLabel") . ' : ') . '<input type="text" class="minwidth300" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . ($placeholder ? ' placeholder="' . $placeholder . '"' : '') . '>';
  2929. } else {
  2930. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2931. }
  2932. }
  2933. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2934. /**
  2935. * Return list of suppliers products
  2936. *
  2937. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2938. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2939. * @param string $htmlname Name of HTML select
  2940. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2941. * @param string $filtre Generic filter. Data must not come from user input.
  2942. * @param string $filterkey Filter of produdts
  2943. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2944. * @param int $outputmode 0=HTML select string, 1=Array
  2945. * @param int $limit Limit of line number
  2946. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2947. * @param string $morecss Add more CSS
  2948. * @param int $showstockinlist Show stock information (slower).
  2949. * @param string $placeholder Placeholder
  2950. * @return array|string Array of keys for json or HTML component
  2951. */
  2952. 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 = '')
  2953. {
  2954. // phpcs:enable
  2955. global $langs, $conf, $user;
  2956. global $hookmanager;
  2957. $out = '';
  2958. $outarray = array();
  2959. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2960. $langs->load('stocks');
  2961. // Units
  2962. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2963. $langs->load('other');
  2964. }
  2965. $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,";
  2966. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2967. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2968. $sql .= " pfp.supplier_reputation";
  2969. // if we use supplier description of the products
  2970. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2971. $sql .= ", pfp.desc_fourn as description";
  2972. } else {
  2973. $sql .= ", p.description";
  2974. }
  2975. // Units
  2976. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2977. $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";
  2978. }
  2979. if (isModEnabled('barcode')) {
  2980. $sql .= ", pfp.barcode";
  2981. }
  2982. $sql .= " FROM " . $this->db->prefix() . "product as p";
  2983. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (" . getEntity('product') . ") )";
  2984. if ($socid > 0) {
  2985. $sql .= " AND pfp.fk_soc = " . ((int) $socid);
  2986. }
  2987. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  2988. // Units
  2989. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2990. $sql .= " LEFT JOIN " . $this->db->prefix() . "c_units u ON u.rowid = p.fk_unit";
  2991. }
  2992. $sql .= " WHERE p.entity IN (" . getEntity('product') . ")";
  2993. if ($statut != -1) {
  2994. $sql .= " AND p.tobuy = " . ((int) $statut);
  2995. }
  2996. if (strval($filtertype) != '') {
  2997. $sql .= " AND p.fk_product_type = " . ((int) $filtertype);
  2998. }
  2999. if (!empty($filtre)) {
  3000. $sql .= " " . $filtre;
  3001. }
  3002. // Add where from hooks
  3003. $parameters = array();
  3004. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3005. $sql .= $hookmanager->resPrint;
  3006. // Add criteria on ref/label
  3007. if ($filterkey != '') {
  3008. $sql .= ' AND (';
  3009. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  3010. // For natural search
  3011. $scrit = explode(' ', $filterkey);
  3012. $i = 0;
  3013. if (count($scrit) > 1) {
  3014. $sql .= "(";
  3015. }
  3016. foreach ($scrit as $crit) {
  3017. if ($i > 0) {
  3018. $sql .= " AND ";
  3019. }
  3020. $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) . "%'";
  3021. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  3022. $sql .= " OR pfp.desc_fourn LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  3023. }
  3024. $sql .= ")";
  3025. $i++;
  3026. }
  3027. if (count($scrit) > 1) {
  3028. $sql .= ")";
  3029. }
  3030. if (isModEnabled('barcode')) {
  3031. $sql .= " OR p.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3032. $sql .= " OR pfp.barcode LIKE '" . $this->db->escape($prefix . $filterkey) . "%'";
  3033. }
  3034. $sql .= ')';
  3035. }
  3036. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3037. $sql .= $this->db->plimit($limit, 0);
  3038. // Build output string
  3039. dol_syslog(get_class($this) . "::select_produits_fournisseurs_list", LOG_DEBUG);
  3040. $result = $this->db->query($sql);
  3041. if ($result) {
  3042. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3043. require_once DOL_DOCUMENT_ROOT . '/core/lib/product.lib.php';
  3044. $num = $this->db->num_rows($result);
  3045. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3046. $out .= '<select class="flat ' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '">';
  3047. if (!$selected) {
  3048. $out .= '<option value="-1" selected>' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3049. } else {
  3050. $out .= '<option value="-1">' . ($placeholder ? $placeholder : '&nbsp;') . '</option>';
  3051. }
  3052. $i = 0;
  3053. while ($i < $num) {
  3054. $objp = $this->db->fetch_object($result);
  3055. if (is_null($objp->idprodfournprice)) {
  3056. // There is no supplier price found, we will use the vat rate for sale
  3057. $objp->tva_tx = $objp->tva_tx_sale;
  3058. $objp->default_vat_code = $objp->default_vat_code_sale;
  3059. }
  3060. $outkey = $objp->idprodfournprice; // id in table of price
  3061. if (!$outkey && $alsoproductwithnosupplierprice) {
  3062. $outkey = 'idprod_' . $objp->rowid; // id of product
  3063. }
  3064. $outref = $objp->ref;
  3065. $outbarcode = $objp->barcode;
  3066. $outqty = 1;
  3067. $outdiscount = 0;
  3068. $outtype = $objp->fk_product_type;
  3069. $outdurationvalue = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3070. $outdurationunit = $outtype == Product::TYPE_SERVICE ? substr($objp->duration, -1) : '';
  3071. // Units
  3072. $outvalUnits = '';
  3073. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3074. if (!empty($objp->unit_short)) {
  3075. $outvalUnits .= ' - ' . $objp->unit_short;
  3076. }
  3077. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3078. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3079. $outvalUnits .= ' - ' . $unitToShow;
  3080. }
  3081. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3082. $unitToShow = $objp->length . ' x ' . $objp->width . ' x ' . $objp->height . ' ' . measuringUnitString(0, 'size', $objp->length_units);
  3083. $outvalUnits .= ' - ' . $unitToShow;
  3084. }
  3085. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3086. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3087. $outvalUnits .= ' - ' . $unitToShow;
  3088. }
  3089. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3090. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3091. $outvalUnits .= ' - ' . $unitToShow;
  3092. }
  3093. if ($outdurationvalue && $outdurationunit) {
  3094. $da = array(
  3095. 'h' => $langs->trans('Hour'),
  3096. 'd' => $langs->trans('Day'),
  3097. 'w' => $langs->trans('Week'),
  3098. 'm' => $langs->trans('Month'),
  3099. 'y' => $langs->trans('Year')
  3100. );
  3101. if (isset($da[$outdurationunit])) {
  3102. $outvalUnits .= ' - ' . $outdurationvalue . ' ' . $langs->transnoentities($da[$outdurationunit] . ($outdurationvalue > 1 ? 's' : ''));
  3103. }
  3104. }
  3105. }
  3106. $objRef = $objp->ref;
  3107. if ($filterkey && $filterkey != '') {
  3108. $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  3109. }
  3110. $objRefFourn = $objp->ref_fourn;
  3111. if ($filterkey && $filterkey != '') {
  3112. $objRefFourn = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3113. }
  3114. $label = $objp->label;
  3115. if ($filterkey && $filterkey != '') {
  3116. $label = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $label, 1);
  3117. }
  3118. $optlabel = $objp->ref;
  3119. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3120. $optlabel .= ' <span class="opacitymedium">(' . $objp->ref_fourn . ')</span>';
  3121. }
  3122. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3123. $optlabel .= ' (' . $outbarcode . ')';
  3124. }
  3125. $optlabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3126. $outvallabel = $objRef;
  3127. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3128. $outvallabel .= ' (' . $objRefFourn . ')';
  3129. }
  3130. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3131. $outvallabel .= ' (' . $outbarcode . ')';
  3132. }
  3133. $outvallabel .= ' - ' . dol_trunc($label, $maxlengtharticle);
  3134. // Units
  3135. $optlabel .= $outvalUnits;
  3136. $outvallabel .= $outvalUnits;
  3137. if (!empty($objp->idprodfournprice)) {
  3138. $outqty = $objp->quantity;
  3139. $outdiscount = $objp->remise_percent;
  3140. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3141. $prod_supplier = new ProductFournisseur($this->db);
  3142. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3143. $prod_supplier->id = $objp->fk_product;
  3144. $prod_supplier->fourn_qty = $objp->quantity;
  3145. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3146. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3147. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3148. $priceparser = new PriceParser($this->db);
  3149. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3150. if ($price_result >= 0) {
  3151. $objp->fprice = $price_result;
  3152. if ($objp->quantity >= 1) {
  3153. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3154. }
  3155. }
  3156. }
  3157. if ($objp->quantity == 1) {
  3158. $optlabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3159. $outvallabel .= ' - ' . price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency) . "/";
  3160. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3161. $outvallabel .= $langs->transnoentities("Unit");
  3162. } else {
  3163. $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;
  3164. $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;
  3165. $optlabel .= ' ' . $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3166. $outvallabel .= ' ' . $langs->transnoentities("Units");
  3167. }
  3168. if ($objp->quantity > 1) {
  3169. $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
  3170. $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
  3171. }
  3172. if ($objp->remise_percent >= 1) {
  3173. $optlabel .= " - " . $langs->trans("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3174. $outvallabel .= " - " . $langs->transnoentities("Discount") . " : " . vatrate($objp->remise_percent) . ' %';
  3175. }
  3176. if ($objp->duration) {
  3177. $optlabel .= " - " . $objp->duration;
  3178. $outvallabel .= " - " . $objp->duration;
  3179. }
  3180. if (!$socid) {
  3181. $optlabel .= " - " . dol_trunc($objp->name, 8);
  3182. $outvallabel .= " - " . dol_trunc($objp->name, 8);
  3183. }
  3184. if ($objp->supplier_reputation) {
  3185. //TODO dictionary
  3186. $reputations = array('' => $langs->trans('Standard'), 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
  3187. $optlabel .= " - " . $reputations[$objp->supplier_reputation];
  3188. $outvallabel .= " - " . $reputations[$objp->supplier_reputation];
  3189. }
  3190. } else {
  3191. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3192. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3193. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3194. } else // No supplier price defined for product, even on other suppliers
  3195. {
  3196. $optlabel .= " - <span class='opacitymedium'>" . $langs->trans("NoPriceDefinedForThisSupplier") . '</span>';
  3197. $outvallabel .= ' - ' . $langs->transnoentities("NoPriceDefinedForThisSupplier");
  3198. }
  3199. }
  3200. if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3201. $novirtualstock = ($showstockinlist == 2);
  3202. if (!empty($user->rights->stock->lire)) {
  3203. $outvallabel .= ' - ' . $langs->trans("Stock") . ': ' . price(price2num($objp->stock, 'MS'));
  3204. if ($objp->stock > 0) {
  3205. $optlabel .= ' - <span class="product_line_stock_ok">';
  3206. } elseif ($objp->stock <= 0) {
  3207. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3208. }
  3209. $optlabel .= $langs->transnoentities("Stock") . ':' . price(price2num($objp->stock, 'MS'));
  3210. $optlabel .= '</span>';
  3211. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3212. $langs->load("stocks");
  3213. $tmpproduct = new Product($this->db);
  3214. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3215. $tmpproduct->load_virtual_stock();
  3216. $virtualstock = $tmpproduct->stock_theorique;
  3217. $outvallabel .= ' - ' . $langs->trans("VirtualStock") . ':' . $virtualstock;
  3218. $optlabel .= ' - ' . $langs->transnoentities("VirtualStock") . ':';
  3219. if ($virtualstock > 0) {
  3220. $optlabel .= '<span class="product_line_stock_ok">';
  3221. } elseif ($virtualstock <= 0) {
  3222. $optlabel .= '<span class="product_line_stock_too_low">';
  3223. }
  3224. $optlabel .= $virtualstock;
  3225. $optlabel .= '</span>';
  3226. unset($tmpproduct);
  3227. }
  3228. }
  3229. }
  3230. $optstart = '<option value="' . $outkey . '"';
  3231. if ($selected && $selected == $objp->idprodfournprice) {
  3232. $optstart .= ' selected';
  3233. }
  3234. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3235. $optstart .= ' disabled';
  3236. }
  3237. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3238. $optstart .= ' data-product-id="' . dol_escape_htmltag($objp->rowid) . '"';
  3239. $optstart .= ' data-price-id="' . dol_escape_htmltag($objp->idprodfournprice) . '"';
  3240. $optstart .= ' data-qty="' . dol_escape_htmltag($objp->quantity) . '"';
  3241. $optstart .= ' data-up="' . dol_escape_htmltag(price2num($objp->unitprice)) . '"';
  3242. $optstart .= ' data-up-locale="' . dol_escape_htmltag(price($objp->unitprice)) . '"';
  3243. $optstart .= ' data-discount="' . dol_escape_htmltag($outdiscount) . '"';
  3244. $optstart .= ' data-tvatx="' . dol_escape_htmltag(price2num($objp->tva_tx)) . '"';
  3245. $optstart .= ' data-tvatx-formated="' . dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)) . '"';
  3246. $optstart .= ' data-default-vat-code="' . dol_escape_htmltag($objp->default_vat_code) . '"';
  3247. }
  3248. $optstart .= ' data-description="' . dol_escape_htmltag($objp->description, 0, 1) . '"';
  3249. $outarrayentry = array(
  3250. 'key' => $outkey,
  3251. 'value' => $outref,
  3252. 'label' => $outvallabel,
  3253. 'qty' => $outqty,
  3254. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3255. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3256. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3257. 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
  3258. 'tva_tx' => price2num($objp->tva_tx),
  3259. 'default_vat_code' => $objp->default_vat_code,
  3260. 'discount' => $outdiscount,
  3261. 'type' => $outtype,
  3262. 'duration_value' => $outdurationvalue,
  3263. 'duration_unit' => $outdurationunit,
  3264. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3265. 'description' => $objp->description
  3266. );
  3267. $parameters = array(
  3268. 'objp' => &$objp,
  3269. 'optstart' => &$optstart,
  3270. 'optlabel' => &$optlabel,
  3271. 'outvallabel' => &$outvallabel,
  3272. 'outarrayentry' => &$outarrayentry
  3273. );
  3274. $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
  3275. // Add new entry
  3276. // "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
  3277. // "label" value of json key array is used by jQuery automatically as text for combo box
  3278. $out .= $optstart . ' data-html="' . dol_escape_htmltag($optlabel) . '">' . $optlabel . "</option>\n";;
  3279. array_push(
  3280. $outarray,
  3281. array(
  3282. 'key' => $outkey,
  3283. 'value' => $outref,
  3284. 'label' => $outvallabel,
  3285. 'qty' => $outqty,
  3286. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3287. 'price_qty_ht_locale' => price($objp->fprice),
  3288. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3289. 'price_unit_ht_locale' => price($objp->unitprice),
  3290. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3291. 'tva_tx_formated' => price($objp->tva_tx),
  3292. 'tva_tx' => price2num($objp->tva_tx),
  3293. 'default_vat_code' => $objp->default_vat_code,
  3294. 'discount' => $outdiscount,
  3295. 'type' => $outtype,
  3296. 'duration_value' => $outdurationvalue,
  3297. 'duration_unit' => $outdurationunit,
  3298. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3299. 'description' => $objp->description
  3300. )
  3301. );
  3302. // Exemple of var_dump $outarray
  3303. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3304. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3305. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3306. //}
  3307. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3308. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3309. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3310. $i++;
  3311. }
  3312. $out .= '</select>';
  3313. $this->db->free($result);
  3314. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3315. $out .= ajax_combobox($htmlname);
  3316. } else {
  3317. dol_print_error($this->db);
  3318. }
  3319. if (empty($outputmode)) {
  3320. return $out;
  3321. }
  3322. return $outarray;
  3323. }
  3324. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3325. /**
  3326. * Return list of suppliers prices for a product
  3327. *
  3328. * @param int $productid Id of product
  3329. * @param string $htmlname Name of HTML field
  3330. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3331. * @return string
  3332. */
  3333. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3334. {
  3335. // phpcs:enable
  3336. global $langs, $conf;
  3337. $langs->load('stocks');
  3338. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3339. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3340. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3341. $sql .= " FROM " . $this->db->prefix() . "product as p";
  3342. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3343. $sql .= " LEFT JOIN " . $this->db->prefix() . "societe as s ON pfp.fk_soc = s.rowid";
  3344. $sql .= " WHERE pfp.entity IN (" . getEntity('productsupplierprice') . ")";
  3345. $sql .= " AND p.tobuy = 1";
  3346. $sql .= " AND s.fournisseur = 1";
  3347. $sql .= " AND p.rowid = " . ((int) $productid);
  3348. if (empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED)) {
  3349. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3350. } else {
  3351. $sql .= " ORDER BY pfp.unitprice ASC";
  3352. }
  3353. dol_syslog(get_class($this) . "::select_product_fourn_price", LOG_DEBUG);
  3354. $result = $this->db->query($sql);
  3355. if ($result) {
  3356. $num = $this->db->num_rows($result);
  3357. $form = '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3358. if (!$num) {
  3359. $form .= '<option value="0">-- ' . $langs->trans("NoSupplierPriceDefinedForThisProduct") . ' --</option>';
  3360. } else {
  3361. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3362. $form .= '<option value="0">&nbsp;</option>';
  3363. $i = 0;
  3364. while ($i < $num) {
  3365. $objp = $this->db->fetch_object($result);
  3366. $opt = '<option value="' . $objp->idprodfournprice . '"';
  3367. //if there is only one supplier, preselect it
  3368. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && !empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED))) {
  3369. $opt .= ' selected';
  3370. }
  3371. $opt .= '>' . $objp->name . ' - ' . $objp->ref_fourn . ' - ';
  3372. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3373. $prod_supplier = new ProductFournisseur($this->db);
  3374. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3375. $prod_supplier->id = $productid;
  3376. $prod_supplier->fourn_qty = $objp->quantity;
  3377. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3378. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3379. require_once DOL_DOCUMENT_ROOT . '/product/dynamic_price/class/price_parser.class.php';
  3380. $priceparser = new PriceParser($this->db);
  3381. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3382. if ($price_result >= 0) {
  3383. $objp->fprice = $price_result;
  3384. if ($objp->quantity >= 1) {
  3385. $objp->unitprice = $objp->fprice / $objp->quantity;
  3386. }
  3387. }
  3388. }
  3389. if ($objp->quantity == 1) {
  3390. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency) . "/";
  3391. }
  3392. $opt .= $objp->quantity . ' ';
  3393. if ($objp->quantity == 1) {
  3394. $opt .= $langs->trans("Unit");
  3395. } else {
  3396. $opt .= $langs->trans("Units");
  3397. }
  3398. if ($objp->quantity > 1) {
  3399. $opt .= " - ";
  3400. $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");
  3401. }
  3402. if ($objp->duration) {
  3403. $opt .= " - " . $objp->duration;
  3404. }
  3405. $opt .= "</option>\n";
  3406. $form .= $opt;
  3407. $i++;
  3408. }
  3409. }
  3410. $form .= '</select>';
  3411. $this->db->free($result);
  3412. return $form;
  3413. } else {
  3414. dol_print_error($this->db);
  3415. }
  3416. }
  3417. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3418. /**
  3419. * Return list of delivery address
  3420. *
  3421. * @param string $selected Id contact pre-selectionn
  3422. * @param int $socid Id of company
  3423. * @param string $htmlname Name of HTML field
  3424. * @param int $showempty Add an empty field
  3425. * @return integer|null
  3426. */
  3427. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3428. {
  3429. // phpcs:enable
  3430. // looking for users
  3431. $sql = "SELECT a.rowid, a.label";
  3432. $sql .= " FROM " . $this->db->prefix() . "societe_address as a";
  3433. $sql .= " WHERE a.fk_soc = " . ((int) $socid);
  3434. $sql .= " ORDER BY a.label ASC";
  3435. dol_syslog(get_class($this) . "::select_address", LOG_DEBUG);
  3436. $resql = $this->db->query($sql);
  3437. if ($resql) {
  3438. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3439. if ($showempty) {
  3440. print '<option value="0">&nbsp;</option>';
  3441. }
  3442. $num = $this->db->num_rows($resql);
  3443. $i = 0;
  3444. if ($num) {
  3445. while ($i < $num) {
  3446. $obj = $this->db->fetch_object($resql);
  3447. if ($selected && $selected == $obj->rowid) {
  3448. print '<option value="' . $obj->rowid . '" selected>' . $obj->label . '</option>';
  3449. } else {
  3450. print '<option value="' . $obj->rowid . '">' . $obj->label . '</option>';
  3451. }
  3452. $i++;
  3453. }
  3454. }
  3455. print '</select>';
  3456. return $num;
  3457. } else {
  3458. dol_print_error($this->db);
  3459. }
  3460. }
  3461. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3462. /**
  3463. * Load into cache list of payment terms
  3464. *
  3465. * @return int Nb of lines loaded, <0 if KO
  3466. */
  3467. public function load_cache_conditions_paiements()
  3468. {
  3469. // phpcs:enable
  3470. global $langs;
  3471. $num = count($this->cache_conditions_paiements);
  3472. if ($num > 0) {
  3473. return 0; // Cache already loaded
  3474. }
  3475. dol_syslog(__METHOD__, LOG_DEBUG);
  3476. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3477. $sql .= " FROM " . $this->db->prefix() . 'c_payment_term';
  3478. $sql .= " WHERE entity IN (" . getEntity('c_payment_term') . ")";
  3479. $sql .= " AND active > 0";
  3480. $sql .= " ORDER BY sortorder";
  3481. $resql = $this->db->query($sql);
  3482. if ($resql) {
  3483. $num = $this->db->num_rows($resql);
  3484. $i = 0;
  3485. while ($i < $num) {
  3486. $obj = $this->db->fetch_object($resql);
  3487. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3488. $label = ($langs->trans("PaymentConditionShort" . $obj->code) != ("PaymentConditionShort" . $obj->code) ? $langs->trans("PaymentConditionShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3489. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3490. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3491. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3492. $i++;
  3493. }
  3494. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3495. return $num;
  3496. } else {
  3497. dol_print_error($this->db);
  3498. return -1;
  3499. }
  3500. }
  3501. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3502. /**
  3503. * Load int a cache property th elist of possible delivery delays.
  3504. *
  3505. * @return int Nb of lines loaded, <0 if KO
  3506. */
  3507. public function load_cache_availability()
  3508. {
  3509. // phpcs:enable
  3510. global $langs;
  3511. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3512. if ($num > 0) {
  3513. return 0; // Cache already loaded
  3514. }
  3515. dol_syslog(__METHOD__, LOG_DEBUG);
  3516. $langs->load('propal');
  3517. $sql = "SELECT rowid, code, label, position";
  3518. $sql .= " FROM " . $this->db->prefix() . 'c_availability';
  3519. $sql .= " WHERE active > 0";
  3520. $resql = $this->db->query($sql);
  3521. if ($resql) {
  3522. $num = $this->db->num_rows($resql);
  3523. $i = 0;
  3524. while ($i < $num) {
  3525. $obj = $this->db->fetch_object($resql);
  3526. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3527. $label = ($langs->trans("AvailabilityType" . $obj->code) != ("AvailabilityType" . $obj->code) ? $langs->trans("AvailabilityType" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3528. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3529. $this->cache_availability[$obj->rowid]['label'] = $label;
  3530. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3531. $i++;
  3532. }
  3533. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3534. return $num;
  3535. } else {
  3536. dol_print_error($this->db);
  3537. return -1;
  3538. }
  3539. }
  3540. /**
  3541. * Retourne la liste des types de delais de livraison possibles
  3542. *
  3543. * @param int $selected Id du type de delais pre-selectionne
  3544. * @param string $htmlname Nom de la zone select
  3545. * @param string $filtertype To add a filter
  3546. * @param int $addempty Add empty entry
  3547. * @param string $morecss More CSS
  3548. * @return void
  3549. */
  3550. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3551. {
  3552. global $langs, $user;
  3553. $this->load_cache_availability();
  3554. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3555. print '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3556. if ($addempty) {
  3557. print '<option value="0">&nbsp;</option>';
  3558. }
  3559. foreach ($this->cache_availability as $id => $arrayavailability) {
  3560. if ($selected == $id) {
  3561. print '<option value="' . $id . '" selected>';
  3562. } else {
  3563. print '<option value="' . $id . '">';
  3564. }
  3565. print dol_escape_htmltag($arrayavailability['label']);
  3566. print '</option>';
  3567. }
  3568. print '</select>';
  3569. if ($user->admin) {
  3570. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3571. }
  3572. print ajax_combobox($htmlname);
  3573. }
  3574. /**
  3575. * Load into cache cache_demand_reason, array of input reasons
  3576. *
  3577. * @return int Nb of lines loaded, <0 if KO
  3578. */
  3579. public function loadCacheInputReason()
  3580. {
  3581. global $langs;
  3582. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3583. if ($num > 0) {
  3584. return 0; // Cache already loaded
  3585. }
  3586. $sql = "SELECT rowid, code, label";
  3587. $sql .= " FROM " . $this->db->prefix() . 'c_input_reason';
  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. $tmparray = array();
  3594. while ($i < $num) {
  3595. $obj = $this->db->fetch_object($resql);
  3596. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3597. $label = ($obj->label != '-' ? $obj->label : '');
  3598. if ($langs->trans("DemandReasonType" . $obj->code) != ("DemandReasonType" . $obj->code)) {
  3599. $label = $langs->trans("DemandReasonType" . $obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3600. }
  3601. if ($langs->trans($obj->code) != $obj->code) {
  3602. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3603. }
  3604. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3605. $tmparray[$obj->rowid]['code'] = $obj->code;
  3606. $tmparray[$obj->rowid]['label'] = $label;
  3607. $i++;
  3608. }
  3609. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3610. unset($tmparray);
  3611. return $num;
  3612. } else {
  3613. dol_print_error($this->db);
  3614. return -1;
  3615. }
  3616. }
  3617. /**
  3618. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3619. * List found into table c_input_reason loaded by loadCacheInputReason
  3620. *
  3621. * @param int $selected Id or code of type origin to select by default
  3622. * @param string $htmlname Nom de la zone select
  3623. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3624. * @param int $addempty Add an empty entry
  3625. * @param string $morecss Add more css to the HTML select component
  3626. * @param int $notooltip Do not show the tooltip for admin
  3627. * @return void
  3628. */
  3629. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3630. {
  3631. global $langs, $user;
  3632. $this->loadCacheInputReason();
  3633. print '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3634. if ($addempty) {
  3635. print '<option value="0"' . (empty($selected) ? ' selected' : '') . '>&nbsp;</option>';
  3636. }
  3637. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3638. if ($arraydemandreason['code'] == $exclude) {
  3639. continue;
  3640. }
  3641. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3642. print '<option value="' . $arraydemandreason['id'] . '" selected>';
  3643. } else {
  3644. print '<option value="' . $arraydemandreason['id'] . '">';
  3645. }
  3646. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3647. print $langs->trans($label);
  3648. print '</option>';
  3649. }
  3650. print '</select>';
  3651. if ($user->admin && empty($notooltip)) {
  3652. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3653. }
  3654. print ajax_combobox('select_' . $htmlname);
  3655. }
  3656. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3657. /**
  3658. * Charge dans cache la liste des types de paiements possibles
  3659. *
  3660. * @return int Nb of lines loaded, <0 if KO
  3661. */
  3662. public function load_cache_types_paiements()
  3663. {
  3664. // phpcs:enable
  3665. global $langs;
  3666. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3667. if ($num > 0) {
  3668. return $num; // Cache already loaded
  3669. }
  3670. dol_syslog(__METHOD__, LOG_DEBUG);
  3671. $this->cache_types_paiements = array();
  3672. $sql = "SELECT id, code, libelle as label, type, active";
  3673. $sql .= " FROM " . $this->db->prefix() . "c_paiement";
  3674. $sql .= " WHERE entity IN (" . getEntity('c_paiement') . ")";
  3675. $resql = $this->db->query($sql);
  3676. if ($resql) {
  3677. $num = $this->db->num_rows($resql);
  3678. $i = 0;
  3679. while ($i < $num) {
  3680. $obj = $this->db->fetch_object($resql);
  3681. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3682. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != ("PaymentTypeShort" . $obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3683. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3684. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3685. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3686. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3687. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3688. $i++;
  3689. }
  3690. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3691. return $num;
  3692. } else {
  3693. dol_print_error($this->db);
  3694. return -1;
  3695. }
  3696. }
  3697. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3698. /**
  3699. * print list of payment modes.
  3700. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3701. * See instead to force the default value by the caller.
  3702. *
  3703. * @param int $selected Id of payment term to preselect by default
  3704. * @param string $htmlname Nom de la zone select
  3705. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3706. * @param int $addempty Add an empty entry
  3707. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3708. * @param string $morecss Add more CSS on select tag
  3709. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3710. * 0 : use default deposit percentage from entry
  3711. * > 0 : force deposit percentage (for example, from company object)
  3712. * @return void
  3713. * @deprecated
  3714. */
  3715. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3716. {
  3717. // phpcs:enable
  3718. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
  3719. }
  3720. /**
  3721. * Return list of payment modes.
  3722. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3723. * See instead to force the default value by the caller.
  3724. *
  3725. * @param int $selected Id of payment term to preselect by default
  3726. * @param string $htmlname Nom de la zone select
  3727. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3728. * @param int $addempty Add an empty entry
  3729. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3730. * @param string $morecss Add more CSS on select tag
  3731. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3732. * 0 : use default deposit percentage from entry
  3733. * > 0 : force deposit percentage (for example, from company object)
  3734. * @return string String for the HTML select component
  3735. */
  3736. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3737. {
  3738. global $langs, $user, $conf;
  3739. $out = '';
  3740. dol_syslog(__METHOD__ . " selected=" . $selected . ", htmlname=" . $htmlname, LOG_DEBUG);
  3741. $this->load_cache_conditions_paiements();
  3742. // Set default value if not already set by caller
  3743. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3744. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3745. }
  3746. $out .= '<select id="' . $htmlname . '" class="flat selectpaymentterms' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3747. if ($addempty) {
  3748. $out .= '<option value="0">&nbsp;</option>';
  3749. }
  3750. $selectedDepositPercent = null;
  3751. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3752. if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
  3753. continue;
  3754. }
  3755. if ($selected == $id) {
  3756. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3757. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3758. } else {
  3759. $out .= '<option value="' . $id . '" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3760. }
  3761. $label = $arrayconditions['label'];
  3762. if (!empty($arrayconditions['deposit_percent'])) {
  3763. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3764. }
  3765. $out .= $label;
  3766. $out .= '</option>';
  3767. }
  3768. $out .= '</select>';
  3769. if ($user->admin && empty($noinfoadmin)) {
  3770. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3771. }
  3772. $out .= ajax_combobox($htmlname);
  3773. if ($deposit_percent >= 0) {
  3774. $out .= ' <span id="' . $htmlname . '_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3775. $out .= $langs->trans('DepositPercent') . ' : ';
  3776. $out .= '<input id="' . $htmlname . '_deposit_percent" name="' . $htmlname . '_deposit_percent" class="maxwidth50" value="' . strval($deposit_percent) . '" />';
  3777. $out .= '</span>';
  3778. $out .= '
  3779. <script>
  3780. $(document).ready(function () {
  3781. $("#' . $htmlname . '").change(function () {
  3782. let $selected = $(this).find("option:selected");
  3783. let depositPercent = $selected.attr("data-deposit_percent");
  3784. if (depositPercent.length > 0) {
  3785. $("#' . $htmlname . '_deposit_percent_container").show().find("#' . $htmlname . '_deposit_percent").val(depositPercent);
  3786. } else {
  3787. $("#' . $htmlname . '_deposit_percent_container").hide();
  3788. }
  3789. return true;
  3790. });
  3791. });
  3792. </script>';
  3793. }
  3794. return $out;
  3795. }
  3796. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3797. /**
  3798. * Return list of payment methods
  3799. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3800. *
  3801. * @param string $selected Id or code or preselected payment mode
  3802. * @param string $htmlname Name of select field
  3803. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3804. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3805. * @param int $empty 1=can be empty, 0 otherwise
  3806. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3807. * @param int $maxlength Max length of label
  3808. * @param int $active Active or not, -1 = all
  3809. * @param string $morecss Add more CSS on select tag
  3810. * @param int $nooutput 1=Return string, do not send to output
  3811. * @return string|void String for the HTML select component
  3812. */
  3813. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3814. {
  3815. // phpcs:enable
  3816. global $langs, $user, $conf;
  3817. $out = '';
  3818. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $filtertype . ", " . $format, LOG_DEBUG);
  3819. $filterarray = array();
  3820. if ($filtertype == 'CRDT') {
  3821. $filterarray = array(0, 2, 3);
  3822. } elseif ($filtertype == 'DBIT') {
  3823. $filterarray = array(1, 2, 3);
  3824. } elseif ($filtertype != '' && $filtertype != '-1') {
  3825. $filterarray = explode(',', $filtertype);
  3826. }
  3827. $this->load_cache_types_paiements();
  3828. // Set default value if not already set by caller
  3829. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3830. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3831. }
  3832. $out .= '<select id="select' . $htmlname . '" class="flat selectpaymenttypes' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3833. if ($empty) {
  3834. $out .= '<option value="">&nbsp;</option>';
  3835. }
  3836. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3837. // If not good status
  3838. if ($active >= 0 && $arraytypes['active'] != $active) {
  3839. continue;
  3840. }
  3841. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3842. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3843. continue;
  3844. }
  3845. // We discard empty line if showempty is on because an empty line has already been output.
  3846. if ($empty && empty($arraytypes['code'])) {
  3847. continue;
  3848. }
  3849. if ($format == 0) {
  3850. $out .= '<option value="' . $id . '"';
  3851. } elseif ($format == 1) {
  3852. $out .= '<option value="' . $arraytypes['code'] . '"';
  3853. } elseif ($format == 2) {
  3854. $out .= '<option value="' . $arraytypes['code'] . '"';
  3855. } elseif ($format == 3) {
  3856. $out .= '<option value="' . $id . '"';
  3857. }
  3858. // Print attribute selected or not
  3859. if ($format == 1 || $format == 2) {
  3860. if ($selected == $arraytypes['code']) {
  3861. $out .= ' selected';
  3862. }
  3863. } else {
  3864. if ($selected == $id) {
  3865. $out .= ' selected';
  3866. }
  3867. }
  3868. $out .= '>';
  3869. $value = '';
  3870. if ($format == 0) {
  3871. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3872. } elseif ($format == 1) {
  3873. $value = $arraytypes['code'];
  3874. } elseif ($format == 2) {
  3875. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3876. } elseif ($format == 3) {
  3877. $value = $arraytypes['code'];
  3878. }
  3879. $out .= $value ? $value : '&nbsp;';
  3880. $out .= '</option>';
  3881. }
  3882. $out .= '</select>';
  3883. if ($user->admin && !$noadmininfo) {
  3884. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3885. }
  3886. $out .= ajax_combobox('select' . $htmlname);
  3887. if (empty($nooutput)) {
  3888. print $out;
  3889. } else {
  3890. return $out;
  3891. }
  3892. }
  3893. /**
  3894. * Selection HT or TTC
  3895. *
  3896. * @param string $selected Id pre-selectionne
  3897. * @param string $htmlname Nom de la zone select
  3898. * @param string $addjscombo Add js combo
  3899. * @return string Code of HTML select to chose tax or not
  3900. */
  3901. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3902. {
  3903. global $langs;
  3904. $return = '<select class="flat maxwidth100" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  3905. $options = array(
  3906. 'HT' => $langs->trans("HT"),
  3907. 'TTC' => $langs->trans("TTC")
  3908. );
  3909. foreach ($options as $id => $value) {
  3910. if ($selected == $id) {
  3911. $return .= '<option value="' . $id . '" selected>' . $value;
  3912. } else {
  3913. $return .= '<option value="' . $id . '">' . $value;
  3914. }
  3915. $return .= '</option>';
  3916. }
  3917. $return .= '</select>';
  3918. if ($addjscombo) {
  3919. $return .= ajax_combobox('select_' . $htmlname);
  3920. }
  3921. return $return;
  3922. }
  3923. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3924. /**
  3925. * Load in cache list of transport mode
  3926. *
  3927. * @return int Nb of lines loaded, <0 if KO
  3928. */
  3929. public function load_cache_transport_mode()
  3930. {
  3931. // phpcs:enable
  3932. global $langs;
  3933. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3934. if ($num > 0) {
  3935. return $num; // Cache already loaded
  3936. }
  3937. dol_syslog(__METHOD__, LOG_DEBUG);
  3938. $this->cache_transport_mode = array();
  3939. $sql = "SELECT rowid, code, label, active";
  3940. $sql .= " FROM " . $this->db->prefix() . "c_transport_mode";
  3941. $sql .= " WHERE entity IN (" . getEntity('c_transport_mode') . ")";
  3942. $resql = $this->db->query($sql);
  3943. if ($resql) {
  3944. $num = $this->db->num_rows($resql);
  3945. $i = 0;
  3946. while ($i < $num) {
  3947. $obj = $this->db->fetch_object($resql);
  3948. // If traduction exist, we use it else we take the default label
  3949. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) != ("PaymentTypeShort" . $obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort" . $obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3950. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3951. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3952. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3953. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3954. $i++;
  3955. }
  3956. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3957. return $num;
  3958. } else {
  3959. dol_print_error($this->db);
  3960. return -1;
  3961. }
  3962. }
  3963. /**
  3964. * Return list of transport mode for intracomm report
  3965. *
  3966. * @param string $selected Id of the transport mode pre-selected
  3967. * @param string $htmlname Name of the select field
  3968. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3969. * @param int $empty 1=can be empty, 0 else
  3970. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3971. * @param int $maxlength Max length of label
  3972. * @param int $active Active or not, -1 = all
  3973. * @param string $morecss Add more CSS on select tag
  3974. * @return void
  3975. */
  3976. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3977. {
  3978. global $langs, $user;
  3979. dol_syslog(__METHOD__ . " " . $selected . ", " . $htmlname . ", " . $format, LOG_DEBUG);
  3980. $this->load_cache_transport_mode();
  3981. print '<select id="select' . $htmlname . '" class="flat selectmodetransport' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '">';
  3982. if ($empty) {
  3983. print '<option value="">&nbsp;</option>';
  3984. }
  3985. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3986. // If not good status
  3987. if ($active >= 0 && $arraytypes['active'] != $active) {
  3988. continue;
  3989. }
  3990. // We discard empty line if showempty is on because an empty line has already been output.
  3991. if ($empty && empty($arraytypes['code'])) {
  3992. continue;
  3993. }
  3994. if ($format == 0) {
  3995. print '<option value="' . $id . '"';
  3996. } elseif ($format == 1) {
  3997. print '<option value="' . $arraytypes['code'] . '"';
  3998. } elseif ($format == 2) {
  3999. print '<option value="' . $arraytypes['code'] . '"';
  4000. } elseif ($format == 3) {
  4001. print '<option value="' . $id . '"';
  4002. }
  4003. // If text is selected, we compare with code, else with id
  4004. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  4005. print ' selected';
  4006. } elseif ($selected == $id) {
  4007. print ' selected';
  4008. }
  4009. print '>';
  4010. $value = '';
  4011. if ($format == 0) {
  4012. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4013. } elseif ($format == 1) {
  4014. $value = $arraytypes['code'];
  4015. } elseif ($format == 2) {
  4016. $value = ($maxlength ? dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4017. } elseif ($format == 3) {
  4018. $value = $arraytypes['code'];
  4019. }
  4020. print $value ? $value : '&nbsp;';
  4021. print '</option>';
  4022. }
  4023. print '</select>';
  4024. if ($user->admin && !$noadmininfo) {
  4025. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4026. }
  4027. }
  4028. /**
  4029. * Return a HTML select list of shipping mode
  4030. *
  4031. * @param string $selected Id shipping mode pre-selected
  4032. * @param string $htmlname Name of select zone
  4033. * @param string $filtre To filter list. This parameter must not come from input of users
  4034. * @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.
  4035. * @param string $moreattrib To add more attribute on select
  4036. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  4037. * @param string $morecss More CSS
  4038. * @return void
  4039. */
  4040. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  4041. {
  4042. global $langs, $conf, $user;
  4043. $langs->load("admin");
  4044. $langs->load("deliveries");
  4045. $sql = "SELECT rowid, code, libelle as label";
  4046. $sql .= " FROM " . $this->db->prefix() . "c_shipment_mode";
  4047. $sql .= " WHERE active > 0";
  4048. if ($filtre) {
  4049. $sql .= " AND " . $filtre;
  4050. }
  4051. $sql .= " ORDER BY libelle ASC";
  4052. dol_syslog(get_class($this) . "::selectShippingMode", LOG_DEBUG);
  4053. $result = $this->db->query($sql);
  4054. if ($result) {
  4055. $num = $this->db->num_rows($result);
  4056. $i = 0;
  4057. if ($num) {
  4058. print '<select id="select' . $htmlname . '" class="flat selectshippingmethod' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4059. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4060. print '<option value="-1">&nbsp;</option>';
  4061. }
  4062. while ($i < $num) {
  4063. $obj = $this->db->fetch_object($result);
  4064. if ($selected == $obj->rowid) {
  4065. print '<option value="' . $obj->rowid . '" selected>';
  4066. } else {
  4067. print '<option value="' . $obj->rowid . '">';
  4068. }
  4069. print ($langs->trans("SendingMethod" . strtoupper($obj->code)) != "SendingMethod" . strtoupper($obj->code)) ? $langs->trans("SendingMethod" . strtoupper($obj->code)) : $obj->label;
  4070. print '</option>';
  4071. $i++;
  4072. }
  4073. print "</select>";
  4074. if ($user->admin && empty($noinfoadmin)) {
  4075. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4076. }
  4077. print ajax_combobox('select' . $htmlname);
  4078. } else {
  4079. print $langs->trans("NoShippingMethodDefined");
  4080. }
  4081. } else {
  4082. dol_print_error($this->db);
  4083. }
  4084. }
  4085. /**
  4086. * Display form to select shipping mode
  4087. *
  4088. * @param string $page Page
  4089. * @param int $selected Id of shipping mode
  4090. * @param string $htmlname Name of select html field
  4091. * @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.
  4092. * @return void
  4093. */
  4094. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4095. {
  4096. global $langs;
  4097. $langs->load("deliveries");
  4098. if ($htmlname != "none") {
  4099. print '<form method="POST" action="' . $page . '">';
  4100. print '<input type="hidden" name="action" value="setshippingmethod">';
  4101. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4102. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4103. print '<input type="submit" class="button valignmiddle" value="' . $langs->trans("Modify") . '">';
  4104. print '</form>';
  4105. } else {
  4106. if ($selected) {
  4107. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4108. print $langs->trans("SendingMethod" . strtoupper($code));
  4109. } else {
  4110. print "&nbsp;";
  4111. }
  4112. }
  4113. }
  4114. /**
  4115. * Creates HTML last in cycle situation invoices selector
  4116. *
  4117. * @param string $selected Preselected ID
  4118. * @param int $socid Company ID
  4119. *
  4120. * @return string HTML select
  4121. */
  4122. public function selectSituationInvoices($selected = '', $socid = 0)
  4123. {
  4124. global $langs;
  4125. $langs->load('bills');
  4126. $opt = '<option value="" selected></option>';
  4127. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4128. $sql .= ' FROM ' . $this->db->prefix() . 'facture';
  4129. $sql .= ' WHERE entity IN (' . getEntity('invoice') . ')';
  4130. $sql .= ' AND situation_counter >= 1';
  4131. $sql .= ' AND fk_soc = ' . (int) $socid;
  4132. $sql .= ' AND type <> 2';
  4133. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4134. $resql = $this->db->query($sql);
  4135. if ($resql && $this->db->num_rows($resql) > 0) {
  4136. // Last seen cycle
  4137. $ref = 0;
  4138. while ($obj = $this->db->fetch_object($resql)) {
  4139. //Same cycle ?
  4140. if ($obj->situation_cycle_ref != $ref) {
  4141. // Just seen this cycle
  4142. $ref = $obj->situation_cycle_ref;
  4143. //not final ?
  4144. if ($obj->situation_final != 1) {
  4145. //Not prov?
  4146. if (substr($obj->ref, 1, 4) != 'PROV') {
  4147. if ($selected == $obj->rowid) {
  4148. $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
  4149. } else {
  4150. $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
  4151. }
  4152. }
  4153. }
  4154. }
  4155. }
  4156. } else {
  4157. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  4158. }
  4159. if ($opt == '<option value ="" selected></option>') {
  4160. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  4161. }
  4162. return $opt;
  4163. }
  4164. /**
  4165. * Creates HTML units selector (code => label)
  4166. *
  4167. * @param string $selected Preselected Unit ID
  4168. * @param string $htmlname Select name
  4169. * @param int $showempty Add a nempty line
  4170. * @param string $unit_type Restrict to one given unit type
  4171. * @return string HTML select
  4172. */
  4173. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4174. {
  4175. global $langs;
  4176. $langs->load('products');
  4177. $return = '<select class="flat" id="' . $htmlname . '" name="' . $htmlname . '">';
  4178. $sql = "SELECT rowid, label, code FROM " . $this->db->prefix() . "c_units";
  4179. $sql .= ' WHERE active > 0';
  4180. if (!empty($unit_type)) {
  4181. $sql .= " AND unit_type = '" . $this->db->escape($unit_type) . "'";
  4182. }
  4183. $sql .= " ORDER BY sortorder";
  4184. $resql = $this->db->query($sql);
  4185. if ($resql && $this->db->num_rows($resql) > 0) {
  4186. if ($showempty) {
  4187. $return .= '<option value="none"></option>';
  4188. }
  4189. while ($res = $this->db->fetch_object($resql)) {
  4190. $unitLabel = $res->label;
  4191. if (!empty($langs->tab_translate['unit' . $res->code])) { // check if Translation is available before
  4192. $unitLabel = $langs->trans('unit' . $res->code) != $res->label ? $langs->trans('unit' . $res->code) : $res->label;
  4193. }
  4194. if ($selected == $res->rowid) {
  4195. $return .= '<option value="' . $res->rowid . '" selected>' . $unitLabel . '</option>';
  4196. } else {
  4197. $return .= '<option value="' . $res->rowid . '">' . $unitLabel . '</option>';
  4198. }
  4199. }
  4200. $return .= '</select>';
  4201. }
  4202. return $return;
  4203. }
  4204. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4205. /**
  4206. * Return a HTML select list of bank accounts
  4207. *
  4208. * @param string $selected Id account pre-selected
  4209. * @param string $htmlname Name of select zone
  4210. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4211. * @param string $filtre To filter list. This parameter must not come from input of users
  4212. * @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.
  4213. * @param string $moreattrib To add more attribute on select
  4214. * @param int $showcurrency Show currency in label
  4215. * @param string $morecss More CSS
  4216. * @param int $nooutput 1=Return string, do not send to output
  4217. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4218. */
  4219. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4220. {
  4221. // phpcs:enable
  4222. global $langs, $conf;
  4223. $out = '';
  4224. $langs->load("admin");
  4225. $num = 0;
  4226. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4227. $sql .= " FROM " . $this->db->prefix() . "bank_account";
  4228. $sql .= " WHERE entity IN (" . getEntity('bank_account') . ")";
  4229. if ($status != 2) {
  4230. $sql .= " AND clos = " . (int) $status;
  4231. }
  4232. if ($filtre) {
  4233. $sql .= " AND " . $filtre;
  4234. }
  4235. $sql .= " ORDER BY label";
  4236. dol_syslog(get_class($this) . "::select_comptes", LOG_DEBUG);
  4237. $result = $this->db->query($sql);
  4238. if ($result) {
  4239. $num = $this->db->num_rows($result);
  4240. $i = 0;
  4241. if ($num) {
  4242. $out .= '<select id="select' . $htmlname . '" class="flat selectbankaccount' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4243. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4244. $out .= '<option value="-1">&nbsp;</option>';
  4245. }
  4246. while ($i < $num) {
  4247. $obj = $this->db->fetch_object($result);
  4248. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4249. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '" selected>';
  4250. } else {
  4251. $out .= '<option value="' . $obj->rowid . '" data-currency-code="' . $obj->currency_code . '">';
  4252. }
  4253. $out .= trim($obj->label);
  4254. if ($showcurrency) {
  4255. $out .= ' (' . $obj->currency_code . ')';
  4256. }
  4257. if ($status == 2 && $obj->status == 1) {
  4258. $out .= ' (' . $langs->trans("Closed") . ')';
  4259. }
  4260. $out .= '</option>';
  4261. $i++;
  4262. }
  4263. $out .= "</select>";
  4264. $out .= ajax_combobox('select' . $htmlname);
  4265. } else {
  4266. if ($status == 0) {
  4267. $out .= '<span class="opacitymedium">' . $langs->trans("NoActiveBankAccountDefined") . '</span>';
  4268. } else {
  4269. $out .= '<span class="opacitymedium">' . $langs->trans("NoBankAccountFound") . '</span>';
  4270. }
  4271. }
  4272. } else {
  4273. dol_print_error($this->db);
  4274. }
  4275. // Output or return
  4276. if (empty($nooutput)) {
  4277. print $out;
  4278. } else {
  4279. return $out;
  4280. }
  4281. return $num;
  4282. }
  4283. /**
  4284. * Return a HTML select list of establishment
  4285. *
  4286. * @param string $selected Id establishment pre-selected
  4287. * @param string $htmlname Name of select zone
  4288. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4289. * @param string $filtre To filter list. This parameter must not come from input of users
  4290. * @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.
  4291. * @param string $moreattrib To add more attribute on select
  4292. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4293. */
  4294. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4295. {
  4296. global $langs, $conf;
  4297. $langs->load("admin");
  4298. $num = 0;
  4299. $sql = "SELECT rowid, name, fk_country, status, entity";
  4300. $sql .= " FROM " . $this->db->prefix() . "establishment";
  4301. $sql .= " WHERE 1=1";
  4302. if ($status != 2) {
  4303. $sql .= " AND status = " . (int) $status;
  4304. }
  4305. if ($filtre) {
  4306. $sql .= " AND " . $filtre;
  4307. }
  4308. $sql .= " ORDER BY name";
  4309. dol_syslog(get_class($this) . "::select_establishment", LOG_DEBUG);
  4310. $result = $this->db->query($sql);
  4311. if ($result) {
  4312. $num = $this->db->num_rows($result);
  4313. $i = 0;
  4314. if ($num) {
  4315. print '<select id="select' . $htmlname . '" class="flat selectestablishment" name="' . $htmlname . '"' . ($moreattrib ? ' ' . $moreattrib : '') . '>';
  4316. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4317. print '<option value="-1">&nbsp;</option>';
  4318. }
  4319. while ($i < $num) {
  4320. $obj = $this->db->fetch_object($result);
  4321. if ($selected == $obj->rowid) {
  4322. print '<option value="' . $obj->rowid . '" selected>';
  4323. } else {
  4324. print '<option value="' . $obj->rowid . '">';
  4325. }
  4326. print trim($obj->name);
  4327. if ($status == 2 && $obj->status == 1) {
  4328. print ' (' . $langs->trans("Closed") . ')';
  4329. }
  4330. print '</option>';
  4331. $i++;
  4332. }
  4333. print "</select>";
  4334. } else {
  4335. if ($status == 0) {
  4336. print '<span class="opacitymedium">' . $langs->trans("NoActiveEstablishmentDefined") . '</span>';
  4337. } else {
  4338. print '<span class="opacitymedium">' . $langs->trans("NoEstablishmentFound") . '</span>';
  4339. }
  4340. }
  4341. } else {
  4342. dol_print_error($this->db);
  4343. }
  4344. }
  4345. /**
  4346. * Display form to select bank account
  4347. *
  4348. * @param string $page Page
  4349. * @param int $selected Id of bank account
  4350. * @param string $htmlname Name of select html field
  4351. * @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.
  4352. * @return void
  4353. */
  4354. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4355. {
  4356. global $langs;
  4357. if ($htmlname != "none") {
  4358. print '<form method="POST" action="' . $page . '">';
  4359. print '<input type="hidden" name="action" value="setbankaccount">';
  4360. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4361. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4362. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4363. if ($nbaccountfound > 0) {
  4364. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  4365. }
  4366. print '</form>';
  4367. } else {
  4368. $langs->load('banks');
  4369. if ($selected) {
  4370. require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
  4371. $bankstatic = new Account($this->db);
  4372. $result = $bankstatic->fetch($selected);
  4373. if ($result) {
  4374. print $bankstatic->getNomUrl(1);
  4375. }
  4376. } else {
  4377. print "&nbsp;";
  4378. }
  4379. }
  4380. }
  4381. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4382. /**
  4383. * Return list of categories having choosed type
  4384. *
  4385. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4386. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4387. * @param string $htmlname HTML field name
  4388. * @param int $maxlength Maximum length for labels
  4389. * @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.
  4390. * $markafterid can be an :
  4391. * - int (id of category)
  4392. * - string (categories ids seprated by comma)
  4393. * - array (list of categories ids)
  4394. * @param int $outputmode 0=HTML select string, 1=Array, 2=Array extended
  4395. * @param int $include [=0] Removed or 1=Keep only
  4396. * @param string $morecss More CSS
  4397. * @return string|array
  4398. * @see select_categories()
  4399. */
  4400. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4401. {
  4402. // phpcs:enable
  4403. global $conf, $langs;
  4404. $langs->load("categories");
  4405. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  4406. // For backward compatibility
  4407. if (is_numeric($type)) {
  4408. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4409. }
  4410. if ($type === Categorie::TYPE_BANK_LINE) {
  4411. // TODO Move this into common category feature
  4412. $cate_arbo = array();
  4413. $sql = "SELECT c.label, c.rowid";
  4414. $sql .= " FROM " . $this->db->prefix() . "bank_categ as c";
  4415. $sql .= " WHERE entity = " . $conf->entity;
  4416. $sql .= " ORDER BY c.label";
  4417. $result = $this->db->query($sql);
  4418. if ($result) {
  4419. $num = $this->db->num_rows($result);
  4420. $i = 0;
  4421. while ($i < $num) {
  4422. $objp = $this->db->fetch_object($result);
  4423. if ($objp) {
  4424. $cate_arbo[$objp->rowid] = array('id' => $objp->rowid, 'fulllabel' => $objp->label, 'color' => '', 'picto' => 'category');
  4425. }
  4426. $i++;
  4427. }
  4428. $this->db->free($result);
  4429. } else {
  4430. dol_print_error($this->db);
  4431. }
  4432. } else {
  4433. $cat = new Categorie($this->db);
  4434. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4435. }
  4436. $outarray = array();
  4437. $output = '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  4438. if (is_array($cate_arbo)) {
  4439. if (!count($cate_arbo)) {
  4440. $output .= '<option value="-1" disabled>' . $langs->trans("NoCategoriesDefined") . '</option>';
  4441. } else {
  4442. $output .= '<option value="-1">&nbsp;</option>';
  4443. foreach ($cate_arbo as $key => $value) {
  4444. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4445. $add = 'selected ';
  4446. } else {
  4447. $add = '';
  4448. }
  4449. $output .= '<option ' . $add . 'value="' . $cate_arbo[$key]['id'] . '"';
  4450. $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')) . '"';
  4451. $output .= '>';
  4452. $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4453. $output .= '</option>';
  4454. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4455. }
  4456. }
  4457. }
  4458. $output .= '</select>';
  4459. $output .= "\n";
  4460. if ($outputmode == 2) {
  4461. return $cate_arbo;
  4462. } elseif ($outputmode) {
  4463. return $outarray;
  4464. }
  4465. return $output;
  4466. }
  4467. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4468. /**
  4469. * Show a confirmation HTML form or AJAX popup
  4470. *
  4471. * @param string $page Url of page to call if confirmation is OK
  4472. * @param string $title Title
  4473. * @param string $question Question
  4474. * @param string $action Action
  4475. * @param array $formquestion An array with forms complementary inputs
  4476. * @param string $selectedchoice "" or "no" or "yes"
  4477. * @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
  4478. * @param int $height Force height of box
  4479. * @param int $width Force width of box
  4480. * @return void
  4481. * @deprecated
  4482. * @see formconfirm()
  4483. */
  4484. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4485. {
  4486. // phpcs:enable
  4487. dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4488. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4489. }
  4490. /**
  4491. * Show a confirmation HTML form or AJAX popup.
  4492. * Easiest way to use this is with useajax=1.
  4493. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4494. * just after calling this method. For example:
  4495. * print '<script type="text/javascript">'."\n";
  4496. * print 'jQuery(document).ready(function() {'."\n";
  4497. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4498. * print '});'."\n";
  4499. * print '</script>'."\n";
  4500. *
  4501. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4502. * @param string $title Title
  4503. * @param string $question Question
  4504. * @param string $action Action
  4505. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...'))
  4506. * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss',
  4507. * 'other', 'onecolumn' or 'hidden'...
  4508. * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0
  4509. * @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
  4510. * @param int|string $height Force height of box (0 = auto)
  4511. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4512. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4513. * @param string $labelbuttonyes Label for Yes
  4514. * @param string $labelbuttonno Label for No
  4515. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4516. */
  4517. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4518. {
  4519. global $langs, $conf;
  4520. $more = '<!-- formconfirm - before call, page=' . dol_escape_htmltag($page) . ' -->';
  4521. $formconfirm = '';
  4522. $inputok = array();
  4523. $inputko = array();
  4524. // Clean parameters
  4525. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4526. if ($conf->browser->layout == 'phone') {
  4527. $width = '95%';
  4528. }
  4529. // Set height automatically if not defined
  4530. if (empty($height)) {
  4531. $height = 220;
  4532. if (is_array($formquestion) && count($formquestion) > 2) {
  4533. $height += ((count($formquestion) - 2) * 24);
  4534. }
  4535. }
  4536. if (is_array($formquestion) && !empty($formquestion)) {
  4537. // First add hidden fields and value
  4538. foreach ($formquestion as $key => $input) {
  4539. if (is_array($input) && !empty($input)) {
  4540. if ($input['type'] == 'hidden') {
  4541. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4542. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4543. $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";
  4544. }
  4545. }
  4546. }
  4547. // Now add questions
  4548. $moreonecolumn = '';
  4549. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">' . "\n";
  4550. foreach ($formquestion as $key => $input) {
  4551. if (is_array($input) && !empty($input)) {
  4552. $size = (!empty($input['size']) ? ' size="' . $input['size'] . '"' : ''); // deprecated. Use morecss instead.
  4553. $moreattr = (!empty($input['moreattr']) ? ' ' . $input['moreattr'] : '');
  4554. $morecss = (!empty($input['morecss']) ? ' ' . $input['morecss'] : '');
  4555. if ($input['type'] == 'text') {
  4556. $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";
  4557. } elseif ($input['type'] == 'password') {
  4558. $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";
  4559. } elseif ($input['type'] == 'textarea') {
  4560. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4561. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4562. $more .= $input['value'];
  4563. $more .= '</textarea>';
  4564. $more .= '</div></div>'."\n";*/
  4565. $moreonecolumn .= '<div class="margintoponly">';
  4566. $moreonecolumn .= $input['label'] . '<br>';
  4567. $moreonecolumn .= '<textarea name="' . dol_escape_htmltag($input['name']) . '" id="' . dol_escape_htmltag($input['name']) . '" class="' . $morecss . '"' . $moreattr . '>';
  4568. $moreonecolumn .= $input['value'];
  4569. $moreonecolumn .= '</textarea>';
  4570. $moreonecolumn .= '</div>';
  4571. } elseif (in_array($input['type'], ['select', 'multiselect'])) {
  4572. if (empty($morecss)) {
  4573. $morecss = 'minwidth100';
  4574. }
  4575. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4576. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4577. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4578. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4579. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4580. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4581. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4582. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
  4583. if (!empty($input['label'])) {
  4584. $more .= $input['label'] . '</div><div class="tagtd left">';
  4585. }
  4586. if ($input['type'] == 'select') {
  4587. $more .= $this->selectarray($input['name'], $input['values'], !empty($input['default']) ? $input['default'] : '-1', $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4588. } else {
  4589. $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);
  4590. }
  4591. $more .= '</div></div>' . "\n";
  4592. } elseif ($input['type'] == 'checkbox') {
  4593. $more .= '<div class="tagtr">';
  4594. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . ' </div><div class="tagtd">';
  4595. $more .= '<input type="checkbox" class="flat' . ($morecss ? ' ' . $morecss : '') . '" id="' . dol_escape_htmltag($input['name']) . '" name="' . dol_escape_htmltag($input['name']) . '"' . $moreattr;
  4596. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4597. $more .= ' checked';
  4598. }
  4599. if (is_bool($input['value']) && $input['value']) {
  4600. $more .= ' checked';
  4601. }
  4602. if (isset($input['disabled'])) {
  4603. $more .= ' disabled';
  4604. }
  4605. $more .= ' /></div>';
  4606. $more .= '</div>' . "\n";
  4607. } elseif ($input['type'] == 'radio') {
  4608. $i = 0;
  4609. foreach ($input['values'] as $selkey => $selval) {
  4610. $more .= '<div class="tagtr">';
  4611. if (isset($input['label'])) {
  4612. if ($i == 0) {
  4613. $more .= '<div class="tagtd' . (empty($input['tdclass']) ? ' tdtop' : (' tdtop ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4614. } else {
  4615. $more .= '<div clas="tagtd' . (empty($input['tdclass']) ? '' : (' "' . $input['tdclass'])) . '">&nbsp;</div>';
  4616. }
  4617. }
  4618. $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;
  4619. if (!empty($input['disabled'])) {
  4620. $more .= ' disabled';
  4621. }
  4622. if (isset($input['default']) && $input['default'] === $selkey) {
  4623. $more .= ' checked="checked"';
  4624. }
  4625. $more .= ' /> ';
  4626. $more .= '<label for="' . dol_escape_htmltag($input['name'] . $selkey) . '" class="valignmiddle">' . $selval . '</label>';
  4627. $more .= '</div></div>' . "\n";
  4628. $i++;
  4629. }
  4630. } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
  4631. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">' . $input['label'] . '</div>';
  4632. $more .= '<div class="tagtd">';
  4633. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4634. $more .= $this->selectDate($input['value'], $input['name'], ($input['type'] == 'datetime' ? 1 : 0), ($input['type'] == 'datetime' ? 1 : 0), 0, '', 1, $addnowlink);
  4635. $more .= '</div></div>' . "\n";
  4636. $formquestion[] = array('name' => $input['name'] . 'day');
  4637. $formquestion[] = array('name' => $input['name'] . 'month');
  4638. $formquestion[] = array('name' => $input['name'] . 'year');
  4639. $formquestion[] = array('name' => $input['name'] . 'hour');
  4640. $formquestion[] = array('name' => $input['name'] . 'min');
  4641. } elseif ($input['type'] == 'other') {
  4642. $more .= '<div class="tagtr"><div class="tagtd' . (empty($input['tdclass']) ? '' : (' ' . $input['tdclass'])) . '">';
  4643. if (!empty($input['label'])) {
  4644. $more .= $input['label'] . '</div><div class="tagtd">';
  4645. }
  4646. $more .= $input['value'];
  4647. $more .= '</div></div>' . "\n";
  4648. } elseif ($input['type'] == 'onecolumn') {
  4649. $moreonecolumn .= '<div class="margintoponly">';
  4650. $moreonecolumn .= $input['value'];
  4651. $moreonecolumn .= '</div>' . "\n";
  4652. } elseif ($input['type'] == 'hidden') {
  4653. // Do nothing more, already added by a previous loop
  4654. } elseif ($input['type'] == 'separator') {
  4655. $more .= '<br>';
  4656. } else {
  4657. $more .= 'Error type ' . $input['type'] . ' for the confirm box is not a supported type';
  4658. }
  4659. }
  4660. }
  4661. $more .= '</div>' . "\n";
  4662. $more .= $moreonecolumn;
  4663. }
  4664. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4665. // 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
  4666. // See page product/card.php for example
  4667. if (!empty($conf->dol_use_jmobile)) {
  4668. $useajax = 0;
  4669. }
  4670. if (empty($conf->use_javascript_ajax)) {
  4671. $useajax = 0;
  4672. }
  4673. if ($useajax) {
  4674. $autoOpen = true;
  4675. $dialogconfirm = 'dialog-confirm';
  4676. $button = '';
  4677. if (!is_numeric($useajax)) {
  4678. $button = $useajax;
  4679. $useajax = 1;
  4680. $autoOpen = false;
  4681. $dialogconfirm .= '-' . $button;
  4682. }
  4683. $pageyes = $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=yes';
  4684. $pageno = ($useajax == 2 ? $page . (preg_match('/\?/', $page) ? '&' : '?') . 'action=' . urlencode($action) . '&confirm=no' : '');
  4685. // Add input fields into list of fields to read during submit (inputok and inputko)
  4686. if (is_array($formquestion)) {
  4687. foreach ($formquestion as $key => $input) {
  4688. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4689. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4690. if (is_array($input) && isset($input['name'])) {
  4691. if (strpos($input['name'], ',') > 0) {
  4692. $inputok = array_merge($inputok, explode(',', $input['name']));
  4693. } else {
  4694. array_push($inputok, $input['name']);
  4695. }
  4696. }
  4697. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4698. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4699. array_push($inputko, $input['name']);
  4700. }
  4701. }
  4702. }
  4703. // Show JQuery confirm box.
  4704. $formconfirm .= '<div id="' . $dialogconfirm . '" title="' . dol_escape_htmltag($title) . '" style="display: none;">';
  4705. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4706. $formconfirm .= '<div class="confirmtext">' . $formquestion['text'] . '</div>' . "\n";
  4707. }
  4708. if (!empty($more)) {
  4709. $formconfirm .= '<div class="confirmquestions">' . $more . '</div>' . "\n";
  4710. }
  4711. $formconfirm .= ($question ? '<div class="confirmmessage">' . img_help('', '') . ' ' . $question . '</div>' : '');
  4712. $formconfirm .= '</div>' . "\n";
  4713. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=" . $page . " -->\n";
  4714. $formconfirm .= '<script type="text/javascript">' . "\n";
  4715. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4716. $formconfirm .= 'jQuery(document).ready(function() {
  4717. $(function() {
  4718. $( "#' . $dialogconfirm . '" ).dialog(
  4719. {
  4720. autoOpen: ' . ($autoOpen ? "true" : "false") . ',';
  4721. if ($newselectedchoice == 'no') {
  4722. $formconfirm .= '
  4723. open: function() {
  4724. $(this).parent().find("button.ui-button:eq(2)").focus();
  4725. },';
  4726. }
  4727. $jsforcursor = '';
  4728. if ($useajax == 1) {
  4729. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor' . "\n";
  4730. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");' . "\n";
  4731. }
  4732. $postconfirmas = 'GET';
  4733. $formconfirm .= '
  4734. resizable: false,
  4735. height: "' . $height . '",
  4736. width: "' . $width . '",
  4737. modal: true,
  4738. closeOnEscape: false,
  4739. buttons: {
  4740. "' . dol_escape_js($langs->transnoentities($labelbuttonyes)) . '": function() {
  4741. var options = "token=' . urlencode(newToken()) . '";
  4742. var inputok = ' . json_encode($inputok) . '; /* List of fields into form */
  4743. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4744. var pageyes = "' . dol_escape_js(!empty($pageyes) ? $pageyes : '') . '";
  4745. if (inputok.length > 0) {
  4746. $.each(inputok, function(i, inputname) {
  4747. var more = "";
  4748. var inputvalue;
  4749. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4750. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4751. } else {
  4752. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4753. inputvalue = $("#" + inputname + more).val();
  4754. }
  4755. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4756. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4757. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4758. });
  4759. }
  4760. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
  4761. if (pageyes.length > 0) {';
  4762. if ($postconfirmas == 'GET') {
  4763. $formconfirm .= 'location.href = urljump;';
  4764. } else {
  4765. $formconfirm .= $jsforcursor;
  4766. $formconfirm .= 'var post = $.post(
  4767. pageyes,
  4768. options,
  4769. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4770. );';
  4771. }
  4772. $formconfirm .= '
  4773. console.log("after post ok");
  4774. }
  4775. $(this).dialog("close");
  4776. },
  4777. "' . dol_escape_js($langs->transnoentities($labelbuttonno)) . '": function() {
  4778. var options = "token=' . urlencode(newToken()) . '";
  4779. var inputko = ' . json_encode($inputko) . '; /* List of fields into form */
  4780. var page = "' . dol_escape_js(!empty($page) ? $page : '') . '";
  4781. var pageno="' . dol_escape_js(!empty($pageno) ? $pageno : '') . '";
  4782. if (inputko.length > 0) {
  4783. $.each(inputko, function(i, inputname) {
  4784. var more = "";
  4785. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4786. var inputvalue = $("#" + inputname + more).val();
  4787. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4788. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4789. });
  4790. }
  4791. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
  4792. //alert(urljump);
  4793. if (pageno.length > 0) {';
  4794. if ($postconfirmas == 'GET') {
  4795. $formconfirm .= 'location.href = urljump;';
  4796. } else {
  4797. $formconfirm .= $jsforcursor;
  4798. $formconfirm .= 'var post = $.post(
  4799. pageno,
  4800. options,
  4801. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4802. );';
  4803. }
  4804. $formconfirm .= '
  4805. console.log("after post ko");
  4806. }
  4807. $(this).dialog("close");
  4808. }
  4809. }
  4810. }
  4811. );
  4812. var button = "' . $button . '";
  4813. if (button.length > 0) {
  4814. $( "#" + button ).click(function() {
  4815. $("#' . $dialogconfirm . '").dialog("open");
  4816. });
  4817. }
  4818. });
  4819. });
  4820. </script>';
  4821. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4822. } else {
  4823. $formconfirm .= "\n<!-- begin formconfirm page=" . dol_escape_htmltag($page) . " -->\n";
  4824. if (empty($disableformtag)) {
  4825. $formconfirm .= '<form method="POST" action="' . $page . '" class="notoptoleftroright">' . "\n";
  4826. }
  4827. $formconfirm .= '<input type="hidden" name="action" value="' . $action . '">' . "\n";
  4828. $formconfirm .= '<input type="hidden" name="token" value="' . newToken() . '">' . "\n";
  4829. $formconfirm .= '<table class="valid centpercent">' . "\n";
  4830. // Line title
  4831. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4832. $formconfirm .= img_picto('', 'pictoconfirm') . ' ' . $title;
  4833. $formconfirm .= '</td></tr>' . "\n";
  4834. // Line text
  4835. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4836. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . $formquestion['text'] . '</td></tr>' . "\n";
  4837. }
  4838. // Line form fields
  4839. if ($more) {
  4840. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">' . "\n";
  4841. $formconfirm .= $more;
  4842. $formconfirm .= '</td></tr>' . "\n";
  4843. }
  4844. // Line with question
  4845. $formconfirm .= '<tr class="valid">';
  4846. $formconfirm .= '<td class="valid">' . $question . '</td>';
  4847. $formconfirm .= '<td class="valid center">';
  4848. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  4849. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="' . $langs->trans("Validate") . '">';
  4850. $formconfirm .= '</td>';
  4851. $formconfirm .= '</tr>' . "\n";
  4852. $formconfirm .= '</table>' . "\n";
  4853. if (empty($disableformtag)) {
  4854. $formconfirm .= "</form>\n";
  4855. }
  4856. $formconfirm .= '<br>';
  4857. if (!empty($conf->use_javascript_ajax)) {
  4858. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4859. $formconfirm .= '<script type="text/javascript">' . "\n";
  4860. $formconfirm .= '
  4861. $(document).ready(function () {
  4862. $(".confirmvalidatebutton").on("click", function() {
  4863. console.log("We click on button");
  4864. $(this).attr("disabled", "disabled");
  4865. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4866. //console.log($(this).closest("form"));
  4867. $(this).closest("form").submit();
  4868. });
  4869. });
  4870. ';
  4871. $formconfirm .= '</script>' . "\n";
  4872. }
  4873. $formconfirm .= "<!-- end formconfirm -->\n";
  4874. }
  4875. return $formconfirm;
  4876. }
  4877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4878. /**
  4879. * Show a form to select a project
  4880. *
  4881. * @param int $page Page
  4882. * @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)
  4883. * @param int $selected Id pre-selected project
  4884. * @param string $htmlname Name of select field
  4885. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4886. * @param int $maxlength Max length
  4887. * @param int $forcefocus Force focus on field (works with javascript only)
  4888. * @param int $nooutput No print is done. String is returned.
  4889. * @param string $textifnoproject Text to show if no project
  4890. * @param string $morecss More CSS
  4891. * @return string Return html content
  4892. */
  4893. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
  4894. {
  4895. // phpcs:enable
  4896. global $langs;
  4897. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  4898. require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
  4899. $out = '';
  4900. $formproject = new FormProjets($this->db);
  4901. $langs->load("project");
  4902. if ($htmlname != "none") {
  4903. $out .= '<form method="post" action="' . $page . '">';
  4904. $out .= '<input type="hidden" name="action" value="classin">';
  4905. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  4906. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
  4907. $out .= '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  4908. $out .= '</form>';
  4909. } else {
  4910. $out .= '<span class="project_head_block">';
  4911. if ($selected) {
  4912. $projet = new Project($this->db);
  4913. $projet->fetch($selected);
  4914. $out .= $projet->getNomUrl(0, '', 1);
  4915. } else {
  4916. $out .= '<span class="opacitymedium">' . $textifnoproject . '</span>';
  4917. }
  4918. $out .= '</span>';
  4919. }
  4920. if (empty($nooutput)) {
  4921. print $out;
  4922. return '';
  4923. }
  4924. return $out;
  4925. }
  4926. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4927. /**
  4928. * Show a form to select payment conditions
  4929. *
  4930. * @param int $page Page
  4931. * @param string $selected Id condition pre-selectionne
  4932. * @param string $htmlname Name of select html field
  4933. * @param int $addempty Add empty entry
  4934. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4935. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  4936. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  4937. * 0 : use default deposit percentage from entry
  4938. * > 0 : force deposit percentage (for example, from company object)
  4939. * @param int $nooutput No print is done. String is returned.
  4940. * @return void
  4941. */
  4942. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
  4943. {
  4944. // phpcs:enable
  4945. global $langs;
  4946. $out = '';
  4947. if ($htmlname != "none") {
  4948. $out .= '<form method="POST" action="' . $page . '">';
  4949. $out .= '<input type="hidden" name="action" value="setconditions">';
  4950. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  4951. if ($type) {
  4952. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  4953. }
  4954. $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  4955. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  4956. $out .= '</form>';
  4957. } else {
  4958. if ($selected) {
  4959. $this->load_cache_conditions_paiements();
  4960. if (isset($this->cache_conditions_paiements[$selected])) {
  4961. $label = $this->cache_conditions_paiements[$selected]['label'];
  4962. if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  4963. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  4964. }
  4965. $out .= $label;
  4966. } else {
  4967. $langs->load('errors');
  4968. $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4969. }
  4970. } else {
  4971. $out .= '&nbsp;';
  4972. }
  4973. }
  4974. if (empty($nooutput)) {
  4975. print $out;
  4976. return '';
  4977. }
  4978. return $out;
  4979. }
  4980. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4981. /**
  4982. * Show a form to select a delivery delay
  4983. *
  4984. * @param int $page Page
  4985. * @param string $selected Id condition pre-selectionne
  4986. * @param string $htmlname Name of select html field
  4987. * @param int $addempty Ajoute entree vide
  4988. * @return void
  4989. */
  4990. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4991. {
  4992. // phpcs:enable
  4993. global $langs;
  4994. if ($htmlname != "none") {
  4995. print '<form method="post" action="' . $page . '">';
  4996. print '<input type="hidden" name="action" value="setavailability">';
  4997. print '<input type="hidden" name="token" value="' . newToken() . '">';
  4998. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4999. print '<input type="submit" name="modify" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5000. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="' . $langs->trans("Cancel") . '">';
  5001. print '</form>';
  5002. } else {
  5003. if ($selected) {
  5004. $this->load_cache_availability();
  5005. print $this->cache_availability[$selected]['label'];
  5006. } else {
  5007. print "&nbsp;";
  5008. }
  5009. }
  5010. }
  5011. /**
  5012. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  5013. * List found into table c_input_reason loaded by loadCacheInputReason
  5014. *
  5015. * @param string $page Page
  5016. * @param string $selected Id condition pre-selectionne
  5017. * @param string $htmlname Name of select html field
  5018. * @param int $addempty Add empty entry
  5019. * @return void
  5020. */
  5021. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  5022. {
  5023. global $langs;
  5024. if ($htmlname != "none") {
  5025. print '<form method="post" action="' . $page . '">';
  5026. print '<input type="hidden" name="action" value="setdemandreason">';
  5027. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5028. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  5029. print '<input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '">';
  5030. print '</form>';
  5031. } else {
  5032. if ($selected) {
  5033. $this->loadCacheInputReason();
  5034. foreach ($this->cache_demand_reason as $key => $val) {
  5035. if ($val['id'] == $selected) {
  5036. print $val['label'];
  5037. break;
  5038. }
  5039. }
  5040. } else {
  5041. print "&nbsp;";
  5042. }
  5043. }
  5044. }
  5045. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5046. /**
  5047. * Show a form + html select a date
  5048. *
  5049. * @param string $page Page
  5050. * @param string $selected Date preselected
  5051. * @param string $htmlname Html name of date input fields or 'none'
  5052. * @param int $displayhour Display hour selector
  5053. * @param int $displaymin Display minutes selector
  5054. * @param int $nooutput 1=No print output, return string
  5055. * @param string $type 'direct-debit' or 'bank-transfer'
  5056. * @return string
  5057. * @see selectDate()
  5058. */
  5059. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  5060. {
  5061. // phpcs:enable
  5062. global $langs;
  5063. $ret = '';
  5064. if ($htmlname != "none") {
  5065. $ret .= '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5066. $ret .= '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5067. $ret .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5068. if ($type) {
  5069. $ret .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5070. }
  5071. $ret .= '<table class="nobordernopadding">';
  5072. $ret .= '<tr><td>';
  5073. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form' . $htmlname, 1, 0);
  5074. $ret .= '</td>';
  5075. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5076. $ret .= '</tr></table></form>';
  5077. } else {
  5078. if ($displayhour) {
  5079. $ret .= dol_print_date($selected, 'dayhour');
  5080. } else {
  5081. $ret .= dol_print_date($selected, 'day');
  5082. }
  5083. }
  5084. if (empty($nooutput)) {
  5085. print $ret;
  5086. }
  5087. return $ret;
  5088. }
  5089. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5090. /**
  5091. * Show a select form to choose a user
  5092. *
  5093. * @param string $page Page
  5094. * @param string $selected Id of user preselected
  5095. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  5096. * @param array $exclude List of users id to exclude
  5097. * @param array $include List of users id to include
  5098. * @return void
  5099. */
  5100. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  5101. {
  5102. // phpcs:enable
  5103. global $langs;
  5104. if ($htmlname != "none") {
  5105. print '<form method="POST" action="' . $page . '" name="form' . $htmlname . '">';
  5106. print '<input type="hidden" name="action" value="set' . $htmlname . '">';
  5107. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5108. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5109. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5110. print '</form>';
  5111. } else {
  5112. if ($selected) {
  5113. require_once DOL_DOCUMENT_ROOT . '/user/class/user.class.php';
  5114. $theuser = new User($this->db);
  5115. $theuser->fetch($selected);
  5116. print $theuser->getNomUrl(1);
  5117. } else {
  5118. print "&nbsp;";
  5119. }
  5120. }
  5121. }
  5122. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5123. /**
  5124. * Show form with payment mode
  5125. *
  5126. * @param string $page Page
  5127. * @param int $selected Id mode pre-selectionne
  5128. * @param string $htmlname Name of select html field
  5129. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5130. * @param int $active Active or not, -1 = all
  5131. * @param int $addempty 1=Add empty entry
  5132. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5133. * @param int $nooutput 1=Return string, no output
  5134. * @return void
  5135. */
  5136. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
  5137. {
  5138. // phpcs:enable
  5139. global $langs;
  5140. $out = '';
  5141. if ($htmlname != "none") {
  5142. $out .= '<form method="POST" action="' . $page . '">';
  5143. $out .= '<input type="hidden" name="action" value="setmode">';
  5144. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5145. if ($type) {
  5146. $out .= '<input type="hidden" name="type" value="' . dol_escape_htmltag($type) . '">';
  5147. }
  5148. $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5149. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5150. $out .= '</form>';
  5151. } else {
  5152. if ($selected) {
  5153. $this->load_cache_types_paiements();
  5154. $out .= $this->cache_types_paiements[$selected]['label'];
  5155. } else {
  5156. $out .= "&nbsp;";
  5157. }
  5158. }
  5159. if ($nooutput) {
  5160. return $out;
  5161. } else {
  5162. print $out;
  5163. }
  5164. }
  5165. /**
  5166. * Show form with transport mode
  5167. *
  5168. * @param string $page Page
  5169. * @param int $selected Id mode pre-select
  5170. * @param string $htmlname Name of select html field
  5171. * @param int $active Active or not, -1 = all
  5172. * @param int $addempty 1=Add empty entry
  5173. * @return void
  5174. */
  5175. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5176. {
  5177. global $langs;
  5178. if ($htmlname != "none") {
  5179. print '<form method="POST" action="' . $page . '">';
  5180. print '<input type="hidden" name="action" value="settransportmode">';
  5181. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5182. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5183. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5184. print '</form>';
  5185. } else {
  5186. if ($selected) {
  5187. $this->load_cache_transport_mode();
  5188. print $this->cache_transport_mode[$selected]['label'];
  5189. } else {
  5190. print "&nbsp;";
  5191. }
  5192. }
  5193. }
  5194. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5195. /**
  5196. * Show form with multicurrency code
  5197. *
  5198. * @param string $page Page
  5199. * @param string $selected code pre-selectionne
  5200. * @param string $htmlname Name of select html field
  5201. * @return void
  5202. */
  5203. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5204. {
  5205. // phpcs:enable
  5206. global $langs;
  5207. if ($htmlname != "none") {
  5208. print '<form method="POST" action="' . $page . '">';
  5209. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5210. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5211. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5212. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5213. print '</form>';
  5214. } else {
  5215. dol_include_once('/core/lib/company.lib.php');
  5216. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5217. }
  5218. }
  5219. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5220. /**
  5221. * Show form with multicurrency rate
  5222. *
  5223. * @param string $page Page
  5224. * @param double $rate Current rate
  5225. * @param string $htmlname Name of select html field
  5226. * @param string $currency Currency code to explain the rate
  5227. * @return void
  5228. */
  5229. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5230. {
  5231. // phpcs:enable
  5232. global $langs, $mysoc, $conf;
  5233. if ($htmlname != "none") {
  5234. print '<form method="POST" action="' . $page . '">';
  5235. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5236. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5237. print '<input type="text" class="maxwidth100" name="' . $htmlname . '" value="' . (!empty($rate) ? price(price2num($rate, 'CU')) : 1) . '" /> ';
  5238. print '<select name="calculation_mode">';
  5239. print '<option value="1">Change ' . $langs->trans("PriceUHT") . ' of lines</option>';
  5240. print '<option value="2">Change ' . $langs->trans("PriceUHTCurrency") . ' of lines</option>';
  5241. print '</select> ';
  5242. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5243. print '</form>';
  5244. } else {
  5245. if (!empty($rate)) {
  5246. print price($rate, 1, $langs, 1, 0);
  5247. if ($currency && $rate != 1) {
  5248. print ' &nbsp; (' . price($rate, 1, $langs, 1, 0) . ' ' . $currency . ' = 1 ' . $conf->currency . ')';
  5249. }
  5250. } else {
  5251. print 1;
  5252. }
  5253. }
  5254. }
  5255. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5256. /**
  5257. * Show a select box with available absolute discounts
  5258. *
  5259. * @param string $page Page URL where form is shown
  5260. * @param int $selected Value pre-selected
  5261. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5262. * @param int $socid Third party id
  5263. * @param float $amount Total amount available
  5264. * @param string $filter SQL filter on discounts
  5265. * @param int $maxvalue Max value for lines that can be selected
  5266. * @param string $more More string to add
  5267. * @param int $hidelist 1=Hide list
  5268. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5269. * @return void
  5270. */
  5271. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5272. {
  5273. // phpcs:enable
  5274. global $conf, $langs;
  5275. if ($htmlname != "none") {
  5276. print '<form method="post" action="' . $page . '">';
  5277. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5278. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5279. print '<div class="inline-block">';
  5280. if (!empty($discount_type)) {
  5281. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5282. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5283. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5284. } else {
  5285. $translationKey = 'HasCreditNoteFromSupplier';
  5286. }
  5287. } else {
  5288. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5289. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5290. } else {
  5291. $translationKey = 'HasCreditNoteFromSupplier';
  5292. }
  5293. }
  5294. } else {
  5295. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5296. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5297. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5298. } else {
  5299. $translationKey = 'CompanyHasCreditNote';
  5300. }
  5301. } else {
  5302. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5303. $translationKey = 'CompanyHasAbsoluteDiscount';
  5304. } else {
  5305. $translationKey = 'CompanyHasCreditNote';
  5306. }
  5307. }
  5308. }
  5309. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5310. if (empty($hidelist)) {
  5311. print ' ';
  5312. }
  5313. print '</div>';
  5314. if (empty($hidelist)) {
  5315. print '<div class="inline-block" style="padding-right: 10px">';
  5316. $newfilter = 'discount_type=' . intval($discount_type);
  5317. if (!empty($discount_type)) {
  5318. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5319. } else {
  5320. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5321. }
  5322. if ($filter) {
  5323. $newfilter .= ' AND (' . $filter . ')';
  5324. }
  5325. // output the combo of discounts
  5326. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5327. if ($nbqualifiedlines > 0) {
  5328. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="' . dol_escape_htmltag($langs->trans("UseLine")) . '"';
  5329. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5330. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5331. }
  5332. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5333. print ' title="' . $langs->trans("UseCreditNoteInInvoicePayment") . '"';
  5334. }
  5335. print '>';
  5336. }
  5337. print '</div>';
  5338. }
  5339. if ($more) {
  5340. print '<div class="inline-block">';
  5341. print $more;
  5342. print '</div>';
  5343. }
  5344. print '</form>';
  5345. } else {
  5346. if ($selected) {
  5347. print $selected;
  5348. } else {
  5349. print "0";
  5350. }
  5351. }
  5352. }
  5353. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5354. /**
  5355. * Show forms to select a contact
  5356. *
  5357. * @param string $page Page
  5358. * @param Societe $societe Filter on third party
  5359. * @param int $selected Id contact pre-selectionne
  5360. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5361. * @return void
  5362. */
  5363. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5364. {
  5365. // phpcs:enable
  5366. global $langs, $conf;
  5367. if ($htmlname != "none") {
  5368. print '<form method="post" action="' . $page . '">';
  5369. print '<input type="hidden" name="action" value="set_contact">';
  5370. print '<input type="hidden" name="token" value="' . newToken() . '">';
  5371. print '<table class="nobordernopadding">';
  5372. print '<tr><td>';
  5373. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5374. $num = $this->num;
  5375. if ($num == 0) {
  5376. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5377. print '<a href="' . DOL_URL_ROOT . '/contact/card.php?socid=' . $societe->id . '&amp;action=create&amp;backtoreferer=1">' . $addcontact . '</a>';
  5378. }
  5379. print '</td>';
  5380. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="' . $langs->trans("Modify") . '"></td>';
  5381. print '</tr></table></form>';
  5382. } else {
  5383. if ($selected) {
  5384. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  5385. $contact = new Contact($this->db);
  5386. $contact->fetch($selected);
  5387. print $contact->getFullName($langs);
  5388. } else {
  5389. print "&nbsp;";
  5390. }
  5391. }
  5392. }
  5393. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5394. /**
  5395. * Output html select to select thirdparty
  5396. *
  5397. * @param string $page Page
  5398. * @param string $selected Id preselected
  5399. * @param string $htmlname Name of HTML select
  5400. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5401. * @param int $showempty Add an empty field
  5402. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5403. * @param int $forcecombo Force to use combo box
  5404. * @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')))
  5405. * @param int $nooutput No print output. Return it only.
  5406. * @param array $excludeids Exclude IDs from the select combo
  5407. * @param string $textifnothirdparty Text to show if no thirdparty
  5408. * @return void|string
  5409. */
  5410. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
  5411. {
  5412. // phpcs:enable
  5413. global $langs;
  5414. $out = '';
  5415. if ($htmlname != "none") {
  5416. $out .= '<form method="post" action="' . $page . '">';
  5417. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5418. $out .= '<input type="hidden" name="token" value="' . newToken() . '">';
  5419. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5420. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans("Modify") . '">';
  5421. $out .= '</form>';
  5422. } else {
  5423. if ($selected) {
  5424. require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  5425. $soc = new Societe($this->db);
  5426. $soc->fetch($selected);
  5427. $out .= $soc->getNomUrl(0, '');
  5428. } else {
  5429. $out .= '<span class="opacitymedium">' . $textifnothirdparty . '</span>';
  5430. }
  5431. }
  5432. if ($nooutput) {
  5433. return $out;
  5434. } else {
  5435. print $out;
  5436. }
  5437. }
  5438. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5439. /**
  5440. * Retourne la liste des devises, dans la langue de l'utilisateur
  5441. *
  5442. * @param string $selected preselected currency code
  5443. * @param string $htmlname name of HTML select list
  5444. * @deprecated
  5445. * @return void
  5446. */
  5447. public function select_currency($selected = '', $htmlname = 'currency_id')
  5448. {
  5449. // phpcs:enable
  5450. print $this->selectCurrency($selected, $htmlname);
  5451. }
  5452. /**
  5453. * Retourne la liste des devises, dans la langue de l'utilisateur
  5454. *
  5455. * @param string $selected preselected currency code
  5456. * @param string $htmlname name of HTML select list
  5457. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5458. * @param string $useempty '1'=Allow empty value
  5459. * @return string
  5460. */
  5461. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5462. {
  5463. global $conf, $langs, $user;
  5464. $langs->loadCacheCurrencies('');
  5465. $out = '';
  5466. if ($selected == 'euro' || $selected == 'euros') {
  5467. $selected = 'EUR'; // Pour compatibilite
  5468. }
  5469. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="' . $htmlname . '" id="' . $htmlname . '">';
  5470. if ($useempty) {
  5471. $out .= '<option value="-1" selected></option>';
  5472. }
  5473. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5474. $labeltoshow = $currency['label'];
  5475. if ($mode == 1) {
  5476. $labeltoshow .= ' <span class="opacitymedium">(' . $code_iso . ')</span>';
  5477. } else {
  5478. $labeltoshow .= ' <span class="opacitymedium">(' . $langs->getCurrencySymbol($code_iso) . ')</span>';
  5479. }
  5480. if ($selected && $selected == $code_iso) {
  5481. $out .= '<option value="' . $code_iso . '" selected data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5482. } else {
  5483. $out .= '<option value="' . $code_iso . '" data-html="' . dol_escape_htmltag($labeltoshow) . '">';
  5484. }
  5485. $out .= $labeltoshow;
  5486. $out .= '</option>';
  5487. }
  5488. $out .= '</select>';
  5489. if ($user->admin) {
  5490. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5491. }
  5492. // Make select dynamic
  5493. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5494. $out .= ajax_combobox($htmlname);
  5495. return $out;
  5496. }
  5497. /**
  5498. * Return array of currencies in user language
  5499. *
  5500. * @param string $selected Preselected currency code
  5501. * @param string $htmlname Name of HTML select list
  5502. * @param integer $useempty 1=Add empty line
  5503. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5504. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5505. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5506. * @param string $morecss More css
  5507. * @return string
  5508. */
  5509. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5510. {
  5511. global $conf, $langs;
  5512. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5513. $TCurrency = array();
  5514. $sql = "SELECT code FROM " . $this->db->prefix() . "multicurrency";
  5515. $sql .= " WHERE entity IN ('" . getEntity('mutlicurrency') . "')";
  5516. if ($filter) {
  5517. $sql .= " AND " . $filter;
  5518. }
  5519. $resql = $this->db->query($sql);
  5520. if ($resql) {
  5521. while ($obj = $this->db->fetch_object($resql)) {
  5522. $TCurrency[$obj->code] = $obj->code;
  5523. }
  5524. }
  5525. $out = '';
  5526. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  5527. if ($useempty) {
  5528. $out .= '<option value="">&nbsp;</option>';
  5529. }
  5530. // If company current currency not in table, we add it into list. Should always be available.
  5531. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5532. $TCurrency[$conf->currency] = $conf->currency;
  5533. }
  5534. if (count($TCurrency) > 0) {
  5535. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5536. if (isset($TCurrency[$code_iso])) {
  5537. if (!empty($selected) && $selected == $code_iso) {
  5538. $out .= '<option value="' . $code_iso . '" selected="selected">';
  5539. } else {
  5540. $out .= '<option value="' . $code_iso . '">';
  5541. }
  5542. $out .= $currency['label'];
  5543. $out .= ' (' . $langs->getCurrencySymbol($code_iso) . ')';
  5544. $out .= '</option>';
  5545. }
  5546. }
  5547. }
  5548. $out .= '</select>';
  5549. // Make select dynamic
  5550. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5551. $out .= ajax_combobox($htmlname);
  5552. return $out;
  5553. }
  5554. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5555. /**
  5556. * Load into the cache vat rates of a country
  5557. *
  5558. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5559. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5560. */
  5561. public function load_cache_vatrates($country_code)
  5562. {
  5563. // phpcs:enable
  5564. global $langs;
  5565. $num = count($this->cache_vatrates);
  5566. if ($num > 0) {
  5567. return $num; // Cache already loaded
  5568. }
  5569. dol_syslog(__METHOD__, LOG_DEBUG);
  5570. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5571. $sql .= " FROM " . $this->db->prefix() . "c_tva as t, " . $this->db->prefix() . "c_country as c";
  5572. $sql .= " WHERE t.fk_pays = c.rowid";
  5573. $sql .= " AND t.active > 0";
  5574. $sql .= " AND c.code IN (" . $this->db->sanitize($country_code, 1) . ")";
  5575. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5576. $resql = $this->db->query($sql);
  5577. if ($resql) {
  5578. $num = $this->db->num_rows($resql);
  5579. if ($num) {
  5580. for ($i = 0; $i < $num; $i++) {
  5581. $obj = $this->db->fetch_object($resql);
  5582. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5583. $this->cache_vatrates[$i]['code'] = $obj->code;
  5584. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5585. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5586. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5587. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5588. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5589. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5590. $this->cache_vatrates[$i]['label'] = $obj->taux . '%' . ($obj->code ? ' (' . $obj->code . ')' : ''); // Label must contains only 0-9 , . % or *
  5591. $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
  5592. $positiverates = '';
  5593. if ($obj->taux) {
  5594. $positiverates .= ($positiverates ? '/' : '') . $obj->taux;
  5595. }
  5596. if ($obj->localtax1) {
  5597. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax1;
  5598. }
  5599. if ($obj->localtax2) {
  5600. $positiverates .= ($positiverates ? '/' : '') . $obj->localtax2;
  5601. }
  5602. if (empty($positiverates)) {
  5603. $positiverates = '0';
  5604. }
  5605. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates . ($obj->code ? ' (' . $obj->code . ')' : ''); // Must never be used as key, only label
  5606. }
  5607. return $num;
  5608. } else {
  5609. $this->error = '<span class="error">' . $langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code) . '</span>';
  5610. return -1;
  5611. }
  5612. } else {
  5613. $this->error = '<span class="error">' . $this->db->error() . '</span>';
  5614. return -2;
  5615. }
  5616. }
  5617. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5618. /**
  5619. * Output an HTML select vat rate.
  5620. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5621. *
  5622. * @param string $htmlname Name of HTML select field
  5623. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5624. * @param Societe $societe_vendeuse Thirdparty seller
  5625. * @param Societe $societe_acheteuse Thirdparty buyer
  5626. * @param int $idprod Id product. O if unknown of NA.
  5627. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5628. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5629. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5630. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5631. * 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.
  5632. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5633. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5634. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5635. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5636. * @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
  5637. * @return string
  5638. */
  5639. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5640. {
  5641. // phpcs:enable
  5642. global $langs, $conf, $mysoc;
  5643. $langs->load('errors');
  5644. $return = '';
  5645. // Define defaultnpr, defaultttx and defaultcode
  5646. $defaultnpr = ($info_bits & 0x01);
  5647. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5648. $defaulttx = str_replace('*', '', $selectedrate);
  5649. $defaultcode = '';
  5650. $reg = array();
  5651. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5652. $defaultcode = $reg[1];
  5653. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5654. }
  5655. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5656. // Check parameters
  5657. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5658. if ($societe_vendeuse->id == $mysoc->id) {
  5659. $return .= '<span class="error">' . $langs->trans("ErrorYourCountryIsNotDefined") . '</span>';
  5660. } else {
  5661. $return .= '<span class="error">' . $langs->trans("ErrorSupplierCountryIsNotDefined") . '</span>';
  5662. }
  5663. return $return;
  5664. }
  5665. //var_dump($societe_acheteuse);
  5666. //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";
  5667. //exit;
  5668. // Define list of countries to use to search VAT rates to show
  5669. // First we defined code_country to use to find list
  5670. if (is_object($societe_vendeuse)) {
  5671. $code_country = "'" . $societe_vendeuse->country_code . "'";
  5672. } else {
  5673. $code_country = "'" . $mysoc->country_code . "'"; // Pour compatibilite ascendente
  5674. }
  5675. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5676. require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
  5677. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5678. // We also add the buyer country code
  5679. if (is_numeric($type)) {
  5680. if ($type == 1) { // We know product is a service
  5681. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5682. }
  5683. } elseif (!$idprod) { // We don't know type of product
  5684. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5685. } else {
  5686. $prodstatic = new Product($this->db);
  5687. $prodstatic->fetch($idprod);
  5688. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5689. $code_country .= ",'" . $societe_acheteuse->country_code . "'";
  5690. }
  5691. }
  5692. }
  5693. }
  5694. // Now we get list
  5695. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5696. if ($num > 0) {
  5697. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5698. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5699. $tmpthirdparty = new Societe($this->db);
  5700. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5701. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5702. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5703. $defaultcode = $reg[1];
  5704. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5705. }
  5706. if (empty($defaulttx)) {
  5707. $defaultnpr = 0;
  5708. }
  5709. }
  5710. // If we fails to find a default vat rate, we take the last one in list
  5711. // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
  5712. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5713. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5714. // We take the last one found in list
  5715. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5716. } else {
  5717. // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
  5718. $defaulttx = '';
  5719. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5720. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5721. }
  5722. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5723. $defaultcode = $reg[1];
  5724. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5725. }
  5726. }
  5727. }
  5728. // Disabled if seller is not subject to VAT
  5729. $disabled = false;
  5730. $title = '';
  5731. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5732. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5733. // of using supplier invoices (this is a very bad idea !)
  5734. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5735. $title = ' title="' . dol_escape_htmltag($langs->trans('VATIsNotUsed')) . '"';
  5736. $disabled = true;
  5737. }
  5738. }
  5739. if (!$options_only) {
  5740. $return .= '<select class="flat minwidth50imp maxwidth100" id="' . $htmlname . '" name="' . $htmlname . '"' . ($disabled ? ' disabled' : '') . $title . '>';
  5741. }
  5742. $selectedfound = false;
  5743. foreach ($this->cache_vatrates as $rate) {
  5744. // Keep only 0 if seller is not subject to VAT
  5745. if ($disabled && $rate['txtva'] != 0) {
  5746. continue;
  5747. }
  5748. // Define key to use into select list
  5749. $key = $rate['txtva'];
  5750. $key .= $rate['nprtva'] ? '*' : '';
  5751. if ($mode > 0 && $rate['code']) {
  5752. $key .= ' (' . $rate['code'] . ')';
  5753. }
  5754. if ($mode < 0) {
  5755. $key = $rate['rowid'];
  5756. }
  5757. $return .= '<option value="' . $key . '"';
  5758. if (!$selectedfound) {
  5759. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5760. if ($defaultcode == $rate['code']) {
  5761. $return .= ' selected';
  5762. $selectedfound = true;
  5763. }
  5764. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5765. $return .= ' selected';
  5766. $selectedfound = true;
  5767. }
  5768. }
  5769. $return .= '>';
  5770. // Show label of VAT
  5771. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5772. // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
  5773. $return .= $rate['labelpositiverates'];
  5774. } else {
  5775. // Simple label
  5776. $return .= vatrate($rate['label']);
  5777. }
  5778. //$return.=($rate['code']?' '.$rate['code']:'');
  5779. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5780. $return .= '</option>';
  5781. }
  5782. if (!$options_only) {
  5783. $return .= '</select>';
  5784. //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
  5785. }
  5786. } else {
  5787. $return .= $this->error;
  5788. }
  5789. $this->num = $num;
  5790. return $return;
  5791. }
  5792. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5793. /**
  5794. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5795. * Fields are preselected with :
  5796. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5797. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5798. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5799. *
  5800. * @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).
  5801. * @param string $prefix Prefix for fields name
  5802. * @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
  5803. * @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
  5804. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5805. * @param string $form_name Not used
  5806. * @param int $d 1=Show days, month, years
  5807. * @param int $addnowlink Add a link "Now"
  5808. * @param int $nooutput Do not output html string but return it
  5809. * @param int $disabled Disable input fields
  5810. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5811. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5812. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5813. * @return string|void Nothing or string if nooutput is 1
  5814. * @deprecated
  5815. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5816. */
  5817. 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 = '')
  5818. {
  5819. // phpcs:enable
  5820. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5821. if (!empty($nooutput)) {
  5822. return $retstring;
  5823. }
  5824. print $retstring;
  5825. return;
  5826. }
  5827. /**
  5828. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5829. * Fields are preselected with :
  5830. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5831. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5832. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5833. *
  5834. * @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).
  5835. * @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).
  5836. * @param string $prefix Prefix for fields name
  5837. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5838. * @param string $forcenewline Force new line between the 2 dates.
  5839. * @return string Html for selectDate
  5840. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5841. */
  5842. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5843. {
  5844. global $langs;
  5845. $ret = $this->selectDate($set_time, $prefix . '_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5846. if ($forcenewline) {
  5847. $ret .= '<br>';
  5848. }
  5849. $ret .= $this->selectDate($set_time_end, $prefix . '_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5850. return $ret;
  5851. }
  5852. /**
  5853. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5854. * Fields are preselected with :
  5855. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5856. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5857. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5858. *
  5859. * @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).
  5860. * @param string $prefix Prefix for fields name
  5861. * @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
  5862. * @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
  5863. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5864. * @param string $form_name Not used
  5865. * @param int $d 1=Show days, month, years
  5866. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5867. * @param int $disabled Disable input fields
  5868. * @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')
  5869. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5870. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5871. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5872. * @param int $stepminutes Specify step for minutes between 1 and 30
  5873. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5874. * @param string $placeholder Placeholder
  5875. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5876. * @return string Html for selectDate
  5877. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5878. */
  5879. 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')
  5880. {
  5881. global $conf, $langs;
  5882. if ($gm === 'auto') {
  5883. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5884. }
  5885. $retstring = '';
  5886. if ($prefix == '') {
  5887. $prefix = 're';
  5888. }
  5889. if ($h == '') {
  5890. $h = 0;
  5891. }
  5892. if ($m == '') {
  5893. $m = 0;
  5894. }
  5895. $emptydate = 0;
  5896. $emptyhours = 0;
  5897. if ($stepminutes <= 0 || $stepminutes > 30) {
  5898. $stepminutes = 1;
  5899. }
  5900. if ($empty == 1) {
  5901. $emptydate = 1;
  5902. $emptyhours = 1;
  5903. }
  5904. if ($empty == 2) {
  5905. $emptydate = 0;
  5906. $emptyhours = 1;
  5907. }
  5908. $orig_set_time = $set_time;
  5909. if ($set_time === '' && $emptydate == 0) {
  5910. include_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  5911. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5912. $set_time = dol_now($gm);
  5913. } else {
  5914. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5915. }
  5916. }
  5917. // Analysis of the pre-selection date
  5918. $reg = array();
  5919. $shour = '';
  5920. $smin = '';
  5921. $ssec = '';
  5922. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5923. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5924. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5925. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5926. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5927. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5928. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5929. } elseif (strval($set_time) != '' && $set_time != -1) {
  5930. // set_time est un timestamps (0 possible)
  5931. $syear = dol_print_date($set_time, "%Y", $gm);
  5932. $smonth = dol_print_date($set_time, "%m", $gm);
  5933. $sday = dol_print_date($set_time, "%d", $gm);
  5934. if ($orig_set_time != '') {
  5935. $shour = dol_print_date($set_time, "%H", $gm);
  5936. $smin = dol_print_date($set_time, "%M", $gm);
  5937. $ssec = dol_print_date($set_time, "%S", $gm);
  5938. }
  5939. } else {
  5940. // Date est '' ou vaut -1
  5941. $syear = '';
  5942. $smonth = '';
  5943. $sday = '';
  5944. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5945. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5946. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5947. }
  5948. if ($h == 3) {
  5949. $shour = '';
  5950. }
  5951. if ($m == 3) {
  5952. $smin = '';
  5953. }
  5954. $nowgmt = dol_now('gmt');
  5955. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5956. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5957. $usecalendar = 'combo';
  5958. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5959. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5960. }
  5961. if ($d) {
  5962. // Show date with popup
  5963. if ($usecalendar != 'combo') {
  5964. $formated_date = '';
  5965. //print "e".$set_time." t ".$conf->format_date_short;
  5966. if (strval($set_time) != '' && $set_time != -1) {
  5967. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5968. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5969. }
  5970. // Calendrier popup version eldy
  5971. if ($usecalendar == "eldy") {
  5972. // Input area to enter date manually
  5973. $retstring .= '<input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate" maxlength="11" value="' . $formated_date . '"';
  5974. $retstring .= ($disabled ? ' disabled' : '');
  5975. $retstring .= ' onChange="dpChangeDay(\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5976. $retstring .= '>';
  5977. // Icon calendar
  5978. $retstringbuttom = '';
  5979. if (!$disabled) {
  5980. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons"';
  5981. $base = DOL_URL_ROOT . '/core/';
  5982. $retstringbuttom .= ' onClick="showDP(\'' . $base . '\',\'' . $prefix . '\',\'' . $langs->trans("FormatDateShortJavaInput") . '\',\'' . $langs->defaultlang . '\');"';
  5983. $retstringbuttom .= '>' . img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"') . '</button>';
  5984. } else {
  5985. $retstringbuttom = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  5986. }
  5987. $retstring = $retstringbuttom . $retstring;
  5988. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  5989. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  5990. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  5991. } elseif ($usecalendar == 'jquery') {
  5992. if (!$disabled) {
  5993. // Output javascript for datepicker
  5994. $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (date('Y') - 100));
  5995. $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (date('Y') + 100));
  5996. $retstring .= "<script type='text/javascript'>";
  5997. $retstring .= "$(function(){ $('#" . $prefix . "').datepicker({
  5998. dateFormat: '" . $langs->trans("FormatDateShortJQueryInput") . "',
  5999. autoclose: true,
  6000. todayHighlight: true,
  6001. yearRange: '" . $minYear . ":" . $maxYear . "',";
  6002. if (!empty($conf->dol_use_jmobile)) {
  6003. $retstring .= "
  6004. beforeShow: function (input, datePicker) {
  6005. input.disabled = true;
  6006. },
  6007. onClose: function (dateText, datePicker) {
  6008. this.disabled = false;
  6009. },
  6010. ";
  6011. }
  6012. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  6013. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  6014. $retstring .= "
  6015. showOn: 'button', /* both has problem with autocompletion */
  6016. buttonImage: '" . DOL_URL_ROOT . "/theme/" . dol_escape_js($conf->theme) . "/img/object_calendarday.png',
  6017. buttonImageOnly: true";
  6018. }
  6019. $retstring .= "
  6020. }) });";
  6021. $retstring .= "</script>";
  6022. }
  6023. // Zone de saisie manuelle de la date
  6024. $retstring .= '<div class="nowraponall inline-block divfordateinput">';
  6025. $retstring .= '<input id="' . $prefix . '" name="' . $prefix . '" type="text" class="maxwidthdate" maxlength="11" value="' . $formated_date . '"';
  6026. $retstring .= ($disabled ? ' disabled' : '');
  6027. $retstring .= ($placeholder ? ' placeholder="' . dol_escape_htmltag($placeholder) . '"' : '');
  6028. $retstring .= ' onChange="dpChangeDay(\'' . dol_escape_js($prefix) . '\',\'' . dol_escape_js($langs->trans("FormatDateShortJavaInput")) . '\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6029. $retstring .= '>';
  6030. // Icone calendrier
  6031. if (!$disabled) {
  6032. /* Not required. Managed by option buttonImage of jquery
  6033. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  6034. $retstring.="<script type='text/javascript'>";
  6035. $retstring.="jQuery(document).ready(function() {";
  6036. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  6037. $retstring.=" jQuery('#".$prefix."').focus();";
  6038. $retstring.=' });';
  6039. $retstring.='});';
  6040. $retstring.="</script>";*/
  6041. } else {
  6042. $retstringbutton = '<button id="' . $prefix . 'Button" type="button" class="dpInvisibleButtons">' . img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"') . '</button>';
  6043. $retsring = $retstringbutton . $retstring;
  6044. }
  6045. $retstring .= '</div>';
  6046. $retstring .= '<input type="hidden" id="' . $prefix . 'day" name="' . $prefix . 'day" value="' . $sday . '">' . "\n";
  6047. $retstring .= '<input type="hidden" id="' . $prefix . 'month" name="' . $prefix . 'month" value="' . $smonth . '">' . "\n";
  6048. $retstring .= '<input type="hidden" id="' . $prefix . 'year" name="' . $prefix . 'year" value="' . $syear . '">' . "\n";
  6049. } else {
  6050. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  6051. }
  6052. } else {
  6053. // Show date with combo selects
  6054. // Day
  6055. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50imp" id="' . $prefix . 'day" name="' . $prefix . 'day">';
  6056. if ($emptydate || $set_time == -1) {
  6057. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6058. }
  6059. for ($day = 1; $day <= 31; $day++) {
  6060. $retstring .= '<option value="' . $day . '"' . ($day == $sday ? ' selected' : '') . '>' . $day . '</option>';
  6061. }
  6062. $retstring .= "</select>";
  6063. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'month" name="' . $prefix . 'month">';
  6064. if ($emptydate || $set_time == -1) {
  6065. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6066. }
  6067. // Month
  6068. for ($month = 1; $month <= 12; $month++) {
  6069. $retstring .= '<option value="' . $month . '"' . ($month == $smonth ? ' selected' : '') . '>';
  6070. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  6071. $retstring .= "</option>";
  6072. }
  6073. $retstring .= "</select>";
  6074. // Year
  6075. if ($emptydate || $set_time == -1) {
  6076. $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 . '">';
  6077. } else {
  6078. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth75imp" id="' . $prefix . 'year" name="' . $prefix . 'year">';
  6079. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  6080. $retstring .= '<option value="' . $year . '"' . ($year == $syear ? ' selected' : '') . '>' . $year . '</option>';
  6081. }
  6082. $retstring .= "</select>\n";
  6083. }
  6084. }
  6085. }
  6086. if ($d && $h) {
  6087. $retstring .= ($h == 2 ? '<br>' : ' ');
  6088. $retstring .= '<span class="nowraponall">';
  6089. }
  6090. if ($h) {
  6091. $hourstart = 0;
  6092. $hourend = 24;
  6093. if ($openinghours != '') {
  6094. $openinghours = explode(',', $openinghours);
  6095. $hourstart = $openinghours[0];
  6096. $hourend = $openinghours[1];
  6097. if ($hourend < $hourstart) {
  6098. $hourend = $hourstart;
  6099. }
  6100. }
  6101. // Show hour
  6102. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'hour' : '') . '" id="' . $prefix . 'hour" name="' . $prefix . 'hour">';
  6103. if ($emptyhours) {
  6104. $retstring .= '<option value="-1">&nbsp;</option>';
  6105. }
  6106. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  6107. if (strlen($hour) < 2) {
  6108. $hour = "0" . $hour;
  6109. }
  6110. $retstring .= '<option value="' . $hour . '"' . (($hour == $shour) ? ' selected' : '') . '>' . $hour;
  6111. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  6112. $retstring .= '</option>';
  6113. }
  6114. $retstring .= '</select>';
  6115. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  6116. if ($m) {
  6117. $retstring .= ":";
  6118. }
  6119. }
  6120. if ($m) {
  6121. // Show minutes
  6122. $retstring .= '<select' . ($disabled ? ' disabled' : '') . ' class="flat valignmiddle maxwidth50 ' . ($fullday ? $fullday . 'min' : '') . '" id="' . $prefix . 'min" name="' . $prefix . 'min">';
  6123. if ($emptyhours) {
  6124. $retstring .= '<option value="-1">&nbsp;</option>';
  6125. }
  6126. for ($min = 0; $min < 60; $min += $stepminutes) {
  6127. if (strlen($min) < 2) {
  6128. $min = "0" . $min;
  6129. }
  6130. $retstring .= '<option value="' . $min . '"' . (($min == $smin) ? ' selected' : '') . '>' . $min . (empty($conf->dol_optimize_smallscreen) ? '' : '') . '</option>';
  6131. }
  6132. $retstring .= '</select>';
  6133. $retstring .= '<input type="hidden" name="' . $prefix . 'sec" value="' . $ssec . '">';
  6134. }
  6135. if ($d && $h) {
  6136. $retstring .= '</span>';
  6137. }
  6138. // Add a "Now" link
  6139. if (!empty($conf->use_javascript_ajax) && $addnowlink) {
  6140. // Script which will be inserted in the onClick of the "Now" link
  6141. $reset_scripts = "";
  6142. if ($addnowlink == 2) { // local computer time
  6143. // pad add leading 0 on numbers
  6144. $reset_scripts .= "Number.prototype.pad = function(size) {
  6145. var s = String(this);
  6146. while (s.length < (size || 2)) {s = '0' + s;}
  6147. return s;
  6148. };
  6149. var d = new Date();";
  6150. }
  6151. // Generate the date part, depending on the use or not of the javascript calendar
  6152. if ($addnowlink == 1) { // server time expressed in user time setup
  6153. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6154. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6155. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6156. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6157. } elseif ($addnowlink == 2) {
  6158. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6159. * This break application for foreign languages.
  6160. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6161. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6162. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6163. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6164. */
  6165. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'day', 'tzuserrel') . '\');';
  6166. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6167. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6168. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6169. }
  6170. /*if ($usecalendar == "eldy")
  6171. {
  6172. $base=DOL_URL_ROOT.'/core/';
  6173. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6174. }
  6175. else
  6176. {
  6177. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6178. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6179. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6180. }*/
  6181. // Update the hour part
  6182. if ($h) {
  6183. if ($fullday) {
  6184. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6185. }
  6186. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6187. if ($addnowlink == 1) {
  6188. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6189. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6190. } elseif ($addnowlink == 2) {
  6191. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(d.getHours().pad());';
  6192. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').change();';
  6193. }
  6194. if ($fullday) {
  6195. $reset_scripts .= ' } ';
  6196. }
  6197. }
  6198. // Update the minute part
  6199. if ($m) {
  6200. if ($fullday) {
  6201. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6202. }
  6203. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6204. if ($addnowlink == 1) {
  6205. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6206. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6207. } elseif ($addnowlink == 2) {
  6208. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(d.getMinutes().pad());';
  6209. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').change();';
  6210. }
  6211. if ($fullday) {
  6212. $reset_scripts .= ' } ';
  6213. }
  6214. }
  6215. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6216. if ($reset_scripts && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6217. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonNow" type="button" name="_useless" value="now" onClick="' . $reset_scripts . '">';
  6218. $retstring .= $langs->trans("Now");
  6219. $retstring .= '</button> ';
  6220. }
  6221. }
  6222. // Add a "Plus one hour" link
  6223. if ($conf->use_javascript_ajax && $addplusone) {
  6224. // Script which will be inserted in the onClick of the "Add plusone" link
  6225. $reset_scripts = "";
  6226. // Generate the date part, depending on the use or not of the javascript calendar
  6227. $reset_scripts .= 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel') . '\');';
  6228. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . dol_print_date($nowgmt, '%d', 'tzuserrel') . '\');';
  6229. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . dol_print_date($nowgmt, '%m', 'tzuserrel') . '\');';
  6230. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . dol_print_date($nowgmt, '%Y', 'tzuserrel') . '\');';
  6231. // Update the hour part
  6232. if ($h) {
  6233. if ($fullday) {
  6234. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6235. }
  6236. $reset_scripts .= 'jQuery(\'#' . $prefix . 'hour\').val(\'' . dol_print_date($nowgmt, '%H', 'tzuserrel') . '\');';
  6237. if ($fullday) {
  6238. $reset_scripts .= ' } ';
  6239. }
  6240. }
  6241. // Update the minute part
  6242. if ($m) {
  6243. if ($fullday) {
  6244. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6245. }
  6246. $reset_scripts .= 'jQuery(\'#' . $prefix . 'min\').val(\'' . dol_print_date($nowgmt, '%M', 'tzuserrel') . '\');';
  6247. if ($fullday) {
  6248. $reset_scripts .= ' } ';
  6249. }
  6250. }
  6251. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6252. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6253. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="' . $prefix . 'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="' . $reset_scripts . '">';
  6254. $retstring .= $langs->trans("DateStartPlusOne");
  6255. $retstring .= '</button> ';
  6256. }
  6257. }
  6258. // Add a link to set data
  6259. if ($conf->use_javascript_ajax && $adddateof) {
  6260. $tmparray = dol_getdate($adddateof);
  6261. if (empty($labeladddateof)) {
  6262. $labeladddateof = $langs->trans("DateInvoice");
  6263. }
  6264. $reset_scripts = 'jQuery(\'#' . $prefix . '\').val(\'' . dol_print_date($adddateof, 'dayinputnoreduce') . '\');';
  6265. $reset_scripts .= 'jQuery(\'#' . $prefix . 'day\').val(\'' . $tmparray['mday'] . '\');';
  6266. $reset_scripts .= 'jQuery(\'#' . $prefix . 'month\').val(\'' . $tmparray['mon'] . '\');';
  6267. $reset_scripts .= 'jQuery(\'#' . $prefix . 'year\').val(\'' . $tmparray['year'] . '\');';
  6268. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="' . $reset_scripts . '">' . $labeladddateof . '</a>';
  6269. }
  6270. return $retstring;
  6271. }
  6272. /**
  6273. * selectTypeDuration
  6274. *
  6275. * @param string $prefix Prefix
  6276. * @param string $selected Selected duration type
  6277. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6278. * @return string HTML select string
  6279. */
  6280. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6281. {
  6282. global $langs;
  6283. $TDurationTypes = array(
  6284. 'y' => $langs->trans('Years'),
  6285. 'm' => $langs->trans('Month'),
  6286. 'w' => $langs->trans('Weeks'),
  6287. 'd' => $langs->trans('Days'),
  6288. 'h' => $langs->trans('Hours'),
  6289. 'i' => $langs->trans('Minutes')
  6290. );
  6291. // Removed undesired duration types
  6292. foreach ($excludetypes as $value) {
  6293. unset($TDurationTypes[$value]);
  6294. }
  6295. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_' . $prefix . 'type_duration" name="' . $prefix . 'type_duration">';
  6296. foreach ($TDurationTypes as $key => $typeduration) {
  6297. $retstring .= '<option value="' . $key . '"';
  6298. if ($key == $selected) {
  6299. $retstring .= " selected";
  6300. }
  6301. $retstring .= ">" . $typeduration . "</option>";
  6302. }
  6303. $retstring .= "</select>";
  6304. $retstring .= ajax_combobox('select_' . $prefix . 'type_duration');
  6305. return $retstring;
  6306. }
  6307. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6308. /**
  6309. * Function to show a form to select a duration on a page
  6310. *
  6311. * @param string $prefix Prefix for input fields
  6312. * @param int $iSecond Default preselected duration (number of seconds or '')
  6313. * @param int $disabled Disable the combo box
  6314. * @param string $typehour If 'select' then input hour and input min is a combo,
  6315. * If 'text' input hour is in text and input min is a text,
  6316. * If 'textselect' input hour is in text and input min is a combo
  6317. * @param integer $minunderhours If 1, show minutes selection under the hours
  6318. * @param int $nooutput Do not output html string but return it
  6319. * @return string|void
  6320. */
  6321. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6322. {
  6323. // phpcs:enable
  6324. global $langs;
  6325. $retstring = '<span class="nowraponall">';
  6326. $hourSelected = 0;
  6327. $minSelected = 0;
  6328. // Hours
  6329. if ($iSecond != '') {
  6330. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  6331. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6332. $minSelected = convertSecondToTime($iSecond, 'min');
  6333. }
  6334. if ($typehour == 'select') {
  6335. $retstring .= '<select class="flat" id="select_' . $prefix . 'hour" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . '>';
  6336. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6337. $retstring .= '<option value="' . $hour . '"';
  6338. if ($hourSelected == $hour) {
  6339. $retstring .= " selected";
  6340. }
  6341. $retstring .= ">" . $hour . "</option>";
  6342. }
  6343. $retstring .= "</select>";
  6344. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6345. $retstring .= '<input placeholder="' . $langs->trans('HourShort') . '" type="number" min="0" name="' . $prefix . 'hour"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputhour" value="' . (($hourSelected != '') ? ((int) $hourSelected) : '') . '">';
  6346. } else {
  6347. return 'BadValueForParameterTypeHour';
  6348. }
  6349. if ($typehour != 'text') {
  6350. $retstring .= ' ' . $langs->trans('HourShort');
  6351. } else {
  6352. $retstring .= '<span class="">:</span>';
  6353. }
  6354. // Minutes
  6355. if ($minunderhours) {
  6356. $retstring .= '<br>';
  6357. } else {
  6358. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6359. }
  6360. if ($typehour == 'select' || $typehour == 'textselect') {
  6361. $retstring .= '<select class="flat" id="select_' . $prefix . 'min" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . '>';
  6362. for ($min = 0; $min <= 55; $min = $min + 5) {
  6363. $retstring .= '<option value="' . $min . '"';
  6364. if ($minSelected == $min) {
  6365. $retstring .= ' selected';
  6366. }
  6367. $retstring .= '>' . $min . '</option>';
  6368. }
  6369. $retstring .= "</select>";
  6370. } elseif ($typehour == 'text') {
  6371. $retstring .= '<input placeholder="' . $langs->trans('MinuteShort') . '" type="number" min="0" name="' . $prefix . 'min"' . ($disabled ? ' disabled' : '') . ' class="flat maxwidth50 inputminute" value="' . (($minSelected != '') ? ((int) $minSelected) : '') . '">';
  6372. }
  6373. if ($typehour != 'text') {
  6374. $retstring .= ' ' . $langs->trans('MinuteShort');
  6375. }
  6376. $retstring .= "</span>";
  6377. if (!empty($nooutput)) {
  6378. return $retstring;
  6379. }
  6380. print $retstring;
  6381. return;
  6382. }
  6383. /**
  6384. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6385. *
  6386. * @param int $selected Preselected tickets
  6387. * @param string $htmlname Name of HTML select field (must be unique in page).
  6388. * @param string $filtertype To add a filter
  6389. * @param int $limit Limit on number of returned lines
  6390. * @param int $status Ticket status
  6391. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6392. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6393. * @param array $ajaxoptions Options for ajax_autocompleter
  6394. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6395. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6396. * @param int $forcecombo Force to use combo box
  6397. * @param string $morecss Add more css on select
  6398. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6399. * @param string $nooutput No print, return the output into a string
  6400. * @return void|string
  6401. */
  6402. 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)
  6403. {
  6404. global $langs, $conf;
  6405. $out = '';
  6406. // check parameters
  6407. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6408. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6409. $placeholder = '';
  6410. if ($selected && empty($selected_input_value)) {
  6411. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6412. $tickettmpselect = new Ticket($this->db);
  6413. $tickettmpselect->fetch($selected);
  6414. $selected_input_value = $tickettmpselect->ref;
  6415. unset($tickettmpselect);
  6416. }
  6417. $urloption = '';
  6418. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6419. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6420. elseif ($hidelabel > 1) {
  6421. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6422. if ($hidelabel == 2) {
  6423. $out .= img_picto($langs->trans("Search"), 'search');
  6424. }
  6425. }
  6426. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6427. if ($hidelabel == 3) {
  6428. $out .= img_picto($langs->trans("Search"), 'search');
  6429. }
  6430. } else {
  6431. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6432. }
  6433. if (empty($nooutput)) print $out;
  6434. else return $out;
  6435. }
  6436. /**
  6437. * Return list of tickets.
  6438. * Called by selectTickets.
  6439. *
  6440. * @param int $selected Preselected ticket
  6441. * @param string $htmlname Name of select html
  6442. * @param string $filtertype Filter on ticket type
  6443. * @param int $limit Limit on number of returned lines
  6444. * @param string $filterkey Filter on ticket ref or subject
  6445. * @param int $status Ticket status
  6446. * @param int $outputmode 0=HTML select string, 1=Array
  6447. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6448. * @param int $forcecombo Force to use combo box
  6449. * @param string $morecss Add more css on select
  6450. * @return array Array of keys for json
  6451. */
  6452. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6453. {
  6454. global $langs, $conf;
  6455. $out = '';
  6456. $outarray = array();
  6457. $selectFields = " p.rowid, p.ref, p.message";
  6458. $sql = "SELECT ";
  6459. $sql .= $selectFields;
  6460. $sql .= " FROM " . $this->db->prefix() . "ticket as p";
  6461. $sql .= ' WHERE p.entity IN (' . getEntity('ticket') . ')';
  6462. // Add criteria on ref/label
  6463. if ($filterkey != '') {
  6464. $sql .= ' AND (';
  6465. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6466. // For natural search
  6467. $scrit = explode(' ', $filterkey);
  6468. $i = 0;
  6469. if (count($scrit) > 1) $sql .= "(";
  6470. foreach ($scrit as $crit) {
  6471. if ($i > 0) $sql .= " AND ";
  6472. $sql .= "(p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%' OR p.subject LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6473. $sql .= ")";
  6474. $i++;
  6475. }
  6476. if (count($scrit) > 1) $sql .= ")";
  6477. $sql .= ')';
  6478. }
  6479. $sql .= $this->db->plimit($limit, 0);
  6480. // Build output string
  6481. dol_syslog(get_class($this) . "::selectTicketsList search tickets", LOG_DEBUG);
  6482. $result = $this->db->query($sql);
  6483. if ($result) {
  6484. require_once DOL_DOCUMENT_ROOT . '/ticket/class/ticket.class.php';
  6485. require_once DOL_DOCUMENT_ROOT . '/core/lib/ticket.lib.php';
  6486. $num = $this->db->num_rows($result);
  6487. $events = null;
  6488. if (!$forcecombo) {
  6489. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6490. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6491. }
  6492. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6493. $textifempty = '';
  6494. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6495. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6496. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6497. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6498. else $textifempty .= $langs->trans("All");
  6499. } else {
  6500. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6501. }
  6502. if ($showempty) $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6503. $i = 0;
  6504. while ($num && $i < $num) {
  6505. $opt = '';
  6506. $optJson = array();
  6507. $objp = $this->db->fetch_object($result);
  6508. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6509. // Add new entry
  6510. // "key" value of json key array is used by jQuery automatically as selected value
  6511. // "label" value of json key array is used by jQuery automatically as text for combo box
  6512. $out .= $opt;
  6513. array_push($outarray, $optJson);
  6514. $i++;
  6515. }
  6516. $out .= '</select>';
  6517. $this->db->free($result);
  6518. if (empty($outputmode)) return $out;
  6519. return $outarray;
  6520. } else {
  6521. dol_print_error($this->db);
  6522. }
  6523. }
  6524. /**
  6525. * constructTicketListOption.
  6526. * This define value for &$opt and &$optJson.
  6527. *
  6528. * @param object $objp Result set of fetch
  6529. * @param string $opt Option (var used for returned value in string option format)
  6530. * @param string $optJson Option (var used for returned value in json format)
  6531. * @param string $selected Preselected value
  6532. * @param string $filterkey Filter key to highlight
  6533. * @return void
  6534. */
  6535. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6536. {
  6537. $outkey = '';
  6538. $outref = '';
  6539. $outtype = '';
  6540. $outkey = $objp->rowid;
  6541. $outref = $objp->ref;
  6542. $outtype = $objp->fk_product_type;
  6543. $opt = '<option value="' . $objp->rowid . '"';
  6544. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6545. $opt .= '>';
  6546. $opt .= $objp->ref;
  6547. $objRef = $objp->ref;
  6548. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6549. $opt .= "</option>\n";
  6550. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6551. }
  6552. /**
  6553. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6554. *
  6555. * @param int $selected Preselected tickets
  6556. * @param string $htmlname Name of HTML select field (must be unique in page).
  6557. * @param string $filtertype To add a filter
  6558. * @param int $limit Limit on number of returned lines
  6559. * @param int $status Ticket status
  6560. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6561. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6562. * @param array $ajaxoptions Options for ajax_autocompleter
  6563. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6564. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6565. * @param int $forcecombo Force to use combo box
  6566. * @param string $morecss Add more css on select
  6567. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6568. * @param string $nooutput No print, return the output into a string
  6569. * @return void|string
  6570. */
  6571. 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)
  6572. {
  6573. global $langs, $conf;
  6574. $out = '';
  6575. // check parameters
  6576. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6577. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6578. $placeholder = '';
  6579. if ($selected && empty($selected_input_value)) {
  6580. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6581. $projecttmpselect = new Project($this->db);
  6582. $projecttmpselect->fetch($selected);
  6583. $selected_input_value = $projecttmpselect->ref;
  6584. unset($projecttmpselect);
  6585. }
  6586. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6587. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6588. elseif ($hidelabel > 1) {
  6589. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6590. if ($hidelabel == 2) {
  6591. $out .= img_picto($langs->trans("Search"), 'search');
  6592. }
  6593. }
  6594. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6595. if ($hidelabel == 3) {
  6596. $out .= img_picto($langs->trans("Search"), 'search');
  6597. }
  6598. } else {
  6599. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6600. }
  6601. if (empty($nooutput)) print $out;
  6602. else return $out;
  6603. }
  6604. /**
  6605. * Return list of projects.
  6606. * Called by selectProjects.
  6607. *
  6608. * @param int $selected Preselected project
  6609. * @param string $htmlname Name of select html
  6610. * @param string $filtertype Filter on project type
  6611. * @param int $limit Limit on number of returned lines
  6612. * @param string $filterkey Filter on project ref or subject
  6613. * @param int $status Ticket status
  6614. * @param int $outputmode 0=HTML select string, 1=Array
  6615. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6616. * @param int $forcecombo Force to use combo box
  6617. * @param string $morecss Add more css on select
  6618. * @return array Array of keys for json
  6619. */
  6620. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6621. {
  6622. global $langs, $conf;
  6623. $out = '';
  6624. $outarray = array();
  6625. $selectFields = " p.rowid, p.ref";
  6626. $sql = "SELECT ";
  6627. $sql .= $selectFields;
  6628. $sql .= " FROM " . $this->db->prefix() . "projet as p";
  6629. $sql .= ' WHERE p.entity IN (' . getEntity('project') . ')';
  6630. // Add criteria on ref/label
  6631. if ($filterkey != '') {
  6632. $sql .= ' AND (';
  6633. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6634. // For natural search
  6635. $scrit = explode(' ', $filterkey);
  6636. $i = 0;
  6637. if (count($scrit) > 1) $sql .= "(";
  6638. foreach ($scrit as $crit) {
  6639. if ($i > 0) $sql .= " AND ";
  6640. $sql .= "p.ref LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6641. $sql .= "";
  6642. $i++;
  6643. }
  6644. if (count($scrit) > 1) $sql .= ")";
  6645. $sql .= ')';
  6646. }
  6647. $sql .= $this->db->plimit($limit, 0);
  6648. // Build output string
  6649. dol_syslog(get_class($this) . "::selectProjectsList search projects", LOG_DEBUG);
  6650. $result = $this->db->query($sql);
  6651. if ($result) {
  6652. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  6653. require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
  6654. $num = $this->db->num_rows($result);
  6655. $events = null;
  6656. if (!$forcecombo) {
  6657. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6658. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6659. }
  6660. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6661. $textifempty = '';
  6662. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6663. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6664. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6665. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6666. else $textifempty .= $langs->trans("All");
  6667. } else {
  6668. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6669. }
  6670. if ($showempty) $out .= '<option value="0" selected>' . $textifempty . '</option>';
  6671. $i = 0;
  6672. while ($num && $i < $num) {
  6673. $opt = '';
  6674. $optJson = array();
  6675. $objp = $this->db->fetch_object($result);
  6676. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6677. // Add new entry
  6678. // "key" value of json key array is used by jQuery automatically as selected value
  6679. // "label" value of json key array is used by jQuery automatically as text for combo box
  6680. $out .= $opt;
  6681. array_push($outarray, $optJson);
  6682. $i++;
  6683. }
  6684. $out .= '</select>';
  6685. $this->db->free($result);
  6686. if (empty($outputmode)) return $out;
  6687. return $outarray;
  6688. } else {
  6689. dol_print_error($this->db);
  6690. }
  6691. }
  6692. /**
  6693. * constructProjectListOption.
  6694. * This define value for &$opt and &$optJson.
  6695. *
  6696. * @param object $objp Result set of fetch
  6697. * @param string $opt Option (var used for returned value in string option format)
  6698. * @param string $optJson Option (var used for returned value in json format)
  6699. * @param string $selected Preselected value
  6700. * @param string $filterkey Filter key to highlight
  6701. * @return void
  6702. */
  6703. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6704. {
  6705. $outkey = '';
  6706. $outval = '';
  6707. $outref = '';
  6708. $outlabel = '';
  6709. $outtype = '';
  6710. $label = $objp->label;
  6711. $outkey = $objp->rowid;
  6712. $outref = $objp->ref;
  6713. $outlabel = $objp->label;
  6714. $outtype = $objp->fk_product_type;
  6715. $opt = '<option value="' . $objp->rowid . '"';
  6716. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6717. $opt .= '>';
  6718. $opt .= $objp->ref;
  6719. $objRef = $objp->ref;
  6720. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $objRef, 1);
  6721. $outval .= $objRef;
  6722. $opt .= "</option>\n";
  6723. $optJson = array('key' => $outkey, 'value' => $outref, 'type' => $outtype);
  6724. }
  6725. /**
  6726. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6727. *
  6728. * @param int $selected Preselected tickets
  6729. * @param string $htmlname Name of HTML select field (must be unique in page).
  6730. * @param string $filtertype To add a filter
  6731. * @param int $limit Limit on number of returned lines
  6732. * @param int $status Ticket status
  6733. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6734. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6735. * @param array $ajaxoptions Options for ajax_autocompleter
  6736. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6737. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6738. * @param int $forcecombo Force to use combo box
  6739. * @param string $morecss Add more css on select
  6740. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6741. * @param string $nooutput No print, return the output into a string
  6742. * @return void|string
  6743. */
  6744. 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)
  6745. {
  6746. global $langs, $conf;
  6747. $out = '';
  6748. // check parameters
  6749. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6750. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6751. $placeholder = '';
  6752. $urloption = '';
  6753. if ($selected && empty($selected_input_value)) {
  6754. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  6755. $adherenttmpselect = new Adherent($this->db);
  6756. $adherenttmpselect->fetch($selected);
  6757. $selected_input_value = $adherenttmpselect->ref;
  6758. unset($adherenttmpselect);
  6759. }
  6760. $urloption = '';
  6761. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT . '/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6762. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel") . ' : ';
  6763. elseif ($hidelabel > 1) {
  6764. $placeholder = ' placeholder="' . $langs->trans("RefOrLabel") . '"';
  6765. if ($hidelabel == 2) {
  6766. $out .= img_picto($langs->trans("Search"), 'search');
  6767. }
  6768. }
  6769. $out .= '<input type="text" class="minwidth100" name="search_' . $htmlname . '" id="search_' . $htmlname . '" value="' . $selected_input_value . '"' . $placeholder . ' ' . (!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '') . ' />';
  6770. if ($hidelabel == 3) {
  6771. $out .= img_picto($langs->trans("Search"), 'search');
  6772. }
  6773. } else {
  6774. $filterkey = '';
  6775. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6776. }
  6777. if (empty($nooutput)) print $out;
  6778. else return $out;
  6779. }
  6780. /**
  6781. * Return list of adherents.
  6782. * Called by selectMembers.
  6783. *
  6784. * @param int $selected Preselected adherent
  6785. * @param string $htmlname Name of select html
  6786. * @param string $filtertype Filter on adherent type
  6787. * @param int $limit Limit on number of returned lines
  6788. * @param string $filterkey Filter on member status
  6789. * @param int $status Member status
  6790. * @param int $outputmode 0=HTML select string, 1=Array
  6791. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6792. * @param int $forcecombo Force to use combo box
  6793. * @param string $morecss Add more css on select
  6794. * @return array Array of keys for json
  6795. */
  6796. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6797. {
  6798. global $langs, $conf;
  6799. $out = '';
  6800. $outarray = array();
  6801. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6802. $sql = "SELECT ";
  6803. $sql .= $selectFields;
  6804. $sql .= " FROM " . $this->db->prefix() . "adherent as p";
  6805. $sql .= ' WHERE p.entity IN (' . getEntity('adherent') . ')';
  6806. // Add criteria on ref/label
  6807. if ($filterkey != '') {
  6808. $sql .= ' AND (';
  6809. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6810. // For natural search
  6811. $scrit = explode(' ', $filterkey);
  6812. $i = 0;
  6813. if (count($scrit) > 1) $sql .= "(";
  6814. foreach ($scrit as $crit) {
  6815. if ($i > 0) $sql .= " AND ";
  6816. $sql .= "(p.firstname LIKE '" . $this->db->escape($prefix . $crit) . "%'";
  6817. $sql .= " OR p.lastname LIKE '" . $this->db->escape($prefix . $crit) . "%')";
  6818. $i++;
  6819. }
  6820. if (count($scrit) > 1) $sql .= ")";
  6821. $sql .= ')';
  6822. }
  6823. if ($status != -1) {
  6824. $sql .= ' AND statut = ' . ((int) $status);
  6825. }
  6826. $sql .= $this->db->plimit($limit, 0);
  6827. // Build output string
  6828. dol_syslog(get_class($this) . "::selectMembersList search adherents", LOG_DEBUG);
  6829. $result = $this->db->query($sql);
  6830. if ($result) {
  6831. require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
  6832. require_once DOL_DOCUMENT_ROOT . '/core/lib/member.lib.php';
  6833. $num = $this->db->num_rows($result);
  6834. $events = null;
  6835. if (!$forcecombo) {
  6836. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  6837. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6838. }
  6839. $out .= '<select class="flat' . ($morecss ? ' ' . $morecss : '') . '" name="' . $htmlname . '" id="' . $htmlname . '">';
  6840. $textifempty = '';
  6841. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6842. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6843. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6844. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6845. else $textifempty .= $langs->trans("All");
  6846. } else {
  6847. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6848. }
  6849. if ($showempty) {
  6850. $out .= '<option value="-1" selected>' . $textifempty . '</option>';
  6851. }
  6852. $i = 0;
  6853. while ($num && $i < $num) {
  6854. $opt = '';
  6855. $optJson = array();
  6856. $objp = $this->db->fetch_object($result);
  6857. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6858. // Add new entry
  6859. // "key" value of json key array is used by jQuery automatically as selected value
  6860. // "label" value of json key array is used by jQuery automatically as text for combo box
  6861. $out .= $opt;
  6862. array_push($outarray, $optJson);
  6863. $i++;
  6864. }
  6865. $out .= '</select>';
  6866. $this->db->free($result);
  6867. if (empty($outputmode)) return $out;
  6868. return $outarray;
  6869. } else {
  6870. dol_print_error($this->db);
  6871. }
  6872. }
  6873. /**
  6874. * constructMemberListOption.
  6875. * This define value for &$opt and &$optJson.
  6876. *
  6877. * @param object $objp Result set of fetch
  6878. * @param string $opt Option (var used for returned value in string option format)
  6879. * @param string $optJson Option (var used for returned value in json format)
  6880. * @param string $selected Preselected value
  6881. * @param string $filterkey Filter key to highlight
  6882. * @return void
  6883. */
  6884. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6885. {
  6886. $outkey = '';
  6887. $outlabel = '';
  6888. $outtype = '';
  6889. $outkey = $objp->rowid;
  6890. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6891. $outtype = $objp->fk_adherent_type;
  6892. $opt = '<option value="' . $objp->rowid . '"';
  6893. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6894. $opt .= '>';
  6895. if (!empty($filterkey) && $filterkey != '') {
  6896. $outlabel = preg_replace('/(' . preg_quote($filterkey, '/') . ')/i', '<strong>$1</strong>', $outlabel, 1);
  6897. }
  6898. $opt .= $outlabel;
  6899. $opt .= "</option>\n";
  6900. $optJson = array('key' => $outkey, 'value' => $outlabel, 'type' => $outtype);
  6901. }
  6902. /**
  6903. * Generic method to select a component from a combo list.
  6904. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6905. * This is the generic method that will replace all specific existing methods.
  6906. *
  6907. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6908. * @param string $htmlname Name of HTML select component
  6909. * @param int $preselectedvalue Preselected value (ID of element)
  6910. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6911. * @param string $searchkey Search criteria
  6912. * @param string $placeholder Place holder
  6913. * @param string $morecss More CSS
  6914. * @param string $moreparams More params provided to ajax call
  6915. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6916. * @param int $disabled 1=Html component is disabled
  6917. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6918. * @return string Return HTML string
  6919. * @see selectForFormsList() select_thirdparty_list()
  6920. */
  6921. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6922. {
  6923. global $conf, $user;
  6924. $objecttmp = null;
  6925. // Example of value for $objectdec:
  6926. // Bom:bom/class/bom.class.php:0:t.status=1
  6927. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6928. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6929. $InfoFieldList = explode(":", $objectdesc, 4);
  6930. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  6931. $reg = array();
  6932. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6933. $InfoFieldList[4] = $reg[1]; // take the sort field
  6934. }
  6935. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6936. $classname = $InfoFieldList[0];
  6937. $classpath = $InfoFieldList[1];
  6938. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6939. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6940. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6941. if (!empty($classpath)) {
  6942. dol_include_once($classpath);
  6943. if ($classname && class_exists($classname)) {
  6944. $objecttmp = new $classname($this->db);
  6945. // Make some replacement
  6946. $sharedentities = getEntity(strtolower($classname));
  6947. $filter = str_replace(
  6948. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6949. array($conf->entity, $sharedentities, $user->id),
  6950. $filter
  6951. );
  6952. }
  6953. }
  6954. if (!is_object($objecttmp)) {
  6955. dol_syslog('Error bad setup of type for field ' . join(',', $InfoFieldList), LOG_WARNING);
  6956. return 'Error bad setup of type for field ' . join(',', $InfoFieldList);
  6957. }
  6958. //var_dump($filter);
  6959. $prefixforautocompletemode = $objecttmp->element;
  6960. if ($prefixforautocompletemode == 'societe') {
  6961. $prefixforautocompletemode = 'company';
  6962. }
  6963. if ($prefixforautocompletemode == 'product') {
  6964. $prefixforautocompletemode = 'produit';
  6965. }
  6966. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6967. dol_syslog(get_class($this) . "::selectForForms filter=" . $filter, LOG_DEBUG);
  6968. $out = '';
  6969. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6970. // No immediate load of all database
  6971. $placeholder = '';
  6972. if ($preselectedvalue && empty($selected_input_value)) {
  6973. $objecttmp->fetch($preselectedvalue);
  6974. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6975. //unset($objecttmp);
  6976. }
  6977. $objectdesc = $classname . ':' . $classpath . ':' . $addcreatebuttonornot . ':' . $filter;
  6978. $urlforajaxcall = DOL_URL_ROOT . '/core/ajax/selectobject.php';
  6979. // No immediate load of all database
  6980. $urloption = 'htmlname=' . urlencode($htmlname) . '&outjson=1&objectdesc=' . urlencode($objectdesc) . '&filter=' . urlencode($filter) . ($sortfield ? '&sortfield=' . urlencode($sortfield) : '');
  6981. // Activate the auto complete using ajax call.
  6982. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6983. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6984. $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) . '"' : '') . ' />';
  6985. } else {
  6986. // Immediate load of table record.
  6987. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
  6988. }
  6989. return $out;
  6990. }
  6991. /**
  6992. * Output html form to select an object.
  6993. * Note, this function is called by selectForForms or by ajax selectobject.php
  6994. *
  6995. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6996. * @param string $htmlname Name of HTML select component
  6997. * @param int $preselectedvalue Preselected value (ID of element)
  6998. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6999. * @param string $searchkey Search value
  7000. * @param string $placeholder Place holder
  7001. * @param string $morecss More CSS
  7002. * @param string $moreparams More params provided to ajax call
  7003. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  7004. * @param int $outputmode 0=HTML select string, 1=Array
  7005. * @param int $disabled 1=Html component is disabled
  7006. * @param string $sortfield Sort field
  7007. * @param string $filter Add more filter
  7008. * @return string|array Return HTML string
  7009. * @see selectForForms()
  7010. */
  7011. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '')
  7012. {
  7013. global $conf, $langs, $user, $hookmanager;
  7014. //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
  7015. $prefixforautocompletemode = $objecttmp->element;
  7016. if ($prefixforautocompletemode == 'societe') {
  7017. $prefixforautocompletemode = 'company';
  7018. }
  7019. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode) . '_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7020. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  7021. $tmpfieldstoshow = '';
  7022. foreach ($objecttmp->fields as $key => $val) {
  7023. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  7024. continue;
  7025. }
  7026. if (!empty($val['showoncombobox'])) {
  7027. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '') . 't.' . $key;
  7028. }
  7029. }
  7030. if ($tmpfieldstoshow) {
  7031. $fieldstoshow = $tmpfieldstoshow;
  7032. }
  7033. } else {
  7034. // For backward compatibility
  7035. $objecttmp->fields['ref'] = array('type' => 'varchar(30)', 'label' => 'Ref', 'showoncombobox' => 1);
  7036. }
  7037. if (empty($fieldstoshow)) {
  7038. if (isset($objecttmp->fields['ref'])) {
  7039. $fieldstoshow = 't.ref';
  7040. } else {
  7041. $langs->load("errors");
  7042. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  7043. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  7044. }
  7045. }
  7046. $out = '';
  7047. $outarray = array();
  7048. $tmparray = array();
  7049. $num = 0;
  7050. // Search data
  7051. $sql = "SELECT t.rowid, " . $fieldstoshow . " FROM " . $this->db->prefix() . $objecttmp->table_element . " as t";
  7052. if (isset($objecttmp->ismultientitymanaged)) {
  7053. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7054. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  7055. $sql .= " INNER JOIN " . $this->db->prefix() . $tmparray[1] . " as parenttable ON parenttable.rowid = t." . $tmparray[0];
  7056. }
  7057. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7058. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7059. $sql .= ", " . $this->db->prefix() . "societe_commerciaux as sc";
  7060. }
  7061. }
  7062. }
  7063. if ($conf->global->PACKAGEHISTORY_FOR_ALL_USERS && $user->array_options['options_user_category'] == 6 && $htmlname == 'search_user_id') {
  7064. $sql .= " INNER JOIN " . $this->db->prefix() . $objecttmp->table_element . "_extrafields as te ON te.fk_object = t.rowid";
  7065. }
  7066. // Add where from hooks
  7067. $parameters = array(
  7068. 'object' => $objecttmp,
  7069. 'htmlname' => $htmlname,
  7070. 'filter' => $filter,
  7071. 'searchkey' => $searchkey
  7072. );
  7073. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  7074. if (!empty($hookmanager->resPrint)) {
  7075. $sql .= $hookmanager->resPrint;
  7076. } else {
  7077. $sql .= " WHERE 1=1";
  7078. if (isset($objecttmp->ismultientitymanaged)) {
  7079. if ($objecttmp->ismultientitymanaged == 1) {
  7080. if ($conf->global->PACKAGEHISTORY_FOR_ALL_USERS && $user->array_options['options_user_category'] == 6 && $htmlname == 'search_user_id') {
  7081. $sql .= " AND t.entity IS NOT NULL AND te.user_category != '6'";
  7082. } else {
  7083. $sql .= " AND t.entity IN (" . getEntity($objecttmp->table_element) . ")";
  7084. }
  7085. }
  7086. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7087. $sql .= " AND parenttable.entity = t." . $tmparray[0];
  7088. }
  7089. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  7090. if ($objecttmp->element == 'societe') {
  7091. $sql .= " AND t.rowid = " . ((int) $user->socid);
  7092. } else {
  7093. $sql .= " AND t.fk_soc = " . ((int) $user->socid);
  7094. }
  7095. }
  7096. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7097. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7098. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = " . ((int) $user->id);
  7099. }
  7100. }
  7101. }
  7102. if ($searchkey != '') {
  7103. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  7104. }
  7105. if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  7106. $errormessage = '';
  7107. $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
  7108. if ($errormessage) {
  7109. return 'Error forging a SQL request from an universal criteria: ' . $errormessage;
  7110. }
  7111. }
  7112. }
  7113. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7114. //$sql.=$this->db->plimit($limit, 0);
  7115. //print $sql;
  7116. // Build output string
  7117. $resql = $this->db->query($sql);
  7118. if ($resql) {
  7119. // Construct $out and $outarray
  7120. $out .= '<select id="' . $htmlname . '" class="flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ($moreparams ? ' ' . $moreparams : '') . ' name="' . $htmlname . '">' . "\n";
  7121. // 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
  7122. $textifempty = '&nbsp;';
  7123. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7124. if (!empty($conf->global->$confkeyforautocompletemode)) {
  7125. if ($showempty && !is_numeric($showempty)) {
  7126. $textifempty = $langs->trans($showempty);
  7127. } else {
  7128. $textifempty .= $langs->trans("All");
  7129. }
  7130. }
  7131. if ($showempty) {
  7132. $out .= '<option value="-1">' . $textifempty . '</option>' . "\n";
  7133. }
  7134. $num = $this->db->num_rows($resql);
  7135. $i = 0;
  7136. if ($num) {
  7137. while ($i < $num) {
  7138. $obj = $this->db->fetch_object($resql);
  7139. $label = '';
  7140. $tmparray = explode(',', $fieldstoshow);
  7141. $oldvalueforshowoncombobox = 0;
  7142. foreach ($tmparray as $key => $val) {
  7143. $val = preg_replace('/t\./', '', $val);
  7144. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7145. $label .= $obj->$val;
  7146. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  7147. }
  7148. if (empty($outputmode)) {
  7149. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7150. $out .= '<option value="' . $obj->rowid . '" selected>' . $label . '</option>';
  7151. } else {
  7152. $out .= '<option value="' . $obj->rowid . '">' . $label . '</option>';
  7153. }
  7154. } else {
  7155. array_push($outarray, array('key' => $obj->rowid, 'value' => $label, 'label' => $label));
  7156. }
  7157. $i++;
  7158. if (($i % 10) == 0) {
  7159. $out .= "\n";
  7160. }
  7161. }
  7162. }
  7163. $out .= '</select>' . "\n";
  7164. if (!$forcecombo) {
  7165. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7166. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  7167. }
  7168. } else {
  7169. dol_print_error($this->db);
  7170. }
  7171. $this->result = array('nbofelement' => $num);
  7172. if ($outputmode) {
  7173. return $outarray;
  7174. }
  7175. return $out;
  7176. }
  7177. /**
  7178. * Return a HTML select string, built from an array of key+value.
  7179. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7180. *
  7181. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7182. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7183. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7184. * @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.
  7185. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7186. * @param int $value_as_key 1 to use value as key
  7187. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7188. * @param int $translate 1=Translate and encode value
  7189. * @param int $maxlen Length maximum for labels
  7190. * @param int $disabled Html select box is disabled
  7191. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7192. * @param string $morecss Add more class to css styles
  7193. * @param int $addjscombo Add js combo
  7194. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7195. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7196. * @param int $nohtmlescape No html escaping.
  7197. * @return string HTML select string.
  7198. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7199. */
  7200. 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)
  7201. {
  7202. global $conf, $langs;
  7203. // Do we want a multiselect ?
  7204. //$jsbeautify = 0;
  7205. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7206. $jsbeautify = 1;
  7207. if ($value_as_key) {
  7208. $array = array_combine($array, $array);
  7209. }
  7210. $out = '';
  7211. if ($addjscombo < 0) {
  7212. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7213. $addjscombo = 1;
  7214. } else {
  7215. $addjscombo = 0;
  7216. }
  7217. }
  7218. $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
  7219. $out .= '<select id="' . preg_replace('/^\./', '', $idname) . '" ' . ($disabled ? 'disabled="disabled" ' : '') . 'class="flat ' . (preg_replace('/^\./', '', $htmlname)) . ($morecss ? ' ' . $morecss : '') . '"';
  7220. $out .= ' name="' . preg_replace('/^\./', '', $htmlname) . '" ' . ($moreparam ? $moreparam : '');
  7221. $out .= '>';
  7222. if ($show_empty) {
  7223. $textforempty = ' ';
  7224. if (!empty($conf->use_javascript_ajax)) {
  7225. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7226. }
  7227. if (!is_numeric($show_empty)) {
  7228. $textforempty = $show_empty;
  7229. }
  7230. $out .= '<option class="optiongrey" ' . ($moreparamonempty ? $moreparamonempty . ' ' : '') . 'value="' . ($show_empty < 0 ? $show_empty : -1) . '"' . ($id == $show_empty ? ' selected' : '') . '>' . $textforempty . '</option>' . "\n";
  7231. }
  7232. if (is_array($array)) {
  7233. // Translate
  7234. if ($translate) {
  7235. foreach ($array as $key => $value) {
  7236. if (!is_array($value)) {
  7237. $array[$key] = $langs->trans($value);
  7238. } else {
  7239. $array[$key]['label'] = $langs->trans($value['label']);
  7240. }
  7241. }
  7242. }
  7243. // Sort
  7244. if ($sort == 'ASC') {
  7245. asort($array);
  7246. } elseif ($sort == 'DESC') {
  7247. arsort($array);
  7248. }
  7249. foreach ($array as $key => $tmpvalue) {
  7250. if (is_array($tmpvalue)) {
  7251. $value = $tmpvalue['label'];
  7252. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7253. $style = empty($tmpvalue['css']) ? '' : ' class="' . $tmpvalue['css'] . '"';
  7254. } else {
  7255. $value = $tmpvalue;
  7256. $disabled = '';
  7257. $style = '';
  7258. }
  7259. if (!empty($disablebademail)) {
  7260. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7261. || ($disablebademail == 2 && preg_match('/---/', $value))
  7262. ) {
  7263. $disabled = ' disabled';
  7264. $style = ' class="warning"';
  7265. }
  7266. }
  7267. if ($key_in_label) {
  7268. if (empty($nohtmlescape)) {
  7269. $selectOptionValue = dol_escape_htmltag($key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value));
  7270. } else {
  7271. $selectOptionValue = $key . ' - ' . ($maxlen ? dol_trunc($value, $maxlen) : $value);
  7272. }
  7273. } else {
  7274. if (empty($nohtmlescape)) {
  7275. $selectOptionValue = dol_escape_htmltag($maxlen ? dol_trunc($value, $maxlen) : $value);
  7276. } else {
  7277. $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
  7278. }
  7279. if ($value == '' || $value == '-') {
  7280. $selectOptionValue = '&nbsp;';
  7281. }
  7282. }
  7283. $out .= '<option value="' . $key . '"';
  7284. $out .= $style . $disabled;
  7285. if (is_array($id)) {
  7286. if (in_array($key, $id) && !$disabled) {
  7287. $out .= ' selected'; // To preselect a value
  7288. }
  7289. } else {
  7290. $id = (string) $id; // if $id = 0, then $id = '0'
  7291. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7292. $out .= ' selected'; // To preselect a value
  7293. }
  7294. }
  7295. if ($nohtmlescape) {
  7296. $out .= ' data-html="' . dol_escape_htmltag($selectOptionValue) . '"';
  7297. }
  7298. if (is_array($tmpvalue)) {
  7299. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7300. if (preg_match('/^data-/', $keyforvalue)) {
  7301. $out .= ' ' . $keyforvalue . '="' . $valueforvalue . '"';
  7302. }
  7303. }
  7304. }
  7305. $out .= '>';
  7306. //var_dump($selectOptionValue);
  7307. $out .= $selectOptionValue;
  7308. $out .= "</option>\n";
  7309. }
  7310. }
  7311. $out .= "</select>";
  7312. // Add code for jquery to use multiselect
  7313. if ($addjscombo && $jsbeautify) {
  7314. // Enhance with select2
  7315. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  7316. $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', ($show_empty < 0 ? (string) $show_empty : '-1'), $morecss);
  7317. }
  7318. return $out;
  7319. }
  7320. /**
  7321. * 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.
  7322. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7323. *
  7324. * @param string $htmlname Name of html select area
  7325. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7326. * @param string $id Preselected key
  7327. * @param string $moreparam Add more parameters onto the select tag
  7328. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7329. * @param int $disabled Html select box is disabled
  7330. * @param int $minimumInputLength Minimum Input Length
  7331. * @param string $morecss Add more class to css styles
  7332. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7333. * @param string $placeholder String to use as placeholder
  7334. * @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)
  7335. * @return string HTML select string
  7336. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7337. */
  7338. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7339. {
  7340. global $conf, $langs;
  7341. global $delayedhtmlcontent; // Will be used later outside of this function
  7342. // TODO Use an internal dolibarr component instead of select2
  7343. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7344. return '';
  7345. }
  7346. $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"></select>';
  7347. $outdelayed = '';
  7348. if (!empty($conf->use_javascript_ajax)) {
  7349. $tmpplugin = 'select2';
  7350. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7351. <script>
  7352. $(document).ready(function () {
  7353. ' . ($callurlonselect ? 'var saveRemoteData = [];' : '') . '
  7354. $(".' . $htmlname . '").select2({
  7355. ajax: {
  7356. dir: "ltr",
  7357. url: "' . $url . '",
  7358. dataType: \'json\',
  7359. delay: 250,
  7360. data: function (params) {
  7361. return {
  7362. q: params.term, // search term
  7363. page: params.page
  7364. };
  7365. },
  7366. processResults: function (data) {
  7367. // parse the results into the format expected by Select2.
  7368. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7369. //console.log(data);
  7370. saveRemoteData = data;
  7371. /* format json result for select2 */
  7372. result = []
  7373. $.each( data, function( key, value ) {
  7374. result.push({id: key, text: value.text});
  7375. });
  7376. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7377. //console.log(result);
  7378. return {results: result, more: false}
  7379. },
  7380. cache: true
  7381. },
  7382. language: select2arrayoflanguage,
  7383. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7384. placeholder: "' . dol_escape_js($placeholder) . '",
  7385. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7386. minimumInputLength: ' . $minimumInputLength . ',
  7387. formatResult: function(result, container, query, escapeMarkup) {
  7388. return escapeMarkup(result.text);
  7389. },
  7390. });
  7391. ' . ($callurlonselect ? '
  7392. /* Code to execute a GET when we select a value */
  7393. $(".' . $htmlname . '").change(function() {
  7394. var selected = $(".' . $htmlname . '").val();
  7395. console.log("We select in selectArrayAjax the entry "+selected)
  7396. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7397. $.each( saveRemoteData, function( key, value ) {
  7398. if (key == selected)
  7399. {
  7400. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7401. location.assign(value.url);
  7402. }
  7403. });
  7404. });' : '') . '
  7405. });
  7406. </script>';
  7407. }
  7408. if ($acceptdelayedhtml) {
  7409. $delayedhtmlcontent .= $outdelayed;
  7410. } else {
  7411. $out .= $outdelayed;
  7412. }
  7413. return $out;
  7414. }
  7415. /**
  7416. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7417. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7418. *
  7419. * @param string $htmlname Name of html select area
  7420. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7421. * @param string $id Preselected key
  7422. * @param string $moreparam Add more parameters onto the select tag
  7423. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7424. * @param int $disabled Html select box is disabled
  7425. * @param int $minimumInputLength Minimum Input Length
  7426. * @param string $morecss Add more class to css styles
  7427. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7428. * @param string $placeholder String to use as placeholder
  7429. * @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)
  7430. * @return string HTML select string
  7431. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7432. */
  7433. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7434. {
  7435. global $conf, $langs;
  7436. global $delayedhtmlcontent; // Will be used later outside of this function
  7437. // TODO Use an internal dolibarr component instead of select2
  7438. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7439. return '';
  7440. }
  7441. $out = '<select type="text" class="' . $htmlname . ($morecss ? ' ' . $morecss : '') . '" ' . ($moreparam ? $moreparam . ' ' : '') . 'name="' . $htmlname . '"><option></option></select>';
  7442. $formattedarrayresult = array();
  7443. foreach ($array as $key => $value) {
  7444. $o = new stdClass();
  7445. $o->id = $key;
  7446. $o->text = $value['text'];
  7447. $o->url = $value['url'];
  7448. $formattedarrayresult[] = $o;
  7449. }
  7450. $outdelayed = '';
  7451. if (!empty($conf->use_javascript_ajax)) {
  7452. $tmpplugin = 'select2';
  7453. $outdelayed = "\n" . '<!-- JS CODE TO ENABLE ' . $tmpplugin . ' for id ' . $htmlname . ' -->
  7454. <script>
  7455. $(document).ready(function () {
  7456. var data = ' . json_encode($formattedarrayresult) . ';
  7457. ' . ($callurlonselect ? 'var saveRemoteData = ' . json_encode($array) . ';' : '') . '
  7458. $(".' . $htmlname . '").select2({
  7459. data: data,
  7460. language: select2arrayoflanguage,
  7461. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7462. placeholder: "' . dol_escape_js($placeholder) . '",
  7463. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7464. minimumInputLength: ' . $minimumInputLength . ',
  7465. formatResult: function(result, container, query, escapeMarkup) {
  7466. return escapeMarkup(result.text);
  7467. },
  7468. matcher: function (params, data) {
  7469. if(! data.id) return null;';
  7470. if ($callurlonselect) {
  7471. // We forge the url with 'sall='
  7472. $outdelayed .= '
  7473. var urlBase = data.url;
  7474. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7475. /* console.log("params.term="+params.term); */
  7476. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7477. saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7478. }
  7479. if (!$disableFiltering) {
  7480. $outdelayed .= '
  7481. if(data.text.match(new RegExp(params.term))) {
  7482. return data;
  7483. }
  7484. return null;';
  7485. } else {
  7486. $outdelayed .= '
  7487. return data;';
  7488. }
  7489. $outdelayed .= '
  7490. }
  7491. });
  7492. ' . ($callurlonselect ? '
  7493. /* Code to execute a GET when we select a value */
  7494. $(".' . $htmlname . '").change(function() {
  7495. var selected = $(".' . $htmlname . '").val();
  7496. console.log("We select "+selected)
  7497. $(".' . $htmlname . '").val(""); /* reset visible combo value */
  7498. $.each( saveRemoteData, function( key, value ) {
  7499. if (key == selected)
  7500. {
  7501. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7502. location.assign(value.url);
  7503. }
  7504. });
  7505. });' : '') . '
  7506. });
  7507. </script>';
  7508. }
  7509. if ($acceptdelayedhtml) {
  7510. $delayedhtmlcontent .= $outdelayed;
  7511. } else {
  7512. $out .= $outdelayed;
  7513. }
  7514. return $out;
  7515. }
  7516. /**
  7517. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7518. *
  7519. * @param string $htmlname Name of select
  7520. * @param array $array Array(key=>value) or Array(key=>array('id'=> , 'label'=> ))
  7521. * @param array $selected Array of keys preselected
  7522. * @param int $key_in_label 1 to show key like in "[key] value"
  7523. * @param int $value_as_key 1 to use value as key
  7524. * @param string $morecss Add more css style
  7525. * @param int $translate Translate and encode value
  7526. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7527. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7528. * @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.
  7529. * @param string $placeholder String to use as placeholder
  7530. * @param int $addjscombo Add js combo
  7531. * @return string HTML multiselect string
  7532. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7533. */
  7534. 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)
  7535. {
  7536. global $conf, $langs;
  7537. $out = '';
  7538. if ($addjscombo < 0) {
  7539. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7540. $addjscombo = 1;
  7541. } else {
  7542. $addjscombo = 0;
  7543. }
  7544. }
  7545. $useenhancedmultiselect = 0;
  7546. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7547. $useenhancedmultiselect = 1;
  7548. }
  7549. // Output select component
  7550. $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";
  7551. if (is_array($array) && !empty($array)) {
  7552. if ($value_as_key) {
  7553. $array = array_combine($array, $array);
  7554. }
  7555. if (!empty($array)) {
  7556. foreach ($array as $key => $value) {
  7557. $tmpkey = $key;
  7558. $tmpvalue = $value;
  7559. $tmpcolor = '';
  7560. $tmppicto = '';
  7561. if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
  7562. $tmpkey = $value['id'];
  7563. $tmpvalue = $value['label'];
  7564. $tmpcolor = $value['color'];
  7565. $tmppicto = $value['picto'];
  7566. }
  7567. $newval = ($translate ? $langs->trans($tmpvalue) : $tmpvalue);
  7568. $newval = ($key_in_label ? $tmpkey . ' - ' . $newval : $newval);
  7569. $out .= '<option value="' . $tmpkey . '"';
  7570. if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
  7571. $out .= ' selected';
  7572. }
  7573. $out .= ' data-html="' . dol_escape_htmltag(($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #' . $tmpcolor . '"') : '') . $newval) . '"';
  7574. $out .= '>';
  7575. $out .= dol_htmlentitiesbr($newval);
  7576. $out .= '</option>' . "\n";
  7577. }
  7578. }
  7579. }
  7580. $out .= '</select>' . "\n";
  7581. // Add code for jquery to use multiselect
  7582. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7583. $out .= "\n" . '<!-- JS CODE TO ENABLE select for id ' . $htmlname . ', addjscombo=' . $addjscombo . ' -->';
  7584. $out .= "\n" . '<script>' . "\n";
  7585. if ($addjscombo == 1) {
  7586. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7587. $out .= 'function formatResult(record, container) {' . "\n";
  7588. $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";
  7589. $out .= ' return record.text;';
  7590. $out .= '};' . "\n";
  7591. $out .= 'function formatSelection(record) {' . "\n";
  7592. if ($elemtype == 'category') {
  7593. $out .= 'return \'<span><img src="' . DOL_URL_ROOT . '/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7594. } else {
  7595. $out .= 'return record.text;';
  7596. }
  7597. $out .= '};' . "\n";
  7598. $out .= '$(document).ready(function () {
  7599. $(\'#' . $htmlname . '\').' . $tmpplugin . '({';
  7600. if ($placeholder) {
  7601. $out .= '
  7602. placeholder: {
  7603. id: \'-1\',
  7604. text: \'' . dol_escape_js($placeholder) . '\'
  7605. },';
  7606. }
  7607. $out .= ' dir: \'ltr\',
  7608. // Specify format function for dropdown item
  7609. formatResult: formatResult,
  7610. templateResult: formatResult, /* For 4.0 */
  7611. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7612. // Specify format function for selected item
  7613. formatSelection: formatSelection,
  7614. templateSelection: formatSelection /* For 4.0 */
  7615. });
  7616. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7617. the size only if component is not hidden by default on load */
  7618. $(\'#' . $htmlname . ' + .select2\').addClass(\'' . $morecss . '\');
  7619. });' . "\n";
  7620. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7621. // Add other js lib
  7622. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7623. // ...
  7624. $out .= 'console.log(\'addjscombo=2 for htmlname=' . $htmlname . '\');';
  7625. $out .= '$(document).ready(function () {
  7626. $(\'#' . $htmlname . '\').multiSelect({
  7627. containerHTML: \'<div class="multi-select-container">\',
  7628. menuHTML: \'<div class="multi-select-menu">\',
  7629. buttonHTML: \'<span class="multi-select-button ' . $morecss . '">\',
  7630. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7631. activeClass: \'multi-select-container--open\',
  7632. noneText: \'' . $placeholder . '\'
  7633. });
  7634. })';
  7635. }
  7636. $out .= '</script>';
  7637. }
  7638. return $out;
  7639. }
  7640. /**
  7641. * 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.
  7642. *
  7643. * @param string $htmlname Name of HTML field
  7644. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7645. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7646. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7647. * @return string HTML multiselect string
  7648. * @see selectarray()
  7649. */
  7650. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7651. {
  7652. global $conf, $langs, $user, $extrafields;
  7653. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7654. return '';
  7655. }
  7656. if (empty($array)) {
  7657. return '';
  7658. }
  7659. $tmpvar = "MAIN_SELECTEDFIELDS_" . $varpage; // To get list of saved selected fields to show
  7660. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7661. $tmparray = explode(',', $user->conf->$tmpvar);
  7662. foreach ($array as $key => $val) {
  7663. //var_dump($key);
  7664. //var_dump($tmparray);
  7665. if (in_array($key, $tmparray)) {
  7666. $array[$key]['checked'] = 1;
  7667. } else {
  7668. $array[$key]['checked'] = 0;
  7669. }
  7670. }
  7671. } else { // There is no list of fields already customized for user
  7672. foreach ($array as $key => $val) {
  7673. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7674. $array[$key]['checked'] = 0;
  7675. }
  7676. }
  7677. }
  7678. $listoffieldsforselection = '';
  7679. $listcheckedstring = '';
  7680. foreach ($array as $key => $val) {
  7681. // var_dump($val);
  7682. // var_dump(array_key_exists('enabled', $val));
  7683. // var_dump(!$val['enabled']);
  7684. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7685. unset($array[$key]); // We don't want this field
  7686. continue;
  7687. }
  7688. if (!empty($val['type']) && $val['type'] == 'separate') {
  7689. // Field remains in array but we don't add it into $listoffieldsforselection
  7690. //$listoffieldsforselection .= '<li>-----</li>';
  7691. continue;
  7692. }
  7693. if ($val['label']) {
  7694. if (!empty($val['langfile']) && is_object($langs)) {
  7695. $langs->load($val['langfile']);
  7696. }
  7697. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7698. $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>';
  7699. $listcheckedstring .= (empty($val['checked']) ? '' : $key . ',');
  7700. }
  7701. }
  7702. $out = '<!-- Component multiSelectArrayWithCheckbox ' . $htmlname . ' -->
  7703. <dl class="dropdown">
  7704. <dt>
  7705. <a href="#' . $htmlname . '">
  7706. ' . img_picto('', 'list') . '
  7707. </a>
  7708. <input type="hidden" class="' . $htmlname . '" name="' . $htmlname . '" value="' . $listcheckedstring . '">
  7709. </dt>
  7710. <dd class="dropdowndd">
  7711. <div class="multiselectcheckbox' . $htmlname . '">
  7712. <ul class="' . $htmlname . ($pos == '1' ? 'left' : '') . '">
  7713. ' . $listoffieldsforselection . '
  7714. </ul>
  7715. </div>
  7716. </dd>
  7717. </dl>
  7718. <script type="text/javascript">
  7719. jQuery(document).ready(function () {
  7720. $(\'.multiselectcheckbox' . $htmlname . ' input[type="checkbox"]\').on(\'click\', function () {
  7721. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7722. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7723. var title = $(this).val() + ",";
  7724. if ($(this).is(\':checked\')) {
  7725. $(\'.' . $htmlname . '\').val(title + $(\'.' . $htmlname . '\').val());
  7726. }
  7727. else {
  7728. $(\'.' . $htmlname . '\').val( $(\'.' . $htmlname . '\').val().replace(title, \'\') )
  7729. }
  7730. // Now, we submit page
  7731. //$(this).parents(\'form:first\').submit();
  7732. });
  7733. });
  7734. </script>
  7735. ';
  7736. return $out;
  7737. }
  7738. /**
  7739. * Render list of categories linked to object with id $id and type $type
  7740. *
  7741. * @param int $id Id of object
  7742. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7743. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7744. * @param int $nolink 1=Do not add html links
  7745. * @return string String with categories
  7746. */
  7747. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7748. {
  7749. include_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  7750. $cat = new Categorie($this->db);
  7751. $categories = $cat->containing($id, $type);
  7752. if ($rendermode == 1) {
  7753. $toprint = array();
  7754. foreach ($categories as $c) {
  7755. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7756. foreach ($ways as $way) {
  7757. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"' . ($c->color ? ' style="background: #' . $c->color . ';"' : ' style="background: #bbb"') . '>' . $way . '</li>';
  7758. }
  7759. }
  7760. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
  7761. }
  7762. if ($rendermode == 0) {
  7763. $arrayselected = array();
  7764. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7765. foreach ($categories as $c) {
  7766. $arrayselected[] = $c->id;
  7767. }
  7768. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7769. }
  7770. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7771. }
  7772. /**
  7773. * Show linked object block.
  7774. *
  7775. * @param CommonObject $object Object we want to show links to
  7776. * @param string $morehtmlright More html to show on right of title
  7777. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7778. * @param string $title Title
  7779. * @return int <0 if KO, >=0 if OK
  7780. */
  7781. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false, $title = 'RelatedObjects')
  7782. {
  7783. global $conf, $langs, $hookmanager;
  7784. global $bc, $action;
  7785. $object->fetchObjectLinked();
  7786. // Bypass the default method
  7787. $hookmanager->initHooks(array('commonobject'));
  7788. $parameters = array(
  7789. 'morehtmlright' => $morehtmlright,
  7790. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7791. );
  7792. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7793. if (empty($reshook)) {
  7794. $nbofdifferenttypes = count($object->linkedObjects);
  7795. print '<!-- showLinkedObjectBlock -->';
  7796. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7797. print '<div class="div-table-responsive-no-min">';
  7798. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="' . $object->element . '" data-elementid="' . $object->id . '" >';
  7799. print '<tr class="liste_titre">';
  7800. print '<td>' . $langs->trans("Type") . '</td>';
  7801. print '<td>' . $langs->trans("Ref") . '</td>';
  7802. print '<td class="center"></td>';
  7803. print '<td class="center">' . $langs->trans("Date") . '</td>';
  7804. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  7805. print '<td class="right">' . $langs->trans("Status") . '</td>';
  7806. print '<td></td>';
  7807. print '</tr>';
  7808. $nboftypesoutput = 0;
  7809. foreach ($object->linkedObjects as $objecttype => $objects) {
  7810. $tplpath = $element = $subelement = $objecttype;
  7811. // to display inport button on tpl
  7812. $showImportButton = false;
  7813. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7814. $showImportButton = true;
  7815. }
  7816. $regs = array();
  7817. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7818. $element = $regs[1];
  7819. $subelement = $regs[2];
  7820. $tplpath = $element . '/' . $subelement;
  7821. }
  7822. $tplname = 'linkedobjectblock';
  7823. // To work with non standard path
  7824. if ($objecttype == 'facture') {
  7825. $tplpath = 'compta/' . $element;
  7826. if (!isModEnabled('facture')) {
  7827. continue; // Do not show if module disabled
  7828. }
  7829. } elseif ($objecttype == 'facturerec') {
  7830. $tplpath = 'compta/facture';
  7831. $tplname = 'linkedobjectblockForRec';
  7832. if (!isModEnabled('facture')) {
  7833. continue; // Do not show if module disabled
  7834. }
  7835. } elseif ($objecttype == 'propal') {
  7836. $tplpath = 'comm/' . $element;
  7837. if (!isModEnabled('propal')) {
  7838. continue; // Do not show if module disabled
  7839. }
  7840. } elseif ($objecttype == 'supplier_proposal') {
  7841. if (!isModEnabled('supplier_proposal')) {
  7842. continue; // Do not show if module disabled
  7843. }
  7844. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
  7845. $tplpath = 'expedition';
  7846. if (!isModEnabled('expedition')) {
  7847. continue; // Do not show if module disabled
  7848. }
  7849. } elseif ($objecttype == 'reception') {
  7850. $tplpath = 'reception';
  7851. if (!isModEnabled('reception')) {
  7852. continue; // Do not show if module disabled
  7853. }
  7854. } elseif ($objecttype == 'delivery') {
  7855. $tplpath = 'delivery';
  7856. if (!isModEnabled('expedition')) {
  7857. continue; // Do not show if module disabled
  7858. }
  7859. } elseif ($objecttype == 'ficheinter') {
  7860. $tplpath = 'fichinter';
  7861. if (!isModEnabled('ficheinter')) {
  7862. continue; // Do not show if module disabled
  7863. }
  7864. } elseif ($objecttype == 'invoice_supplier') {
  7865. $tplpath = 'fourn/facture';
  7866. } elseif ($objecttype == 'order_supplier') {
  7867. $tplpath = 'fourn/commande';
  7868. } elseif ($objecttype == 'expensereport') {
  7869. $tplpath = 'expensereport';
  7870. } elseif ($objecttype == 'subscription') {
  7871. $tplpath = 'adherents';
  7872. } elseif ($objecttype == 'conferenceorbooth') {
  7873. $tplpath = 'eventorganization';
  7874. } elseif ($objecttype == 'conferenceorboothattendee') {
  7875. $tplpath = 'eventorganization';
  7876. } elseif ($objecttype == 'mo') {
  7877. $tplpath = 'mrp';
  7878. if (!isModEnabled('mrp')) {
  7879. continue; // Do not show if module disabled
  7880. }
  7881. }
  7882. global $linkedObjectBlock;
  7883. $linkedObjectBlock = $objects;
  7884. // Output template part (modules that overwrite templates must declare this into descriptor)
  7885. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/' . $tplpath . '/tpl'));
  7886. foreach ($dirtpls as $reldir) {
  7887. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7888. global $noMoreLinkedObjectBlockAfter;
  7889. $noMoreLinkedObjectBlockAfter = 1;
  7890. }
  7891. $res = @include dol_buildpath($reldir . '/' . $tplname . '.tpl.php');
  7892. if ($res) {
  7893. $nboftypesoutput++;
  7894. break;
  7895. }
  7896. }
  7897. }
  7898. if (!$nboftypesoutput) {
  7899. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">' . $langs->trans("None") . '</span></td></tr>';
  7900. }
  7901. print '</table>';
  7902. if (!empty($compatibleImportElementsList)) {
  7903. $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
  7904. }
  7905. print '</div>';
  7906. return $nbofdifferenttypes;
  7907. }
  7908. }
  7909. /**
  7910. * Show block with links to link to other objects.
  7911. *
  7912. * @param CommonObject $object Object we want to show links to
  7913. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7914. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7915. * @return string <0 if KO, >0 if OK
  7916. */
  7917. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7918. {
  7919. global $conf, $langs, $hookmanager;
  7920. global $action;
  7921. $linktoelem = '';
  7922. $linktoelemlist = '';
  7923. $listofidcompanytoscan = '';
  7924. if (!is_object($object->thirdparty)) {
  7925. $object->fetch_thirdparty();
  7926. }
  7927. $possiblelinks = array();
  7928. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7929. $listofidcompanytoscan = $object->thirdparty->id;
  7930. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7931. $listofidcompanytoscan .= ',' . $object->thirdparty->parent;
  7932. }
  7933. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7934. include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  7935. $tmpproject = new Project($this->db);
  7936. $tmpproject->fetch($object->fk_project);
  7937. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7938. $listofidcompanytoscan .= ',' . $tmpproject->socid;
  7939. }
  7940. unset($tmpproject);
  7941. }
  7942. $possiblelinks = array(
  7943. 'propal' => array(
  7944. 'enabled' => isModEnabled('propal'),
  7945. 'perms' => 1,
  7946. 'label' => 'LinkToProposal',
  7947. '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') . ')'
  7948. ),
  7949. 'shipping' => array(
  7950. 'enabled' => isModEnabled('expedition'),
  7951. 'perms' => 1,
  7952. 'label' => 'LinkToExpedition',
  7953. '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') . ')'
  7954. ),
  7955. 'order' => array(
  7956. 'enabled' => isModEnabled('commande'),
  7957. 'perms' => 1,
  7958. 'label' => 'LinkToOrder',
  7959. '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') . ')'
  7960. ),
  7961. 'invoice' => array(
  7962. 'enabled' => isModEnabled('facture'),
  7963. 'perms' => 1,
  7964. 'label' => 'LinkToInvoice',
  7965. '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') . ')'
  7966. ),
  7967. 'invoice_template' => array(
  7968. 'enabled' => isModEnabled('facture'),
  7969. 'perms' => 1,
  7970. 'label' => 'LinkToTemplateInvoice',
  7971. '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') . ')'
  7972. ),
  7973. 'contrat' => array(
  7974. 'enabled' => isModEnabled('contrat'),
  7975. 'perms' => 1,
  7976. 'label' => 'LinkToContract',
  7977. '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
  7978. 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'
  7979. ),
  7980. 'fichinter' => array(
  7981. 'enabled' => isModEnabled('ficheinter'),
  7982. 'perms' => 1,
  7983. 'label' => 'LinkToIntervention',
  7984. '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') . ')'
  7985. ),
  7986. 'supplier_proposal' => array(
  7987. 'enabled' => (isModEnabled('supplier_proposal') ? $conf->supplier_proposal->enabled : 0),
  7988. 'perms' => 1,
  7989. 'label' => 'LinkToSupplierProposal',
  7990. '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') . ')'
  7991. ),
  7992. 'order_supplier' => array(
  7993. 'enabled' => (isModEnabled("supplier_order") ? $conf->supplier_order->enabled : 0),
  7994. 'perms' => 1,
  7995. 'label' => 'LinkToSupplierOrder',
  7996. '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') . ')'
  7997. ),
  7998. 'invoice_supplier' => array(
  7999. 'enabled' => (isModEnabled("supplier_invoice") ? $conf->supplier_invoice->enabled : 0),
  8000. 'perms' => 1,
  8001. 'label' => 'LinkToSupplierInvoice',
  8002. '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') . ')'
  8003. ),
  8004. 'ticket' => array(
  8005. 'enabled' => isModEnabled('ticket'),
  8006. 'perms' => 1,
  8007. 'label' => 'LinkToTicket',
  8008. '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') . ')'
  8009. ),
  8010. 'mo' => array(
  8011. 'enabled' => isModEnabled('mrp'),
  8012. 'perms' => 1,
  8013. 'label' => 'LinkToMo',
  8014. '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') . ')'
  8015. )
  8016. );
  8017. }
  8018. if ($object->table_element == 'commande_fournisseur') {
  8019. $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') . ')';
  8020. } elseif ($object->table_element == 'mrp_mo') {
  8021. $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') . ')';
  8022. }
  8023. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  8024. // Can complete the possiblelink array
  8025. $hookmanager->initHooks(array('commonobject'));
  8026. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  8027. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8028. }
  8029. if (empty($reshook)) {
  8030. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8031. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  8032. }
  8033. } elseif ($reshook > 0) {
  8034. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8035. $possiblelinks = $hookmanager->resArray;
  8036. }
  8037. }
  8038. foreach ($possiblelinks as $key => $possiblelink) {
  8039. $num = 0;
  8040. if (empty($possiblelink['enabled'])) {
  8041. continue;
  8042. }
  8043. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  8044. print '<div id="' . $key . 'list"' . (empty($conf->use_javascript_ajax) ? '' : ' style="display:none"') . '>';
  8045. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8046. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  8047. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8048. print '<input type="hidden" name="action" value="addlinkbyref">';
  8049. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8050. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8051. print '<table class="noborder">';
  8052. print '<tr>';
  8053. print '<td>' . $langs->trans("Ref") . '</td>';
  8054. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;';
  8055. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
  8056. print '<input type="submit" class="button smallpaddingimp" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  8057. print '</tr>';
  8058. print '</table>';
  8059. print '</form>';
  8060. }
  8061. $sql = $possiblelink['sql'];
  8062. $resqllist = $this->db->query($sql);
  8063. if ($resqllist) {
  8064. $num = $this->db->num_rows($resqllist);
  8065. $i = 0;
  8066. print '<br>';
  8067. print '<form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinked' . $key . '">';
  8068. print '<input type="hidden" name="action" value="addlink">';
  8069. print '<input type="hidden" name="token" value="' . newToken() . '">';
  8070. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8071. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8072. print '<table class="noborder">';
  8073. print '<tr class="liste_titre">';
  8074. print '<td class="nowrap"></td>';
  8075. print '<td class="center">' . $langs->trans("Ref") . '</td>';
  8076. print '<td class="left">' . $langs->trans("RefCustomer") . '</td>';
  8077. print '<td class="right">' . $langs->trans("AmountHTShort") . '</td>';
  8078. print '<td class="left">' . $langs->trans("Company") . '</td>';
  8079. print '</tr>';
  8080. while ($i < $num) {
  8081. $objp = $this->db->fetch_object($resqllist);
  8082. print '<tr class="oddeven">';
  8083. print '<td class="left">';
  8084. print '<input type="radio" name="idtolinkto" id="' . $key . '_' . $objp->rowid . '" value="' . $objp->rowid . '">';
  8085. print '</td>';
  8086. print '<td class="center"><label for="' . $key . '_' . $objp->rowid . '">' . $objp->ref . '</label></td>';
  8087. print '<td>' . (!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')) . '</td>';
  8088. print '<td class="right">';
  8089. if ($possiblelink['label'] == 'LinkToContract') {
  8090. $form = new Form($this->db);
  8091. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")) . ' ';
  8092. }
  8093. print '<span class="amount">' . (isset($objp->total_ht) ? price($objp->total_ht) : '') . '</span>';
  8094. print '</td>';
  8095. print '<td>' . $objp->name . '</td>';
  8096. print '</tr>';
  8097. $i++;
  8098. }
  8099. print '</table>';
  8100. print '<div class="center">';
  8101. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="' . $langs->trans('ToLink') . '">';
  8102. if (empty($conf->use_javascript_ajax)) {
  8103. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8104. } else {
  8105. print '<input type="submit"; onclick="javascript:jQuery(\'#' . $key . 'list\').toggle(); return false;" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="' . $langs->trans("Cancel") . '"></div>';
  8106. }
  8107. print '</form>';
  8108. $this->db->free($resqllist);
  8109. } else {
  8110. dol_print_error($this->db);
  8111. }
  8112. print '</div>';
  8113. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  8114. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8115. $linktoelemlist .= '<li><a href="#linkto' . $key . '" class="linkto dropdowncloseonclick" rel="' . $key . '">' . $langs->trans($possiblelink['label']) . ' (' . $num . ')</a></li>';
  8116. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  8117. } else {
  8118. $linktoelemlist .= '<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  8119. }
  8120. }
  8121. }
  8122. if ($linktoelemlist) {
  8123. $linktoelem = '
  8124. <dl class="dropdown" id="linktoobjectname">
  8125. ';
  8126. if (!empty($conf->use_javascript_ajax)) {
  8127. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>' . $langs->trans("LinkTo") . '...</a></dt>';
  8128. }
  8129. $linktoelem .= '<dd>
  8130. <div class="multiselectlinkto">
  8131. <ul class="ulselectedfields">' . $linktoelemlist . '
  8132. </ul>
  8133. </div>
  8134. </dd>
  8135. </dl>';
  8136. } else {
  8137. $linktoelem = '';
  8138. }
  8139. if (!empty($conf->use_javascript_ajax)) {
  8140. print '<!-- Add js to show linkto box -->
  8141. <script>
  8142. jQuery(document).ready(function() {
  8143. jQuery(".linkto").click(function() {
  8144. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  8145. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  8146. });
  8147. });
  8148. </script>
  8149. ';
  8150. }
  8151. return $linktoelem;
  8152. }
  8153. /**
  8154. * Return an html string with a select combo box to choose yes or no
  8155. *
  8156. * @param string $htmlname Name of html select field
  8157. * @param string $value Pre-selected value
  8158. * @param int $option 0 return yes/no, 1 return 1/0
  8159. * @param bool $disabled true or false
  8160. * @param int $useempty 1=Add empty line
  8161. * @param int $addjscombo 1=Add js beautifier on combo box
  8162. * @param string $morecss More CSS
  8163. * @param string $labelyes Label for Yes
  8164. * @param string $labelno Label for No
  8165. * @return string See option
  8166. */
  8167. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8168. {
  8169. global $langs;
  8170. $yes = "yes";
  8171. $no = "no";
  8172. if ($option) {
  8173. $yes = "1";
  8174. $no = "0";
  8175. }
  8176. $disabled = ($disabled ? ' disabled' : '');
  8177. $resultyesno = '<select class="flat width75' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . '"' . $disabled . '>' . "\n";
  8178. if ($useempty) {
  8179. $resultyesno .= '<option value="-1"' . (($value < 0) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8180. }
  8181. if (("$value" == 'yes') || ($value == 1)) {
  8182. $resultyesno .= '<option value="' . $yes . '" selected>' . $langs->trans($labelyes) . '</option>' . "\n";
  8183. $resultyesno .= '<option value="' . $no . '">' . $langs->trans($labelno) . '</option>' . "\n";
  8184. } else {
  8185. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8186. $resultyesno .= '<option value="' . $yes . '">' . $langs->trans($labelyes) . '</option>' . "\n";
  8187. $resultyesno .= '<option value="' . $no . '"' . $selected . '>' . $langs->trans($labelno) . '</option>' . "\n";
  8188. }
  8189. $resultyesno .= '</select>' . "\n";
  8190. if ($addjscombo) {
  8191. $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
  8192. }
  8193. return $resultyesno;
  8194. }
  8195. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8196. /**
  8197. * Return list of export templates
  8198. *
  8199. * @param string $selected Id modele pre-selectionne
  8200. * @param string $htmlname Name of HTML select
  8201. * @param string $type Type of searched templates
  8202. * @param int $useempty Affiche valeur vide dans liste
  8203. * @return void
  8204. */
  8205. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8206. {
  8207. // phpcs:enable
  8208. $sql = "SELECT rowid, label";
  8209. $sql .= " FROM " . $this->db->prefix() . "export_model";
  8210. $sql .= " WHERE type = '" . $this->db->escape($type) . "'";
  8211. $sql .= " ORDER BY rowid";
  8212. $result = $this->db->query($sql);
  8213. if ($result) {
  8214. print '<select class="flat" id="select_' . $htmlname . '" name="' . $htmlname . '">';
  8215. if ($useempty) {
  8216. print '<option value="-1">&nbsp;</option>';
  8217. }
  8218. $num = $this->db->num_rows($result);
  8219. $i = 0;
  8220. while ($i < $num) {
  8221. $obj = $this->db->fetch_object($result);
  8222. if ($selected == $obj->rowid) {
  8223. print '<option value="' . $obj->rowid . '" selected>';
  8224. } else {
  8225. print '<option value="' . $obj->rowid . '">';
  8226. }
  8227. print $obj->label;
  8228. print '</option>';
  8229. $i++;
  8230. }
  8231. print "</select>";
  8232. } else {
  8233. dol_print_error($this->db);
  8234. }
  8235. }
  8236. /**
  8237. * Return a HTML area with the reference of object and a navigation bar for a business object
  8238. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8239. *
  8240. * @param object $object Object to show.
  8241. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8242. * @param string $morehtml More html content to output just before the nav bar.
  8243. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8244. * @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.
  8245. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8246. * @param string $morehtmlref More html to show after ref.
  8247. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8248. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8249. * @param string $morehtmlleft More html code to show before ref.
  8250. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8251. * @param string $morehtmlright More html code to show after ref.
  8252. * @return string Portion HTML with ref + navigation buttons
  8253. */
  8254. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8255. {
  8256. global $conf, $langs, $hookmanager, $extralanguages;
  8257. $ret = '';
  8258. if (empty($fieldid)) {
  8259. $fieldid = 'rowid';
  8260. }
  8261. if (empty($fieldref)) {
  8262. $fieldref = 'ref';
  8263. }
  8264. // Preparing gender's display if there is one
  8265. $addgendertxt = '';
  8266. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8267. $addgendertxt = ' ';
  8268. switch ($object->gender) {
  8269. case 'man':
  8270. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8271. break;
  8272. case 'woman':
  8273. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8274. break;
  8275. case 'other':
  8276. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8277. break;
  8278. }
  8279. }
  8280. /*
  8281. $addadmin = '';
  8282. if (property_exists($object, 'admin')) {
  8283. if (isModEnabled('multicompany') && !empty($object->admin) && empty($object->entity)) {
  8284. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8285. } elseif (!empty($object->admin)) {
  8286. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8287. }
  8288. }*/
  8289. // Add where from hooks
  8290. if (is_object($hookmanager)) {
  8291. $parameters = array('showrefnav' => true);
  8292. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8293. $object->next_prev_filter .= $hookmanager->resPrint;
  8294. }
  8295. $previous_ref = $next_ref = '';
  8296. if ($shownav) {
  8297. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8298. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8299. $navurl = $_SERVER["PHP_SELF"];
  8300. // Special case for project/task page
  8301. if ($paramid == 'project_ref') {
  8302. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8303. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8304. $paramid = 'ref';
  8305. }
  8306. }
  8307. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8308. // accesskey is for Mac: CTRL + key for all browsers
  8309. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8310. if ($conf->browser->name == 'chrome') {
  8311. $stringforfirstkey .= ' ALT +';
  8312. } elseif ($conf->browser->name == 'firefox') {
  8313. $stringforfirstkey .= ' ALT + SHIFT +';
  8314. } else {
  8315. $stringforfirstkey .= ' CTL +';
  8316. }
  8317. $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>';
  8318. $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>';
  8319. }
  8320. //print "xx".$previous_ref."x".$next_ref;
  8321. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8322. // Right part of banner
  8323. if ($morehtmlright) {
  8324. $ret .= '<div class="inline-block floatleft">' . $morehtmlright . '</div>';
  8325. }
  8326. if ($previous_ref || $next_ref || $morehtml) {
  8327. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8328. }
  8329. if ($morehtml) {
  8330. $ret .= '<li class="noborder litext' . (($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '') . '">' . $morehtml . '</li>';
  8331. }
  8332. if ($shownav && ($previous_ref || $next_ref)) {
  8333. $ret .= '<li class="pagination">' . $previous_ref . '</li>';
  8334. $ret .= '<li class="pagination">' . $next_ref . '</li>';
  8335. }
  8336. if ($previous_ref || $next_ref || $morehtml) {
  8337. $ret .= '</ul></div>';
  8338. }
  8339. $parameters = array();
  8340. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8341. if (empty($reshook)) {
  8342. $morehtmlstatus .= $hookmanager->resPrint;
  8343. } else {
  8344. $morehtmlstatus = $hookmanager->resPrint;
  8345. }
  8346. if ($morehtmlstatus) {
  8347. $ret .= '<div class="statusref">' . $morehtmlstatus . '</div>';
  8348. }
  8349. $parameters = array();
  8350. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8351. if (empty($reshook)) {
  8352. $morehtmlref .= $hookmanager->resPrint;
  8353. } elseif ($reshook > 0) {
  8354. $morehtmlref = $hookmanager->resPrint;
  8355. }
  8356. // Left part of banner
  8357. if ($morehtmlleft) {
  8358. if ($conf->browser->layout == 'phone') {
  8359. $ret .= '<!-- morehtmlleft --><div class="floatleft">' . $morehtmlleft . '</div>'; // class="center" to have photo in middle
  8360. } else {
  8361. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">' . $morehtmlleft . '</div>';
  8362. }
  8363. }
  8364. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8365. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid' . (($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '') . '">';
  8366. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8367. if ($object->element == 'societe') {
  8368. $ret .= dol_htmlentities($object->name);
  8369. // List of extra languages
  8370. $arrayoflangcode = array();
  8371. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8372. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8373. }
  8374. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8375. if (!is_object($extralanguages)) {
  8376. include_once DOL_DOCUMENT_ROOT . '/core/class/extralanguages.class.php';
  8377. $extralanguages = new ExtraLanguages($this->db);
  8378. }
  8379. $extralanguages->fetch_name_extralanguages('societe');
  8380. if (!empty($extralanguages->attributes['societe']['name'])) {
  8381. $object->fetchValuesForExtraLanguages();
  8382. $htmltext = '';
  8383. // If there is extra languages
  8384. foreach ($arrayoflangcode as $extralangcode) {
  8385. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8386. if ($object->array_languages['name'][$extralangcode]) {
  8387. $htmltext .= $object->array_languages['name'][$extralangcode];
  8388. } else {
  8389. $htmltext .= '<span class="opacitymedium">' . $langs->trans("SwitchInEditModeToAddTranslation") . '</span>';
  8390. }
  8391. }
  8392. $ret .= '<!-- Show translations of name -->' . "\n";
  8393. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8394. }
  8395. }
  8396. } elseif ($object->element == 'member') {
  8397. $ret .= $object->ref . '<br>';
  8398. $fullname = $object->getFullName($langs);
  8399. if ($object->morphy == 'mor' && $object->societe) {
  8400. $ret .= dol_htmlentities($object->societe) . ((!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '');
  8401. } else {
  8402. $ret .= dol_htmlentities($fullname) . $addgendertxt . ((!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities($object->societe) . ')' : '');
  8403. }
  8404. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8405. $ret .= dol_htmlentities($object->getFullName($langs)) . $addgendertxt;
  8406. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8407. $ret .= $object->ref . '<br>' . $object->label;
  8408. } elseif (in_array($object->element, array('adherent_type'))) {
  8409. $ret .= $object->label;
  8410. } elseif ($object->element == 'ecm_directories') {
  8411. $ret .= '';
  8412. } elseif ($fieldref != 'none') {
  8413. $ret .= dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "");
  8414. }
  8415. if ($morehtmlref) {
  8416. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8417. if (substr($morehtmlref, 0, 4) != '<div') {
  8418. $ret .= ' ';
  8419. }
  8420. $ret .= $morehtmlref;
  8421. }
  8422. $ret .= '</div>';
  8423. $ret .= '</div><!-- End banner content -->';
  8424. return $ret;
  8425. }
  8426. /**
  8427. * Return HTML code to output a barcode
  8428. *
  8429. * @param Object $object Object containing data to retrieve file name
  8430. * @param int $width Width of photo
  8431. * @param string $morecss More CSS on img of barcode
  8432. * @return string HTML code to output barcode
  8433. */
  8434. public function showbarcode(&$object, $width = 100, $morecss = '')
  8435. {
  8436. global $conf;
  8437. //Check if barcode is filled in the card
  8438. if (empty($object->barcode)) {
  8439. return '';
  8440. }
  8441. // Complete object if not complete
  8442. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8443. $result = $object->fetch_barcode();
  8444. //Check if fetch_barcode() failed
  8445. if ($result < 1) {
  8446. return '<!-- ErrorFetchBarcode -->';
  8447. }
  8448. }
  8449. // Barcode image
  8450. $url = DOL_URL_ROOT . '/viewimage.php?modulepart=barcode&generator=' . urlencode($object->barcode_type_coder) . '&code=' . urlencode($object->barcode) . '&encoding=' . urlencode($object->barcode_type_code);
  8451. $out = '<!-- url barcode = ' . $url . ' -->';
  8452. $out .= '<img src="' . $url . '"' . ($morecss ? ' class="' . $morecss . '"' : '') . '>';
  8453. return $out;
  8454. }
  8455. /**
  8456. * Return HTML code to output a photo
  8457. *
  8458. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8459. * @param object $object Object containing data to retrieve file name
  8460. * @param int $width Width of photo
  8461. * @param int $height Height of photo (auto if 0)
  8462. * @param int $caneditfield Add edit fields
  8463. * @param string $cssclass CSS name to use on img for photo
  8464. * @param string $imagesize 'mini', 'small' or '' (original)
  8465. * @param int $addlinktofullsize Add link to fullsize image
  8466. * @param int $cache 1=Accept to use image in cache
  8467. * @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 ''.
  8468. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8469. * @return string HTML code to output photo
  8470. */
  8471. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8472. {
  8473. global $conf, $langs;
  8474. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8475. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8476. $ret = '';
  8477. $dir = '';
  8478. $file = '';
  8479. $originalfile = '';
  8480. $altfile = '';
  8481. $email = '';
  8482. $capture = '';
  8483. if ($modulepart == 'societe') {
  8484. $dir = $conf->societe->multidir_output[$entity];
  8485. if (!empty($object->logo)) {
  8486. if (dolIsAllowedForPreview($object->logo)) {
  8487. if ((string) $imagesize == 'mini') {
  8488. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8489. } elseif ((string) $imagesize == 'small') {
  8490. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . getImageFileNameForSize($object->logo, '_small');
  8491. } else {
  8492. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8493. }
  8494. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty') . 'logos/' . $object->logo;
  8495. }
  8496. }
  8497. $email = $object->email;
  8498. } elseif ($modulepart == 'contact') {
  8499. $dir = $conf->societe->multidir_output[$entity] . '/contact';
  8500. if (!empty($object->photo)) {
  8501. if (dolIsAllowedForPreview($object->photo)) {
  8502. if ((string) $imagesize == 'mini') {
  8503. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8504. } elseif ((string) $imagesize == 'small') {
  8505. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8506. } else {
  8507. $file = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8508. }
  8509. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact') . 'photos/' . $object->photo;
  8510. }
  8511. }
  8512. $email = $object->email;
  8513. $capture = 'user';
  8514. } elseif ($modulepart == 'userphoto') {
  8515. $dir = $conf->user->dir_output;
  8516. if (!empty($object->photo)) {
  8517. if (dolIsAllowedForPreview($object->photo)) {
  8518. if ((string) $imagesize == 'mini') {
  8519. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8520. } elseif ((string) $imagesize == 'small') {
  8521. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8522. } else {
  8523. $file = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8524. }
  8525. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user') . 'photos/' . $object->photo;
  8526. }
  8527. }
  8528. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8529. $altfile = $object->id . ".jpg"; // For backward compatibility
  8530. }
  8531. $email = $object->email;
  8532. $capture = 'user';
  8533. } elseif ($modulepart == 'memberphoto') {
  8534. $dir = $conf->adherent->dir_output;
  8535. if (!empty($object->photo)) {
  8536. if (dolIsAllowedForPreview($object->photo)) {
  8537. if ((string) $imagesize == 'mini') {
  8538. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8539. } elseif ((string) $imagesize == 'small') {
  8540. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8541. } else {
  8542. $file = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8543. }
  8544. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member') . 'photos/' . $object->photo;
  8545. }
  8546. }
  8547. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8548. $altfile = $object->id . ".jpg"; // For backward compatibility
  8549. }
  8550. $email = $object->email;
  8551. $capture = 'user';
  8552. } else {
  8553. // Generic case to show photos
  8554. $dir = $conf->$modulepart->dir_output;
  8555. if (!empty($object->photo)) {
  8556. if (dolIsAllowedForPreview($object->photo)) {
  8557. if ((string) $imagesize == 'mini') {
  8558. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_mini');
  8559. } elseif ((string) $imagesize == 'small') {
  8560. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . getImageFileNameForSize($object->photo, '_small');
  8561. } else {
  8562. $file = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8563. }
  8564. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart) . 'photos/' . $object->photo;
  8565. }
  8566. }
  8567. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8568. $altfile = $object->id . ".jpg"; // For backward compatibility
  8569. }
  8570. $email = $object->email;
  8571. }
  8572. if ($forcecapture) {
  8573. $capture = $forcecapture;
  8574. }
  8575. if ($dir) {
  8576. if ($file && file_exists($dir . "/" . $file)) {
  8577. if ($addlinktofullsize) {
  8578. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8579. if ($urladvanced) {
  8580. $ret .= '<a href="' . $urladvanced . '">';
  8581. } else {
  8582. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8583. }
  8584. }
  8585. $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 . '">';
  8586. if ($addlinktofullsize) {
  8587. $ret .= '</a>';
  8588. }
  8589. } elseif ($altfile && file_exists($dir . "/" . $altfile)) {
  8590. if ($addlinktofullsize) {
  8591. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity=' . $entity);
  8592. if ($urladvanced) {
  8593. $ret .= '<a href="' . $urladvanced . '">';
  8594. } else {
  8595. $ret .= '<a href="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $modulepart . '&entity=' . $entity . '&file=' . urlencode($originalfile) . '&cache=' . $cache . '">';
  8596. }
  8597. }
  8598. $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 . '">';
  8599. if ($addlinktofullsize) {
  8600. $ret .= '</a>';
  8601. }
  8602. } else {
  8603. $nophoto = '/public/theme/common/nophoto.png';
  8604. $defaultimg = 'identicon'; // For gravatar
  8605. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8606. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8607. $nophoto = 'company';
  8608. } else {
  8609. $nophoto = '/public/theme/common/user_anonymous.png';
  8610. if (!empty($object->gender) && $object->gender == 'man') {
  8611. $nophoto = '/public/theme/common/user_man.png';
  8612. }
  8613. if (!empty($object->gender) && $object->gender == 'woman') {
  8614. $nophoto = '/public/theme/common/user_woman.png';
  8615. }
  8616. }
  8617. }
  8618. if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
  8619. // see https://gravatar.com/site/implement/images/php/
  8620. $ret .= '<!-- Put link to gravatar -->';
  8621. $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
  8622. } else {
  8623. if ($nophoto == 'company') {
  8624. $ret .= '<div class="divforspanimg photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . '>' . img_picto('', 'company') . '</div>';
  8625. $ret .= '<div class="difforspanimgright"></div>';
  8626. } else {
  8627. $ret .= '<img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="" ' . ($width ? ' width="' . $width . '"' : '') . ($height ? ' height="' . $height . '"' : '') . ' src="' . DOL_URL_ROOT . $nophoto . '">';
  8628. }
  8629. }
  8630. }
  8631. if ($caneditfield) {
  8632. if ($object->photo) {
  8633. $ret .= "<br>\n";
  8634. }
  8635. $ret .= '<table class="nobordernopadding centpercent">';
  8636. if ($object->photo) {
  8637. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">' . $langs->trans("Delete") . '</label><br><br></td></tr>';
  8638. }
  8639. $ret .= '<tr><td class="tdoverflow">';
  8640. $maxfilesizearray = getMaxFileSizeArray();
  8641. $maxmin = $maxfilesizearray['maxmin'];
  8642. if ($maxmin > 0) {
  8643. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="' . ($maxmin * 1024) . '">'; // MAX_FILE_SIZE must precede the field type=file
  8644. }
  8645. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"' . ($capture ? ' capture="' . $capture . '"' : '') . '>';
  8646. $ret .= '</td></tr>';
  8647. $ret .= '</table>';
  8648. }
  8649. } else {
  8650. dol_print_error('', 'Call of showphoto with wrong parameters modulepart=' . $modulepart);
  8651. }
  8652. return $ret;
  8653. }
  8654. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8655. /**
  8656. * Return select list of groups
  8657. *
  8658. * @param string|object $selected Id group or group preselected
  8659. * @param string $htmlname Field name in form
  8660. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8661. * @param string|array $exclude Array list of groups id to exclude
  8662. * @param int $disabled If select list must be disabled
  8663. * @param string|array $include Array list of groups id to include
  8664. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8665. * @param string $force_entity '0' or Ids of environment to force
  8666. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8667. * @param string $morecss More css to add to html component
  8668. * @return string
  8669. * @see select_dolusers()
  8670. */
  8671. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8672. {
  8673. // phpcs:enable
  8674. global $conf, $user, $langs;
  8675. // Permettre l'exclusion de groupes
  8676. $excludeGroups = null;
  8677. if (is_array($exclude)) {
  8678. $excludeGroups = implode(",", $exclude);
  8679. }
  8680. // Permettre l'inclusion de groupes
  8681. $includeGroups = null;
  8682. if (is_array($include)) {
  8683. $includeGroups = implode(",", $include);
  8684. }
  8685. if (!is_array($selected)) {
  8686. $selected = array($selected);
  8687. }
  8688. $out = '';
  8689. // On recherche les groupes
  8690. $sql = "SELECT ug.rowid, ug.nom as name";
  8691. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8692. $sql .= ", e.label";
  8693. }
  8694. $sql .= " FROM " . $this->db->prefix() . "usergroup as ug ";
  8695. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8696. $sql .= " LEFT JOIN " . $this->db->prefix() . "entity as e ON e.rowid=ug.entity";
  8697. if ($force_entity) {
  8698. $sql .= " WHERE ug.entity IN (0, " . $force_entity . ")";
  8699. } else {
  8700. $sql .= " WHERE ug.entity IS NOT NULL";
  8701. }
  8702. } else {
  8703. $sql .= " WHERE ug.entity IN (0, " . $conf->entity . ")";
  8704. }
  8705. if (is_array($exclude) && $excludeGroups) {
  8706. $sql .= " AND ug.rowid NOT IN (" . $this->db->sanitize($excludeGroups) . ")";
  8707. }
  8708. if (is_array($include) && $includeGroups) {
  8709. $sql .= " AND ug.rowid IN (" . $this->db->sanitize($includeGroups) . ")";
  8710. }
  8711. $sql .= " ORDER BY ug.nom ASC";
  8712. dol_syslog(get_class($this) . "::select_dolgroups", LOG_DEBUG);
  8713. $resql = $this->db->query($sql);
  8714. if ($resql) {
  8715. // Enhance with select2
  8716. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  8717. $out .= '<select class="flat minwidth200' . ($morecss ? ' ' . $morecss : '') . '" id="' . $htmlname . '" name="' . $htmlname . ($multiple ? '[]' : '') . '" ' . ($multiple ? 'multiple' : '') . ' ' . ($disabled ? ' disabled' : '') . '>';
  8718. $num = $this->db->num_rows($resql);
  8719. $i = 0;
  8720. if ($num) {
  8721. if ($show_empty && !$multiple) {
  8722. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '>&nbsp;</option>' . "\n";
  8723. }
  8724. while ($i < $num) {
  8725. $obj = $this->db->fetch_object($resql);
  8726. $disableline = 0;
  8727. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8728. $disableline = 1;
  8729. }
  8730. $out .= '<option value="' . $obj->rowid . '"';
  8731. if ($disableline) {
  8732. $out .= ' disabled';
  8733. }
  8734. 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))) {
  8735. $out .= ' selected';
  8736. }
  8737. $out .= '>';
  8738. $out .= $obj->name;
  8739. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8740. $out .= " (" . $obj->label . ")";
  8741. }
  8742. $out .= '</option>';
  8743. $i++;
  8744. }
  8745. } else {
  8746. if ($show_empty) {
  8747. $out .= '<option value="-1"' . (in_array(-1, $selected) ? ' selected' : '') . '></option>' . "\n";
  8748. }
  8749. $out .= '<option value="" disabled>' . $langs->trans("NoUserGroupDefined") . '</option>';
  8750. }
  8751. $out .= '</select>';
  8752. $out .= ajax_combobox($htmlname);
  8753. } else {
  8754. dol_print_error($this->db);
  8755. }
  8756. return $out;
  8757. }
  8758. /**
  8759. * Return HTML to show the search and clear seach button
  8760. *
  8761. * @param string $pos position colon on liste value left or right
  8762. * @return string
  8763. */
  8764. public function showFilterButtons($pos = '')
  8765. {
  8766. $out = '<div class="nowraponall">';
  8767. if ($pos == 'left') {
  8768. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8769. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8770. } else {
  8771. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8772. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8773. }
  8774. $out .= '</div>';
  8775. return $out;
  8776. }
  8777. /**
  8778. * Return HTML to show the search and clear search button
  8779. *
  8780. * @param string $cssclass CSS class
  8781. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8782. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8783. * @return string
  8784. */
  8785. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8786. {
  8787. global $conf, $langs;
  8788. $out = '';
  8789. if (!empty($conf->use_javascript_ajax)) {
  8790. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
  8791. }
  8792. $out .= '<script>
  8793. $(document).ready(function() {
  8794. $("#' . $cssclass . 's").click(function() {
  8795. if($(this).is(\':checked\')){
  8796. console.log("We check all ' . $cssclass . ' and trigger the change method");
  8797. $(".' . $cssclass . '").prop(\'checked\', true).trigger(\'change\');
  8798. }
  8799. else
  8800. {
  8801. console.log("We uncheck all");
  8802. $(".' . $cssclass . '").prop(\'checked\', false).trigger(\'change\');
  8803. }' . "\n";
  8804. if ($calljsfunction) {
  8805. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8806. }
  8807. $out .= ' });
  8808. $(".' . $cssclass . '").change(function() {
  8809. $(this).closest("tr").toggleClass("highlight", this.checked);
  8810. });
  8811. });
  8812. </script>';
  8813. return $out;
  8814. }
  8815. /**
  8816. * Return HTML to show the search and clear seach button
  8817. *
  8818. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8819. * @param string $cssclass CSS class
  8820. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8821. * @param string $massactionname Mass action name
  8822. * @return string
  8823. */
  8824. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8825. {
  8826. $out = $this->showFilterButtons();
  8827. if ($addcheckuncheckall) {
  8828. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8829. }
  8830. return $out;
  8831. }
  8832. /**
  8833. * Return HTML to show the select of expense categories
  8834. *
  8835. * @param string $selected preselected category
  8836. * @param string $htmlname name of HTML select list
  8837. * @param integer $useempty 1=Add empty line
  8838. * @param array $excludeid id to exclude
  8839. * @param string $target htmlname of target select to bind event
  8840. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8841. * @param array $params param to give
  8842. * @param int $info_admin Show the tooltip help picto to setup list
  8843. * @return string
  8844. */
  8845. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8846. {
  8847. global $langs, $user;
  8848. $out = '';
  8849. $sql = "SELECT rowid, label FROM " . $this->db->prefix() . "c_exp_tax_cat WHERE active = 1";
  8850. $sql .= " AND entity IN (0," . getEntity('exp_tax_cat') . ")";
  8851. if (!empty($excludeid)) {
  8852. $sql .= " AND rowid NOT IN (" . $this->db->sanitize(implode(',', $excludeid)) . ")";
  8853. }
  8854. $sql .= " ORDER BY label";
  8855. $resql = $this->db->query($sql);
  8856. if ($resql) {
  8857. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp maxwidth200">';
  8858. if ($useempty) {
  8859. $out .= '<option value="0">&nbsp;</option>';
  8860. }
  8861. while ($obj = $this->db->fetch_object($resql)) {
  8862. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . $langs->trans($obj->label) . '</option>';
  8863. }
  8864. $out .= '</select>';
  8865. $out .= ajax_combobox('select_' . $htmlname);
  8866. if (!empty($htmlname) && $user->admin && $info_admin) {
  8867. $out .= ' ' . info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8868. }
  8869. if (!empty($target)) {
  8870. $sql = "SELECT c.id FROM " . $this->db->prefix() . "c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8871. $resql = $this->db->query($sql);
  8872. if ($resql) {
  8873. if ($this->db->num_rows($resql) > 0) {
  8874. $obj = $this->db->fetch_object($resql);
  8875. $out .= '<script>
  8876. $(function() {
  8877. $("select[name=' . $target . ']").on("change", function() {
  8878. var current_val = $(this).val();
  8879. if (current_val == ' . $obj->id . ') {';
  8880. if (!empty($default_selected) || !empty($selected)) {
  8881. $out .= '$("select[name=' . $htmlname . ']").val("' . ($default_selected > 0 ? $default_selected : $selected) . '");';
  8882. }
  8883. $out .= '
  8884. $("select[name=' . $htmlname . ']").change();
  8885. }
  8886. });
  8887. $("select[name=' . $htmlname . ']").change(function() {
  8888. if ($("select[name=' . $target . ']").val() == ' . $obj->id . ') {
  8889. // get price of kilometer to fill the unit price
  8890. $.ajax({
  8891. method: "POST",
  8892. dataType: "json",
  8893. data: { fk_c_exp_tax_cat: $(this).val(), token: \'' . currentToken() . '\' },
  8894. url: "' . (DOL_URL_ROOT . '/expensereport/ajax/ajaxik.php?' . join('&', $params)) . '",
  8895. }).done(function( data, textStatus, jqXHR ) {
  8896. console.log(data);
  8897. if (typeof data.up != "undefined") {
  8898. $("input[name=value_unit]").val(data.up);
  8899. $("select[name=' . $htmlname . ']").attr("title", data.title);
  8900. } else {
  8901. $("input[name=value_unit]").val("");
  8902. $("select[name=' . $htmlname . ']").attr("title", "");
  8903. }
  8904. });
  8905. }
  8906. });
  8907. });
  8908. </script>';
  8909. }
  8910. }
  8911. }
  8912. } else {
  8913. dol_print_error($this->db);
  8914. }
  8915. return $out;
  8916. }
  8917. /**
  8918. * Return HTML to show the select ranges of expense range
  8919. *
  8920. * @param string $selected preselected category
  8921. * @param string $htmlname name of HTML select list
  8922. * @param integer $useempty 1=Add empty line
  8923. * @return string
  8924. */
  8925. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8926. {
  8927. global $conf, $langs;
  8928. $out = '';
  8929. $sql = "SELECT rowid, range_ik FROM " . $this->db->prefix() . "c_exp_tax_range";
  8930. $sql .= " WHERE entity = " . $conf->entity . " AND active = 1";
  8931. $resql = $this->db->query($sql);
  8932. if ($resql) {
  8933. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  8934. if ($useempty) {
  8935. $out .= '<option value="0"></option>';
  8936. }
  8937. while ($obj = $this->db->fetch_object($resql)) {
  8938. $out .= '<option ' . ($selected == $obj->rowid ? 'selected="selected"' : '') . ' value="' . $obj->rowid . '">' . price($obj->range_ik, 0, $langs, 1, 0) . '</option>';
  8939. }
  8940. $out .= '</select>';
  8941. } else {
  8942. dol_print_error($this->db);
  8943. }
  8944. return $out;
  8945. }
  8946. /**
  8947. * Return HTML to show a select of expense
  8948. *
  8949. * @param string $selected preselected category
  8950. * @param string $htmlname name of HTML select list
  8951. * @param integer $useempty 1=Add empty choice
  8952. * @param integer $allchoice 1=Add all choice
  8953. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8954. * @return string
  8955. */
  8956. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8957. {
  8958. global $langs;
  8959. $out = '';
  8960. $sql = "SELECT id, code, label FROM " . $this->db->prefix() . "c_type_fees";
  8961. $sql .= " WHERE active = 1";
  8962. $resql = $this->db->query($sql);
  8963. if ($resql) {
  8964. $out = '<select id="select_' . $htmlname . '" name="' . $htmlname . '" class="' . $htmlname . ' flat minwidth75imp">';
  8965. if ($useempty) {
  8966. $out .= '<option value="0"></option>';
  8967. }
  8968. if ($allchoice) {
  8969. $out .= '<option value="-1">' . $langs->trans('AllExpenseReport') . '</option>';
  8970. }
  8971. $field = 'code';
  8972. if ($useid) {
  8973. $field = 'id';
  8974. }
  8975. while ($obj = $this->db->fetch_object($resql)) {
  8976. $key = $langs->trans($obj->code);
  8977. $out .= '<option ' . ($selected == $obj->{$field} ? 'selected="selected"' : '') . ' value="' . $obj->{$field} . '">' . ($key != $obj->code ? $key : $obj->label) . '</option>';
  8978. }
  8979. $out .= '</select>';
  8980. } else {
  8981. dol_print_error($this->db);
  8982. }
  8983. return $out;
  8984. }
  8985. /**
  8986. * Output a combo list with invoices qualified for a third party
  8987. *
  8988. * @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)
  8989. * @param int $selected Id invoice preselected
  8990. * @param string $htmlname Name of HTML select
  8991. * @param int $maxlength Maximum length of label
  8992. * @param int $option_only Return only html options lines without the select tag
  8993. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8994. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8995. * @param int $forcefocus Force focus on field (works with javascript only)
  8996. * @param int $disabled Disabled
  8997. * @param string $morecss More css added to the select component
  8998. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8999. * @param string $showproject 'all' = Show project info, ''=Hide project info
  9000. * @param User $usertofilter User object to use for filtering
  9001. * @return int Nbr of project if OK, <0 if KO
  9002. */
  9003. 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)
  9004. {
  9005. global $user, $conf, $langs;
  9006. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  9007. if (is_null($usertofilter)) {
  9008. $usertofilter = $user;
  9009. }
  9010. $out = '';
  9011. $hideunselectables = false;
  9012. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  9013. $hideunselectables = true;
  9014. }
  9015. if (empty($projectsListId)) {
  9016. if (empty($usertofilter->rights->projet->all->lire)) {
  9017. $projectstatic = new Project($this->db);
  9018. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  9019. }
  9020. }
  9021. // Search all projects
  9022. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  9023. p.title, p.fk_soc, p.fk_statut, p.public,";
  9024. $sql .= ' s.nom as name';
  9025. $sql .= ' FROM ' . $this->db->prefix() . 'projet as p';
  9026. $sql .= ' LEFT JOIN ' . $this->db->prefix() . 'societe as s ON s.rowid = p.fk_soc,';
  9027. $sql .= ' ' . $this->db->prefix() . 'facture as f';
  9028. $sql .= " WHERE p.entity IN (" . getEntity('project') . ")";
  9029. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  9030. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  9031. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  9032. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  9033. $sql .= " ORDER BY p.ref, f.ref ASC";
  9034. $resql = $this->db->query($sql);
  9035. if ($resql) {
  9036. // Use select2 selector
  9037. if (!empty($conf->use_javascript_ajax)) {
  9038. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9039. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9040. $out .= $comboenhancement;
  9041. $morecss = 'minwidth200imp maxwidth500';
  9042. }
  9043. if (empty($option_only)) {
  9044. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9045. }
  9046. if (!empty($show_empty)) {
  9047. $out .= '<option value="0" class="optiongrey">';
  9048. if (!is_numeric($show_empty)) {
  9049. $out .= $show_empty;
  9050. } else {
  9051. $out .= '&nbsp;';
  9052. }
  9053. $out .= '</option>';
  9054. }
  9055. $num = $this->db->num_rows($resql);
  9056. $i = 0;
  9057. if ($num) {
  9058. while ($i < $num) {
  9059. $obj = $this->db->fetch_object($resql);
  9060. // 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.
  9061. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  9062. // Do nothing
  9063. } else {
  9064. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  9065. $i++;
  9066. continue;
  9067. }
  9068. $labeltoshow = '';
  9069. if ($showproject == 'all') {
  9070. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  9071. if ($obj->name) {
  9072. $labeltoshow .= ' - ' . $obj->name; // Soc name
  9073. }
  9074. $disabled = 0;
  9075. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  9076. $disabled = 1;
  9077. $labeltoshow .= ' - ' . $langs->trans("Draft");
  9078. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  9079. if ($discard_closed == 2) {
  9080. $disabled = 1;
  9081. }
  9082. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9083. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  9084. $disabled = 1;
  9085. $labeltoshow .= ' - ' . $langs->trans("LinkedToAnotherCompany");
  9086. }
  9087. }
  9088. if (!empty($selected) && $selected == $obj->rowid) {
  9089. $out .= '<option value="' . $obj->rowid . '" selected';
  9090. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9091. $out .= '>' . $labeltoshow . '</option>';
  9092. } else {
  9093. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  9094. $resultat = '';
  9095. } else {
  9096. $resultat = '<option value="' . $obj->rowid . '"';
  9097. if ($disabled) {
  9098. $resultat .= ' disabled';
  9099. }
  9100. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  9101. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  9102. $resultat .= '>';
  9103. $resultat .= $labeltoshow;
  9104. $resultat .= '</option>';
  9105. }
  9106. $out .= $resultat;
  9107. }
  9108. }
  9109. $i++;
  9110. }
  9111. }
  9112. if (empty($option_only)) {
  9113. $out .= '</select>';
  9114. }
  9115. print $out;
  9116. $this->db->free($resql);
  9117. return $num;
  9118. } else {
  9119. dol_print_error($this->db);
  9120. return -1;
  9121. }
  9122. }
  9123. /**
  9124. * Output a combo list with invoices qualified for a third party
  9125. *
  9126. * @param int $selected Id invoice preselected
  9127. * @param string $htmlname Name of HTML select
  9128. * @param int $maxlength Maximum length of label
  9129. * @param int $option_only Return only html options lines without the select tag
  9130. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9131. * @param int $forcefocus Force focus on field (works with javascript only)
  9132. * @param int $disabled Disabled
  9133. * @param string $morecss More css added to the select component
  9134. * @return int Nbr of project if OK, <0 if KO
  9135. */
  9136. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  9137. {
  9138. global $user, $conf, $langs;
  9139. $out = '';
  9140. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  9141. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  9142. //$sql.= ', el.fk_source';
  9143. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  9144. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  9145. $sql .= " ORDER BY f.titre ASC";
  9146. $resql = $this->db->query($sql);
  9147. if ($resql) {
  9148. // Use select2 selector
  9149. if (!empty($conf->use_javascript_ajax)) {
  9150. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9151. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9152. $out .= $comboenhancement;
  9153. $morecss = 'minwidth200imp maxwidth500';
  9154. }
  9155. if (empty($option_only)) {
  9156. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9157. }
  9158. if (!empty($show_empty)) {
  9159. $out .= '<option value="0" class="optiongrey">';
  9160. if (!is_numeric($show_empty)) {
  9161. $out .= $show_empty;
  9162. } else {
  9163. $out .= '&nbsp;';
  9164. }
  9165. $out .= '</option>';
  9166. }
  9167. $num = $this->db->num_rows($resql);
  9168. if ($num) {
  9169. while ($obj = $this->db->fetch_object($resql)) {
  9170. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9171. $disabled = 0;
  9172. if (!empty($obj->suspended)) {
  9173. $disabled = 1;
  9174. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9175. }
  9176. if (!empty($selected) && $selected == $obj->rowid) {
  9177. $out .= '<option value="' . $obj->rowid . '" selected';
  9178. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9179. $out .= '>' . $labeltoshow . '</option>';
  9180. } else {
  9181. if ($disabled && ($selected != $obj->rowid)) {
  9182. $resultat = '';
  9183. } else {
  9184. $resultat = '<option value="' . $obj->rowid . '"';
  9185. if ($disabled) {
  9186. $resultat .= ' disabled';
  9187. }
  9188. $resultat .= '>';
  9189. $resultat .= $labeltoshow;
  9190. $resultat .= '</option>';
  9191. }
  9192. $out .= $resultat;
  9193. }
  9194. }
  9195. }
  9196. if (empty($option_only)) {
  9197. $out .= '</select>';
  9198. }
  9199. print $out;
  9200. $this->db->free($resql);
  9201. return $num;
  9202. } else {
  9203. $this->errors[] = $this->db->lasterror;
  9204. return -1;
  9205. }
  9206. }
  9207. /**
  9208. * Output the component to make advanced search criteries
  9209. *
  9210. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9211. * @param array $search_component_params Array of selected search criterias
  9212. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9213. * @param string $search_component_params_hidden String with $search_component_params criterias
  9214. * @return string HTML component for advanced search
  9215. */
  9216. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9217. {
  9218. global $langs;
  9219. $ret = '';
  9220. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9221. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  9222. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9223. $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="' . dol_escape_htmltag($langs->trans("Filters")) . '" id="idsubimgproductdistribution"></span>';
  9224. //$ret .= $langs->trans("Filters");
  9225. $ret .= '</a>';
  9226. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9227. // Show select fields as tags.
  9228. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9229. if ($search_component_params_hidden) {
  9230. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9231. $search_component_params_hidden .= '(' . $search_component_params_hidden . ')';
  9232. }
  9233. $errormessage = '';
  9234. $searchtags = forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage);
  9235. if ($errormessage) {
  9236. print 'ERROR in parsing search string: ' . dol_escape_htmltag($errormessage);
  9237. }
  9238. //var_dump($searchtags);
  9239. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> ' . dol_escape_htmltag($searchtags) . '</span>';
  9240. }
  9241. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9242. //$ret .= search_component_params
  9243. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9244. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9245. $show_search_component_params_hidden = 1;
  9246. if ($show_search_component_params_hidden) {
  9247. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9248. }
  9249. $ret .= "<!-- We store the full search string into this field. For example: (t.ref:like:'SO-%') and ((t.ref:like:'CO-%') or (t.ref:like:'AA%')) -->";
  9250. $ret .= '<input type="hidden" name="search_component_params_hidden" value="' . dol_escape_htmltag($search_component_params_hidden) . '">';
  9251. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  9252. foreach ($arrayofcriterias as $criterias) {
  9253. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9254. if (in_array('search_' . $criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9255. continue;
  9256. }
  9257. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9258. continue;
  9259. }
  9260. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9261. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_start">';
  9262. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startyear">';
  9263. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startmonth">';
  9264. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_startday">';
  9265. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_end">';
  9266. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endyear">';
  9267. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endmonth">';
  9268. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '_endday">';
  9269. } else {
  9270. $ret .= '<input type="hidden" name="search_' . $criteriafamilykey . '">';
  9271. }
  9272. }
  9273. }
  9274. $ret .= '</div>';
  9275. $ret .= "<!-- Syntax of 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";
  9276. $ret .= '<input type="text" placeholder="' . $langs->trans("Search") . '" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9277. $ret .= '</div>';
  9278. $ret .= '</div>';
  9279. return $ret;
  9280. }
  9281. /**
  9282. * selectModelMail
  9283. *
  9284. * @param string $prefix Prefix
  9285. * @param string $modelType Model type
  9286. * @param int $default 1=Show also Default mail template
  9287. * @param int $addjscombo Add js combobox
  9288. * @return string HTML select string
  9289. */
  9290. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9291. {
  9292. global $langs, $user;
  9293. $retstring = '';
  9294. $TModels = array();
  9295. include_once DOL_DOCUMENT_ROOT . '/core/class/html.formmail.class.php';
  9296. $formmail = new FormMail($this->db);
  9297. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9298. if ($default) {
  9299. $TModels[0] = $langs->trans('DefaultMailModel');
  9300. }
  9301. if ($result > 0) {
  9302. foreach ($formmail->lines_model as $model) {
  9303. $TModels[$model->id] = $model->label;
  9304. }
  9305. }
  9306. $retstring .= '<select class="flat" id="select_' . $prefix . 'model_mail" name="' . $prefix . 'model_mail">';
  9307. foreach ($TModels as $id_model => $label_model) {
  9308. $retstring .= '<option value="' . $id_model . '"';
  9309. $retstring .= ">" . $label_model . "</option>";
  9310. }
  9311. $retstring .= "</select>";
  9312. if ($addjscombo) {
  9313. $retstring .= ajax_combobox('select_' . $prefix . 'model_mail');
  9314. }
  9315. return $retstring;
  9316. }
  9317. /**
  9318. * Output the buttons to submit a creation/edit form
  9319. *
  9320. * @param string $save_label Alternative label for save button
  9321. * @param string $cancel_label Alternative label for cancel button
  9322. * @param array $morebuttons Add additional buttons between save and cancel
  9323. * @param bool $withoutdiv Option to remove enclosing centered div
  9324. * @param string $morecss More CSS
  9325. * @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.
  9326. * @return string Html code with the buttons
  9327. */
  9328. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9329. {
  9330. global $langs;
  9331. $buttons = array();
  9332. $save = array(
  9333. 'name' => 'save',
  9334. 'label_key' => $save_label,
  9335. );
  9336. if ($save_label == 'Create' || $save_label == 'Add') {
  9337. $save['name'] = 'add';
  9338. } elseif ($save_label == 'Modify') {
  9339. $save['name'] = 'edit';
  9340. }
  9341. $cancel = array(
  9342. 'name' => 'cancel',
  9343. 'label_key' => 'Cancel',
  9344. );
  9345. !empty($save_label) ? $buttons[] = $save : '';
  9346. if (!empty($morebuttons)) {
  9347. $buttons[] = $morebuttons;
  9348. }
  9349. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9350. $retstring = $withoutdiv ? '' : '<div class="center">';
  9351. foreach ($buttons as $button) {
  9352. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9353. if ($button['name'] !== 'cancel') {
  9354. $retstring .= '<input type="submit" class="button button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->trans($button['label_key'])) . '">';
  9355. } else {
  9356. $retstring .= '<a class="button button-' . $cancel['name'] . '" href="' . dol_buildpath($cancelURL, 1) . '?restore_lastsearch_values=1' . (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans($cancel['label_key']) . '</a>';
  9357. }
  9358. }
  9359. $retstring .= $withoutdiv ? '' : '</div>';
  9360. if ($dol_openinpopup) {
  9361. $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . $dol_openinpopup . ' context, so we enable the close of dialog on cancel -->' . "\n";
  9362. $retstring .= '<script>';
  9363. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9364. e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . $dol_openinpopup . '\');
  9365. window.parent.jQuery(\'#idfordialog' . $dol_openinpopup . '\').dialog(\'close\');
  9366. });';
  9367. $retstring .= '</script>';
  9368. }
  9369. return $retstring;
  9370. }
  9371. /**
  9372. * Output the buttons to submit a creation/edit form
  9373. *
  9374. * @param string $save_label Alternative label for save button
  9375. * @param string $cancel_label Alternative label for cancel button
  9376. * @param array $morebuttons Add additional buttons between save and cancel
  9377. * @param bool $withoutdiv Option to remove enclosing centered div
  9378. * @param string $morecss More CSS
  9379. * @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.
  9380. * @return string Html code with the buttons
  9381. */
  9382. public function buttonsSaveCancelOwn($save_label = 'Save', $cancel_label = 'Cancel', $cancelURL = '', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9383. {
  9384. global $langs;
  9385. $buttons = array();
  9386. $save = array(
  9387. 'name' => 'save',
  9388. 'label_key' => $save_label,
  9389. );
  9390. if ($save_label == 'Create' || $save_label == 'Add') {
  9391. $save['name'] = 'add';
  9392. } elseif ($save_label == 'Modify') {
  9393. $save['name'] = 'edit';
  9394. }
  9395. $cancel = array(
  9396. 'name' => 'cancel',
  9397. 'label_key' => 'Cancel',
  9398. );
  9399. !empty($save_label) ? $buttons[] = $save : '';
  9400. if (!empty($morebuttons)) {
  9401. $buttons[] = $morebuttons;
  9402. }
  9403. //!empty($cancel_label) ? $buttons[] = $cancel : '';
  9404. $retstring = $withoutdiv ? '' : '<div class="center">';
  9405. foreach ($buttons as $button) {
  9406. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9407. $retstring .= '<input type="submit" class="button button-' . $button['name'] . ($morecss ? ' ' . $morecss : '') . ' ' . $addclass . '" name="' . $button['name'] . '" value="' . dol_escape_htmltag($langs->trans($button['label_key'])) . '">';
  9408. }
  9409. if ($cancel_label == "Cancel") {
  9410. $retstring .= '<a class="button button-' . $cancel['name'] . '" href="' . dol_buildpath($cancelURL, 1) . '?restore_lastsearch_values=1' . (!empty($socid) ? '&socid=' . $socid : '') . '">' . $langs->trans($cancel['label_key']) . '</a>';
  9411. }
  9412. $retstring .= $withoutdiv ? '' : '</div>';
  9413. if ($dol_openinpopup) {
  9414. $retstring .= '<!-- buttons are shown into a $dol_openinpopup=' . $dol_openinpopup . ' context, so we enable the close of dialog on cancel -->' . "\n";
  9415. $retstring .= '<script>';
  9416. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9417. e.preventDefault(); console.log(\'We click on cancel in iframe popup ' . $dol_openinpopup . '\');
  9418. window.parent.jQuery(\'#idfordialog' . $dol_openinpopup . '\').dialog(\'close\');
  9419. });';
  9420. $retstring .= '</script>';
  9421. }
  9422. return $retstring;
  9423. }
  9424. }