html.form.class.php 434 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421
  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 ($forceall == 1 || (empty($forceall) && isModEnabled("product") && isModEnabled("service"))
  1025. || (empty($forceall) && !isModEnabled('product') && !isModEnabled('service'))) {
  1026. if (empty($hidetext)) {
  1027. print $langs->trans("Type").': ';
  1028. }
  1029. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  1030. if ($showempty) {
  1031. print '<option value="-1"';
  1032. if ($selected == -1) {
  1033. print ' selected';
  1034. }
  1035. print '>&nbsp;</option>';
  1036. }
  1037. print '<option value="0"';
  1038. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1039. print ' selected';
  1040. }
  1041. print '>'.$langs->trans("Product");
  1042. print '<option value="1"';
  1043. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1044. print ' selected';
  1045. }
  1046. print '>'.$langs->trans("Service");
  1047. print '</select>';
  1048. print ajax_combobox('select_'.$htmlname);
  1049. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1050. }
  1051. if ((empty($forceall) && !isModEnabled('product') && isModEnabled("service")) || $forceall == 3) {
  1052. print $langs->trans("Service");
  1053. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1054. }
  1055. if ((empty($forceall) && isModEnabled("product") && !isModEnabled('service')) || $forceall == 2) {
  1056. print $langs->trans("Product");
  1057. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1058. }
  1059. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1060. 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
  1061. }
  1062. }
  1063. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1064. /**
  1065. * Load into cache cache_types_fees, array of types of fees
  1066. *
  1067. * @return int Nb of lines loaded, <0 if KO
  1068. */
  1069. public function load_cache_types_fees()
  1070. {
  1071. // phpcs:enable
  1072. global $langs;
  1073. $num = count($this->cache_types_fees);
  1074. if ($num > 0) {
  1075. return 0; // Cache already loaded
  1076. }
  1077. dol_syslog(__METHOD__, LOG_DEBUG);
  1078. $langs->load("trips");
  1079. $sql = "SELECT c.code, c.label";
  1080. $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
  1081. $sql .= " WHERE active > 0";
  1082. $resql = $this->db->query($sql);
  1083. if ($resql) {
  1084. $num = $this->db->num_rows($resql);
  1085. $i = 0;
  1086. while ($i < $num) {
  1087. $obj = $this->db->fetch_object($resql);
  1088. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1089. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1090. $this->cache_types_fees[$obj->code] = $label;
  1091. $i++;
  1092. }
  1093. asort($this->cache_types_fees);
  1094. return $num;
  1095. } else {
  1096. dol_print_error($this->db);
  1097. return -1;
  1098. }
  1099. }
  1100. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1101. /**
  1102. * Return list of types of notes
  1103. *
  1104. * @param string $selected Preselected type
  1105. * @param string $htmlname Name of field in form
  1106. * @param int $showempty Add an empty field
  1107. * @return void
  1108. */
  1109. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1110. {
  1111. // phpcs:enable
  1112. global $user, $langs;
  1113. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1114. $this->load_cache_types_fees();
  1115. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1116. if ($showempty) {
  1117. print '<option value="-1"';
  1118. if ($selected == -1) {
  1119. print ' selected';
  1120. }
  1121. print '>&nbsp;</option>';
  1122. }
  1123. foreach ($this->cache_types_fees as $key => $value) {
  1124. print '<option value="'.$key.'"';
  1125. if ($key == $selected) {
  1126. print ' selected';
  1127. }
  1128. print '>';
  1129. print $value;
  1130. print '</option>';
  1131. }
  1132. print '</select>';
  1133. if ($user->admin) {
  1134. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1135. }
  1136. }
  1137. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1138. /**
  1139. * Output html form to select a third party
  1140. *
  1141. * @param string $selected Preselected type
  1142. * @param string $htmlname Name of field in form
  1143. * @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)')
  1144. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1145. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1146. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1147. * @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')))
  1148. * @param int $limit Maximum number of elements
  1149. * @param string $morecss Add more css styles to the SELECT component
  1150. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1151. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1152. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1153. * @param array $ajaxoptions Options for ajax_autocompleter
  1154. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1155. * @param array $excludeids Exclude IDs from the select combo
  1156. * @param int $showcode Show code
  1157. * @return string HTML string with select box for thirdparty.
  1158. */
  1159. 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)
  1160. {
  1161. // phpcs:enable
  1162. global $conf, $user, $langs;
  1163. $out = '';
  1164. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1165. if (is_null($ajaxoptions)) {
  1166. $ajaxoptions = array();
  1167. }
  1168. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1169. // No immediate load of all database
  1170. $placeholder = '';
  1171. if ($selected && empty($selected_input_value)) {
  1172. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1173. $societetmp = new Societe($this->db);
  1174. $societetmp->fetch($selected);
  1175. $selected_input_value = $societetmp->name;
  1176. unset($societetmp);
  1177. }
  1178. // mode 1
  1179. $urloption = 'htmlname='.urlencode(str_replace('.', '_', $htmlname)).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '').($showcode ? '&showcode='.urlencode($showcode) : '');
  1180. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1181. if (empty($hidelabel)) {
  1182. print $langs->trans("RefOrLabel").' : ';
  1183. } elseif ($hidelabel > 1) {
  1184. $placeholder = $langs->trans("RefOrLabel");
  1185. if ($hidelabel == 2) {
  1186. $out .= img_picto($langs->trans("Search"), 'search');
  1187. }
  1188. }
  1189. $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' : '').' />';
  1190. if ($hidelabel == 3) {
  1191. $out .= img_picto($langs->trans("Search"), 'search');
  1192. }
  1193. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1194. } else {
  1195. // Immediate load of all database
  1196. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1197. }
  1198. return $out;
  1199. }
  1200. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1201. /**
  1202. * Output html form to select a third party.
  1203. * 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.
  1204. *
  1205. * @param string $selected Preselected type
  1206. * @param string $htmlname Name of field in form
  1207. * @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.
  1208. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1209. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1210. * @param int $forcecombo Force to use standard HTML select component without beautification
  1211. * @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')))
  1212. * @param string $filterkey Filter on key value
  1213. * @param int $outputmode 0=HTML select string, 1=Array
  1214. * @param int $limit Limit number of answers
  1215. * @param string $morecss Add more css styles to the SELECT component
  1216. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1217. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1218. * @param array $excludeids Exclude IDs from the select combo
  1219. * @param int $showcode Show code in list
  1220. * @return string HTML string with
  1221. */
  1222. 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)
  1223. {
  1224. // phpcs:enable
  1225. global $conf, $user, $langs;
  1226. global $hookmanager;
  1227. $out = '';
  1228. $num = 0;
  1229. $outarray = array();
  1230. if ($selected === '') {
  1231. $selected = array();
  1232. } elseif (!is_array($selected)) {
  1233. $selected = array($selected);
  1234. }
  1235. // Clean $filter that may contains sql conditions so sql code
  1236. if (function_exists('testSqlAndScriptInject')) {
  1237. if (testSqlAndScriptInject($filter, 3) > 0) {
  1238. $filter = '';
  1239. }
  1240. }
  1241. // We search companies
  1242. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1243. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1244. $sql .= ", s.address, s.zip, s.town";
  1245. $sql .= ", dictp.code as country_code";
  1246. }
  1247. $sql .= " FROM ".$this->db->prefix()."societe as s";
  1248. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1249. $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
  1250. }
  1251. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1252. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  1253. }
  1254. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1255. if (!empty($user->socid)) {
  1256. $sql .= " AND s.rowid = ".((int) $user->socid);
  1257. }
  1258. if ($filter) {
  1259. $sql .= " AND (".$filter.")";
  1260. }
  1261. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1262. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1263. }
  1264. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1265. $sql .= " AND s.status <> 0";
  1266. }
  1267. if (!empty($excludeids)) {
  1268. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1269. }
  1270. // Add where from hooks
  1271. $parameters = array();
  1272. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1273. $sql .= $hookmanager->resPrint;
  1274. // Add criteria
  1275. if ($filterkey && $filterkey != '') {
  1276. $sql .= " AND (";
  1277. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1278. // For natural search
  1279. $scrit = explode(' ', $filterkey);
  1280. $i = 0;
  1281. if (count($scrit) > 1) {
  1282. $sql .= "(";
  1283. }
  1284. foreach ($scrit as $crit) {
  1285. if ($i > 0) {
  1286. $sql .= " AND ";
  1287. }
  1288. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1289. $i++;
  1290. }
  1291. if (count($scrit) > 1) {
  1292. $sql .= ")";
  1293. }
  1294. if (isModEnabled('barcode')) {
  1295. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1296. }
  1297. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1298. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1299. $sql .= ")";
  1300. }
  1301. $sql .= $this->db->order("nom", "ASC");
  1302. $sql .= $this->db->plimit($limit, 0);
  1303. // Build output string
  1304. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1305. $resql = $this->db->query($sql);
  1306. if ($resql) {
  1307. if (!$forcecombo) {
  1308. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1309. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1310. }
  1311. // Construct $out and $outarray
  1312. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1313. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1314. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1315. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1316. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1317. if ($showempty && !is_numeric($showempty)) {
  1318. $textifempty = $langs->trans($showempty);
  1319. } else {
  1320. $textifempty .= $langs->trans("All");
  1321. }
  1322. }
  1323. if ($showempty) {
  1324. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1325. }
  1326. $companytemp = new Societe($this->db);
  1327. $num = $this->db->num_rows($resql);
  1328. $i = 0;
  1329. if ($num) {
  1330. while ($i < $num) {
  1331. $obj = $this->db->fetch_object($resql);
  1332. $label = '';
  1333. if ($showcode || !empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) {
  1334. if (($obj->client) && (!empty($obj->code_client))) {
  1335. $label = $obj->code_client.' - ';
  1336. }
  1337. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1338. $label .= $obj->code_fournisseur.' - ';
  1339. }
  1340. $label .= ' '.$obj->name;
  1341. } else {
  1342. $label = $obj->name;
  1343. }
  1344. if (!empty($obj->name_alias)) {
  1345. $label .= ' ('.$obj->name_alias.')';
  1346. }
  1347. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1348. $label .= ' - '.$obj->tva_intra;
  1349. }
  1350. $labelhtml = $label;
  1351. if ($showtype) {
  1352. $companytemp->id = $obj->rowid;
  1353. $companytemp->client = $obj->client;
  1354. $companytemp->fournisseur = $obj->fournisseur;
  1355. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1356. if ($tmptype) {
  1357. $labelhtml .= ' '.$tmptype;
  1358. }
  1359. if ($obj->client || $obj->fournisseur) {
  1360. $label .= ' (';
  1361. }
  1362. if ($obj->client == 1 || $obj->client == 3) {
  1363. $label .= $langs->trans("Customer");
  1364. }
  1365. if ($obj->client == 2 || $obj->client == 3) {
  1366. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1367. }
  1368. if ($obj->fournisseur) {
  1369. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1370. }
  1371. if ($obj->client || $obj->fournisseur) {
  1372. $label .= ')';
  1373. }
  1374. }
  1375. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1376. $s = ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1377. if (!empty($obj->country_code)) {
  1378. $s .= ', '.$langs->trans('Country'.$obj->country_code);
  1379. }
  1380. $label .= $s;
  1381. $labelhtml .= $s;
  1382. }
  1383. if (empty($outputmode)) {
  1384. if (in_array($obj->rowid, $selected)) {
  1385. $out .= '<option value="'.$obj->rowid.'" selected data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
  1386. } else {
  1387. $out .= '<option value="'.$obj->rowid.'" data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
  1388. }
  1389. } else {
  1390. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label, 'labelhtml'=>$labelhtml));
  1391. }
  1392. $i++;
  1393. if (($i % 10) == 0) {
  1394. $out .= "\n";
  1395. }
  1396. }
  1397. }
  1398. $out .= '</select>'."\n";
  1399. } else {
  1400. dol_print_error($this->db);
  1401. }
  1402. $this->result = array('nbofthirdparties'=>$num);
  1403. if ($outputmode) {
  1404. return $outarray;
  1405. }
  1406. return $out;
  1407. }
  1408. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1409. /**
  1410. * Return HTML combo list of absolute discounts
  1411. *
  1412. * @param string $selected Id remise fixe pre-selectionnee
  1413. * @param string $htmlname Nom champ formulaire
  1414. * @param string $filter Criteres optionnels de filtre
  1415. * @param int $socid Id of thirdparty
  1416. * @param int $maxvalue Max value for lines that can be selected
  1417. * @return int Return number of qualifed lines in list
  1418. */
  1419. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1420. {
  1421. // phpcs:enable
  1422. global $langs, $conf;
  1423. // On recherche les remises
  1424. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1425. $sql .= " re.description, re.fk_facture_source";
  1426. $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
  1427. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1428. $sql .= " AND re.entity = ".$conf->entity;
  1429. if ($filter) {
  1430. $sql .= " AND ".$filter;
  1431. }
  1432. $sql .= " ORDER BY re.description ASC";
  1433. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1434. $resql = $this->db->query($sql);
  1435. if ($resql) {
  1436. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1437. $num = $this->db->num_rows($resql);
  1438. $qualifiedlines = $num;
  1439. $i = 0;
  1440. if ($num) {
  1441. print '<option value="0">&nbsp;</option>';
  1442. while ($i < $num) {
  1443. $obj = $this->db->fetch_object($resql);
  1444. $desc = dol_trunc($obj->description, 40);
  1445. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1446. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1447. }
  1448. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1449. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1450. }
  1451. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1452. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1453. }
  1454. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1455. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1456. }
  1457. $selectstring = '';
  1458. if ($selected > 0 && $selected == $obj->rowid) {
  1459. $selectstring = ' selected';
  1460. }
  1461. $disabled = '';
  1462. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1463. $qualifiedlines--;
  1464. $disabled = ' disabled';
  1465. }
  1466. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1467. $tmpfac = new Facture($this->db);
  1468. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1469. $desc = $desc.' - '.$tmpfac->ref;
  1470. }
  1471. }
  1472. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1473. $i++;
  1474. }
  1475. }
  1476. print '</select>';
  1477. print ajax_combobox('select_'.$htmlname);
  1478. return $qualifiedlines;
  1479. } else {
  1480. dol_print_error($this->db);
  1481. return -1;
  1482. }
  1483. }
  1484. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1485. /**
  1486. * Return list of all contacts (for a third party or all)
  1487. *
  1488. * @param int $socid Id ot third party or 0 for all
  1489. * @param string $selected Id contact pre-selectionne
  1490. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1491. * @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
  1492. * @param string $exclude List of contacts id to exclude
  1493. * @param string $limitto Disable answers that are not id in this array list
  1494. * @param integer $showfunction Add function into label
  1495. * @param string $morecss Add more class to class style
  1496. * @param integer $showsoc Add company into label
  1497. * @param int $forcecombo Force to use combo box
  1498. * @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')))
  1499. * @param bool $options_only Return options only (for ajax treatment)
  1500. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1501. * @param string $htmlid Html id to use instead of htmlname
  1502. * @return int <0 if KO, Nb of contact in list if OK
  1503. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1504. */
  1505. 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 = '')
  1506. {
  1507. // phpcs:enable
  1508. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1509. return $this->num;
  1510. }
  1511. /**
  1512. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1513. * This also set the number of contacts found into $this->num
  1514. *
  1515. * @since 9.0 Add afterSelectContactOptions hook
  1516. *
  1517. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1518. * @param array|int $selected Array of ID of pre-selected contact id
  1519. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1520. * @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
  1521. * @param string $exclude List of contacts id to exclude
  1522. * @param string $limitto Disable answers that are not id in this array list
  1523. * @param integer $showfunction Add function into label
  1524. * @param string $morecss Add more class to class style
  1525. * @param bool $options_only Return options only (for ajax treatment)
  1526. * @param integer $showsoc Add company into label
  1527. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1528. * @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')))
  1529. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1530. * @param string $htmlid Html id to use instead of htmlname
  1531. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1532. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1533. * @return int|string <0 if KO, HTML with select string if OK.
  1534. */
  1535. 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)
  1536. {
  1537. global $conf, $langs, $hookmanager, $action;
  1538. $langs->load('companies');
  1539. if (empty($htmlid)) {
  1540. $htmlid = $htmlname;
  1541. }
  1542. $num = 0;
  1543. if ($selected === '') {
  1544. $selected = array();
  1545. } elseif (!is_array($selected)) {
  1546. $selected = array($selected);
  1547. }
  1548. $out = '';
  1549. if (!is_object($hookmanager)) {
  1550. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1551. $hookmanager = new HookManager($this->db);
  1552. }
  1553. // We search third parties
  1554. $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";
  1555. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1556. $sql .= ", s.nom as company, s.town AS company_town";
  1557. }
  1558. $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
  1559. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1560. $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
  1561. }
  1562. $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
  1563. if ($socid > 0 || $socid == -1) {
  1564. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1565. }
  1566. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1567. $sql .= " AND sp.statut <> 0";
  1568. }
  1569. // Add where from hooks
  1570. $parameters = array();
  1571. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1572. $sql .= $hookmanager->resPrint;
  1573. $sql .= " ORDER BY sp.lastname ASC";
  1574. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1575. $resql = $this->db->query($sql);
  1576. if ($resql) {
  1577. $num = $this->db->num_rows($resql);
  1578. if ($htmlname != 'none' && !$options_only) {
  1579. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1580. }
  1581. if ($showempty && ! is_numeric($showempty)) {
  1582. $textforempty = $showempty;
  1583. $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
  1584. } else {
  1585. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1586. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1587. }
  1588. if ($showempty == 2) {
  1589. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1590. }
  1591. }
  1592. $i = 0;
  1593. if ($num) {
  1594. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1595. $contactstatic = new Contact($this->db);
  1596. while ($i < $num) {
  1597. $obj = $this->db->fetch_object($resql);
  1598. // Set email (or phones) and town extended infos
  1599. $extendedInfos = '';
  1600. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1601. $extendedInfos = array();
  1602. $email = trim($obj->email);
  1603. if (!empty($email)) {
  1604. $extendedInfos[] = $email;
  1605. } else {
  1606. $phone = trim($obj->phone);
  1607. $phone_perso = trim($obj->phone_perso);
  1608. $phone_mobile = trim($obj->phone_mobile);
  1609. if (!empty($phone)) {
  1610. $extendedInfos[] = $phone;
  1611. }
  1612. if (!empty($phone_perso)) {
  1613. $extendedInfos[] = $phone_perso;
  1614. }
  1615. if (!empty($phone_mobile)) {
  1616. $extendedInfos[] = $phone_mobile;
  1617. }
  1618. }
  1619. $contact_town = trim($obj->contact_town);
  1620. $company_town = trim($obj->company_town);
  1621. if (!empty($contact_town)) {
  1622. $extendedInfos[] = $contact_town;
  1623. } elseif (!empty($company_town)) {
  1624. $extendedInfos[] = $company_town;
  1625. }
  1626. $extendedInfos = implode(' - ', $extendedInfos);
  1627. if (!empty($extendedInfos)) {
  1628. $extendedInfos = ' - '.$extendedInfos;
  1629. }
  1630. }
  1631. $contactstatic->id = $obj->rowid;
  1632. $contactstatic->lastname = $obj->lastname;
  1633. $contactstatic->firstname = $obj->firstname;
  1634. if ($obj->statut == 1) {
  1635. if ($htmlname != 'none') {
  1636. $disabled = 0;
  1637. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1638. $disabled = 1;
  1639. }
  1640. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1641. $disabled = 1;
  1642. }
  1643. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1644. $out .= '<option value="'.$obj->rowid.'"';
  1645. if ($disabled) {
  1646. $out .= ' disabled';
  1647. }
  1648. $out .= ' selected>';
  1649. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1650. if ($showfunction && $obj->poste) {
  1651. $out .= ' ('.$obj->poste.')';
  1652. }
  1653. if (($showsoc > 0) && $obj->company) {
  1654. $out .= ' - ('.$obj->company.')';
  1655. }
  1656. $out .= '</option>';
  1657. } else {
  1658. $out .= '<option value="'.$obj->rowid.'"';
  1659. if ($disabled) {
  1660. $out .= ' disabled';
  1661. }
  1662. $out .= '>';
  1663. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1664. if ($showfunction && $obj->poste) {
  1665. $out .= ' ('.$obj->poste.')';
  1666. }
  1667. if (($showsoc > 0) && $obj->company) {
  1668. $out .= ' - ('.$obj->company.')';
  1669. }
  1670. $out .= '</option>';
  1671. }
  1672. } else {
  1673. if (in_array($obj->rowid, $selected)) {
  1674. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1675. if ($showfunction && $obj->poste) {
  1676. $out .= ' ('.$obj->poste.')';
  1677. }
  1678. if (($showsoc > 0) && $obj->company) {
  1679. $out .= ' - ('.$obj->company.')';
  1680. }
  1681. }
  1682. }
  1683. }
  1684. $i++;
  1685. }
  1686. } else {
  1687. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1688. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1689. $out .= $labeltoshow;
  1690. $out .= '</option>';
  1691. }
  1692. $parameters = array(
  1693. 'socid'=>$socid,
  1694. 'htmlname'=>$htmlname,
  1695. 'resql'=>$resql,
  1696. 'out'=>&$out,
  1697. 'showfunction'=>$showfunction,
  1698. 'showsoc'=>$showsoc,
  1699. );
  1700. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1701. if ($htmlname != 'none' && !$options_only) {
  1702. $out .= '</select>';
  1703. }
  1704. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1705. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1706. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1707. }
  1708. $this->num = $num;
  1709. return $out;
  1710. } else {
  1711. dol_print_error($this->db);
  1712. return -1;
  1713. }
  1714. }
  1715. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1716. /**
  1717. * Return the HTML select list of users
  1718. *
  1719. * @param string $selected Id user preselected
  1720. * @param string $htmlname Field name in form
  1721. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1722. * @param array $exclude Array list of users id to exclude
  1723. * @param int $disabled If select list must be disabled
  1724. * @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
  1725. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1726. * @param string $force_entity '0' or Ids of environment to force
  1727. * @return void
  1728. * @deprecated Use select_dolusers instead
  1729. * @see select_dolusers()
  1730. */
  1731. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1732. {
  1733. // phpcs:enable
  1734. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1735. }
  1736. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1737. /**
  1738. * Return select list of users
  1739. *
  1740. * @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)
  1741. * @param string $htmlname Field name in form
  1742. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1743. * @param array $exclude Array list of users id to exclude
  1744. * @param int $disabled If select list must be disabled
  1745. * @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
  1746. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1747. * @param string $force_entity '0' or Ids of environment to force
  1748. * @param int $maxlength Maximum length of string into list (0=no limit)
  1749. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1750. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1751. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1752. * @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.
  1753. * @param string $morecss More css
  1754. * @param int $notdisabled Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1755. * @param int $outputmode 0=HTML select string, 1=Array
  1756. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1757. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1758. * @return string HTML select string
  1759. * @see select_dolgroups()
  1760. */
  1761. 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)
  1762. {
  1763. // phpcs:enable
  1764. global $conf, $user, $langs, $hookmanager;
  1765. global $action;
  1766. // If no preselected user defined, we take current user
  1767. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1768. $selected = $user->id;
  1769. }
  1770. if ($selected === '') {
  1771. $selected = array();
  1772. } elseif (!is_array($selected)) {
  1773. $selected = array($selected);
  1774. }
  1775. $excludeUsers = null;
  1776. $includeUsers = null;
  1777. // Permettre l'exclusion d'utilisateurs
  1778. if (is_array($exclude)) {
  1779. $excludeUsers = implode(",", $exclude);
  1780. }
  1781. // Permettre l'inclusion d'utilisateurs
  1782. if (is_array($include)) {
  1783. $includeUsers = implode(",", $include);
  1784. } elseif ($include == 'hierarchy') {
  1785. // Build list includeUsers to have only hierarchy
  1786. $includeUsers = implode(",", $user->getAllChildIds(0));
  1787. } elseif ($include == 'hierarchyme') {
  1788. // Build list includeUsers to have only hierarchy and current user
  1789. $includeUsers = implode(",", $user->getAllChildIds(1));
  1790. }
  1791. $out = '';
  1792. $outarray = array();
  1793. // Forge request to select users
  1794. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1795. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1796. $sql .= ", e.label";
  1797. }
  1798. $sql .= " FROM ".$this->db->prefix()."user as u";
  1799. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  1800. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
  1801. if ($force_entity) {
  1802. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1803. } else {
  1804. $sql .= " WHERE u.entity IS NOT NULL";
  1805. }
  1806. } else {
  1807. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1808. $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
  1809. $sql .= " ON ug.fk_user = u.rowid";
  1810. $sql .= " WHERE ug.entity = ".$conf->entity;
  1811. } else {
  1812. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1813. }
  1814. }
  1815. if (!empty($user->socid)) {
  1816. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1817. }
  1818. if (is_array($exclude) && $excludeUsers) {
  1819. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1820. }
  1821. if ($includeUsers) {
  1822. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1823. }
  1824. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $notdisabled) {
  1825. $sql .= " AND u.statut <> 0";
  1826. }
  1827. if (!empty($morefilter)) {
  1828. $sql .= " ".$morefilter;
  1829. }
  1830. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1831. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1832. if (!empty($reshook)) {
  1833. $sql .= $hookmanager->resPrint;
  1834. }
  1835. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1836. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1837. } else {
  1838. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1839. }
  1840. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1841. $resql = $this->db->query($sql);
  1842. if ($resql) {
  1843. $num = $this->db->num_rows($resql);
  1844. $i = 0;
  1845. if ($num) {
  1846. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1847. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1848. if ($show_empty && !$multiple) {
  1849. $textforempty = ' ';
  1850. if (!empty($conf->use_javascript_ajax)) {
  1851. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1852. }
  1853. if (!is_numeric($show_empty)) {
  1854. $textforempty = $show_empty;
  1855. }
  1856. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1857. }
  1858. if ($show_every) {
  1859. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1860. }
  1861. $userstatic = new User($this->db);
  1862. while ($i < $num) {
  1863. $obj = $this->db->fetch_object($resql);
  1864. $userstatic->id = $obj->rowid;
  1865. $userstatic->lastname = $obj->lastname;
  1866. $userstatic->firstname = $obj->firstname;
  1867. $userstatic->photo = $obj->photo;
  1868. $userstatic->statut = $obj->status;
  1869. $userstatic->entity = $obj->entity;
  1870. $userstatic->admin = $obj->admin;
  1871. $disableline = '';
  1872. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1873. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1874. }
  1875. $labeltoshow = ''; $labeltoshowhtml = '';
  1876. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1877. $fullNameMode = 0;
  1878. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1879. $fullNameMode = 1; //Firstname+lastname
  1880. }
  1881. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1882. $labeltoshowhtml .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1883. if (empty($obj->firstname) && empty($obj->lastname)) {
  1884. $labeltoshow .= $obj->login;
  1885. $labeltoshowhtml .= $obj->login;
  1886. }
  1887. // Complete name with a more info string like: ' (info1 - info2 - ...)'
  1888. $moreinfo = ''; $moreinfohtml = '';
  1889. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1890. $moreinfo .= ($moreinfo ? ' - ' : ' (');
  1891. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(');
  1892. $moreinfo .= $obj->login;
  1893. $moreinfohtml .= $obj->login;
  1894. }
  1895. if ($showstatus >= 0) {
  1896. if ($obj->status == 1 && $showstatus == 1) {
  1897. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1898. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans('Enabled');
  1899. }
  1900. if ($obj->status == 0 && $showstatus == 1) {
  1901. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1902. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans('Disabled');
  1903. }
  1904. }
  1905. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1906. if (!$obj->entity) {
  1907. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1908. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').$langs->trans("AllEntities");
  1909. } else {
  1910. if ($obj->entity != $conf->entity) {
  1911. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1912. $moreinfohtml .= ($moreinfohtml ? ' - ' : ' <span class="opacitymedium">(').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1913. }
  1914. }
  1915. }
  1916. $moreinfo .= ($moreinfo ? ')' : '');
  1917. $moreinfohtml .= ($moreinfohtml ? ')' : '');
  1918. if ($disableline && $disableline != '1') {
  1919. // Add text from $enableonlytext parameter
  1920. $moreinfo .= ' - '.$disableline;
  1921. $moreinfohtml .= ' - '.$disableline;
  1922. }
  1923. $labeltoshow .= $moreinfo;
  1924. $labeltoshowhtml .= $moreinfohtml;
  1925. $out .= '<option value="'.$obj->rowid.'"';
  1926. if ($disableline) {
  1927. $out .= ' disabled';
  1928. }
  1929. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1930. $out .= ' selected';
  1931. }
  1932. $out .= ' data-html="';
  1933. $outhtml = '';
  1934. // if (!empty($obj->photo)) {
  1935. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1936. // }
  1937. if ($showstatus >= 0 && $obj->status == 0) {
  1938. $outhtml .= '<strike class="opacitymediumxxx">';
  1939. }
  1940. $outhtml .= $labeltoshowhtml;
  1941. if ($showstatus >= 0 && $obj->status == 0) {
  1942. $outhtml .= '</strike>';
  1943. }
  1944. $out .= dol_escape_htmltag($outhtml);
  1945. $out .= '">';
  1946. $out .= $labeltoshow;
  1947. $out .= '</option>';
  1948. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1949. $i++;
  1950. }
  1951. } else {
  1952. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1953. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1954. }
  1955. $out .= '</select>';
  1956. if ($num && !$forcecombo) {
  1957. // Enhance with select2
  1958. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1959. $out .= ajax_combobox($htmlname);
  1960. }
  1961. } else {
  1962. dol_print_error($this->db);
  1963. }
  1964. if ($outputmode) {
  1965. return $outarray;
  1966. }
  1967. return $out;
  1968. }
  1969. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1970. /**
  1971. * Return select list of users. Selected users are stored into session.
  1972. * List of users are provided into $_SESSION['assignedtouser'].
  1973. *
  1974. * @param string $action Value for $action
  1975. * @param string $htmlname Field name in form
  1976. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1977. * @param array $exclude Array list of users id to exclude
  1978. * @param int $disabled If select list must be disabled
  1979. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1980. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1981. * @param int $force_entity '0' or Ids of environment to force
  1982. * @param int $maxlength Maximum length of string into list (0=no limit)
  1983. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1984. * @param string $morefilter Add more filters into sql request
  1985. * @param int $showproperties Show properties of each attendees
  1986. * @param array $listofuserid Array with properties of each user
  1987. * @param array $listofcontactid Array with properties of each contact
  1988. * @param array $listofotherid Array with properties of each other contact
  1989. * @return string HTML select string
  1990. * @see select_dolgroups()
  1991. */
  1992. 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())
  1993. {
  1994. // phpcs:enable
  1995. global $conf, $user, $langs;
  1996. $userstatic = new User($this->db);
  1997. $out = '';
  1998. $assignedtouser = array();
  1999. if (!empty($_SESSION['assignedtouser'])) {
  2000. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  2001. }
  2002. $nbassignetouser = count($assignedtouser);
  2003. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  2004. if ($nbassignetouser) {
  2005. $out .= '<ul class="attendees">';
  2006. }
  2007. $i = 0;
  2008. $ownerid = 0;
  2009. foreach ($assignedtouser as $key => $value) {
  2010. if ($value['id'] == $ownerid) {
  2011. continue;
  2012. }
  2013. $out .= '<li>';
  2014. $userstatic->fetch($value['id']);
  2015. $out .= $userstatic->getNomUrl(-1);
  2016. if ($i == 0) {
  2017. $ownerid = $value['id'];
  2018. $out .= ' ('.$langs->trans("Owner").')';
  2019. }
  2020. if ($nbassignetouser > 1 && $action != 'view') {
  2021. $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.'">';
  2022. }
  2023. // Show my availability
  2024. if ($showproperties) {
  2025. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  2026. $out .= '<div class="myavailability inline-block">';
  2027. $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>';
  2028. $out .= '</div>';
  2029. }
  2030. }
  2031. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2032. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2033. $out .= '</li>';
  2034. $i++;
  2035. }
  2036. if ($nbassignetouser) {
  2037. $out .= '</ul>';
  2038. }
  2039. // Method with no ajax
  2040. if ($action != 'view') {
  2041. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2042. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  2043. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2044. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2045. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  2046. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  2047. $out .= '});';
  2048. $out .= '})</script>';
  2049. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2050. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  2051. $out .= '<br>';
  2052. }
  2053. return $out;
  2054. }
  2055. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2056. /**
  2057. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2058. *
  2059. * @param int $selected Preselected products
  2060. * @param string $htmlname Name of HTML select field (must be unique in page).
  2061. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2062. * @param int $limit Limit on number of returned lines
  2063. * @param int $price_level Level of price to show
  2064. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2065. * @param int $finished 2=all, 1=finished, 0=raw material
  2066. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2067. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2068. * @param array $ajaxoptions Options for ajax_autocompleter
  2069. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2070. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2071. * @param int $forcecombo Force to use combo box
  2072. * @param string $morecss Add more css on select
  2073. * @param int $hidepriceinlabel 1=Hide prices in label
  2074. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2075. * 'warehouseopen' = count products from open warehouses,
  2076. * 'warehouseclosed' = count products from closed warehouses,
  2077. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2078. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2079. * @param string $nooutput No print, return the output into a string
  2080. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2081. * @return void|string
  2082. */
  2083. 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)
  2084. {
  2085. // phpcs:enable
  2086. global $langs, $conf;
  2087. $out = '';
  2088. // check parameters
  2089. $price_level = (!empty($price_level) ? $price_level : 0);
  2090. if (is_null($ajaxoptions)) {
  2091. $ajaxoptions = array();
  2092. }
  2093. if (strval($filtertype) === '' && (isModEnabled("product") || isModEnabled("service"))) {
  2094. if (isModEnabled("product") && !isModEnabled('service')) {
  2095. $filtertype = '0';
  2096. } elseif (!isModEnabled('product') && isModEnabled("service")) {
  2097. $filtertype = '1';
  2098. }
  2099. }
  2100. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2101. $placeholder = '';
  2102. if ($selected && empty($selected_input_value)) {
  2103. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2104. $producttmpselect = new Product($this->db);
  2105. $producttmpselect->fetch($selected);
  2106. $selected_input_value = $producttmpselect->ref;
  2107. unset($producttmpselect);
  2108. }
  2109. // handle case where product or service module is disabled + no filter specified
  2110. if ($filtertype == '') {
  2111. if (!isModEnabled('product')) { // when product module is disabled, show services only
  2112. $filtertype = 1;
  2113. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2114. $filtertype = 0;
  2115. }
  2116. }
  2117. // mode=1 means customers products
  2118. $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;
  2119. //Price by customer
  2120. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2121. $urloption .= '&socid='.$socid;
  2122. }
  2123. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2124. if (isModEnabled('variants') && is_array($selected_combinations)) {
  2125. // Code to automatically insert with javascript the select of attributes under the select of product
  2126. // when a parent of variant has been selected.
  2127. $out .= '
  2128. <!-- script to auto show attributes select tags if a variant was selected -->
  2129. <script>
  2130. // auto show attributes fields
  2131. selected = '.json_encode($selected_combinations).';
  2132. combvalues = {};
  2133. jQuery(document).ready(function () {
  2134. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2135. if (jQuery(this).val() == \'free\') {
  2136. jQuery(\'div#attributes_box\').empty();
  2137. }
  2138. });
  2139. jQuery("input#'.$htmlname.'").change(function () {
  2140. if (!jQuery(this).val()) {
  2141. jQuery(\'div#attributes_box\').empty();
  2142. return;
  2143. }
  2144. console.log("A change has started. We get variants fields to inject html select");
  2145. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2146. id: jQuery(this).val()
  2147. }, function (data) {
  2148. jQuery(\'div#attributes_box\').empty();
  2149. jQuery.each(data, function (key, val) {
  2150. combvalues[val.id] = val.values;
  2151. var span = jQuery(document.createElement(\'div\')).css({
  2152. \'display\': \'table-row\'
  2153. });
  2154. span.append(
  2155. jQuery(document.createElement(\'div\')).text(val.label).css({
  2156. \'font-weight\': \'bold\',
  2157. \'display\': \'table-cell\'
  2158. })
  2159. );
  2160. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2161. \'margin-left\': \'15px\',
  2162. \'white-space\': \'pre\'
  2163. }).append(
  2164. jQuery(document.createElement(\'option\')).val(\'\')
  2165. );
  2166. jQuery.each(combvalues[val.id], function (key, val) {
  2167. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2168. if (selected[val.fk_product_attribute] == val.id) {
  2169. tag.attr(\'selected\', \'selected\');
  2170. }
  2171. html.append(tag);
  2172. });
  2173. span.append(html);
  2174. jQuery(\'div#attributes_box\').append(span);
  2175. });
  2176. })
  2177. });
  2178. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2179. });
  2180. </script>
  2181. ';
  2182. }
  2183. if (empty($hidelabel)) {
  2184. $out .= $langs->trans("RefOrLabel").' : ';
  2185. } elseif ($hidelabel > 1) {
  2186. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2187. if ($hidelabel == 2) {
  2188. $out .= img_picto($langs->trans("Search"), 'search');
  2189. }
  2190. }
  2191. $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' : '').' />';
  2192. if ($hidelabel == 3) {
  2193. $out .= img_picto($langs->trans("Search"), 'search');
  2194. }
  2195. } else {
  2196. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2197. }
  2198. if (empty($nooutput)) {
  2199. print $out;
  2200. } else {
  2201. return $out;
  2202. }
  2203. }
  2204. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2205. /**
  2206. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2207. *
  2208. * @param int $selected Preselected BOM id
  2209. * @param string $htmlname Name of HTML select field (must be unique in page).
  2210. * @param int $limit Limit on number of returned lines
  2211. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2212. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2213. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2214. * @param string $morecss Add more css on select
  2215. * @param string $nooutput No print, return the output into a string
  2216. * @param int $forcecombo Force to use combo box
  2217. * @param array $TProducts Add filter on a defined product
  2218. * @return void|string
  2219. */
  2220. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2221. {
  2222. // phpcs:enable
  2223. global $conf, $user, $langs, $db;
  2224. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2225. $error = 0;
  2226. $out = '';
  2227. if (!$forcecombo) {
  2228. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2229. $events = array();
  2230. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2231. }
  2232. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2233. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2234. $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
  2235. $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
  2236. if (!empty($status)) $sql.= ' AND status = '. (int) $status;
  2237. if (!empty($type)) $sql.= ' AND bomtype = '. (int) $type;
  2238. if (!empty($TProducts)) $sql .= ' AND fk_product IN ('.$this->db->sanitize(implode(',', $TProducts)).')';
  2239. if (!empty($limit)) $sql.= ' LIMIT '. (int) $limit;
  2240. $resql = $db->query($sql);
  2241. if ($resql) {
  2242. if ($showempty) {
  2243. $out .= '<option value="-1"';
  2244. if (empty($selected)) $out .= ' selected';
  2245. $out .= '>&nbsp;</option>';
  2246. }
  2247. while ($obj = $db->fetch_object($resql)) {
  2248. $product = new Product($db);
  2249. $res = $product->fetch($obj->fk_product);
  2250. $out .= '<option value="'.$obj->rowid.'"';
  2251. if ($obj->rowid == $selected) $out .= 'selected';
  2252. $out .= '>'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
  2253. }
  2254. } else {
  2255. $error++;
  2256. dol_print_error($db);
  2257. }
  2258. if (empty($nooutput)) {
  2259. print $out;
  2260. } else {
  2261. return $out;
  2262. }
  2263. }
  2264. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2265. /**
  2266. * Return list of products for a customer.
  2267. * Called by select_produits.
  2268. *
  2269. * @param int $selected Preselected product
  2270. * @param string $htmlname Name of select html
  2271. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2272. * @param int $limit Limit on number of returned lines
  2273. * @param int $price_level Level of price to show
  2274. * @param string $filterkey Filter on product
  2275. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2276. * @param int $finished Filter on finished field: 2=No filter
  2277. * @param int $outputmode 0=HTML select string, 1=Array
  2278. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2279. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2280. * @param int $forcecombo Force to use combo box
  2281. * @param string $morecss Add more css on select
  2282. * @param int $hidepriceinlabel 1=Hide prices in label
  2283. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2284. * 'warehouseopen' = count products from open warehouses,
  2285. * 'warehouseclosed' = count products from closed warehouses,
  2286. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2287. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2288. * @return array Array of keys for json
  2289. */
  2290. 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)
  2291. {
  2292. // phpcs:enable
  2293. global $langs, $conf;
  2294. global $hookmanager;
  2295. $out = '';
  2296. $outarray = array();
  2297. // Units
  2298. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2299. $langs->load('other');
  2300. }
  2301. $warehouseStatusArray = array();
  2302. if (!empty($warehouseStatus)) {
  2303. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2304. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2305. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2306. }
  2307. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2308. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2309. }
  2310. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2311. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2312. }
  2313. }
  2314. $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";
  2315. if (count($warehouseStatusArray)) {
  2316. $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
  2317. } else {
  2318. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2319. }
  2320. $sql = "SELECT ";
  2321. $sql .= $selectFields.$selectFieldsGrouped;
  2322. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2323. //Product category
  2324. $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
  2325. FROM ".$this->db->prefix()."categorie_product
  2326. WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
  2327. LIMIT 1
  2328. ) AS categorie_product_id ";
  2329. }
  2330. //Price by customer
  2331. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2332. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2333. $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';
  2334. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2335. }
  2336. // Units
  2337. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2338. $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";
  2339. $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';
  2340. }
  2341. // Multilang : we add translation
  2342. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2343. $sql .= ", pl.label as label_translated";
  2344. $sql .= ", pl.description as description_translated";
  2345. $selectFields .= ", label_translated";
  2346. $selectFields .= ", description_translated";
  2347. }
  2348. // Price by quantity
  2349. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2350. $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
  2351. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2352. $sql .= " AND price_level = ".((int) $price_level);
  2353. }
  2354. $sql .= " ORDER BY date_price";
  2355. $sql .= " DESC LIMIT 1) as price_rowid";
  2356. $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
  2357. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2358. $sql .= " AND price_level = ".((int) $price_level);
  2359. }
  2360. $sql .= " ORDER BY date_price";
  2361. $sql .= " DESC LIMIT 1) as price_by_qty";
  2362. $selectFields .= ", price_rowid, price_by_qty";
  2363. }
  2364. $sql .= " FROM ".$this->db->prefix()."product as p";
  2365. if (count($warehouseStatusArray)) {
  2366. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
  2367. $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2368. $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.
  2369. }
  2370. // include search in supplier ref
  2371. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2372. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2373. }
  2374. //Price by customer
  2375. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2376. $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2377. }
  2378. // Units
  2379. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2380. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2381. }
  2382. // Multilang : we add translation
  2383. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2384. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
  2385. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2386. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2387. $soc = new Societe($this->db);
  2388. $result = $soc->fetch($socid);
  2389. if ($result > 0 && !empty($soc->default_lang)) {
  2390. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2391. } else {
  2392. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2393. }
  2394. } else {
  2395. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2396. }
  2397. }
  2398. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2399. $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2400. }
  2401. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2402. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2403. $sql .= " AND pac.rowid IS NULL";
  2404. }
  2405. if ($finished == 0) {
  2406. $sql .= " AND p.finished = ".((int) $finished);
  2407. } elseif ($finished == 1) {
  2408. $sql .= " AND p.finished = ".((int) $finished);
  2409. if ($status >= 0) {
  2410. $sql .= " AND p.tosell = ".((int) $status);
  2411. }
  2412. } elseif ($status >= 0) {
  2413. $sql .= " AND p.tosell = ".((int) $status);
  2414. }
  2415. if ($status_purchase >= 0) {
  2416. $sql .= " AND p.tobuy = ".((int) $status_purchase);
  2417. }
  2418. // Filter by product type
  2419. if (strval($filtertype) != '') {
  2420. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2421. } elseif (!isModEnabled('product')) { // when product module is disabled, show services only
  2422. $sql .= " AND p.fk_product_type = 1";
  2423. } elseif (!isModEnabled('service')) { // when service module is disabled, show products only
  2424. $sql .= " AND p.fk_product_type = 0";
  2425. }
  2426. // Add where from hooks
  2427. $parameters = array();
  2428. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2429. $sql .= $hookmanager->resPrint;
  2430. // Add criteria on ref/label
  2431. if ($filterkey != '') {
  2432. $sql .= ' AND (';
  2433. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2434. // For natural search
  2435. $scrit = explode(' ', $filterkey);
  2436. $i = 0;
  2437. if (count($scrit) > 1) {
  2438. $sql .= "(";
  2439. }
  2440. foreach ($scrit as $crit) {
  2441. if ($i > 0) {
  2442. $sql .= " AND ";
  2443. }
  2444. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2445. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2446. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2447. }
  2448. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2449. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2450. }
  2451. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2452. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2453. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2454. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2455. }
  2456. }
  2457. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2458. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2459. }
  2460. $sql .= ")";
  2461. $i++;
  2462. }
  2463. if (count($scrit) > 1) {
  2464. $sql .= ")";
  2465. }
  2466. if (isModEnabled('barcode')) {
  2467. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2468. }
  2469. $sql .= ')';
  2470. }
  2471. if (count($warehouseStatusArray)) {
  2472. $sql .= " GROUP BY ".$selectFields;
  2473. }
  2474. //Sort by category
  2475. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2476. $sql .= " ORDER BY categorie_product_id ";
  2477. //ASC OR DESC order
  2478. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2479. } else {
  2480. $sql .= $this->db->order("p.ref");
  2481. }
  2482. $sql .= $this->db->plimit($limit, 0);
  2483. // Build output string
  2484. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2485. $result = $this->db->query($sql);
  2486. if ($result) {
  2487. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2488. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2489. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2490. $num = $this->db->num_rows($result);
  2491. $events = null;
  2492. if (!$forcecombo) {
  2493. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2494. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2495. }
  2496. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2497. $textifempty = '';
  2498. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2499. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2500. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2501. if ($showempty && !is_numeric($showempty)) {
  2502. $textifempty = $langs->trans($showempty);
  2503. } else {
  2504. $textifempty .= $langs->trans("All");
  2505. }
  2506. } else {
  2507. if ($showempty && !is_numeric($showempty)) {
  2508. $textifempty = $langs->trans($showempty);
  2509. }
  2510. }
  2511. if ($showempty) {
  2512. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2513. }
  2514. $i = 0;
  2515. while ($num && $i < $num) {
  2516. $opt = '';
  2517. $optJson = array();
  2518. $objp = $this->db->fetch_object($result);
  2519. 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
  2520. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2521. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2522. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2523. $sql .= " ORDER BY quantity ASC";
  2524. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2525. $result2 = $this->db->query($sql);
  2526. if ($result2) {
  2527. $nb_prices = $this->db->num_rows($result2);
  2528. $j = 0;
  2529. while ($nb_prices && $j < $nb_prices) {
  2530. $objp2 = $this->db->fetch_object($result2);
  2531. $objp->price_by_qty_rowid = $objp2->rowid;
  2532. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2533. $objp->price_by_qty_quantity = $objp2->quantity;
  2534. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2535. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2536. // For backward compatibility
  2537. $objp->quantity = $objp2->quantity;
  2538. $objp->price = $objp2->price;
  2539. $objp->unitprice = $objp2->unitprice;
  2540. $objp->remise_percent = $objp2->remise_percent;
  2541. //$objp->tva_tx is not overwritten by $objp2 value
  2542. //$objp->default_vat_code is not overwritten by $objp2 value
  2543. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2544. $j++;
  2545. // Add new entry
  2546. // "key" value of json key array is used by jQuery automatically as selected value
  2547. // "label" value of json key array is used by jQuery automatically as text for combo box
  2548. $out .= $opt;
  2549. array_push($outarray, $optJson);
  2550. }
  2551. }
  2552. } else {
  2553. if (isModEnabled('dynamicprices') && !empty($objp->fk_price_expression)) {
  2554. $price_product = new Product($this->db);
  2555. $price_product->fetch($objp->rowid, '', '', 1);
  2556. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2557. $priceparser = new PriceParser($this->db);
  2558. $price_result = $priceparser->parseProduct($price_product);
  2559. if ($price_result >= 0) {
  2560. $objp->price = $price_result;
  2561. $objp->unitprice = $price_result;
  2562. //Calculate the VAT
  2563. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2564. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2565. }
  2566. }
  2567. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2568. // Add new entry
  2569. // "key" value of json key array is used by jQuery automatically as selected value
  2570. // "label" value of json key array is used by jQuery automatically as text for combo box
  2571. $out .= $opt;
  2572. array_push($outarray, $optJson);
  2573. }
  2574. $i++;
  2575. }
  2576. $out .= '</select>';
  2577. $this->db->free($result);
  2578. if (empty($outputmode)) {
  2579. return $out;
  2580. }
  2581. return $outarray;
  2582. } else {
  2583. dol_print_error($this->db);
  2584. }
  2585. }
  2586. /**
  2587. * Function to forge the string with OPTIONs of SELECT.
  2588. * This define value for &$opt and &$optJson.
  2589. * This function is called by select_produits_list().
  2590. *
  2591. * @param object $objp Resultset of fetch
  2592. * @param string $opt Option (var used for returned value in string option format)
  2593. * @param string $optJson Option (var used for returned value in json format)
  2594. * @param int $price_level Price level
  2595. * @param string $selected Preselected value
  2596. * @param int $hidepriceinlabel Hide price in label
  2597. * @param string $filterkey Filter key to highlight
  2598. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2599. * @return void
  2600. */
  2601. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2602. {
  2603. global $langs, $conf, $user;
  2604. $outkey = '';
  2605. $outval = '';
  2606. $outref = '';
  2607. $outlabel = '';
  2608. $outlabel_translated = '';
  2609. $outdesc = '';
  2610. $outdesc_translated = '';
  2611. $outbarcode = '';
  2612. $outorigin = '';
  2613. $outtype = '';
  2614. $outprice_ht = '';
  2615. $outprice_ttc = '';
  2616. $outpricebasetype = '';
  2617. $outtva_tx = '';
  2618. $outdefault_vat_code = '';
  2619. $outqty = 1;
  2620. $outdiscount = 0;
  2621. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2622. $label = $objp->label;
  2623. if (!empty($objp->label_translated)) {
  2624. $label = $objp->label_translated;
  2625. }
  2626. if (!empty($filterkey) && $filterkey != '') {
  2627. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2628. }
  2629. $outkey = $objp->rowid;
  2630. $outref = $objp->ref;
  2631. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2632. $outlabel = $objp->label;
  2633. $outdesc = $objp->description;
  2634. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  2635. $outlabel_translated = $objp->label_translated;
  2636. $outdesc_translated = $objp->description_translated;
  2637. }
  2638. $outbarcode = $objp->barcode;
  2639. $outorigin = $objp->fk_country;
  2640. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2641. $outtype = $objp->fk_product_type;
  2642. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2643. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2644. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2645. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2646. }
  2647. // Units
  2648. $outvalUnits = '';
  2649. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2650. if (!empty($objp->unit_short)) {
  2651. $outvalUnits .= ' - '.$objp->unit_short;
  2652. }
  2653. }
  2654. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2655. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2656. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2657. $outvalUnits .= ' - '.$unitToShow;
  2658. }
  2659. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2660. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2661. $outvalUnits .= ' - '.$unitToShow;
  2662. }
  2663. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2664. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2665. $outvalUnits .= ' - '.$unitToShow;
  2666. }
  2667. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2668. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2669. $outvalUnits .= ' - '.$unitToShow;
  2670. }
  2671. }
  2672. if ($outdurationvalue && $outdurationunit) {
  2673. $da = array(
  2674. 'h' => $langs->trans('Hour'),
  2675. 'd' => $langs->trans('Day'),
  2676. 'w' => $langs->trans('Week'),
  2677. 'm' => $langs->trans('Month'),
  2678. 'y' => $langs->trans('Year')
  2679. );
  2680. if (isset($da[$outdurationunit])) {
  2681. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2682. }
  2683. }
  2684. $opt = '<option value="'.$objp->rowid.'"';
  2685. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2686. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2687. $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.'"';
  2688. }
  2689. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2690. if (!empty($user->rights->stock->lire)) {
  2691. if ($objp->stock > 0) {
  2692. $opt .= ' class="product_line_stock_ok"';
  2693. } elseif ($objp->stock <= 0) {
  2694. $opt .= ' class="product_line_stock_too_low"';
  2695. }
  2696. }
  2697. }
  2698. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2699. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2700. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2701. }
  2702. $opt .= '>';
  2703. $opt .= $objp->ref;
  2704. if (!empty($objp->custref)) {
  2705. $opt.= ' (' . $objp->custref . ')';
  2706. }
  2707. if ($outbarcode) {
  2708. $opt .= ' ('.$outbarcode.')';
  2709. }
  2710. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2711. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2712. $opt .= ' ('.getCountry($outorigin, 1).')';
  2713. }
  2714. $objRef = $objp->ref;
  2715. if (!empty($objp->custref)) {
  2716. $objRef .= ' (' . $objp->custref . ')';
  2717. }
  2718. if (!empty($filterkey) && $filterkey != '') {
  2719. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2720. }
  2721. $outval .= $objRef;
  2722. if ($outbarcode) {
  2723. $outval .= ' ('.$outbarcode.')';
  2724. }
  2725. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2726. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2727. $outval .= ' ('.getCountry($outorigin, 1).')';
  2728. }
  2729. // Units
  2730. $opt .= $outvalUnits;
  2731. $outval .= $outvalUnits;
  2732. $found = 0;
  2733. // Multiprice
  2734. // If we need a particular price level (from 1 to n)
  2735. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2736. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2737. $sql .= " FROM ".$this->db->prefix()."product_price";
  2738. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2739. $sql .= " AND entity IN (".getEntity('productprice').")";
  2740. $sql .= " AND price_level = ".((int) $price_level);
  2741. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2742. $sql .= " LIMIT 1";
  2743. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2744. $result2 = $this->db->query($sql);
  2745. if ($result2) {
  2746. $objp2 = $this->db->fetch_object($result2);
  2747. if ($objp2) {
  2748. $found = 1;
  2749. if ($objp2->price_base_type == 'HT') {
  2750. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2751. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2752. } else {
  2753. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2754. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2755. }
  2756. $outprice_ht = price($objp2->price);
  2757. $outprice_ttc = price($objp2->price_ttc);
  2758. $outpricebasetype = $objp2->price_base_type;
  2759. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2760. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2761. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2762. } else {
  2763. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2764. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2765. }
  2766. }
  2767. } else {
  2768. dol_print_error($this->db);
  2769. }
  2770. }
  2771. // Price by quantity
  2772. 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))) {
  2773. $found = 1;
  2774. $outqty = $objp->quantity;
  2775. $outdiscount = $objp->remise_percent;
  2776. if ($objp->quantity == 1) {
  2777. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2778. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2779. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2780. $outval .= $langs->transnoentities("Unit");
  2781. } else {
  2782. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2783. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2784. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2785. $outval .= $langs->transnoentities("Units");
  2786. }
  2787. $outprice_ht = price($objp->unitprice);
  2788. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2789. $outpricebasetype = $objp->price_base_type;
  2790. $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
  2791. $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
  2792. }
  2793. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2794. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2795. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2796. }
  2797. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2798. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2799. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2800. }
  2801. // Price by customer
  2802. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2803. if (!empty($objp->idprodcustprice)) {
  2804. $found = 1;
  2805. if ($objp->custprice_base_type == 'HT') {
  2806. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2807. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2808. } else {
  2809. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2810. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2811. }
  2812. $outprice_ht = price($objp->custprice);
  2813. $outprice_ttc = price($objp->custprice_ttc);
  2814. $outpricebasetype = $objp->custprice_base_type;
  2815. $outtva_tx = $objp->custtva_tx;
  2816. $outdefault_vat_code = $objp->custdefault_vat_code;
  2817. }
  2818. }
  2819. // If level no defined or multiprice not found, we used the default price
  2820. if (empty($hidepriceinlabel) && !$found) {
  2821. if ($objp->price_base_type == 'HT') {
  2822. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2823. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2824. } else {
  2825. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2826. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2827. }
  2828. $outprice_ht = price($objp->price);
  2829. $outprice_ttc = price($objp->price_ttc);
  2830. $outpricebasetype = $objp->price_base_type;
  2831. $outtva_tx = $objp->tva_tx;
  2832. $outdefault_vat_code = $objp->default_vat_code;
  2833. }
  2834. if (isModEnabled('stock') && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2835. if (!empty($user->rights->stock->lire)) {
  2836. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2837. if ($objp->stock > 0) {
  2838. $outval .= ' - <span class="product_line_stock_ok">';
  2839. } elseif ($objp->stock <= 0) {
  2840. $outval .= ' - <span class="product_line_stock_too_low">';
  2841. }
  2842. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2843. $outval .= '</span>';
  2844. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2845. $langs->load("stocks");
  2846. $tmpproduct = new Product($this->db);
  2847. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2848. $tmpproduct->load_virtual_stock();
  2849. $virtualstock = $tmpproduct->stock_theorique;
  2850. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2851. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2852. if ($virtualstock > 0) {
  2853. $outval .= '<span class="product_line_stock_ok">';
  2854. } elseif ($virtualstock <= 0) {
  2855. $outval .= '<span class="product_line_stock_too_low">';
  2856. }
  2857. $outval .= $virtualstock;
  2858. $outval .= '</span>';
  2859. unset($tmpproduct);
  2860. }
  2861. }
  2862. }
  2863. $opt .= "</option>\n";
  2864. $optJson = array(
  2865. 'key'=>$outkey,
  2866. 'value'=>$outref,
  2867. 'label'=>$outval,
  2868. 'label2'=>$outlabel,
  2869. 'desc'=>$outdesc,
  2870. 'type'=>$outtype,
  2871. 'price_ht'=>price2num($outprice_ht),
  2872. 'price_ttc'=>price2num($outprice_ttc),
  2873. 'price_ht_locale'=>price(price2num($outprice_ht)),
  2874. 'price_ttc_locale'=>price(price2num($outprice_ttc)),
  2875. 'pricebasetype'=>$outpricebasetype,
  2876. 'tva_tx'=>$outtva_tx,
  2877. 'default_vat_code'=>$outdefault_vat_code,
  2878. 'qty'=>$outqty,
  2879. 'discount'=>$outdiscount,
  2880. 'duration_value'=>$outdurationvalue,
  2881. 'duration_unit'=>$outdurationunit,
  2882. 'pbq'=>$outpbq,
  2883. 'labeltrans'=>$outlabel_translated,
  2884. 'desctrans'=>$outdesc_translated,
  2885. 'ref_customer'=>$outrefcust
  2886. );
  2887. }
  2888. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2889. /**
  2890. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2891. *
  2892. * @param int $socid Id third party
  2893. * @param string $selected Preselected product
  2894. * @param string $htmlname Name of HTML Select
  2895. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2896. * @param string $filtre For a SQL filter
  2897. * @param array $ajaxoptions Options for ajax_autocompleter
  2898. * @param int $hidelabel Hide label (0=no, 1=yes)
  2899. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2900. * @param string $morecss More CSS
  2901. * @param string $placeholder Placeholder
  2902. * @return void
  2903. */
  2904. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2905. {
  2906. // phpcs:enable
  2907. global $langs, $conf;
  2908. global $price_level, $status, $finished;
  2909. if (!isset($status)) {
  2910. $status = 1;
  2911. }
  2912. $selected_input_value = '';
  2913. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2914. if ($selected > 0) {
  2915. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2916. $producttmpselect = new Product($this->db);
  2917. $producttmpselect->fetch($selected);
  2918. $selected_input_value = $producttmpselect->ref;
  2919. unset($producttmpselect);
  2920. }
  2921. // mode=2 means suppliers products
  2922. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2923. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2924. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2925. } else {
  2926. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2927. }
  2928. }
  2929. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2930. /**
  2931. * Return list of suppliers products
  2932. *
  2933. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2934. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2935. * @param string $htmlname Name of HTML select
  2936. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2937. * @param string $filtre Generic filter. Data must not come from user input.
  2938. * @param string $filterkey Filter of produdts
  2939. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2940. * @param int $outputmode 0=HTML select string, 1=Array
  2941. * @param int $limit Limit of line number
  2942. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2943. * @param string $morecss Add more CSS
  2944. * @param int $showstockinlist Show stock information (slower).
  2945. * @param string $placeholder Placeholder
  2946. * @return array|string Array of keys for json or HTML component
  2947. */
  2948. 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 = '')
  2949. {
  2950. // phpcs:enable
  2951. global $langs, $conf, $user;
  2952. global $hookmanager;
  2953. $out = '';
  2954. $outarray = array();
  2955. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2956. $langs->load('stocks');
  2957. // Units
  2958. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2959. $langs->load('other');
  2960. }
  2961. $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,";
  2962. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2963. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2964. $sql .= " pfp.supplier_reputation";
  2965. // if we use supplier description of the products
  2966. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2967. $sql .= ", pfp.desc_fourn as description";
  2968. } else {
  2969. $sql .= ", p.description";
  2970. }
  2971. // Units
  2972. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2973. $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";
  2974. }
  2975. if (isModEnabled('barcode')) {
  2976. $sql .= ", pfp.barcode";
  2977. }
  2978. $sql .= " FROM ".$this->db->prefix()."product as p";
  2979. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2980. if ($socid > 0) {
  2981. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2982. }
  2983. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  2984. // Units
  2985. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2986. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2987. }
  2988. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2989. if ($statut != -1) {
  2990. $sql .= " AND p.tobuy = ".((int) $statut);
  2991. }
  2992. if (strval($filtertype) != '') {
  2993. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2994. }
  2995. if (!empty($filtre)) {
  2996. $sql .= " ".$filtre;
  2997. }
  2998. // Add where from hooks
  2999. $parameters = array();
  3000. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  3001. $sql .= $hookmanager->resPrint;
  3002. // Add criteria on ref/label
  3003. if ($filterkey != '') {
  3004. $sql .= ' AND (';
  3005. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  3006. // For natural search
  3007. $scrit = explode(' ', $filterkey);
  3008. $i = 0;
  3009. if (count($scrit) > 1) {
  3010. $sql .= "(";
  3011. }
  3012. foreach ($scrit as $crit) {
  3013. if ($i > 0) {
  3014. $sql .= " AND ";
  3015. }
  3016. $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)."%'";
  3017. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  3018. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  3019. }
  3020. $sql .= ")";
  3021. $i++;
  3022. }
  3023. if (count($scrit) > 1) {
  3024. $sql .= ")";
  3025. }
  3026. if (isModEnabled('barcode')) {
  3027. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  3028. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  3029. }
  3030. $sql .= ')';
  3031. }
  3032. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3033. $sql .= $this->db->plimit($limit, 0);
  3034. // Build output string
  3035. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  3036. $result = $this->db->query($sql);
  3037. if ($result) {
  3038. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3039. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  3040. $num = $this->db->num_rows($result);
  3041. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3042. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  3043. if (!$selected) {
  3044. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  3045. } else {
  3046. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  3047. }
  3048. $i = 0;
  3049. while ($i < $num) {
  3050. $objp = $this->db->fetch_object($result);
  3051. if (is_null($objp->idprodfournprice)) {
  3052. // There is no supplier price found, we will use the vat rate for sale
  3053. $objp->tva_tx = $objp->tva_tx_sale;
  3054. $objp->default_vat_code = $objp->default_vat_code_sale;
  3055. }
  3056. $outkey = $objp->idprodfournprice; // id in table of price
  3057. if (!$outkey && $alsoproductwithnosupplierprice) {
  3058. $outkey = 'idprod_'.$objp->rowid; // id of product
  3059. }
  3060. $outref = $objp->ref;
  3061. $outbarcode = $objp->barcode;
  3062. $outqty = 1;
  3063. $outdiscount = 0;
  3064. $outtype = $objp->fk_product_type;
  3065. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3066. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  3067. // Units
  3068. $outvalUnits = '';
  3069. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3070. if (!empty($objp->unit_short)) {
  3071. $outvalUnits .= ' - '.$objp->unit_short;
  3072. }
  3073. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3074. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3075. $outvalUnits .= ' - '.$unitToShow;
  3076. }
  3077. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3078. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  3079. $outvalUnits .= ' - '.$unitToShow;
  3080. }
  3081. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3082. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3083. $outvalUnits .= ' - '.$unitToShow;
  3084. }
  3085. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3086. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3087. $outvalUnits .= ' - '.$unitToShow;
  3088. }
  3089. if ($outdurationvalue && $outdurationunit) {
  3090. $da = array(
  3091. 'h' => $langs->trans('Hour'),
  3092. 'd' => $langs->trans('Day'),
  3093. 'w' => $langs->trans('Week'),
  3094. 'm' => $langs->trans('Month'),
  3095. 'y' => $langs->trans('Year')
  3096. );
  3097. if (isset($da[$outdurationunit])) {
  3098. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  3099. }
  3100. }
  3101. }
  3102. $objRef = $objp->ref;
  3103. if ($filterkey && $filterkey != '') {
  3104. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  3105. }
  3106. $objRefFourn = $objp->ref_fourn;
  3107. if ($filterkey && $filterkey != '') {
  3108. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3109. }
  3110. $label = $objp->label;
  3111. if ($filterkey && $filterkey != '') {
  3112. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  3113. }
  3114. $optlabel = $objp->ref;
  3115. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3116. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  3117. }
  3118. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3119. $optlabel .= ' ('.$outbarcode.')';
  3120. }
  3121. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3122. $outvallabel = $objRef;
  3123. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3124. $outvallabel .= ' ('.$objRefFourn.')';
  3125. }
  3126. if (isModEnabled('barcode') && !empty($objp->barcode)) {
  3127. $outvallabel .= ' ('.$outbarcode.')';
  3128. }
  3129. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3130. // Units
  3131. $optlabel .= $outvalUnits;
  3132. $outvallabel .= $outvalUnits;
  3133. if (!empty($objp->idprodfournprice)) {
  3134. $outqty = $objp->quantity;
  3135. $outdiscount = $objp->remise_percent;
  3136. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3137. $prod_supplier = new ProductFournisseur($this->db);
  3138. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3139. $prod_supplier->id = $objp->fk_product;
  3140. $prod_supplier->fourn_qty = $objp->quantity;
  3141. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3142. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3143. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3144. $priceparser = new PriceParser($this->db);
  3145. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3146. if ($price_result >= 0) {
  3147. $objp->fprice = $price_result;
  3148. if ($objp->quantity >= 1) {
  3149. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3150. }
  3151. }
  3152. }
  3153. if ($objp->quantity == 1) {
  3154. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3155. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3156. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3157. $outvallabel .= $langs->transnoentities("Unit");
  3158. } else {
  3159. $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;
  3160. $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;
  3161. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3162. $outvallabel .= ' '.$langs->transnoentities("Units");
  3163. }
  3164. if ($objp->quantity > 1) {
  3165. $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
  3166. $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
  3167. }
  3168. if ($objp->remise_percent >= 1) {
  3169. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3170. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3171. }
  3172. if ($objp->duration) {
  3173. $optlabel .= " - ".$objp->duration;
  3174. $outvallabel .= " - ".$objp->duration;
  3175. }
  3176. if (!$socid) {
  3177. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3178. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3179. }
  3180. if ($objp->supplier_reputation) {
  3181. //TODO dictionary
  3182. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3183. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3184. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3185. }
  3186. } else {
  3187. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3188. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3189. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3190. } else // No supplier price defined for product, even on other suppliers
  3191. {
  3192. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3193. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3194. }
  3195. }
  3196. if (isModEnabled('stock') && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3197. $novirtualstock = ($showstockinlist == 2);
  3198. if (!empty($user->rights->stock->lire)) {
  3199. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3200. if ($objp->stock > 0) {
  3201. $optlabel .= ' - <span class="product_line_stock_ok">';
  3202. } elseif ($objp->stock <= 0) {
  3203. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3204. }
  3205. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3206. $optlabel .= '</span>';
  3207. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3208. $langs->load("stocks");
  3209. $tmpproduct = new Product($this->db);
  3210. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3211. $tmpproduct->load_virtual_stock();
  3212. $virtualstock = $tmpproduct->stock_theorique;
  3213. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3214. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3215. if ($virtualstock > 0) {
  3216. $optlabel .= '<span class="product_line_stock_ok">';
  3217. } elseif ($virtualstock <= 0) {
  3218. $optlabel .= '<span class="product_line_stock_too_low">';
  3219. }
  3220. $optlabel .= $virtualstock;
  3221. $optlabel .= '</span>';
  3222. unset($tmpproduct);
  3223. }
  3224. }
  3225. }
  3226. $optstart = '<option value="'.$outkey.'"';
  3227. if ($selected && $selected == $objp->idprodfournprice) {
  3228. $optstart .= ' selected';
  3229. }
  3230. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3231. $optstart .= ' disabled';
  3232. }
  3233. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3234. $optstart .= ' data-product-id="'.dol_escape_htmltag($objp->rowid).'"';
  3235. $optstart .= ' data-price-id="'.dol_escape_htmltag($objp->idprodfournprice).'"';
  3236. $optstart .= ' data-qty="'.dol_escape_htmltag($objp->quantity).'"';
  3237. $optstart .= ' data-up="'.dol_escape_htmltag(price2num($objp->unitprice)).'"';
  3238. $optstart .= ' data-up-locale="'.dol_escape_htmltag(price($objp->unitprice)).'"';
  3239. $optstart .= ' data-discount="'.dol_escape_htmltag($outdiscount).'"';
  3240. $optstart .= ' data-tvatx="'.dol_escape_htmltag(price2num($objp->tva_tx)).'"';
  3241. $optstart .= ' data-tvatx-formated="'.dol_escape_htmltag(price($objp->tva_tx, 0, $langs, 1, -1, 2)).'"';
  3242. $optstart .= ' data-default-vat-code="'.dol_escape_htmltag($objp->default_vat_code).'"';
  3243. }
  3244. $optstart .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3245. $outarrayentry = array(
  3246. 'key' => $outkey,
  3247. 'value' => $outref,
  3248. 'label' => $outvallabel,
  3249. 'qty' => $outqty,
  3250. 'price_qty_ht' => price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3251. 'price_unit_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3252. 'price_ht' => price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3253. 'tva_tx_formated' => price($objp->tva_tx, 0, $langs, 1, -1, 2),
  3254. 'tva_tx' => price2num($objp->tva_tx),
  3255. 'default_vat_code' => $objp->default_vat_code,
  3256. 'discount' => $outdiscount,
  3257. 'type' => $outtype,
  3258. 'duration_value' => $outdurationvalue,
  3259. 'duration_unit' => $outdurationunit,
  3260. 'disabled' => (empty($objp->idprodfournprice) ? true : false),
  3261. 'description' => $objp->description
  3262. );
  3263. $parameters = array(
  3264. 'objp' => &$objp,
  3265. 'optstart' => &$optstart,
  3266. 'optlabel' => &$optlabel,
  3267. 'outvallabel' => &$outvallabel,
  3268. 'outarrayentry' => &$outarrayentry
  3269. );
  3270. $reshook = $hookmanager->executeHooks('selectProduitsFournisseurListOption', $parameters, $this);
  3271. // Add new entry
  3272. // "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
  3273. // "label" value of json key array is used by jQuery automatically as text for combo box
  3274. $out .= $optstart . ' data-html="'.dol_escape_htmltag($optlabel).'">' . $optlabel . "</option>\n";;
  3275. array_push(
  3276. $outarray,
  3277. array('key'=>$outkey,
  3278. 'value'=>$outref,
  3279. 'label'=>$outvallabel,
  3280. 'qty'=>$outqty,
  3281. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3282. 'price_qty_ht_locale'=>price($objp->fprice),
  3283. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3284. 'price_unit_ht_locale'=>price($objp->unitprice),
  3285. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3286. 'tva_tx_formated' => price($objp->tva_tx),
  3287. 'tva_tx'=>price2num($objp->tva_tx),
  3288. 'default_vat_code'=>$objp->default_vat_code,
  3289. 'discount'=>$outdiscount,
  3290. 'type'=>$outtype,
  3291. 'duration_value'=>$outdurationvalue,
  3292. 'duration_unit'=>$outdurationunit,
  3293. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3294. 'description'=>$objp->description
  3295. )
  3296. );
  3297. // Exemple of var_dump $outarray
  3298. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3299. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3300. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3301. //}
  3302. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3303. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3304. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3305. $i++;
  3306. }
  3307. $out .= '</select>';
  3308. $this->db->free($result);
  3309. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3310. $out .= ajax_combobox($htmlname);
  3311. } else {
  3312. dol_print_error($this->db);
  3313. }
  3314. if (empty($outputmode)) {
  3315. return $out;
  3316. }
  3317. return $outarray;
  3318. }
  3319. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3320. /**
  3321. * Return list of suppliers prices for a product
  3322. *
  3323. * @param int $productid Id of product
  3324. * @param string $htmlname Name of HTML field
  3325. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3326. * @return string
  3327. */
  3328. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3329. {
  3330. // phpcs:enable
  3331. global $langs, $conf;
  3332. $langs->load('stocks');
  3333. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3334. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3335. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3336. $sql .= " FROM ".$this->db->prefix()."product as p";
  3337. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3338. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  3339. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3340. $sql .= " AND p.tobuy = 1";
  3341. $sql .= " AND s.fournisseur = 1";
  3342. $sql .= " AND p.rowid = ".((int) $productid);
  3343. if (empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED)) {
  3344. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3345. } else {
  3346. $sql .= " ORDER BY pfp.unitprice ASC";
  3347. }
  3348. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3349. $result = $this->db->query($sql);
  3350. if ($result) {
  3351. $num = $this->db->num_rows($result);
  3352. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3353. if (!$num) {
  3354. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3355. } else {
  3356. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3357. $form .= '<option value="0">&nbsp;</option>';
  3358. $i = 0;
  3359. while ($i < $num) {
  3360. $objp = $this->db->fetch_object($result);
  3361. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3362. //if there is only one supplier, preselect it
  3363. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier) || ($i == 0 && !empty($conf->global->PRODUCT_BEST_SUPPLIER_PRICE_PRESELECTED))) {
  3364. $opt .= ' selected';
  3365. }
  3366. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3367. if (isModEnabled('dynamicprices') && !empty($objp->fk_supplier_price_expression)) {
  3368. $prod_supplier = new ProductFournisseur($this->db);
  3369. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3370. $prod_supplier->id = $productid;
  3371. $prod_supplier->fourn_qty = $objp->quantity;
  3372. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3373. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3374. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3375. $priceparser = new PriceParser($this->db);
  3376. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3377. if ($price_result >= 0) {
  3378. $objp->fprice = $price_result;
  3379. if ($objp->quantity >= 1) {
  3380. $objp->unitprice = $objp->fprice / $objp->quantity;
  3381. }
  3382. }
  3383. }
  3384. if ($objp->quantity == 1) {
  3385. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3386. }
  3387. $opt .= $objp->quantity.' ';
  3388. if ($objp->quantity == 1) {
  3389. $opt .= $langs->trans("Unit");
  3390. } else {
  3391. $opt .= $langs->trans("Units");
  3392. }
  3393. if ($objp->quantity > 1) {
  3394. $opt .= " - ";
  3395. $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");
  3396. }
  3397. if ($objp->duration) {
  3398. $opt .= " - ".$objp->duration;
  3399. }
  3400. $opt .= "</option>\n";
  3401. $form .= $opt;
  3402. $i++;
  3403. }
  3404. }
  3405. $form .= '</select>';
  3406. $this->db->free($result);
  3407. return $form;
  3408. } else {
  3409. dol_print_error($this->db);
  3410. }
  3411. }
  3412. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3413. /**
  3414. * Return list of delivery address
  3415. *
  3416. * @param string $selected Id contact pre-selectionn
  3417. * @param int $socid Id of company
  3418. * @param string $htmlname Name of HTML field
  3419. * @param int $showempty Add an empty field
  3420. * @return integer|null
  3421. */
  3422. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3423. {
  3424. // phpcs:enable
  3425. // looking for users
  3426. $sql = "SELECT a.rowid, a.label";
  3427. $sql .= " FROM ".$this->db->prefix()."societe_address as a";
  3428. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3429. $sql .= " ORDER BY a.label ASC";
  3430. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3431. $resql = $this->db->query($sql);
  3432. if ($resql) {
  3433. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3434. if ($showempty) {
  3435. print '<option value="0">&nbsp;</option>';
  3436. }
  3437. $num = $this->db->num_rows($resql);
  3438. $i = 0;
  3439. if ($num) {
  3440. while ($i < $num) {
  3441. $obj = $this->db->fetch_object($resql);
  3442. if ($selected && $selected == $obj->rowid) {
  3443. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3444. } else {
  3445. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3446. }
  3447. $i++;
  3448. }
  3449. }
  3450. print '</select>';
  3451. return $num;
  3452. } else {
  3453. dol_print_error($this->db);
  3454. }
  3455. }
  3456. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3457. /**
  3458. * Load into cache list of payment terms
  3459. *
  3460. * @return int Nb of lines loaded, <0 if KO
  3461. */
  3462. public function load_cache_conditions_paiements()
  3463. {
  3464. // phpcs:enable
  3465. global $langs;
  3466. $num = count($this->cache_conditions_paiements);
  3467. if ($num > 0) {
  3468. return 0; // Cache already loaded
  3469. }
  3470. dol_syslog(__METHOD__, LOG_DEBUG);
  3471. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3472. $sql .= " FROM ".$this->db->prefix().'c_payment_term';
  3473. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3474. $sql .= " AND active > 0";
  3475. $sql .= " ORDER BY sortorder";
  3476. $resql = $this->db->query($sql);
  3477. if ($resql) {
  3478. $num = $this->db->num_rows($resql);
  3479. $i = 0;
  3480. while ($i < $num) {
  3481. $obj = $this->db->fetch_object($resql);
  3482. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3483. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3484. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3485. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3486. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3487. $i++;
  3488. }
  3489. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3490. return $num;
  3491. } else {
  3492. dol_print_error($this->db);
  3493. return -1;
  3494. }
  3495. }
  3496. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3497. /**
  3498. * Load int a cache property th elist of possible delivery delays.
  3499. *
  3500. * @return int Nb of lines loaded, <0 if KO
  3501. */
  3502. public function load_cache_availability()
  3503. {
  3504. // phpcs:enable
  3505. global $langs;
  3506. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3507. if ($num > 0) {
  3508. return 0; // Cache already loaded
  3509. }
  3510. dol_syslog(__METHOD__, LOG_DEBUG);
  3511. $langs->load('propal');
  3512. $sql = "SELECT rowid, code, label, position";
  3513. $sql .= " FROM ".$this->db->prefix().'c_availability';
  3514. $sql .= " WHERE active > 0";
  3515. $resql = $this->db->query($sql);
  3516. if ($resql) {
  3517. $num = $this->db->num_rows($resql);
  3518. $i = 0;
  3519. while ($i < $num) {
  3520. $obj = $this->db->fetch_object($resql);
  3521. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3522. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3523. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3524. $this->cache_availability[$obj->rowid]['label'] = $label;
  3525. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3526. $i++;
  3527. }
  3528. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3529. return $num;
  3530. } else {
  3531. dol_print_error($this->db);
  3532. return -1;
  3533. }
  3534. }
  3535. /**
  3536. * Retourne la liste des types de delais de livraison possibles
  3537. *
  3538. * @param int $selected Id du type de delais pre-selectionne
  3539. * @param string $htmlname Nom de la zone select
  3540. * @param string $filtertype To add a filter
  3541. * @param int $addempty Add empty entry
  3542. * @param string $morecss More CSS
  3543. * @return void
  3544. */
  3545. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3546. {
  3547. global $langs, $user;
  3548. $this->load_cache_availability();
  3549. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3550. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3551. if ($addempty) {
  3552. print '<option value="0">&nbsp;</option>';
  3553. }
  3554. foreach ($this->cache_availability as $id => $arrayavailability) {
  3555. if ($selected == $id) {
  3556. print '<option value="'.$id.'" selected>';
  3557. } else {
  3558. print '<option value="'.$id.'">';
  3559. }
  3560. print dol_escape_htmltag($arrayavailability['label']);
  3561. print '</option>';
  3562. }
  3563. print '</select>';
  3564. if ($user->admin) {
  3565. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3566. }
  3567. print ajax_combobox($htmlname);
  3568. }
  3569. /**
  3570. * Load into cache cache_demand_reason, array of input reasons
  3571. *
  3572. * @return int Nb of lines loaded, <0 if KO
  3573. */
  3574. public function loadCacheInputReason()
  3575. {
  3576. global $langs;
  3577. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3578. if ($num > 0) {
  3579. return 0; // Cache already loaded
  3580. }
  3581. $sql = "SELECT rowid, code, label";
  3582. $sql .= " FROM ".$this->db->prefix().'c_input_reason';
  3583. $sql .= " WHERE active > 0";
  3584. $resql = $this->db->query($sql);
  3585. if ($resql) {
  3586. $num = $this->db->num_rows($resql);
  3587. $i = 0;
  3588. $tmparray = array();
  3589. while ($i < $num) {
  3590. $obj = $this->db->fetch_object($resql);
  3591. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3592. $label = ($obj->label != '-' ? $obj->label : '');
  3593. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3594. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3595. }
  3596. if ($langs->trans($obj->code) != $obj->code) {
  3597. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3598. }
  3599. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3600. $tmparray[$obj->rowid]['code'] = $obj->code;
  3601. $tmparray[$obj->rowid]['label'] = $label;
  3602. $i++;
  3603. }
  3604. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3605. unset($tmparray);
  3606. return $num;
  3607. } else {
  3608. dol_print_error($this->db);
  3609. return -1;
  3610. }
  3611. }
  3612. /**
  3613. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3614. * List found into table c_input_reason loaded by loadCacheInputReason
  3615. *
  3616. * @param int $selected Id or code of type origin to select by default
  3617. * @param string $htmlname Nom de la zone select
  3618. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3619. * @param int $addempty Add an empty entry
  3620. * @param string $morecss Add more css to the HTML select component
  3621. * @param int $notooltip Do not show the tooltip for admin
  3622. * @return void
  3623. */
  3624. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3625. {
  3626. global $langs, $user;
  3627. $this->loadCacheInputReason();
  3628. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3629. if ($addempty) {
  3630. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3631. }
  3632. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3633. if ($arraydemandreason['code'] == $exclude) {
  3634. continue;
  3635. }
  3636. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3637. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3638. } else {
  3639. print '<option value="'.$arraydemandreason['id'].'">';
  3640. }
  3641. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3642. print $langs->trans($label);
  3643. print '</option>';
  3644. }
  3645. print '</select>';
  3646. if ($user->admin && empty($notooltip)) {
  3647. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3648. }
  3649. print ajax_combobox('select_'.$htmlname);
  3650. }
  3651. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3652. /**
  3653. * Charge dans cache la liste des types de paiements possibles
  3654. *
  3655. * @return int Nb of lines loaded, <0 if KO
  3656. */
  3657. public function load_cache_types_paiements()
  3658. {
  3659. // phpcs:enable
  3660. global $langs;
  3661. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3662. if ($num > 0) {
  3663. return $num; // Cache already loaded
  3664. }
  3665. dol_syslog(__METHOD__, LOG_DEBUG);
  3666. $this->cache_types_paiements = array();
  3667. $sql = "SELECT id, code, libelle as label, type, active";
  3668. $sql .= " FROM ".$this->db->prefix()."c_paiement";
  3669. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3670. $resql = $this->db->query($sql);
  3671. if ($resql) {
  3672. $num = $this->db->num_rows($resql);
  3673. $i = 0;
  3674. while ($i < $num) {
  3675. $obj = $this->db->fetch_object($resql);
  3676. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3677. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3678. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3679. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3680. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3681. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3682. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3683. $i++;
  3684. }
  3685. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3686. return $num;
  3687. } else {
  3688. dol_print_error($this->db);
  3689. return -1;
  3690. }
  3691. }
  3692. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3693. /**
  3694. * print list of payment modes.
  3695. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3696. * See instead to force the default value by the caller.
  3697. *
  3698. * @param int $selected Id of payment term to preselect by default
  3699. * @param string $htmlname Nom de la zone select
  3700. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3701. * @param int $addempty Add an empty entry
  3702. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3703. * @param string $morecss Add more CSS on select tag
  3704. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3705. * 0 : use default deposit percentage from entry
  3706. * > 0 : force deposit percentage (for example, from company object)
  3707. * @return void
  3708. * @deprecated
  3709. */
  3710. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3711. {
  3712. // phpcs:enable
  3713. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
  3714. }
  3715. /**
  3716. * Return list of payment modes.
  3717. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3718. * See instead to force the default value by the caller.
  3719. *
  3720. * @param int $selected Id of payment term to preselect by default
  3721. * @param string $htmlname Nom de la zone select
  3722. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3723. * @param int $addempty Add an empty entry
  3724. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3725. * @param string $morecss Add more CSS on select tag
  3726. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3727. * 0 : use default deposit percentage from entry
  3728. * > 0 : force deposit percentage (for example, from company object)
  3729. * @return string String for the HTML select component
  3730. */
  3731. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3732. {
  3733. global $langs, $user, $conf;
  3734. $out = '';
  3735. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3736. $this->load_cache_conditions_paiements();
  3737. // Set default value if not already set by caller
  3738. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3739. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3740. }
  3741. $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3742. if ($addempty) {
  3743. $out.= '<option value="0">&nbsp;</option>';
  3744. }
  3745. $selectedDepositPercent = null;
  3746. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3747. if ($filtertype <= 0 && !empty($arrayconditions['deposit_percent'])) {
  3748. continue;
  3749. }
  3750. if ($selected == $id) {
  3751. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3752. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3753. } else {
  3754. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3755. }
  3756. $label = $arrayconditions['label'];
  3757. if (!empty($arrayconditions['deposit_percent'])) {
  3758. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3759. }
  3760. $out.= $label;
  3761. $out.= '</option>';
  3762. }
  3763. $out.= '</select>';
  3764. if ($user->admin && empty($noinfoadmin)) {
  3765. $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3766. }
  3767. $out.= ajax_combobox($htmlname);
  3768. if ($deposit_percent >= 0) {
  3769. $out .= ' <span id="'.$htmlname.'_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3770. $out .= $langs->trans('DepositPercent') . ' : ';
  3771. $out .= '<input id="'.$htmlname.'_deposit_percent" name="'.$htmlname.'_deposit_percent" class="maxwidth50" value="' . strval($deposit_percent) . '" />';
  3772. $out .= '</span>';
  3773. $out .= '
  3774. <script>
  3775. $(document).ready(function () {
  3776. $("#' . $htmlname . '").change(function () {
  3777. let $selected = $(this).find("option:selected");
  3778. let depositPercent = $selected.attr("data-deposit_percent");
  3779. if (depositPercent.length > 0) {
  3780. $("#'.$htmlname.'_deposit_percent_container").show().find("#'.$htmlname.'_deposit_percent").val(depositPercent);
  3781. } else {
  3782. $("#'.$htmlname.'_deposit_percent_container").hide();
  3783. }
  3784. return true;
  3785. });
  3786. });
  3787. </script>';
  3788. }
  3789. return $out;
  3790. }
  3791. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3792. /**
  3793. * Return list of payment methods
  3794. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3795. *
  3796. * @param string $selected Id or code or preselected payment mode
  3797. * @param string $htmlname Name of select field
  3798. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3799. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3800. * @param int $empty 1=can be empty, 0 otherwise
  3801. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3802. * @param int $maxlength Max length of label
  3803. * @param int $active Active or not, -1 = all
  3804. * @param string $morecss Add more CSS on select tag
  3805. * @param int $nooutput 1=Return string, do not send to output
  3806. * @return string|void String for the HTML select component
  3807. */
  3808. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3809. {
  3810. // phpcs:enable
  3811. global $langs, $user, $conf;
  3812. $out = '';
  3813. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3814. $filterarray = array();
  3815. if ($filtertype == 'CRDT') {
  3816. $filterarray = array(0, 2, 3);
  3817. } elseif ($filtertype == 'DBIT') {
  3818. $filterarray = array(1, 2, 3);
  3819. } elseif ($filtertype != '' && $filtertype != '-1') {
  3820. $filterarray = explode(',', $filtertype);
  3821. }
  3822. $this->load_cache_types_paiements();
  3823. // Set default value if not already set by caller
  3824. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3825. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3826. }
  3827. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3828. if ($empty) {
  3829. $out .= '<option value="">&nbsp;</option>';
  3830. }
  3831. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3832. // If not good status
  3833. if ($active >= 0 && $arraytypes['active'] != $active) {
  3834. continue;
  3835. }
  3836. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3837. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3838. continue;
  3839. }
  3840. // We discard empty line if showempty is on because an empty line has already been output.
  3841. if ($empty && empty($arraytypes['code'])) {
  3842. continue;
  3843. }
  3844. if ($format == 0) {
  3845. $out .= '<option value="'.$id.'"';
  3846. } elseif ($format == 1) {
  3847. $out .= '<option value="'.$arraytypes['code'].'"';
  3848. } elseif ($format == 2) {
  3849. $out .= '<option value="'.$arraytypes['code'].'"';
  3850. } elseif ($format == 3) {
  3851. $out .= '<option value="'.$id.'"';
  3852. }
  3853. // Print attribute selected or not
  3854. if ($format == 1 || $format == 2) {
  3855. if ($selected == $arraytypes['code']) {
  3856. $out .= ' selected';
  3857. }
  3858. } else {
  3859. if ($selected == $id) {
  3860. $out .= ' selected';
  3861. }
  3862. }
  3863. $out .= '>';
  3864. $value = '';
  3865. if ($format == 0) {
  3866. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3867. } elseif ($format == 1) {
  3868. $value = $arraytypes['code'];
  3869. } elseif ($format == 2) {
  3870. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3871. } elseif ($format == 3) {
  3872. $value = $arraytypes['code'];
  3873. }
  3874. $out .= $value ? $value : '&nbsp;';
  3875. $out .= '</option>';
  3876. }
  3877. $out .= '</select>';
  3878. if ($user->admin && !$noadmininfo) {
  3879. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3880. }
  3881. $out .= ajax_combobox('select'.$htmlname);
  3882. if (empty($nooutput)) {
  3883. print $out;
  3884. } else {
  3885. return $out;
  3886. }
  3887. }
  3888. /**
  3889. * Selection HT or TTC
  3890. *
  3891. * @param string $selected Id pre-selectionne
  3892. * @param string $htmlname Nom de la zone select
  3893. * @param string $addjscombo Add js combo
  3894. * @return string Code of HTML select to chose tax or not
  3895. */
  3896. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3897. {
  3898. global $langs;
  3899. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3900. $options = array(
  3901. 'HT'=>$langs->trans("HT"),
  3902. 'TTC'=>$langs->trans("TTC")
  3903. );
  3904. foreach ($options as $id => $value) {
  3905. if ($selected == $id) {
  3906. $return .= '<option value="'.$id.'" selected>'.$value;
  3907. } else {
  3908. $return .= '<option value="'.$id.'">'.$value;
  3909. }
  3910. $return .= '</option>';
  3911. }
  3912. $return .= '</select>';
  3913. if ($addjscombo) {
  3914. $return .= ajax_combobox('select_'.$htmlname);
  3915. }
  3916. return $return;
  3917. }
  3918. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3919. /**
  3920. * Load in cache list of transport mode
  3921. *
  3922. * @return int Nb of lines loaded, <0 if KO
  3923. */
  3924. public function load_cache_transport_mode()
  3925. {
  3926. // phpcs:enable
  3927. global $langs;
  3928. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3929. if ($num > 0) {
  3930. return $num; // Cache already loaded
  3931. }
  3932. dol_syslog(__METHOD__, LOG_DEBUG);
  3933. $this->cache_transport_mode = array();
  3934. $sql = "SELECT rowid, code, label, active";
  3935. $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
  3936. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3937. $resql = $this->db->query($sql);
  3938. if ($resql) {
  3939. $num = $this->db->num_rows($resql);
  3940. $i = 0;
  3941. while ($i < $num) {
  3942. $obj = $this->db->fetch_object($resql);
  3943. // If traduction exist, we use it else we take the default label
  3944. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3945. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3946. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3947. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3948. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3949. $i++;
  3950. }
  3951. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3952. return $num;
  3953. } else {
  3954. dol_print_error($this->db);
  3955. return -1;
  3956. }
  3957. }
  3958. /**
  3959. * Return list of transport mode for intracomm report
  3960. *
  3961. * @param string $selected Id of the transport mode pre-selected
  3962. * @param string $htmlname Name of the select field
  3963. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3964. * @param int $empty 1=can be empty, 0 else
  3965. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3966. * @param int $maxlength Max length of label
  3967. * @param int $active Active or not, -1 = all
  3968. * @param string $morecss Add more CSS on select tag
  3969. * @return void
  3970. */
  3971. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3972. {
  3973. global $langs, $user;
  3974. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3975. $this->load_cache_transport_mode();
  3976. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3977. if ($empty) {
  3978. print '<option value="">&nbsp;</option>';
  3979. }
  3980. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3981. // If not good status
  3982. if ($active >= 0 && $arraytypes['active'] != $active) {
  3983. continue;
  3984. }
  3985. // We discard empty line if showempty is on because an empty line has already been output.
  3986. if ($empty && empty($arraytypes['code'])) {
  3987. continue;
  3988. }
  3989. if ($format == 0) {
  3990. print '<option value="'.$id.'"';
  3991. } elseif ($format == 1) {
  3992. print '<option value="'.$arraytypes['code'].'"';
  3993. } elseif ($format == 2) {
  3994. print '<option value="'.$arraytypes['code'].'"';
  3995. } elseif ($format == 3) {
  3996. print '<option value="'.$id.'"';
  3997. }
  3998. // If text is selected, we compare with code, else with id
  3999. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  4000. print ' selected';
  4001. } elseif ($selected == $id) {
  4002. print ' selected';
  4003. }
  4004. print '>';
  4005. $value = '';
  4006. if ($format == 0) {
  4007. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4008. } elseif ($format == 1) {
  4009. $value = $arraytypes['code'];
  4010. } elseif ($format == 2) {
  4011. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  4012. } elseif ($format == 3) {
  4013. $value = $arraytypes['code'];
  4014. }
  4015. print $value ? $value : '&nbsp;';
  4016. print '</option>';
  4017. }
  4018. print '</select>';
  4019. if ($user->admin && !$noadmininfo) {
  4020. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4021. }
  4022. }
  4023. /**
  4024. * Return a HTML select list of shipping mode
  4025. *
  4026. * @param string $selected Id shipping mode pre-selected
  4027. * @param string $htmlname Name of select zone
  4028. * @param string $filtre To filter list. This parameter must not come from input of users
  4029. * @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.
  4030. * @param string $moreattrib To add more attribute on select
  4031. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  4032. * @param string $morecss More CSS
  4033. * @return void
  4034. */
  4035. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  4036. {
  4037. global $langs, $conf, $user;
  4038. $langs->load("admin");
  4039. $langs->load("deliveries");
  4040. $sql = "SELECT rowid, code, libelle as label";
  4041. $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
  4042. $sql .= " WHERE active > 0";
  4043. if ($filtre) {
  4044. $sql .= " AND ".$filtre;
  4045. }
  4046. $sql .= " ORDER BY libelle ASC";
  4047. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  4048. $result = $this->db->query($sql);
  4049. if ($result) {
  4050. $num = $this->db->num_rows($result);
  4051. $i = 0;
  4052. if ($num) {
  4053. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4054. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4055. print '<option value="-1">&nbsp;</option>';
  4056. }
  4057. while ($i < $num) {
  4058. $obj = $this->db->fetch_object($result);
  4059. if ($selected == $obj->rowid) {
  4060. print '<option value="'.$obj->rowid.'" selected>';
  4061. } else {
  4062. print '<option value="'.$obj->rowid.'">';
  4063. }
  4064. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  4065. print '</option>';
  4066. $i++;
  4067. }
  4068. print "</select>";
  4069. if ($user->admin && empty($noinfoadmin)) {
  4070. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4071. }
  4072. print ajax_combobox('select'.$htmlname);
  4073. } else {
  4074. print $langs->trans("NoShippingMethodDefined");
  4075. }
  4076. } else {
  4077. dol_print_error($this->db);
  4078. }
  4079. }
  4080. /**
  4081. * Display form to select shipping mode
  4082. *
  4083. * @param string $page Page
  4084. * @param int $selected Id of shipping mode
  4085. * @param string $htmlname Name of select html field
  4086. * @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.
  4087. * @return void
  4088. */
  4089. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4090. {
  4091. global $langs;
  4092. $langs->load("deliveries");
  4093. if ($htmlname != "none") {
  4094. print '<form method="POST" action="'.$page.'">';
  4095. print '<input type="hidden" name="action" value="setshippingmethod">';
  4096. print '<input type="hidden" name="token" value="'.newToken().'">';
  4097. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4098. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4099. print '</form>';
  4100. } else {
  4101. if ($selected) {
  4102. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4103. print $langs->trans("SendingMethod".strtoupper($code));
  4104. } else {
  4105. print "&nbsp;";
  4106. }
  4107. }
  4108. }
  4109. /**
  4110. * Creates HTML last in cycle situation invoices selector
  4111. *
  4112. * @param string $selected Preselected ID
  4113. * @param int $socid Company ID
  4114. *
  4115. * @return string HTML select
  4116. */
  4117. public function selectSituationInvoices($selected = '', $socid = 0)
  4118. {
  4119. global $langs;
  4120. $langs->load('bills');
  4121. $opt = '<option value="" selected></option>';
  4122. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4123. $sql .= ' FROM '.$this->db->prefix().'facture';
  4124. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  4125. $sql .= ' AND situation_counter >= 1';
  4126. $sql .= ' AND fk_soc = '.(int) $socid;
  4127. $sql .= ' AND type <> 2';
  4128. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4129. $resql = $this->db->query($sql);
  4130. if ($resql && $this->db->num_rows($resql) > 0) {
  4131. // Last seen cycle
  4132. $ref = 0;
  4133. while ($obj = $this->db->fetch_object($resql)) {
  4134. //Same cycle ?
  4135. if ($obj->situation_cycle_ref != $ref) {
  4136. // Just seen this cycle
  4137. $ref = $obj->situation_cycle_ref;
  4138. //not final ?
  4139. if ($obj->situation_final != 1) {
  4140. //Not prov?
  4141. if (substr($obj->ref, 1, 4) != 'PROV') {
  4142. if ($selected == $obj->rowid) {
  4143. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  4144. } else {
  4145. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  4146. }
  4147. }
  4148. }
  4149. }
  4150. }
  4151. } else {
  4152. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4153. }
  4154. if ($opt == '<option value ="" selected></option>') {
  4155. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  4156. }
  4157. return $opt;
  4158. }
  4159. /**
  4160. * Creates HTML units selector (code => label)
  4161. *
  4162. * @param string $selected Preselected Unit ID
  4163. * @param string $htmlname Select name
  4164. * @param int $showempty Add a nempty line
  4165. * @param string $unit_type Restrict to one given unit type
  4166. * @return string HTML select
  4167. */
  4168. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4169. {
  4170. global $langs;
  4171. $langs->load('products');
  4172. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  4173. $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
  4174. $sql .= ' WHERE active > 0';
  4175. if (!empty($unit_type)) {
  4176. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  4177. }
  4178. $sql .= " ORDER BY sortorder";
  4179. $resql = $this->db->query($sql);
  4180. if ($resql && $this->db->num_rows($resql) > 0) {
  4181. if ($showempty) {
  4182. $return .= '<option value="none"></option>';
  4183. }
  4184. while ($res = $this->db->fetch_object($resql)) {
  4185. $unitLabel = $res->label;
  4186. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  4187. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  4188. }
  4189. if ($selected == $res->rowid) {
  4190. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  4191. } else {
  4192. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  4193. }
  4194. }
  4195. $return .= '</select>';
  4196. }
  4197. return $return;
  4198. }
  4199. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4200. /**
  4201. * Return a HTML select list of bank accounts
  4202. *
  4203. * @param string $selected Id account pre-selected
  4204. * @param string $htmlname Name of select zone
  4205. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4206. * @param string $filtre To filter list. This parameter must not come from input of users
  4207. * @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.
  4208. * @param string $moreattrib To add more attribute on select
  4209. * @param int $showcurrency Show currency in label
  4210. * @param string $morecss More CSS
  4211. * @param int $nooutput 1=Return string, do not send to output
  4212. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4213. */
  4214. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4215. {
  4216. // phpcs:enable
  4217. global $langs, $conf;
  4218. $out = '';
  4219. $langs->load("admin");
  4220. $num = 0;
  4221. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4222. $sql .= " FROM ".$this->db->prefix()."bank_account";
  4223. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  4224. if ($status != 2) {
  4225. $sql .= " AND clos = ".(int) $status;
  4226. }
  4227. if ($filtre) {
  4228. $sql .= " AND ".$filtre;
  4229. }
  4230. $sql .= " ORDER BY label";
  4231. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  4232. $result = $this->db->query($sql);
  4233. if ($result) {
  4234. $num = $this->db->num_rows($result);
  4235. $i = 0;
  4236. if ($num) {
  4237. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4238. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4239. $out .= '<option value="-1">&nbsp;</option>';
  4240. }
  4241. while ($i < $num) {
  4242. $obj = $this->db->fetch_object($result);
  4243. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4244. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  4245. } else {
  4246. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  4247. }
  4248. $out .= trim($obj->label);
  4249. if ($showcurrency) {
  4250. $out .= ' ('.$obj->currency_code.')';
  4251. }
  4252. if ($status == 2 && $obj->status == 1) {
  4253. $out .= ' ('.$langs->trans("Closed").')';
  4254. }
  4255. $out .= '</option>';
  4256. $i++;
  4257. }
  4258. $out .= "</select>";
  4259. $out .= ajax_combobox('select'.$htmlname);
  4260. } else {
  4261. if ($status == 0) {
  4262. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4263. } else {
  4264. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4265. }
  4266. }
  4267. } else {
  4268. dol_print_error($this->db);
  4269. }
  4270. // Output or return
  4271. if (empty($nooutput)) {
  4272. print $out;
  4273. } else {
  4274. return $out;
  4275. }
  4276. return $num;
  4277. }
  4278. /**
  4279. * Return a HTML select list of establishment
  4280. *
  4281. * @param string $selected Id establishment pre-selected
  4282. * @param string $htmlname Name of select zone
  4283. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4284. * @param string $filtre To filter list. This parameter must not come from input of users
  4285. * @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.
  4286. * @param string $moreattrib To add more attribute on select
  4287. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4288. */
  4289. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4290. {
  4291. global $langs, $conf;
  4292. $langs->load("admin");
  4293. $num = 0;
  4294. $sql = "SELECT rowid, name, fk_country, status, entity";
  4295. $sql .= " FROM ".$this->db->prefix()."establishment";
  4296. $sql .= " WHERE 1=1";
  4297. if ($status != 2) {
  4298. $sql .= " AND status = ".(int) $status;
  4299. }
  4300. if ($filtre) {
  4301. $sql .= " AND ".$filtre;
  4302. }
  4303. $sql .= " ORDER BY name";
  4304. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4305. $result = $this->db->query($sql);
  4306. if ($result) {
  4307. $num = $this->db->num_rows($result);
  4308. $i = 0;
  4309. if ($num) {
  4310. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4311. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4312. print '<option value="-1">&nbsp;</option>';
  4313. }
  4314. while ($i < $num) {
  4315. $obj = $this->db->fetch_object($result);
  4316. if ($selected == $obj->rowid) {
  4317. print '<option value="'.$obj->rowid.'" selected>';
  4318. } else {
  4319. print '<option value="'.$obj->rowid.'">';
  4320. }
  4321. print trim($obj->name);
  4322. if ($status == 2 && $obj->status == 1) {
  4323. print ' ('.$langs->trans("Closed").')';
  4324. }
  4325. print '</option>';
  4326. $i++;
  4327. }
  4328. print "</select>";
  4329. } else {
  4330. if ($status == 0) {
  4331. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4332. } else {
  4333. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4334. }
  4335. }
  4336. } else {
  4337. dol_print_error($this->db);
  4338. }
  4339. }
  4340. /**
  4341. * Display form to select bank account
  4342. *
  4343. * @param string $page Page
  4344. * @param int $selected Id of bank account
  4345. * @param string $htmlname Name of select html field
  4346. * @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.
  4347. * @return void
  4348. */
  4349. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4350. {
  4351. global $langs;
  4352. if ($htmlname != "none") {
  4353. print '<form method="POST" action="'.$page.'">';
  4354. print '<input type="hidden" name="action" value="setbankaccount">';
  4355. print '<input type="hidden" name="token" value="'.newToken().'">';
  4356. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4357. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4358. if ($nbaccountfound > 0) {
  4359. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4360. }
  4361. print '</form>';
  4362. } else {
  4363. $langs->load('banks');
  4364. if ($selected) {
  4365. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4366. $bankstatic = new Account($this->db);
  4367. $result = $bankstatic->fetch($selected);
  4368. if ($result) {
  4369. print $bankstatic->getNomUrl(1);
  4370. }
  4371. } else {
  4372. print "&nbsp;";
  4373. }
  4374. }
  4375. }
  4376. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4377. /**
  4378. * Return list of categories having choosed type
  4379. *
  4380. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4381. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4382. * @param string $htmlname HTML field name
  4383. * @param int $maxlength Maximum length for labels
  4384. * @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.
  4385. * $markafterid can be an :
  4386. * - int (id of category)
  4387. * - string (categories ids seprated by comma)
  4388. * - array (list of categories ids)
  4389. * @param int $outputmode 0=HTML select string, 1=Array, 2=Array extended
  4390. * @param int $include [=0] Removed or 1=Keep only
  4391. * @param string $morecss More CSS
  4392. * @return string|array
  4393. * @see select_categories()
  4394. */
  4395. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4396. {
  4397. // phpcs:enable
  4398. global $conf, $langs;
  4399. $langs->load("categories");
  4400. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4401. // For backward compatibility
  4402. if (is_numeric($type)) {
  4403. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4404. }
  4405. if ($type === Categorie::TYPE_BANK_LINE) {
  4406. // TODO Move this into common category feature
  4407. $cate_arbo = array();
  4408. $sql = "SELECT c.label, c.rowid";
  4409. $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
  4410. $sql .= " WHERE entity = ".$conf->entity;
  4411. $sql .= " ORDER BY c.label";
  4412. $result = $this->db->query($sql);
  4413. if ($result) {
  4414. $num = $this->db->num_rows($result);
  4415. $i = 0;
  4416. while ($i < $num) {
  4417. $objp = $this->db->fetch_object($result);
  4418. if ($objp) {
  4419. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label, 'color'=>'', 'picto'=>'category');
  4420. }
  4421. $i++;
  4422. }
  4423. $this->db->free($result);
  4424. } else {
  4425. dol_print_error($this->db);
  4426. }
  4427. } else {
  4428. $cat = new Categorie($this->db);
  4429. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4430. }
  4431. $outarray = array();
  4432. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4433. if (is_array($cate_arbo)) {
  4434. if (!count($cate_arbo)) {
  4435. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4436. } else {
  4437. $output .= '<option value="-1">&nbsp;</option>';
  4438. foreach ($cate_arbo as $key => $value) {
  4439. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4440. $add = 'selected ';
  4441. } else {
  4442. $add = '';
  4443. }
  4444. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'"';
  4445. $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')).'"';
  4446. $output .= '>';
  4447. $output .= dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle');
  4448. $output .= '</option>';
  4449. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4450. }
  4451. }
  4452. }
  4453. $output .= '</select>';
  4454. $output .= "\n";
  4455. if ($outputmode == 2) {
  4456. return $cate_arbo;
  4457. } elseif ($outputmode) {
  4458. return $outarray;
  4459. }
  4460. return $output;
  4461. }
  4462. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4463. /**
  4464. * Show a confirmation HTML form or AJAX popup
  4465. *
  4466. * @param string $page Url of page to call if confirmation is OK
  4467. * @param string $title Title
  4468. * @param string $question Question
  4469. * @param string $action Action
  4470. * @param array $formquestion An array with forms complementary inputs
  4471. * @param string $selectedchoice "" or "no" or "yes"
  4472. * @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
  4473. * @param int $height Force height of box
  4474. * @param int $width Force width of box
  4475. * @return void
  4476. * @deprecated
  4477. * @see formconfirm()
  4478. */
  4479. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4480. {
  4481. // phpcs:enable
  4482. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4483. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4484. }
  4485. /**
  4486. * Show a confirmation HTML form or AJAX popup.
  4487. * Easiest way to use this is with useajax=1.
  4488. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4489. * just after calling this method. For example:
  4490. * print '<script type="text/javascript">'."\n";
  4491. * print 'jQuery(document).ready(function() {'."\n";
  4492. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4493. * print '});'."\n";
  4494. * print '</script>'."\n";
  4495. *
  4496. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4497. * @param string $title Title
  4498. * @param string $question Question
  4499. * @param string $action Action
  4500. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>'autofocus' or 'style=...'))
  4501. * 'type' can be 'text', 'password', 'checkbox', 'radio', 'date', 'datetime', 'select', 'multiselect', 'morecss',
  4502. * 'other', 'onecolumn' or 'hidden'...
  4503. * @param int|string $selectedchoice '' or 'no', or 'yes' or '1', 1, '0' or 0
  4504. * @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
  4505. * @param int|string $height Force height of box (0 = auto)
  4506. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4507. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4508. * @param string $labelbuttonyes Label for Yes
  4509. * @param string $labelbuttonno Label for No
  4510. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4511. */
  4512. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4513. {
  4514. global $langs, $conf;
  4515. $more = '<!-- formconfirm - before call, page='.dol_escape_htmltag($page).' -->';
  4516. $formconfirm = '';
  4517. $inputok = array();
  4518. $inputko = array();
  4519. // Clean parameters
  4520. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4521. if ($conf->browser->layout == 'phone') {
  4522. $width = '95%';
  4523. }
  4524. // Set height automatically if not defined
  4525. if (empty($height)) {
  4526. $height = 220;
  4527. if (is_array($formquestion) && count($formquestion) > 2) {
  4528. $height += ((count($formquestion) - 2) * 24);
  4529. }
  4530. }
  4531. if (is_array($formquestion) && !empty($formquestion)) {
  4532. // First add hidden fields and value
  4533. foreach ($formquestion as $key => $input) {
  4534. if (is_array($input) && !empty($input)) {
  4535. if ($input['type'] == 'hidden') {
  4536. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4537. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4538. $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";
  4539. }
  4540. }
  4541. }
  4542. // Now add questions
  4543. $moreonecolumn = '';
  4544. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4545. foreach ($formquestion as $key => $input) {
  4546. if (is_array($input) && !empty($input)) {
  4547. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4548. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4549. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4550. if ($input['type'] == 'text') {
  4551. $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";
  4552. } elseif ($input['type'] == 'password') {
  4553. $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";
  4554. } elseif ($input['type'] == 'textarea') {
  4555. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4556. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4557. $more .= $input['value'];
  4558. $more .= '</textarea>';
  4559. $more .= '</div></div>'."\n";*/
  4560. $moreonecolumn .= '<div class="margintoponly">';
  4561. $moreonecolumn .= $input['label'].'<br>';
  4562. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4563. $moreonecolumn .= $input['value'];
  4564. $moreonecolumn .= '</textarea>';
  4565. $moreonecolumn .= '</div>';
  4566. } elseif (in_array($input['type'], ['select', 'multiselect'])) {
  4567. if (empty($morecss)) {
  4568. $morecss = 'minwidth100';
  4569. }
  4570. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4571. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4572. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4573. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4574. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4575. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4576. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4577. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4578. if (!empty($input['label'])) {
  4579. $more .= $input['label'].'</div><div class="tagtd left">';
  4580. }
  4581. if ($input['type'] == 'select') {
  4582. $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);
  4583. } else {
  4584. $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);
  4585. }
  4586. $more .= '</div></div>'."\n";
  4587. } elseif ($input['type'] == 'checkbox') {
  4588. $more .= '<div class="tagtr">';
  4589. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4590. $more .= '<input type="checkbox" class="flat'.($morecss ? ' '.$morecss : '').'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4591. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4592. $more .= ' checked';
  4593. }
  4594. if (is_bool($input['value']) && $input['value']) {
  4595. $more .= ' checked';
  4596. }
  4597. if (isset($input['disabled'])) {
  4598. $more .= ' disabled';
  4599. }
  4600. $more .= ' /></div>';
  4601. $more .= '</div>'."\n";
  4602. } elseif ($input['type'] == 'radio') {
  4603. $i = 0;
  4604. foreach ($input['values'] as $selkey => $selval) {
  4605. $more .= '<div class="tagtr">';
  4606. if (isset($input['label'])) {
  4607. if ($i == 0) {
  4608. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4609. } else {
  4610. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4611. }
  4612. }
  4613. $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;
  4614. if (!empty($input['disabled'])) {
  4615. $more .= ' disabled';
  4616. }
  4617. if (isset($input['default']) && $input['default'] === $selkey) {
  4618. $more .= ' checked="checked"';
  4619. }
  4620. $more .= ' /> ';
  4621. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'" class="valignmiddle">'.$selval.'</label>';
  4622. $more .= '</div></div>'."\n";
  4623. $i++;
  4624. }
  4625. } elseif ($input['type'] == 'date' || $input['type'] == 'datetime') {
  4626. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4627. $more .= '<div class="tagtd">';
  4628. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4629. $more .= $this->selectDate($input['value'], $input['name'], ($input['type'] == 'datetime' ? 1 : 0), ($input['type'] == 'datetime' ? 1 : 0), 0, '', 1, $addnowlink);
  4630. $more .= '</div></div>'."\n";
  4631. $formquestion[] = array('name'=>$input['name'].'day');
  4632. $formquestion[] = array('name'=>$input['name'].'month');
  4633. $formquestion[] = array('name'=>$input['name'].'year');
  4634. $formquestion[] = array('name'=>$input['name'].'hour');
  4635. $formquestion[] = array('name'=>$input['name'].'min');
  4636. } elseif ($input['type'] == 'other') {
  4637. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4638. if (!empty($input['label'])) {
  4639. $more .= $input['label'].'</div><div class="tagtd">';
  4640. }
  4641. $more .= $input['value'];
  4642. $more .= '</div></div>'."\n";
  4643. } elseif ($input['type'] == 'onecolumn') {
  4644. $moreonecolumn .= '<div class="margintoponly">';
  4645. $moreonecolumn .= $input['value'];
  4646. $moreonecolumn .= '</div>'."\n";
  4647. } elseif ($input['type'] == 'hidden') {
  4648. // Do nothing more, already added by a previous loop
  4649. } elseif ($input['type'] == 'separator') {
  4650. $more .= '<br>';
  4651. } else {
  4652. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4653. }
  4654. }
  4655. }
  4656. $more .= '</div>'."\n";
  4657. $more .= $moreonecolumn;
  4658. }
  4659. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4660. // 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
  4661. // See page product/card.php for example
  4662. if (!empty($conf->dol_use_jmobile)) {
  4663. $useajax = 0;
  4664. }
  4665. if (empty($conf->use_javascript_ajax)) {
  4666. $useajax = 0;
  4667. }
  4668. if ($useajax) {
  4669. $autoOpen = true;
  4670. $dialogconfirm = 'dialog-confirm';
  4671. $button = '';
  4672. if (!is_numeric($useajax)) {
  4673. $button = $useajax;
  4674. $useajax = 1;
  4675. $autoOpen = false;
  4676. $dialogconfirm .= '-'.$button;
  4677. }
  4678. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=yes';
  4679. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=no' : '');
  4680. // Add input fields into list of fields to read during submit (inputok and inputko)
  4681. if (is_array($formquestion)) {
  4682. foreach ($formquestion as $key => $input) {
  4683. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4684. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4685. if (is_array($input) && isset($input['name'])) {
  4686. if (strpos($input['name'], ',') > 0) {
  4687. $inputok = array_merge($inputok, explode(',', $input['name']));
  4688. } else {
  4689. array_push($inputok, $input['name']);
  4690. }
  4691. }
  4692. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4693. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4694. array_push($inputko, $input['name']);
  4695. }
  4696. }
  4697. }
  4698. // Show JQuery confirm box.
  4699. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4700. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4701. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4702. }
  4703. if (!empty($more)) {
  4704. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4705. }
  4706. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4707. $formconfirm .= '</div>'."\n";
  4708. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4709. $formconfirm .= '<script type="text/javascript">'."\n";
  4710. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4711. $formconfirm .= 'jQuery(document).ready(function() {
  4712. $(function() {
  4713. $( "#'.$dialogconfirm.'" ).dialog(
  4714. {
  4715. autoOpen: '.($autoOpen ? "true" : "false").',';
  4716. if ($newselectedchoice == 'no') {
  4717. $formconfirm .= '
  4718. open: function() {
  4719. $(this).parent().find("button.ui-button:eq(2)").focus();
  4720. },';
  4721. }
  4722. $jsforcursor = '';
  4723. if ($useajax == 1) {
  4724. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor'."\n";
  4725. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");'."\n";
  4726. }
  4727. $postconfirmas = 'GET';
  4728. $formconfirm .= '
  4729. resizable: false,
  4730. height: "'.$height.'",
  4731. width: "'.$width.'",
  4732. modal: true,
  4733. closeOnEscape: false,
  4734. buttons: {
  4735. "'.dol_escape_js($langs->transnoentities($labelbuttonyes)).'": function() {
  4736. var options = "token='.urlencode(newToken()).'";
  4737. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4738. var page = "'.dol_escape_js(!empty($page) ? $page : '').'";
  4739. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4740. if (inputok.length > 0) {
  4741. $.each(inputok, function(i, inputname) {
  4742. var more = "";
  4743. var inputvalue;
  4744. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4745. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4746. } else {
  4747. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4748. inputvalue = $("#" + inputname + more).val();
  4749. }
  4750. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4751. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4752. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4753. });
  4754. }
  4755. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "&") + options;
  4756. if (pageyes.length > 0) {';
  4757. if ($postconfirmas == 'GET') {
  4758. $formconfirm .= 'location.href = urljump;';
  4759. } else {
  4760. $formconfirm .= $jsforcursor;
  4761. $formconfirm .= 'var post = $.post(
  4762. pageyes,
  4763. options,
  4764. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4765. );';
  4766. }
  4767. $formconfirm .= '
  4768. console.log("after post ok");
  4769. }
  4770. $(this).dialog("close");
  4771. },
  4772. "'.dol_escape_js($langs->transnoentities($labelbuttonno)).'": function() {
  4773. var options = "token='.urlencode(newToken()).'";
  4774. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4775. var page = "'.dol_escape_js(!empty($page) ? $page : '').'";
  4776. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4777. if (inputko.length > 0) {
  4778. $.each(inputko, function(i, inputname) {
  4779. var more = "";
  4780. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4781. var inputvalue = $("#" + inputname + more).val();
  4782. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4783. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4784. });
  4785. }
  4786. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "&") + options;
  4787. //alert(urljump);
  4788. if (pageno.length > 0) {';
  4789. if ($postconfirmas == 'GET') {
  4790. $formconfirm .= 'location.href = urljump;';
  4791. } else {
  4792. $formconfirm .= $jsforcursor;
  4793. $formconfirm .= 'var post = $.post(
  4794. pageno,
  4795. options,
  4796. function(data) { $("body").html(data); jQuery("html,body,#id-container").removeClass("cursorwait"); }
  4797. );';
  4798. }
  4799. $formconfirm .= '
  4800. console.log("after post ko");
  4801. }
  4802. $(this).dialog("close");
  4803. }
  4804. }
  4805. }
  4806. );
  4807. var button = "'.$button.'";
  4808. if (button.length > 0) {
  4809. $( "#" + button ).click(function() {
  4810. $("#'.$dialogconfirm.'").dialog("open");
  4811. });
  4812. }
  4813. });
  4814. });
  4815. </script>';
  4816. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4817. } else {
  4818. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4819. if (empty($disableformtag)) {
  4820. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4821. }
  4822. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4823. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4824. $formconfirm .= '<table class="valid centpercent">'."\n";
  4825. // Line title
  4826. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4827. $formconfirm .= img_picto('', 'pictoconfirm').' '.$title;
  4828. $formconfirm .= '</td></tr>'."\n";
  4829. // Line text
  4830. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4831. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4832. }
  4833. // Line form fields
  4834. if ($more) {
  4835. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4836. $formconfirm .= $more;
  4837. $formconfirm .= '</td></tr>'."\n";
  4838. }
  4839. // Line with question
  4840. $formconfirm .= '<tr class="valid">';
  4841. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4842. $formconfirm .= '<td class="valid center">';
  4843. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  4844. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
  4845. $formconfirm .= '</td>';
  4846. $formconfirm .= '</tr>'."\n";
  4847. $formconfirm .= '</table>'."\n";
  4848. if (empty($disableformtag)) {
  4849. $formconfirm .= "</form>\n";
  4850. }
  4851. $formconfirm .= '<br>';
  4852. if (!empty($conf->use_javascript_ajax)) {
  4853. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4854. $formconfirm .= '<script type="text/javascript">'."\n";
  4855. $formconfirm .= '
  4856. $(document).ready(function () {
  4857. $(".confirmvalidatebutton").on("click", function() {
  4858. console.log("We click on button");
  4859. $(this).attr("disabled", "disabled");
  4860. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4861. //console.log($(this).closest("form"));
  4862. $(this).closest("form").submit();
  4863. });
  4864. });
  4865. ';
  4866. $formconfirm .= '</script>'."\n";
  4867. }
  4868. $formconfirm .= "<!-- end formconfirm -->\n";
  4869. }
  4870. return $formconfirm;
  4871. }
  4872. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4873. /**
  4874. * Show a form to select a project
  4875. *
  4876. * @param int $page Page
  4877. * @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)
  4878. * @param int $selected Id pre-selected project
  4879. * @param string $htmlname Name of select field
  4880. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4881. * @param int $maxlength Max length
  4882. * @param int $forcefocus Force focus on field (works with javascript only)
  4883. * @param int $nooutput No print is done. String is returned.
  4884. * @param string $textifnoproject Text to show if no project
  4885. * @param string $morecss More CSS
  4886. * @return string Return html content
  4887. */
  4888. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0, $textifnoproject = '', $morecss = '')
  4889. {
  4890. // phpcs:enable
  4891. global $langs;
  4892. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4893. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4894. $out = '';
  4895. $formproject = new FormProjets($this->db);
  4896. $langs->load("project");
  4897. if ($htmlname != "none") {
  4898. $out .= '<form method="post" action="'.$page.'">';
  4899. $out .= '<input type="hidden" name="action" value="classin">';
  4900. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4901. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1, 0, $morecss);
  4902. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4903. $out .= '</form>';
  4904. } else {
  4905. $out .= '<span class="project_head_block">';
  4906. if ($selected) {
  4907. $projet = new Project($this->db);
  4908. $projet->fetch($selected);
  4909. $out .= $projet->getNomUrl(0, '', 1);
  4910. } else {
  4911. $out .= '<span class="opacitymedium">'.$textifnoproject.'</span>';
  4912. }
  4913. $out .= '</span>';
  4914. }
  4915. if (empty($nooutput)) {
  4916. print $out;
  4917. return '';
  4918. }
  4919. return $out;
  4920. }
  4921. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4922. /**
  4923. * Show a form to select payment conditions
  4924. *
  4925. * @param int $page Page
  4926. * @param string $selected Id condition pre-selectionne
  4927. * @param string $htmlname Name of select html field
  4928. * @param int $addempty Add empty entry
  4929. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4930. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  4931. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  4932. * 0 : use default deposit percentage from entry
  4933. * > 0 : force deposit percentage (for example, from company object)
  4934. * @param int $nooutput No print is done. String is returned.
  4935. * @return void
  4936. */
  4937. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1, $nooutput = 0)
  4938. {
  4939. // phpcs:enable
  4940. global $langs;
  4941. $out = '';
  4942. if ($htmlname != "none") {
  4943. $out .= '<form method="POST" action="'.$page.'">';
  4944. $out .= '<input type="hidden" name="action" value="setconditions">';
  4945. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4946. if ($type) {
  4947. $out .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4948. }
  4949. $out .= $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  4950. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4951. $out .= '</form>';
  4952. } else {
  4953. if ($selected) {
  4954. $this->load_cache_conditions_paiements();
  4955. if (isset($this->cache_conditions_paiements[$selected])) {
  4956. $label = $this->cache_conditions_paiements[$selected]['label'];
  4957. if (!empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  4958. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  4959. }
  4960. $out .= $label;
  4961. } else {
  4962. $langs->load('errors');
  4963. $out .= $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4964. }
  4965. } else {
  4966. $out .= '&nbsp;';
  4967. }
  4968. }
  4969. if (empty($nooutput)) {
  4970. print $out;
  4971. return '';
  4972. }
  4973. return $out;
  4974. }
  4975. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4976. /**
  4977. * Show a form to select a delivery delay
  4978. *
  4979. * @param int $page Page
  4980. * @param string $selected Id condition pre-selectionne
  4981. * @param string $htmlname Name of select html field
  4982. * @param int $addempty Ajoute entree vide
  4983. * @return void
  4984. */
  4985. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4986. {
  4987. // phpcs:enable
  4988. global $langs;
  4989. if ($htmlname != "none") {
  4990. print '<form method="post" action="'.$page.'">';
  4991. print '<input type="hidden" name="action" value="setavailability">';
  4992. print '<input type="hidden" name="token" value="'.newToken().'">';
  4993. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4994. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4995. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4996. print '</form>';
  4997. } else {
  4998. if ($selected) {
  4999. $this->load_cache_availability();
  5000. print $this->cache_availability[$selected]['label'];
  5001. } else {
  5002. print "&nbsp;";
  5003. }
  5004. }
  5005. }
  5006. /**
  5007. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  5008. * List found into table c_input_reason loaded by loadCacheInputReason
  5009. *
  5010. * @param string $page Page
  5011. * @param string $selected Id condition pre-selectionne
  5012. * @param string $htmlname Name of select html field
  5013. * @param int $addempty Add empty entry
  5014. * @return void
  5015. */
  5016. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  5017. {
  5018. global $langs;
  5019. if ($htmlname != "none") {
  5020. print '<form method="post" action="'.$page.'">';
  5021. print '<input type="hidden" name="action" value="setdemandreason">';
  5022. print '<input type="hidden" name="token" value="'.newToken().'">';
  5023. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  5024. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  5025. print '</form>';
  5026. } else {
  5027. if ($selected) {
  5028. $this->loadCacheInputReason();
  5029. foreach ($this->cache_demand_reason as $key => $val) {
  5030. if ($val['id'] == $selected) {
  5031. print $val['label'];
  5032. break;
  5033. }
  5034. }
  5035. } else {
  5036. print "&nbsp;";
  5037. }
  5038. }
  5039. }
  5040. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5041. /**
  5042. * Show a form + html select a date
  5043. *
  5044. * @param string $page Page
  5045. * @param string $selected Date preselected
  5046. * @param string $htmlname Html name of date input fields or 'none'
  5047. * @param int $displayhour Display hour selector
  5048. * @param int $displaymin Display minutes selector
  5049. * @param int $nooutput 1=No print output, return string
  5050. * @param string $type 'direct-debit' or 'bank-transfer'
  5051. * @return string
  5052. * @see selectDate()
  5053. */
  5054. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  5055. {
  5056. // phpcs:enable
  5057. global $langs;
  5058. $ret = '';
  5059. if ($htmlname != "none") {
  5060. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  5061. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  5062. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  5063. if ($type) {
  5064. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  5065. }
  5066. $ret .= '<table class="nobordernopadding">';
  5067. $ret .= '<tr><td>';
  5068. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  5069. $ret .= '</td>';
  5070. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5071. $ret .= '</tr></table></form>';
  5072. } else {
  5073. if ($displayhour) {
  5074. $ret .= dol_print_date($selected, 'dayhour');
  5075. } else {
  5076. $ret .= dol_print_date($selected, 'day');
  5077. }
  5078. }
  5079. if (empty($nooutput)) {
  5080. print $ret;
  5081. }
  5082. return $ret;
  5083. }
  5084. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5085. /**
  5086. * Show a select form to choose a user
  5087. *
  5088. * @param string $page Page
  5089. * @param string $selected Id of user preselected
  5090. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  5091. * @param array $exclude List of users id to exclude
  5092. * @param array $include List of users id to include
  5093. * @return void
  5094. */
  5095. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  5096. {
  5097. // phpcs:enable
  5098. global $langs;
  5099. if ($htmlname != "none") {
  5100. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  5101. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  5102. print '<input type="hidden" name="token" value="'.newToken().'">';
  5103. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5104. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5105. print '</form>';
  5106. } else {
  5107. if ($selected) {
  5108. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  5109. $theuser = new User($this->db);
  5110. $theuser->fetch($selected);
  5111. print $theuser->getNomUrl(1);
  5112. } else {
  5113. print "&nbsp;";
  5114. }
  5115. }
  5116. }
  5117. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5118. /**
  5119. * Show form with payment mode
  5120. *
  5121. * @param string $page Page
  5122. * @param int $selected Id mode pre-selectionne
  5123. * @param string $htmlname Name of select html field
  5124. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5125. * @param int $active Active or not, -1 = all
  5126. * @param int $addempty 1=Add empty entry
  5127. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5128. * @param int $nooutput 1=Return string, no output
  5129. * @return void
  5130. */
  5131. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '', $nooutput = 0)
  5132. {
  5133. // phpcs:enable
  5134. global $langs;
  5135. $out = '';
  5136. if ($htmlname != "none") {
  5137. $out .= '<form method="POST" action="'.$page.'">';
  5138. $out .= '<input type="hidden" name="action" value="setmode">';
  5139. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5140. if ($type) {
  5141. $out .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  5142. }
  5143. $out .= $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5144. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5145. $out .= '</form>';
  5146. } else {
  5147. if ($selected) {
  5148. $this->load_cache_types_paiements();
  5149. $out .= $this->cache_types_paiements[$selected]['label'];
  5150. } else {
  5151. $out .= "&nbsp;";
  5152. }
  5153. }
  5154. if ($nooutput) {
  5155. return $out;
  5156. } else {
  5157. print $out;
  5158. }
  5159. }
  5160. /**
  5161. * Show form with transport mode
  5162. *
  5163. * @param string $page Page
  5164. * @param int $selected Id mode pre-select
  5165. * @param string $htmlname Name of select html field
  5166. * @param int $active Active or not, -1 = all
  5167. * @param int $addempty 1=Add empty entry
  5168. * @return void
  5169. */
  5170. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5171. {
  5172. global $langs;
  5173. if ($htmlname != "none") {
  5174. print '<form method="POST" action="'.$page.'">';
  5175. print '<input type="hidden" name="action" value="settransportmode">';
  5176. print '<input type="hidden" name="token" value="'.newToken().'">';
  5177. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5178. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5179. print '</form>';
  5180. } else {
  5181. if ($selected) {
  5182. $this->load_cache_transport_mode();
  5183. print $this->cache_transport_mode[$selected]['label'];
  5184. } else {
  5185. print "&nbsp;";
  5186. }
  5187. }
  5188. }
  5189. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5190. /**
  5191. * Show form with multicurrency code
  5192. *
  5193. * @param string $page Page
  5194. * @param string $selected code pre-selectionne
  5195. * @param string $htmlname Name of select html field
  5196. * @return void
  5197. */
  5198. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5199. {
  5200. // phpcs:enable
  5201. global $langs;
  5202. if ($htmlname != "none") {
  5203. print '<form method="POST" action="'.$page.'">';
  5204. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5205. print '<input type="hidden" name="token" value="'.newToken().'">';
  5206. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5207. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5208. print '</form>';
  5209. } else {
  5210. dol_include_once('/core/lib/company.lib.php');
  5211. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5212. }
  5213. }
  5214. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5215. /**
  5216. * Show form with multicurrency rate
  5217. *
  5218. * @param string $page Page
  5219. * @param double $rate Current rate
  5220. * @param string $htmlname Name of select html field
  5221. * @param string $currency Currency code to explain the rate
  5222. * @return void
  5223. */
  5224. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5225. {
  5226. // phpcs:enable
  5227. global $langs, $mysoc, $conf;
  5228. if ($htmlname != "none") {
  5229. print '<form method="POST" action="'.$page.'">';
  5230. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5231. print '<input type="hidden" name="token" value="'.newToken().'">';
  5232. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  5233. print '<select name="calculation_mode">';
  5234. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  5235. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  5236. print '</select> ';
  5237. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5238. print '</form>';
  5239. } else {
  5240. if (!empty($rate)) {
  5241. print price($rate, 1, $langs, 1, 0);
  5242. if ($currency && $rate != 1) {
  5243. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  5244. }
  5245. } else {
  5246. print 1;
  5247. }
  5248. }
  5249. }
  5250. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5251. /**
  5252. * Show a select box with available absolute discounts
  5253. *
  5254. * @param string $page Page URL where form is shown
  5255. * @param int $selected Value pre-selected
  5256. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5257. * @param int $socid Third party id
  5258. * @param float $amount Total amount available
  5259. * @param string $filter SQL filter on discounts
  5260. * @param int $maxvalue Max value for lines that can be selected
  5261. * @param string $more More string to add
  5262. * @param int $hidelist 1=Hide list
  5263. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5264. * @return void
  5265. */
  5266. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5267. {
  5268. // phpcs:enable
  5269. global $conf, $langs;
  5270. if ($htmlname != "none") {
  5271. print '<form method="post" action="'.$page.'">';
  5272. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5273. print '<input type="hidden" name="token" value="'.newToken().'">';
  5274. print '<div class="inline-block">';
  5275. if (!empty($discount_type)) {
  5276. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5277. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5278. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5279. } else {
  5280. $translationKey = 'HasCreditNoteFromSupplier';
  5281. }
  5282. } else {
  5283. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5284. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5285. } else {
  5286. $translationKey = 'HasCreditNoteFromSupplier';
  5287. }
  5288. }
  5289. } else {
  5290. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5291. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5292. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5293. } else {
  5294. $translationKey = 'CompanyHasCreditNote';
  5295. }
  5296. } else {
  5297. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5298. $translationKey = 'CompanyHasAbsoluteDiscount';
  5299. } else {
  5300. $translationKey = 'CompanyHasCreditNote';
  5301. }
  5302. }
  5303. }
  5304. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5305. if (empty($hidelist)) {
  5306. print ' ';
  5307. }
  5308. print '</div>';
  5309. if (empty($hidelist)) {
  5310. print '<div class="inline-block" style="padding-right: 10px">';
  5311. $newfilter = 'discount_type='.intval($discount_type);
  5312. if (!empty($discount_type)) {
  5313. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5314. } else {
  5315. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5316. }
  5317. if ($filter) {
  5318. $newfilter .= ' AND ('.$filter.')';
  5319. }
  5320. // output the combo of discounts
  5321. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5322. if ($nbqualifiedlines > 0) {
  5323. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  5324. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5325. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5326. }
  5327. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5328. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5329. }
  5330. print '>';
  5331. }
  5332. print '</div>';
  5333. }
  5334. if ($more) {
  5335. print '<div class="inline-block">';
  5336. print $more;
  5337. print '</div>';
  5338. }
  5339. print '</form>';
  5340. } else {
  5341. if ($selected) {
  5342. print $selected;
  5343. } else {
  5344. print "0";
  5345. }
  5346. }
  5347. }
  5348. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5349. /**
  5350. * Show forms to select a contact
  5351. *
  5352. * @param string $page Page
  5353. * @param Societe $societe Filter on third party
  5354. * @param int $selected Id contact pre-selectionne
  5355. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5356. * @return void
  5357. */
  5358. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5359. {
  5360. // phpcs:enable
  5361. global $langs, $conf;
  5362. if ($htmlname != "none") {
  5363. print '<form method="post" action="'.$page.'">';
  5364. print '<input type="hidden" name="action" value="set_contact">';
  5365. print '<input type="hidden" name="token" value="'.newToken().'">';
  5366. print '<table class="nobordernopadding">';
  5367. print '<tr><td>';
  5368. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5369. $num = $this->num;
  5370. if ($num == 0) {
  5371. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5372. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5373. }
  5374. print '</td>';
  5375. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5376. print '</tr></table></form>';
  5377. } else {
  5378. if ($selected) {
  5379. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5380. $contact = new Contact($this->db);
  5381. $contact->fetch($selected);
  5382. print $contact->getFullName($langs);
  5383. } else {
  5384. print "&nbsp;";
  5385. }
  5386. }
  5387. }
  5388. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5389. /**
  5390. * Output html select to select thirdparty
  5391. *
  5392. * @param string $page Page
  5393. * @param string $selected Id preselected
  5394. * @param string $htmlname Name of HTML select
  5395. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5396. * @param int $showempty Add an empty field
  5397. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5398. * @param int $forcecombo Force to use combo box
  5399. * @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')))
  5400. * @param int $nooutput No print output. Return it only.
  5401. * @param array $excludeids Exclude IDs from the select combo
  5402. * @param string $textifnothirdparty Text to show if no thirdparty
  5403. * @return void|string
  5404. */
  5405. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array(), $textifnothirdparty = '')
  5406. {
  5407. // phpcs:enable
  5408. global $langs;
  5409. $out = '';
  5410. if ($htmlname != "none") {
  5411. $out .= '<form method="post" action="'.$page.'">';
  5412. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5413. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5414. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5415. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5416. $out .= '</form>';
  5417. } else {
  5418. if ($selected) {
  5419. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5420. $soc = new Societe($this->db);
  5421. $soc->fetch($selected);
  5422. $out .= $soc->getNomUrl(0, '');
  5423. } else {
  5424. $out .= '<span class="opacitymedium">'.$textifnothirdparty.'</span>';
  5425. }
  5426. }
  5427. if ($nooutput) {
  5428. return $out;
  5429. } else {
  5430. print $out;
  5431. }
  5432. }
  5433. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5434. /**
  5435. * Retourne la liste des devises, dans la langue de l'utilisateur
  5436. *
  5437. * @param string $selected preselected currency code
  5438. * @param string $htmlname name of HTML select list
  5439. * @deprecated
  5440. * @return void
  5441. */
  5442. public function select_currency($selected = '', $htmlname = 'currency_id')
  5443. {
  5444. // phpcs:enable
  5445. print $this->selectCurrency($selected, $htmlname);
  5446. }
  5447. /**
  5448. * Retourne la liste des devises, dans la langue de l'utilisateur
  5449. *
  5450. * @param string $selected preselected currency code
  5451. * @param string $htmlname name of HTML select list
  5452. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5453. * @param string $useempty '1'=Allow empty value
  5454. * @return string
  5455. */
  5456. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5457. {
  5458. global $conf, $langs, $user;
  5459. $langs->loadCacheCurrencies('');
  5460. $out = '';
  5461. if ($selected == 'euro' || $selected == 'euros') {
  5462. $selected = 'EUR'; // Pour compatibilite
  5463. }
  5464. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5465. if ($useempty) {
  5466. $out .= '<option value="-1" selected></option>';
  5467. }
  5468. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5469. $labeltoshow = $currency['label'];
  5470. if ($mode == 1) {
  5471. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5472. } else {
  5473. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5474. }
  5475. if ($selected && $selected == $code_iso) {
  5476. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5477. } else {
  5478. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5479. }
  5480. $out .= $labeltoshow;
  5481. $out .= '</option>';
  5482. }
  5483. $out .= '</select>';
  5484. if ($user->admin) {
  5485. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5486. }
  5487. // Make select dynamic
  5488. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5489. $out .= ajax_combobox($htmlname);
  5490. return $out;
  5491. }
  5492. /**
  5493. * Return array of currencies in user language
  5494. *
  5495. * @param string $selected Preselected currency code
  5496. * @param string $htmlname Name of HTML select list
  5497. * @param integer $useempty 1=Add empty line
  5498. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5499. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5500. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5501. * @param string $morecss More css
  5502. * @return string
  5503. */
  5504. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5505. {
  5506. global $conf, $langs;
  5507. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5508. $TCurrency = array();
  5509. $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
  5510. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5511. if ($filter) {
  5512. $sql .= " AND ".$filter;
  5513. }
  5514. $resql = $this->db->query($sql);
  5515. if ($resql) {
  5516. while ($obj = $this->db->fetch_object($resql)) {
  5517. $TCurrency[$obj->code] = $obj->code;
  5518. }
  5519. }
  5520. $out = '';
  5521. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  5522. if ($useempty) {
  5523. $out .= '<option value="">&nbsp;</option>';
  5524. }
  5525. // If company current currency not in table, we add it into list. Should always be available.
  5526. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5527. $TCurrency[$conf->currency] = $conf->currency;
  5528. }
  5529. if (count($TCurrency) > 0) {
  5530. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5531. if (isset($TCurrency[$code_iso])) {
  5532. if (!empty($selected) && $selected == $code_iso) {
  5533. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5534. } else {
  5535. $out .= '<option value="'.$code_iso.'">';
  5536. }
  5537. $out .= $currency['label'];
  5538. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5539. $out .= '</option>';
  5540. }
  5541. }
  5542. }
  5543. $out .= '</select>';
  5544. // Make select dynamic
  5545. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5546. $out .= ajax_combobox($htmlname);
  5547. return $out;
  5548. }
  5549. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5550. /**
  5551. * Load into the cache vat rates of a country
  5552. *
  5553. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5554. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5555. */
  5556. public function load_cache_vatrates($country_code)
  5557. {
  5558. // phpcs:enable
  5559. global $langs;
  5560. $num = count($this->cache_vatrates);
  5561. if ($num > 0) {
  5562. return $num; // Cache already loaded
  5563. }
  5564. dol_syslog(__METHOD__, LOG_DEBUG);
  5565. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5566. $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
  5567. $sql .= " WHERE t.fk_pays = c.rowid";
  5568. $sql .= " AND t.active > 0";
  5569. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5570. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5571. $resql = $this->db->query($sql);
  5572. if ($resql) {
  5573. $num = $this->db->num_rows($resql);
  5574. if ($num) {
  5575. for ($i = 0; $i < $num; $i++) {
  5576. $obj = $this->db->fetch_object($resql);
  5577. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5578. $this->cache_vatrates[$i]['code'] = $obj->code;
  5579. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5580. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5581. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5582. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5583. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5584. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5585. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5586. $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
  5587. $positiverates = '';
  5588. if ($obj->taux) {
  5589. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5590. }
  5591. if ($obj->localtax1) {
  5592. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5593. }
  5594. if ($obj->localtax2) {
  5595. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5596. }
  5597. if (empty($positiverates)) {
  5598. $positiverates = '0';
  5599. }
  5600. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5601. }
  5602. return $num;
  5603. } else {
  5604. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5605. return -1;
  5606. }
  5607. } else {
  5608. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5609. return -2;
  5610. }
  5611. }
  5612. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5613. /**
  5614. * Output an HTML select vat rate.
  5615. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5616. *
  5617. * @param string $htmlname Name of HTML select field
  5618. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5619. * @param Societe $societe_vendeuse Thirdparty seller
  5620. * @param Societe $societe_acheteuse Thirdparty buyer
  5621. * @param int $idprod Id product. O if unknown of NA.
  5622. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5623. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5624. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5625. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5626. * 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.
  5627. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5628. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5629. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5630. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5631. * @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
  5632. * @return string
  5633. */
  5634. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5635. {
  5636. // phpcs:enable
  5637. global $langs, $conf, $mysoc;
  5638. $langs->load('errors');
  5639. $return = '';
  5640. // Define defaultnpr, defaultttx and defaultcode
  5641. $defaultnpr = ($info_bits & 0x01);
  5642. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5643. $defaulttx = str_replace('*', '', $selectedrate);
  5644. $defaultcode = '';
  5645. $reg = array();
  5646. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5647. $defaultcode = $reg[1];
  5648. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5649. }
  5650. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5651. // Check parameters
  5652. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5653. if ($societe_vendeuse->id == $mysoc->id) {
  5654. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5655. } else {
  5656. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5657. }
  5658. return $return;
  5659. }
  5660. //var_dump($societe_acheteuse);
  5661. //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";
  5662. //exit;
  5663. // Define list of countries to use to search VAT rates to show
  5664. // First we defined code_country to use to find list
  5665. if (is_object($societe_vendeuse)) {
  5666. $code_country = "'".$societe_vendeuse->country_code."'";
  5667. } else {
  5668. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5669. }
  5670. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5671. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5672. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5673. // We also add the buyer country code
  5674. if (is_numeric($type)) {
  5675. if ($type == 1) { // We know product is a service
  5676. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5677. }
  5678. } elseif (!$idprod) { // We don't know type of product
  5679. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5680. } else {
  5681. $prodstatic = new Product($this->db);
  5682. $prodstatic->fetch($idprod);
  5683. if ($prodstatic->type == Product::TYPE_SERVICE) { // We know product is a service
  5684. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5685. }
  5686. }
  5687. }
  5688. }
  5689. // Now we get list
  5690. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5691. if ($num > 0) {
  5692. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5693. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5694. $tmpthirdparty = new Societe($this->db);
  5695. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5696. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5697. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5698. $defaultcode = $reg[1];
  5699. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5700. }
  5701. if (empty($defaulttx)) {
  5702. $defaultnpr = 0;
  5703. }
  5704. }
  5705. // If we fails to find a default vat rate, we take the last one in list
  5706. // Because they are sorted in ascending order, the last one will be the higher one (we suppose the higher one is the current rate)
  5707. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5708. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5709. // We take the last one found in list
  5710. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5711. } else {
  5712. // We will use the rate defined into MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS
  5713. $defaulttx = '';
  5714. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5715. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5716. }
  5717. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5718. $defaultcode = $reg[1];
  5719. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5720. }
  5721. }
  5722. }
  5723. // Disabled if seller is not subject to VAT
  5724. $disabled = false;
  5725. $title = '';
  5726. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5727. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5728. // of using supplier invoices (this is a very bad idea !)
  5729. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5730. $title = ' title="'.dol_escape_htmltag($langs->trans('VATIsNotUsed')).'"';
  5731. $disabled = true;
  5732. }
  5733. }
  5734. if (!$options_only) {
  5735. $return .= '<select class="flat minwidth50imp maxwidth100" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5736. }
  5737. $selectedfound = false;
  5738. foreach ($this->cache_vatrates as $rate) {
  5739. // Keep only 0 if seller is not subject to VAT
  5740. if ($disabled && $rate['txtva'] != 0) {
  5741. continue;
  5742. }
  5743. // Define key to use into select list
  5744. $key = $rate['txtva'];
  5745. $key .= $rate['nprtva'] ? '*' : '';
  5746. if ($mode > 0 && $rate['code']) {
  5747. $key .= ' ('.$rate['code'].')';
  5748. }
  5749. if ($mode < 0) {
  5750. $key = $rate['rowid'];
  5751. }
  5752. $return .= '<option value="'.$key.'"';
  5753. if (!$selectedfound) {
  5754. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5755. if ($defaultcode == $rate['code']) {
  5756. $return .= ' selected';
  5757. $selectedfound = true;
  5758. }
  5759. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5760. $return .= ' selected';
  5761. $selectedfound = true;
  5762. }
  5763. }
  5764. $return .= '>';
  5765. // Show label of VAT
  5766. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5767. // Label with all localtax and code. For example: x.y / a.b / c.d (CODE)'
  5768. $return .= $rate['labelpositiverates'];
  5769. } else {
  5770. // Simple label
  5771. $return .= vatrate($rate['label']);
  5772. }
  5773. //$return.=($rate['code']?' '.$rate['code']:'');
  5774. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5775. $return .= '</option>';
  5776. }
  5777. if (!$options_only) {
  5778. $return .= '</select>';
  5779. //$return .= ajax_combobox($htmlname); // This break for the moment the dynamic autoselection of a value when selecting a product in object lines
  5780. }
  5781. } else {
  5782. $return .= $this->error;
  5783. }
  5784. $this->num = $num;
  5785. return $return;
  5786. }
  5787. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5788. /**
  5789. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5790. * Fields are preselected with :
  5791. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5792. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5793. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5794. *
  5795. * @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).
  5796. * @param string $prefix Prefix for fields name
  5797. * @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
  5798. * @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
  5799. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5800. * @param string $form_name Not used
  5801. * @param int $d 1=Show days, month, years
  5802. * @param int $addnowlink Add a link "Now"
  5803. * @param int $nooutput Do not output html string but return it
  5804. * @param int $disabled Disable input fields
  5805. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5806. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5807. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5808. * @return string|void Nothing or string if nooutput is 1
  5809. * @deprecated
  5810. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5811. */
  5812. 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 = '')
  5813. {
  5814. // phpcs:enable
  5815. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5816. if (!empty($nooutput)) {
  5817. return $retstring;
  5818. }
  5819. print $retstring;
  5820. return;
  5821. }
  5822. /**
  5823. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5824. * Fields are preselected with :
  5825. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5826. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5827. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5828. *
  5829. * @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).
  5830. * @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).
  5831. * @param string $prefix Prefix for fields name
  5832. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5833. * @param string $forcenewline Force new line between the 2 dates.
  5834. * @return string Html for selectDate
  5835. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5836. */
  5837. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5838. {
  5839. global $langs;
  5840. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5841. if ($forcenewline) {
  5842. $ret .= '<br>';
  5843. }
  5844. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5845. return $ret;
  5846. }
  5847. /**
  5848. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5849. * Fields are preselected with :
  5850. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5851. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5852. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5853. *
  5854. * @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).
  5855. * @param string $prefix Prefix for fields name
  5856. * @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
  5857. * @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
  5858. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5859. * @param string $form_name Not used
  5860. * @param int $d 1=Show days, month, years
  5861. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5862. * @param int $disabled Disable input fields
  5863. * @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')
  5864. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5865. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5866. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5867. * @param int $stepminutes Specify step for minutes between 1 and 30
  5868. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5869. * @param string $placeholder Placeholder
  5870. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5871. * @return string Html for selectDate
  5872. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5873. */
  5874. 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')
  5875. {
  5876. global $conf, $langs;
  5877. if ($gm === 'auto') {
  5878. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5879. }
  5880. $retstring = '';
  5881. if ($prefix == '') {
  5882. $prefix = 're';
  5883. }
  5884. if ($h == '') {
  5885. $h = 0;
  5886. }
  5887. if ($m == '') {
  5888. $m = 0;
  5889. }
  5890. $emptydate = 0;
  5891. $emptyhours = 0;
  5892. if ($stepminutes <= 0 || $stepminutes > 30) {
  5893. $stepminutes = 1;
  5894. }
  5895. if ($empty == 1) {
  5896. $emptydate = 1;
  5897. $emptyhours = 1;
  5898. }
  5899. if ($empty == 2) {
  5900. $emptydate = 0;
  5901. $emptyhours = 1;
  5902. }
  5903. $orig_set_time = $set_time;
  5904. if ($set_time === '' && $emptydate == 0) {
  5905. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5906. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5907. $set_time = dol_now($gm);
  5908. } else {
  5909. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5910. }
  5911. }
  5912. // Analysis of the pre-selection date
  5913. $reg = array();
  5914. $shour = '';
  5915. $smin = '';
  5916. $ssec = '';
  5917. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5918. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5919. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5920. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5921. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5922. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5923. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5924. } elseif (strval($set_time) != '' && $set_time != -1) {
  5925. // set_time est un timestamps (0 possible)
  5926. $syear = dol_print_date($set_time, "%Y", $gm);
  5927. $smonth = dol_print_date($set_time, "%m", $gm);
  5928. $sday = dol_print_date($set_time, "%d", $gm);
  5929. if ($orig_set_time != '') {
  5930. $shour = dol_print_date($set_time, "%H", $gm);
  5931. $smin = dol_print_date($set_time, "%M", $gm);
  5932. $ssec = dol_print_date($set_time, "%S", $gm);
  5933. }
  5934. } else {
  5935. // Date est '' ou vaut -1
  5936. $syear = '';
  5937. $smonth = '';
  5938. $sday = '';
  5939. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5940. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5941. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5942. }
  5943. if ($h == 3) {
  5944. $shour = '';
  5945. }
  5946. if ($m == 3) {
  5947. $smin = '';
  5948. }
  5949. $nowgmt = dol_now('gmt');
  5950. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5951. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5952. $usecalendar = 'combo';
  5953. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5954. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5955. }
  5956. if ($d) {
  5957. // Show date with popup
  5958. if ($usecalendar != 'combo') {
  5959. $formated_date = '';
  5960. //print "e".$set_time." t ".$conf->format_date_short;
  5961. if (strval($set_time) != '' && $set_time != -1) {
  5962. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5963. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5964. }
  5965. // Calendrier popup version eldy
  5966. if ($usecalendar == "eldy") {
  5967. // Input area to enter date manually
  5968. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5969. $retstring .= ($disabled ? ' disabled' : '');
  5970. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5971. $retstring .= '>';
  5972. // Icon calendar
  5973. $retstringbuttom = '';
  5974. if (!$disabled) {
  5975. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5976. $base = DOL_URL_ROOT.'/core/';
  5977. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5978. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5979. } else {
  5980. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5981. }
  5982. $retstring = $retstringbuttom.$retstring;
  5983. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5984. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5985. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5986. } elseif ($usecalendar == 'jquery') {
  5987. if (!$disabled) {
  5988. // Output javascript for datepicker
  5989. $minYear = getDolGlobalInt('MIN_YEAR_SELECT_DATE', (date('Y') - 100));
  5990. $maxYear = getDolGlobalInt('MAX_YEAR_SELECT_DATE', (date('Y') + 100));
  5991. $retstring .= "<script type='text/javascript'>";
  5992. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5993. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5994. autoclose: true,
  5995. todayHighlight: true,
  5996. yearRange: '".$minYear.":".$maxYear."',";
  5997. if (!empty($conf->dol_use_jmobile)) {
  5998. $retstring .= "
  5999. beforeShow: function (input, datePicker) {
  6000. input.disabled = true;
  6001. },
  6002. onClose: function (dateText, datePicker) {
  6003. this.disabled = false;
  6004. },
  6005. ";
  6006. }
  6007. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  6008. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  6009. $retstring .= "
  6010. showOn: 'button', /* both has problem with autocompletion */
  6011. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  6012. buttonImageOnly: true";
  6013. }
  6014. $retstring .= "
  6015. }) });";
  6016. $retstring .= "</script>";
  6017. }
  6018. // Zone de saisie manuelle de la date
  6019. $retstring .= '<div class="nowraponall inline-block divfordateinput">';
  6020. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  6021. $retstring .= ($disabled ? ' disabled' : '');
  6022. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  6023. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  6024. $retstring .= '>';
  6025. // Icone calendrier
  6026. if (!$disabled) {
  6027. /* Not required. Managed by option buttonImage of jquery
  6028. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  6029. $retstring.="<script type='text/javascript'>";
  6030. $retstring.="jQuery(document).ready(function() {";
  6031. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  6032. $retstring.=" jQuery('#".$prefix."').focus();";
  6033. $retstring.=' });';
  6034. $retstring.='});';
  6035. $retstring.="</script>";*/
  6036. } else {
  6037. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  6038. $retsring = $retstringbutton.$retstring;
  6039. }
  6040. $retstring .= '</div>';
  6041. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  6042. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  6043. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  6044. } else {
  6045. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  6046. }
  6047. } else {
  6048. // Show date with combo selects
  6049. // Day
  6050. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  6051. if ($emptydate || $set_time == -1) {
  6052. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6053. }
  6054. for ($day = 1; $day <= 31; $day++) {
  6055. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  6056. }
  6057. $retstring .= "</select>";
  6058. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  6059. if ($emptydate || $set_time == -1) {
  6060. $retstring .= '<option value="0" selected>&nbsp;</option>';
  6061. }
  6062. // Month
  6063. for ($month = 1; $month <= 12; $month++) {
  6064. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  6065. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  6066. $retstring .= "</option>";
  6067. }
  6068. $retstring .= "</select>";
  6069. // Year
  6070. if ($emptydate || $set_time == -1) {
  6071. $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.'">';
  6072. } else {
  6073. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  6074. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  6075. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  6076. }
  6077. $retstring .= "</select>\n";
  6078. }
  6079. }
  6080. }
  6081. if ($d && $h) {
  6082. $retstring .= ($h == 2 ? '<br>' : ' ');
  6083. $retstring .= '<span class="nowraponall">';
  6084. }
  6085. if ($h) {
  6086. $hourstart = 0;
  6087. $hourend = 24;
  6088. if ($openinghours != '') {
  6089. $openinghours = explode(',', $openinghours);
  6090. $hourstart = $openinghours[0];
  6091. $hourend = $openinghours[1];
  6092. if ($hourend < $hourstart) {
  6093. $hourend = $hourstart;
  6094. }
  6095. }
  6096. // Show hour
  6097. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  6098. if ($emptyhours) {
  6099. $retstring .= '<option value="-1">&nbsp;</option>';
  6100. }
  6101. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  6102. if (strlen($hour) < 2) {
  6103. $hour = "0".$hour;
  6104. }
  6105. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  6106. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  6107. $retstring .= '</option>';
  6108. }
  6109. $retstring .= '</select>';
  6110. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  6111. if ($m) {
  6112. $retstring .= ":";
  6113. }
  6114. }
  6115. if ($m) {
  6116. // Show minutes
  6117. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  6118. if ($emptyhours) {
  6119. $retstring .= '<option value="-1">&nbsp;</option>';
  6120. }
  6121. for ($min = 0; $min < 60; $min += $stepminutes) {
  6122. if (strlen($min) < 2) {
  6123. $min = "0".$min;
  6124. }
  6125. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  6126. }
  6127. $retstring .= '</select>';
  6128. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  6129. }
  6130. if ($d && $h) {
  6131. $retstring .= '</span>';
  6132. }
  6133. // Add a "Now" link
  6134. if (!empty($conf->use_javascript_ajax) && $addnowlink) {
  6135. // Script which will be inserted in the onClick of the "Now" link
  6136. $reset_scripts = "";
  6137. if ($addnowlink == 2) { // local computer time
  6138. // pad add leading 0 on numbers
  6139. $reset_scripts .= "Number.prototype.pad = function(size) {
  6140. var s = String(this);
  6141. while (s.length < (size || 2)) {s = '0' + s;}
  6142. return s;
  6143. };
  6144. var d = new Date();";
  6145. }
  6146. // Generate the date part, depending on the use or not of the javascript calendar
  6147. if ($addnowlink == 1) { // server time expressed in user time setup
  6148. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  6149. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6150. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6151. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6152. } elseif ($addnowlink == 2) {
  6153. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6154. * This break application for foreign languages.
  6155. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6156. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6157. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6158. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6159. */
  6160. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  6161. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6162. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6163. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6164. }
  6165. /*if ($usecalendar == "eldy")
  6166. {
  6167. $base=DOL_URL_ROOT.'/core/';
  6168. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6169. }
  6170. else
  6171. {
  6172. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6173. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6174. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6175. }*/
  6176. // Update the hour part
  6177. if ($h) {
  6178. if ($fullday) {
  6179. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6180. }
  6181. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6182. if ($addnowlink == 1) {
  6183. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6184. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  6185. } elseif ($addnowlink == 2) {
  6186. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  6187. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  6188. }
  6189. if ($fullday) {
  6190. $reset_scripts .= ' } ';
  6191. }
  6192. }
  6193. // Update the minute part
  6194. if ($m) {
  6195. if ($fullday) {
  6196. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6197. }
  6198. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6199. if ($addnowlink == 1) {
  6200. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6201. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6202. } elseif ($addnowlink == 2) {
  6203. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  6204. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6205. }
  6206. if ($fullday) {
  6207. $reset_scripts .= ' } ';
  6208. }
  6209. }
  6210. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6211. if ($reset_scripts && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  6212. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  6213. $retstring .= $langs->trans("Now");
  6214. $retstring .= '</button> ';
  6215. }
  6216. }
  6217. // Add a "Plus one hour" link
  6218. if ($conf->use_javascript_ajax && $addplusone) {
  6219. // Script which will be inserted in the onClick of the "Add plusone" link
  6220. $reset_scripts = "";
  6221. // Generate the date part, depending on the use or not of the javascript calendar
  6222. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  6223. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6224. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6225. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6226. // Update the hour part
  6227. if ($h) {
  6228. if ($fullday) {
  6229. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6230. }
  6231. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6232. if ($fullday) {
  6233. $reset_scripts .= ' } ';
  6234. }
  6235. }
  6236. // Update the minute part
  6237. if ($m) {
  6238. if ($fullday) {
  6239. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6240. }
  6241. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6242. if ($fullday) {
  6243. $reset_scripts .= ' } ';
  6244. }
  6245. }
  6246. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6247. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6248. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  6249. $retstring .= $langs->trans("DateStartPlusOne");
  6250. $retstring .= '</button> ';
  6251. }
  6252. }
  6253. // Add a link to set data
  6254. if ($conf->use_javascript_ajax && $adddateof) {
  6255. $tmparray = dol_getdate($adddateof);
  6256. if (empty($labeladddateof)) {
  6257. $labeladddateof = $langs->trans("DateInvoice");
  6258. }
  6259. $reset_scripts = 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');';
  6260. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.$tmparray['mday'].'\');';
  6261. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.$tmparray['mon'].'\');';
  6262. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.$tmparray['year'].'\');';
  6263. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="'.$reset_scripts.'">'.$labeladddateof.'</a>';
  6264. }
  6265. return $retstring;
  6266. }
  6267. /**
  6268. * selectTypeDuration
  6269. *
  6270. * @param string $prefix Prefix
  6271. * @param string $selected Selected duration type
  6272. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6273. * @return string HTML select string
  6274. */
  6275. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6276. {
  6277. global $langs;
  6278. $TDurationTypes = array(
  6279. 'y'=>$langs->trans('Years'),
  6280. 'm'=>$langs->trans('Month'),
  6281. 'w'=>$langs->trans('Weeks'),
  6282. 'd'=>$langs->trans('Days'),
  6283. 'h'=>$langs->trans('Hours'),
  6284. 'i'=>$langs->trans('Minutes')
  6285. );
  6286. // Removed undesired duration types
  6287. foreach ($excludetypes as $value) {
  6288. unset($TDurationTypes[$value]);
  6289. }
  6290. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  6291. foreach ($TDurationTypes as $key => $typeduration) {
  6292. $retstring .= '<option value="'.$key.'"';
  6293. if ($key == $selected) {
  6294. $retstring .= " selected";
  6295. }
  6296. $retstring .= ">".$typeduration."</option>";
  6297. }
  6298. $retstring .= "</select>";
  6299. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  6300. return $retstring;
  6301. }
  6302. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6303. /**
  6304. * Function to show a form to select a duration on a page
  6305. *
  6306. * @param string $prefix Prefix for input fields
  6307. * @param int $iSecond Default preselected duration (number of seconds or '')
  6308. * @param int $disabled Disable the combo box
  6309. * @param string $typehour If 'select' then input hour and input min is a combo,
  6310. * If 'text' input hour is in text and input min is a text,
  6311. * If 'textselect' input hour is in text and input min is a combo
  6312. * @param integer $minunderhours If 1, show minutes selection under the hours
  6313. * @param int $nooutput Do not output html string but return it
  6314. * @return string|void
  6315. */
  6316. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6317. {
  6318. // phpcs:enable
  6319. global $langs;
  6320. $retstring = '<span class="nowraponall">';
  6321. $hourSelected = 0;
  6322. $minSelected = 0;
  6323. // Hours
  6324. if ($iSecond != '') {
  6325. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6326. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6327. $minSelected = convertSecondToTime($iSecond, 'min');
  6328. }
  6329. if ($typehour == 'select') {
  6330. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  6331. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6332. $retstring .= '<option value="'.$hour.'"';
  6333. if ($hourSelected == $hour) {
  6334. $retstring .= " selected";
  6335. }
  6336. $retstring .= ">".$hour."</option>";
  6337. }
  6338. $retstring .= "</select>";
  6339. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6340. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  6341. } else {
  6342. return 'BadValueForParameterTypeHour';
  6343. }
  6344. if ($typehour != 'text') {
  6345. $retstring .= ' '.$langs->trans('HourShort');
  6346. } else {
  6347. $retstring .= '<span class="">:</span>';
  6348. }
  6349. // Minutes
  6350. if ($minunderhours) {
  6351. $retstring .= '<br>';
  6352. } else {
  6353. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6354. }
  6355. if ($typehour == 'select' || $typehour == 'textselect') {
  6356. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  6357. for ($min = 0; $min <= 55; $min = $min + 5) {
  6358. $retstring .= '<option value="'.$min.'"';
  6359. if ($minSelected == $min) {
  6360. $retstring .= ' selected';
  6361. }
  6362. $retstring .= '>'.$min.'</option>';
  6363. }
  6364. $retstring .= "</select>";
  6365. } elseif ($typehour == 'text') {
  6366. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6367. }
  6368. if ($typehour != 'text') {
  6369. $retstring .= ' '.$langs->trans('MinuteShort');
  6370. }
  6371. $retstring.="</span>";
  6372. if (!empty($nooutput)) {
  6373. return $retstring;
  6374. }
  6375. print $retstring;
  6376. return;
  6377. }
  6378. /**
  6379. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6380. *
  6381. * @param int $selected Preselected tickets
  6382. * @param string $htmlname Name of HTML select field (must be unique in page).
  6383. * @param string $filtertype To add a filter
  6384. * @param int $limit Limit on number of returned lines
  6385. * @param int $status Ticket status
  6386. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6387. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6388. * @param array $ajaxoptions Options for ajax_autocompleter
  6389. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6390. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6391. * @param int $forcecombo Force to use combo box
  6392. * @param string $morecss Add more css on select
  6393. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6394. * @param string $nooutput No print, return the output into a string
  6395. * @return void|string
  6396. */
  6397. 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)
  6398. {
  6399. global $langs, $conf;
  6400. $out = '';
  6401. // check parameters
  6402. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6403. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6404. $placeholder = '';
  6405. if ($selected && empty($selected_input_value)) {
  6406. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6407. $tickettmpselect = new Ticket($this->db);
  6408. $tickettmpselect->fetch($selected);
  6409. $selected_input_value = $tickettmpselect->ref;
  6410. unset($tickettmpselect);
  6411. }
  6412. $urloption = '';
  6413. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6414. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6415. elseif ($hidelabel > 1) {
  6416. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6417. if ($hidelabel == 2) {
  6418. $out .= img_picto($langs->trans("Search"), 'search');
  6419. }
  6420. }
  6421. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6422. if ($hidelabel == 3) {
  6423. $out .= img_picto($langs->trans("Search"), 'search');
  6424. }
  6425. } else {
  6426. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6427. }
  6428. if (empty($nooutput)) print $out;
  6429. else return $out;
  6430. }
  6431. /**
  6432. * Return list of tickets.
  6433. * Called by selectTickets.
  6434. *
  6435. * @param int $selected Preselected ticket
  6436. * @param string $htmlname Name of select html
  6437. * @param string $filtertype Filter on ticket type
  6438. * @param int $limit Limit on number of returned lines
  6439. * @param string $filterkey Filter on ticket ref or subject
  6440. * @param int $status Ticket status
  6441. * @param int $outputmode 0=HTML select string, 1=Array
  6442. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6443. * @param int $forcecombo Force to use combo box
  6444. * @param string $morecss Add more css on select
  6445. * @return array Array of keys for json
  6446. */
  6447. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6448. {
  6449. global $langs, $conf;
  6450. $out = '';
  6451. $outarray = array();
  6452. $selectFields = " p.rowid, p.ref, p.message";
  6453. $sql = "SELECT ";
  6454. $sql .= $selectFields;
  6455. $sql .= " FROM ".$this->db->prefix()."ticket as p";
  6456. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6457. // Add criteria on ref/label
  6458. if ($filterkey != '') {
  6459. $sql .= ' AND (';
  6460. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6461. // For natural search
  6462. $scrit = explode(' ', $filterkey);
  6463. $i = 0;
  6464. if (count($scrit) > 1) $sql .= "(";
  6465. foreach ($scrit as $crit) {
  6466. if ($i > 0) $sql .= " AND ";
  6467. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6468. $sql .= ")";
  6469. $i++;
  6470. }
  6471. if (count($scrit) > 1) $sql .= ")";
  6472. $sql .= ')';
  6473. }
  6474. $sql .= $this->db->plimit($limit, 0);
  6475. // Build output string
  6476. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6477. $result = $this->db->query($sql);
  6478. if ($result) {
  6479. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6480. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6481. $num = $this->db->num_rows($result);
  6482. $events = null;
  6483. if (!$forcecombo) {
  6484. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6485. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6486. }
  6487. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6488. $textifempty = '';
  6489. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6490. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6491. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6492. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6493. else $textifempty .= $langs->trans("All");
  6494. } else {
  6495. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6496. }
  6497. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6498. $i = 0;
  6499. while ($num && $i < $num) {
  6500. $opt = '';
  6501. $optJson = array();
  6502. $objp = $this->db->fetch_object($result);
  6503. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6504. // Add new entry
  6505. // "key" value of json key array is used by jQuery automatically as selected value
  6506. // "label" value of json key array is used by jQuery automatically as text for combo box
  6507. $out .= $opt;
  6508. array_push($outarray, $optJson);
  6509. $i++;
  6510. }
  6511. $out .= '</select>';
  6512. $this->db->free($result);
  6513. if (empty($outputmode)) return $out;
  6514. return $outarray;
  6515. } else {
  6516. dol_print_error($this->db);
  6517. }
  6518. }
  6519. /**
  6520. * constructTicketListOption.
  6521. * This define value for &$opt and &$optJson.
  6522. *
  6523. * @param object $objp Result set of fetch
  6524. * @param string $opt Option (var used for returned value in string option format)
  6525. * @param string $optJson Option (var used for returned value in json format)
  6526. * @param string $selected Preselected value
  6527. * @param string $filterkey Filter key to highlight
  6528. * @return void
  6529. */
  6530. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6531. {
  6532. $outkey = '';
  6533. $outref = '';
  6534. $outtype = '';
  6535. $outkey = $objp->rowid;
  6536. $outref = $objp->ref;
  6537. $outtype = $objp->fk_product_type;
  6538. $opt = '<option value="'.$objp->rowid.'"';
  6539. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6540. $opt .= '>';
  6541. $opt .= $objp->ref;
  6542. $objRef = $objp->ref;
  6543. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6544. $opt .= "</option>\n";
  6545. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6546. }
  6547. /**
  6548. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6549. *
  6550. * @param int $selected Preselected tickets
  6551. * @param string $htmlname Name of HTML select field (must be unique in page).
  6552. * @param string $filtertype To add a filter
  6553. * @param int $limit Limit on number of returned lines
  6554. * @param int $status Ticket status
  6555. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6556. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6557. * @param array $ajaxoptions Options for ajax_autocompleter
  6558. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6559. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6560. * @param int $forcecombo Force to use combo box
  6561. * @param string $morecss Add more css on select
  6562. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6563. * @param string $nooutput No print, return the output into a string
  6564. * @return void|string
  6565. */
  6566. 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)
  6567. {
  6568. global $langs, $conf;
  6569. $out = '';
  6570. // check parameters
  6571. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6572. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6573. $placeholder = '';
  6574. if ($selected && empty($selected_input_value)) {
  6575. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6576. $projecttmpselect = new Project($this->db);
  6577. $projecttmpselect->fetch($selected);
  6578. $selected_input_value = $projecttmpselect->ref;
  6579. unset($projecttmpselect);
  6580. }
  6581. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6582. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6583. elseif ($hidelabel > 1) {
  6584. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6585. if ($hidelabel == 2) {
  6586. $out .= img_picto($langs->trans("Search"), 'search');
  6587. }
  6588. }
  6589. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6590. if ($hidelabel == 3) {
  6591. $out .= img_picto($langs->trans("Search"), 'search');
  6592. }
  6593. } else {
  6594. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6595. }
  6596. if (empty($nooutput)) print $out;
  6597. else return $out;
  6598. }
  6599. /**
  6600. * Return list of projects.
  6601. * Called by selectProjects.
  6602. *
  6603. * @param int $selected Preselected project
  6604. * @param string $htmlname Name of select html
  6605. * @param string $filtertype Filter on project type
  6606. * @param int $limit Limit on number of returned lines
  6607. * @param string $filterkey Filter on project ref or subject
  6608. * @param int $status Ticket status
  6609. * @param int $outputmode 0=HTML select string, 1=Array
  6610. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6611. * @param int $forcecombo Force to use combo box
  6612. * @param string $morecss Add more css on select
  6613. * @return array Array of keys for json
  6614. */
  6615. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6616. {
  6617. global $langs, $conf;
  6618. $out = '';
  6619. $outarray = array();
  6620. $selectFields = " p.rowid, p.ref";
  6621. $sql = "SELECT ";
  6622. $sql .= $selectFields;
  6623. $sql .= " FROM ".$this->db->prefix()."projet as p";
  6624. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6625. // Add criteria on ref/label
  6626. if ($filterkey != '') {
  6627. $sql .= ' AND (';
  6628. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6629. // For natural search
  6630. $scrit = explode(' ', $filterkey);
  6631. $i = 0;
  6632. if (count($scrit) > 1) $sql .= "(";
  6633. foreach ($scrit as $crit) {
  6634. if ($i > 0) $sql .= " AND ";
  6635. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6636. $sql .= "";
  6637. $i++;
  6638. }
  6639. if (count($scrit) > 1) $sql .= ")";
  6640. $sql .= ')';
  6641. }
  6642. $sql .= $this->db->plimit($limit, 0);
  6643. // Build output string
  6644. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6645. $result = $this->db->query($sql);
  6646. if ($result) {
  6647. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6648. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6649. $num = $this->db->num_rows($result);
  6650. $events = null;
  6651. if (!$forcecombo) {
  6652. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6653. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6654. }
  6655. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6656. $textifempty = '';
  6657. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6658. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6659. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6660. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6661. else $textifempty .= $langs->trans("All");
  6662. } else {
  6663. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6664. }
  6665. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6666. $i = 0;
  6667. while ($num && $i < $num) {
  6668. $opt = '';
  6669. $optJson = array();
  6670. $objp = $this->db->fetch_object($result);
  6671. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6672. // Add new entry
  6673. // "key" value of json key array is used by jQuery automatically as selected value
  6674. // "label" value of json key array is used by jQuery automatically as text for combo box
  6675. $out .= $opt;
  6676. array_push($outarray, $optJson);
  6677. $i++;
  6678. }
  6679. $out .= '</select>';
  6680. $this->db->free($result);
  6681. if (empty($outputmode)) return $out;
  6682. return $outarray;
  6683. } else {
  6684. dol_print_error($this->db);
  6685. }
  6686. }
  6687. /**
  6688. * constructProjectListOption.
  6689. * This define value for &$opt and &$optJson.
  6690. *
  6691. * @param object $objp Result set of fetch
  6692. * @param string $opt Option (var used for returned value in string option format)
  6693. * @param string $optJson Option (var used for returned value in json format)
  6694. * @param string $selected Preselected value
  6695. * @param string $filterkey Filter key to highlight
  6696. * @return void
  6697. */
  6698. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6699. {
  6700. $outkey = '';
  6701. $outval = '';
  6702. $outref = '';
  6703. $outlabel = '';
  6704. $outtype = '';
  6705. $label = $objp->label;
  6706. $outkey = $objp->rowid;
  6707. $outref = $objp->ref;
  6708. $outlabel = $objp->label;
  6709. $outtype = $objp->fk_product_type;
  6710. $opt = '<option value="'.$objp->rowid.'"';
  6711. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6712. $opt .= '>';
  6713. $opt .= $objp->ref;
  6714. $objRef = $objp->ref;
  6715. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6716. $outval .= $objRef;
  6717. $opt .= "</option>\n";
  6718. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6719. }
  6720. /**
  6721. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6722. *
  6723. * @param int $selected Preselected tickets
  6724. * @param string $htmlname Name of HTML select field (must be unique in page).
  6725. * @param string $filtertype To add a filter
  6726. * @param int $limit Limit on number of returned lines
  6727. * @param int $status Ticket status
  6728. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6729. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6730. * @param array $ajaxoptions Options for ajax_autocompleter
  6731. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6732. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6733. * @param int $forcecombo Force to use combo box
  6734. * @param string $morecss Add more css on select
  6735. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6736. * @param string $nooutput No print, return the output into a string
  6737. * @return void|string
  6738. */
  6739. 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)
  6740. {
  6741. global $langs, $conf;
  6742. $out = '';
  6743. // check parameters
  6744. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6745. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6746. $placeholder = '';
  6747. $urloption = '';
  6748. if ($selected && empty($selected_input_value)) {
  6749. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6750. $adherenttmpselect = new Adherent($this->db);
  6751. $adherenttmpselect->fetch($selected);
  6752. $selected_input_value = $adherenttmpselect->ref;
  6753. unset($adherenttmpselect);
  6754. }
  6755. $urloption = '';
  6756. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6757. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6758. elseif ($hidelabel > 1) {
  6759. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6760. if ($hidelabel == 2) {
  6761. $out .= img_picto($langs->trans("Search"), 'search');
  6762. }
  6763. }
  6764. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6765. if ($hidelabel == 3) {
  6766. $out .= img_picto($langs->trans("Search"), 'search');
  6767. }
  6768. } else {
  6769. $filterkey = '';
  6770. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6771. }
  6772. if (empty($nooutput)) print $out;
  6773. else return $out;
  6774. }
  6775. /**
  6776. * Return list of adherents.
  6777. * Called by selectMembers.
  6778. *
  6779. * @param int $selected Preselected adherent
  6780. * @param string $htmlname Name of select html
  6781. * @param string $filtertype Filter on adherent type
  6782. * @param int $limit Limit on number of returned lines
  6783. * @param string $filterkey Filter on member status
  6784. * @param int $status Member status
  6785. * @param int $outputmode 0=HTML select string, 1=Array
  6786. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6787. * @param int $forcecombo Force to use combo box
  6788. * @param string $morecss Add more css on select
  6789. * @return array Array of keys for json
  6790. */
  6791. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6792. {
  6793. global $langs, $conf;
  6794. $out = '';
  6795. $outarray = array();
  6796. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6797. $sql = "SELECT ";
  6798. $sql .= $selectFields;
  6799. $sql .= " FROM ".$this->db->prefix()."adherent as p";
  6800. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6801. // Add criteria on ref/label
  6802. if ($filterkey != '') {
  6803. $sql .= ' AND (';
  6804. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6805. // For natural search
  6806. $scrit = explode(' ', $filterkey);
  6807. $i = 0;
  6808. if (count($scrit) > 1) $sql .= "(";
  6809. foreach ($scrit as $crit) {
  6810. if ($i > 0) $sql .= " AND ";
  6811. $sql .= "(p.firstname LIKE '".$this->db->escape($prefix.$crit)."%'";
  6812. $sql .= " OR p.lastname LIKE '".$this->db->escape($prefix.$crit)."%')";
  6813. $i++;
  6814. }
  6815. if (count($scrit) > 1) $sql .= ")";
  6816. $sql .= ')';
  6817. }
  6818. if ($status != -1) {
  6819. $sql .= ' AND statut = '.((int) $status);
  6820. }
  6821. $sql .= $this->db->plimit($limit, 0);
  6822. // Build output string
  6823. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6824. $result = $this->db->query($sql);
  6825. if ($result) {
  6826. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6827. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6828. $num = $this->db->num_rows($result);
  6829. $events = null;
  6830. if (!$forcecombo) {
  6831. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6832. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6833. }
  6834. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6835. $textifempty = '';
  6836. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6837. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6838. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6839. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6840. else $textifempty .= $langs->trans("All");
  6841. } else {
  6842. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6843. }
  6844. if ($showempty) {
  6845. $out .= '<option value="-1" selected>'.$textifempty.'</option>';
  6846. }
  6847. $i = 0;
  6848. while ($num && $i < $num) {
  6849. $opt = '';
  6850. $optJson = array();
  6851. $objp = $this->db->fetch_object($result);
  6852. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6853. // Add new entry
  6854. // "key" value of json key array is used by jQuery automatically as selected value
  6855. // "label" value of json key array is used by jQuery automatically as text for combo box
  6856. $out .= $opt;
  6857. array_push($outarray, $optJson);
  6858. $i++;
  6859. }
  6860. $out .= '</select>';
  6861. $this->db->free($result);
  6862. if (empty($outputmode)) return $out;
  6863. return $outarray;
  6864. } else {
  6865. dol_print_error($this->db);
  6866. }
  6867. }
  6868. /**
  6869. * constructMemberListOption.
  6870. * This define value for &$opt and &$optJson.
  6871. *
  6872. * @param object $objp Result set of fetch
  6873. * @param string $opt Option (var used for returned value in string option format)
  6874. * @param string $optJson Option (var used for returned value in json format)
  6875. * @param string $selected Preselected value
  6876. * @param string $filterkey Filter key to highlight
  6877. * @return void
  6878. */
  6879. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6880. {
  6881. $outkey = '';
  6882. $outlabel = '';
  6883. $outtype = '';
  6884. $outkey = $objp->rowid;
  6885. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6886. $outtype = $objp->fk_adherent_type;
  6887. $opt = '<option value="'.$objp->rowid.'"';
  6888. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6889. $opt .= '>';
  6890. if (!empty($filterkey) && $filterkey != '') {
  6891. $outlabel = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $outlabel, 1);
  6892. }
  6893. $opt .= $outlabel;
  6894. $opt .= "</option>\n";
  6895. $optJson = array('key'=>$outkey, 'value'=>$outlabel, 'type'=>$outtype);
  6896. }
  6897. /**
  6898. * Generic method to select a component from a combo list.
  6899. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6900. * This is the generic method that will replace all specific existing methods.
  6901. *
  6902. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6903. * @param string $htmlname Name of HTML select component
  6904. * @param int $preselectedvalue Preselected value (ID of element)
  6905. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6906. * @param string $searchkey Search criteria
  6907. * @param string $placeholder Place holder
  6908. * @param string $morecss More CSS
  6909. * @param string $moreparams More params provided to ajax call
  6910. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6911. * @param int $disabled 1=Html component is disabled
  6912. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6913. * @return string Return HTML string
  6914. * @see selectForFormsList() select_thirdparty_list()
  6915. */
  6916. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6917. {
  6918. global $conf, $user;
  6919. $objecttmp = null;
  6920. // Example of value for $objectdec:
  6921. // Bom:bom/class/bom.class.php:0:t.status=1
  6922. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6923. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6924. $InfoFieldList = explode(":", $objectdesc, 4);
  6925. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  6926. $reg = array();
  6927. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6928. $InfoFieldList[4] = $reg[1]; // take the sort field
  6929. }
  6930. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6931. $classname = $InfoFieldList[0];
  6932. $classpath = $InfoFieldList[1];
  6933. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6934. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6935. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6936. if (!empty($classpath)) {
  6937. dol_include_once($classpath);
  6938. if ($classname && class_exists($classname)) {
  6939. $objecttmp = new $classname($this->db);
  6940. // Make some replacement
  6941. $sharedentities = getEntity(strtolower($classname));
  6942. $filter = str_replace(
  6943. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6944. array($conf->entity, $sharedentities, $user->id),
  6945. $filter
  6946. );
  6947. }
  6948. }
  6949. if (!is_object($objecttmp)) {
  6950. dol_syslog('Error bad setup of type for field '.join(',', $InfoFieldList), LOG_WARNING);
  6951. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6952. }
  6953. //var_dump($filter);
  6954. $prefixforautocompletemode = $objecttmp->element;
  6955. if ($prefixforautocompletemode == 'societe') {
  6956. $prefixforautocompletemode = 'company';
  6957. }
  6958. if ($prefixforautocompletemode == 'product') {
  6959. $prefixforautocompletemode = 'produit';
  6960. }
  6961. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6962. dol_syslog(get_class($this)."::selectForForms filter=".$filter, LOG_DEBUG);
  6963. $out = '';
  6964. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6965. // No immediate load of all database
  6966. $placeholder = '';
  6967. if ($preselectedvalue && empty($selected_input_value)) {
  6968. $objecttmp->fetch($preselectedvalue);
  6969. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6970. //unset($objecttmp);
  6971. }
  6972. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6973. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6974. // No immediate load of all database
  6975. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6976. // Activate the auto complete using ajax call.
  6977. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6978. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6979. $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).'"' : '') .' />';
  6980. } else {
  6981. // Immediate load of table record.
  6982. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield, $filter);
  6983. }
  6984. return $out;
  6985. }
  6986. /**
  6987. * Output html form to select an object.
  6988. * Note, this function is called by selectForForms or by ajax selectobject.php
  6989. *
  6990. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6991. * @param string $htmlname Name of HTML select component
  6992. * @param int $preselectedvalue Preselected value (ID of element)
  6993. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6994. * @param string $searchkey Search value
  6995. * @param string $placeholder Place holder
  6996. * @param string $morecss More CSS
  6997. * @param string $moreparams More params provided to ajax call
  6998. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6999. * @param int $outputmode 0=HTML select string, 1=Array
  7000. * @param int $disabled 1=Html component is disabled
  7001. * @param string $sortfield Sort field
  7002. * @param string $filter Add more filter
  7003. * @return string|array Return HTML string
  7004. * @see selectForForms()
  7005. */
  7006. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '', $filter = '')
  7007. {
  7008. global $conf, $langs, $user, $hookmanager;
  7009. //print "$htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, $outputmode, $disabled";
  7010. $prefixforautocompletemode = $objecttmp->element;
  7011. if ($prefixforautocompletemode == 'societe') {
  7012. $prefixforautocompletemode = 'company';
  7013. }
  7014. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  7015. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  7016. $tmpfieldstoshow = '';
  7017. foreach ($objecttmp->fields as $key => $val) {
  7018. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  7019. continue;
  7020. }
  7021. if (!empty($val['showoncombobox'])) {
  7022. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  7023. }
  7024. }
  7025. if ($tmpfieldstoshow) {
  7026. $fieldstoshow = $tmpfieldstoshow;
  7027. }
  7028. } else {
  7029. // For backward compatibility
  7030. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  7031. }
  7032. if (empty($fieldstoshow)) {
  7033. if (isset($objecttmp->fields['ref'])) {
  7034. $fieldstoshow = 't.ref';
  7035. } else {
  7036. $langs->load("errors");
  7037. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  7038. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  7039. }
  7040. }
  7041. $out = '';
  7042. $outarray = array();
  7043. $tmparray = array();
  7044. $num = 0;
  7045. // Search data
  7046. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".$this->db->prefix().$objecttmp->table_element." as t";
  7047. if (isset($objecttmp->ismultientitymanaged)) {
  7048. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7049. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  7050. $sql .= " INNER JOIN ".$this->db->prefix().$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  7051. }
  7052. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7053. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7054. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  7055. }
  7056. }
  7057. }
  7058. // Add where from hooks
  7059. $parameters = array(
  7060. 'object' => $objecttmp,
  7061. 'htmlname' => $htmlname,
  7062. 'filter' => $filter,
  7063. 'searchkey' => $searchkey
  7064. );
  7065. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  7066. if (!empty($hookmanager->resPrint)) {
  7067. $sql .= $hookmanager->resPrint;
  7068. } else {
  7069. $sql .= " WHERE 1=1";
  7070. if (isset($objecttmp->ismultientitymanaged)) {
  7071. if ($objecttmp->ismultientitymanaged == 1) {
  7072. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  7073. }
  7074. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  7075. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  7076. }
  7077. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  7078. if ($objecttmp->element == 'societe') {
  7079. $sql .= " AND t.rowid = ".((int) $user->socid);
  7080. } else {
  7081. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  7082. }
  7083. }
  7084. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  7085. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  7086. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  7087. }
  7088. }
  7089. }
  7090. if ($searchkey != '') {
  7091. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  7092. }
  7093. if ($filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  7094. $errormessage = '';
  7095. $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
  7096. if ($errormessage) {
  7097. return 'Error forging a SQL request from an universal criteria: '.$errormessage;
  7098. }
  7099. }
  7100. }
  7101. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7102. //$sql.=$this->db->plimit($limit, 0);
  7103. //print $sql;
  7104. // Build output string
  7105. $resql = $this->db->query($sql);
  7106. if ($resql) {
  7107. // Construct $out and $outarray
  7108. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  7109. // 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
  7110. $textifempty = '&nbsp;';
  7111. //if (!empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7112. if (!empty($conf->global->$confkeyforautocompletemode)) {
  7113. if ($showempty && !is_numeric($showempty)) {
  7114. $textifempty = $langs->trans($showempty);
  7115. } else {
  7116. $textifempty .= $langs->trans("All");
  7117. }
  7118. }
  7119. if ($showempty) {
  7120. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  7121. }
  7122. $num = $this->db->num_rows($resql);
  7123. $i = 0;
  7124. if ($num) {
  7125. while ($i < $num) {
  7126. $obj = $this->db->fetch_object($resql);
  7127. $label = '';
  7128. $tmparray = explode(',', $fieldstoshow);
  7129. $oldvalueforshowoncombobox = 0;
  7130. foreach ($tmparray as $key => $val) {
  7131. $val = preg_replace('/t\./', '', $val);
  7132. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7133. $label .= $obj->$val;
  7134. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  7135. }
  7136. if (empty($outputmode)) {
  7137. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7138. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  7139. } else {
  7140. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  7141. }
  7142. } else {
  7143. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  7144. }
  7145. $i++;
  7146. if (($i % 10) == 0) {
  7147. $out .= "\n";
  7148. }
  7149. }
  7150. }
  7151. $out .= '</select>'."\n";
  7152. if (!$forcecombo) {
  7153. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7154. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  7155. }
  7156. } else {
  7157. dol_print_error($this->db);
  7158. }
  7159. $this->result = array('nbofelement'=>$num);
  7160. if ($outputmode) {
  7161. return $outarray;
  7162. }
  7163. return $out;
  7164. }
  7165. /**
  7166. * Return a HTML select string, built from an array of key+value.
  7167. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7168. *
  7169. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7170. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7171. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7172. * @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.
  7173. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7174. * @param int $value_as_key 1 to use value as key
  7175. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7176. * @param int $translate 1=Translate and encode value
  7177. * @param int $maxlen Length maximum for labels
  7178. * @param int $disabled Html select box is disabled
  7179. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7180. * @param string $morecss Add more class to css styles
  7181. * @param int $addjscombo Add js combo
  7182. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7183. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7184. * @param int $nohtmlescape No html escaping.
  7185. * @return string HTML select string.
  7186. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7187. */
  7188. 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)
  7189. {
  7190. global $conf, $langs;
  7191. // Do we want a multiselect ?
  7192. //$jsbeautify = 0;
  7193. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7194. $jsbeautify = 1;
  7195. if ($value_as_key) {
  7196. $array = array_combine($array, $array);
  7197. }
  7198. $out = '';
  7199. if ($addjscombo < 0) {
  7200. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7201. $addjscombo = 1;
  7202. } else {
  7203. $addjscombo = 0;
  7204. }
  7205. }
  7206. $idname = str_replace(array('[', ']'), array('', ''), $htmlname);
  7207. $out .= '<select id="'.preg_replace('/^\./', '', $idname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  7208. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  7209. $out .= '>';
  7210. if ($show_empty) {
  7211. $textforempty = ' ';
  7212. if (!empty($conf->use_javascript_ajax)) {
  7213. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7214. }
  7215. if (!is_numeric($show_empty)) {
  7216. $textforempty = $show_empty;
  7217. }
  7218. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  7219. }
  7220. if (is_array($array)) {
  7221. // Translate
  7222. if ($translate) {
  7223. foreach ($array as $key => $value) {
  7224. if (!is_array($value)) {
  7225. $array[$key] = $langs->trans($value);
  7226. } else {
  7227. $array[$key]['label'] = $langs->trans($value['label']);
  7228. }
  7229. }
  7230. }
  7231. // Sort
  7232. if ($sort == 'ASC') {
  7233. asort($array);
  7234. } elseif ($sort == 'DESC') {
  7235. arsort($array);
  7236. }
  7237. foreach ($array as $key => $tmpvalue) {
  7238. if (is_array($tmpvalue)) {
  7239. $value = $tmpvalue['label'];
  7240. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7241. $style = empty($tmpvalue['css']) ? '' : ' class="'.$tmpvalue['css'].'"';
  7242. } else {
  7243. $value = $tmpvalue;
  7244. $disabled = '';
  7245. $style = '';
  7246. }
  7247. if (!empty($disablebademail)) {
  7248. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7249. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7250. $disabled = ' disabled';
  7251. $style = ' class="warning"';
  7252. }
  7253. }
  7254. if ($key_in_label) {
  7255. if (empty($nohtmlescape)) {
  7256. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  7257. } else {
  7258. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  7259. }
  7260. } else {
  7261. if (empty($nohtmlescape)) {
  7262. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  7263. } else {
  7264. $selectOptionValue = $maxlen ? dol_trunc($value, $maxlen) : $value;
  7265. }
  7266. if ($value == '' || $value == '-') {
  7267. $selectOptionValue = '&nbsp;';
  7268. }
  7269. }
  7270. $out .= '<option value="'.$key.'"';
  7271. $out .= $style.$disabled;
  7272. if (is_array($id)) {
  7273. if (in_array($key, $id) && !$disabled) {
  7274. $out .= ' selected'; // To preselect a value
  7275. }
  7276. } else {
  7277. $id = (string) $id; // if $id = 0, then $id = '0'
  7278. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7279. $out .= ' selected'; // To preselect a value
  7280. }
  7281. }
  7282. if ($nohtmlescape) {
  7283. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  7284. }
  7285. if (is_array($tmpvalue)) {
  7286. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7287. if (preg_match('/^data-/', $keyforvalue)) {
  7288. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  7289. }
  7290. }
  7291. }
  7292. $out .= '>';
  7293. //var_dump($selectOptionValue);
  7294. $out .= $selectOptionValue;
  7295. $out .= "</option>\n";
  7296. }
  7297. }
  7298. $out .= "</select>";
  7299. // Add code for jquery to use multiselect
  7300. if ($addjscombo && $jsbeautify) {
  7301. // Enhance with select2
  7302. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7303. $out .= ajax_combobox($idname, array(), 0, 0, 'resolve', ($show_empty < 0 ? (string) $show_empty : '-1'), $morecss);
  7304. }
  7305. return $out;
  7306. }
  7307. /**
  7308. * 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.
  7309. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7310. *
  7311. * @param string $htmlname Name of html select area
  7312. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7313. * @param string $id Preselected key
  7314. * @param string $moreparam Add more parameters onto the select tag
  7315. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7316. * @param int $disabled Html select box is disabled
  7317. * @param int $minimumInputLength Minimum Input Length
  7318. * @param string $morecss Add more class to css styles
  7319. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7320. * @param string $placeholder String to use as placeholder
  7321. * @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)
  7322. * @return string HTML select string
  7323. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7324. */
  7325. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7326. {
  7327. global $conf, $langs;
  7328. global $delayedhtmlcontent; // Will be used later outside of this function
  7329. // TODO Use an internal dolibarr component instead of select2
  7330. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7331. return '';
  7332. }
  7333. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  7334. $outdelayed = '';
  7335. if (!empty($conf->use_javascript_ajax)) {
  7336. $tmpplugin = 'select2';
  7337. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7338. <script>
  7339. $(document).ready(function () {
  7340. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  7341. $(".'.$htmlname.'").select2({
  7342. ajax: {
  7343. dir: "ltr",
  7344. url: "'.$url.'",
  7345. dataType: \'json\',
  7346. delay: 250,
  7347. data: function (params) {
  7348. return {
  7349. q: params.term, // search term
  7350. page: params.page
  7351. };
  7352. },
  7353. processResults: function (data) {
  7354. // parse the results into the format expected by Select2.
  7355. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7356. //console.log(data);
  7357. saveRemoteData = data;
  7358. /* format json result for select2 */
  7359. result = []
  7360. $.each( data, function( key, value ) {
  7361. result.push({id: key, text: value.text});
  7362. });
  7363. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7364. //console.log(result);
  7365. return {results: result, more: false}
  7366. },
  7367. cache: true
  7368. },
  7369. language: select2arrayoflanguage,
  7370. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7371. placeholder: "'.dol_escape_js($placeholder).'",
  7372. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7373. minimumInputLength: '.$minimumInputLength.',
  7374. formatResult: function(result, container, query, escapeMarkup) {
  7375. return escapeMarkup(result.text);
  7376. },
  7377. });
  7378. '.($callurlonselect ? '
  7379. /* Code to execute a GET when we select a value */
  7380. $(".'.$htmlname.'").change(function() {
  7381. var selected = $(".'.$htmlname.'").val();
  7382. console.log("We select in selectArrayAjax the entry "+selected)
  7383. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7384. $.each( saveRemoteData, function( key, value ) {
  7385. if (key == selected)
  7386. {
  7387. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7388. location.assign(value.url);
  7389. }
  7390. });
  7391. });' : '').'
  7392. });
  7393. </script>';
  7394. }
  7395. if ($acceptdelayedhtml) {
  7396. $delayedhtmlcontent .= $outdelayed;
  7397. } else {
  7398. $out .= $outdelayed;
  7399. }
  7400. return $out;
  7401. }
  7402. /**
  7403. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7404. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7405. *
  7406. * @param string $htmlname Name of html select area
  7407. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7408. * @param string $id Preselected key
  7409. * @param string $moreparam Add more parameters onto the select tag
  7410. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7411. * @param int $disabled Html select box is disabled
  7412. * @param int $minimumInputLength Minimum Input Length
  7413. * @param string $morecss Add more class to css styles
  7414. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7415. * @param string $placeholder String to use as placeholder
  7416. * @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)
  7417. * @return string HTML select string
  7418. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7419. */
  7420. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7421. {
  7422. global $conf, $langs;
  7423. global $delayedhtmlcontent; // Will be used later outside of this function
  7424. // TODO Use an internal dolibarr component instead of select2
  7425. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7426. return '';
  7427. }
  7428. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7429. $formattedarrayresult = array();
  7430. foreach ($array as $key => $value) {
  7431. $o = new stdClass();
  7432. $o->id = $key;
  7433. $o->text = $value['text'];
  7434. $o->url = $value['url'];
  7435. $formattedarrayresult[] = $o;
  7436. }
  7437. $outdelayed = '';
  7438. if (!empty($conf->use_javascript_ajax)) {
  7439. $tmpplugin = 'select2';
  7440. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7441. <script>
  7442. $(document).ready(function () {
  7443. var data = '.json_encode($formattedarrayresult).';
  7444. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7445. $(".'.$htmlname.'").select2({
  7446. data: data,
  7447. language: select2arrayoflanguage,
  7448. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7449. placeholder: "'.dol_escape_js($placeholder).'",
  7450. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7451. minimumInputLength: '.$minimumInputLength.',
  7452. formatResult: function(result, container, query, escapeMarkup) {
  7453. return escapeMarkup(result.text);
  7454. },
  7455. matcher: function (params, data) {
  7456. if(! data.id) return null;';
  7457. if ($callurlonselect) {
  7458. // We forge the url with 'sall='
  7459. $outdelayed .= '
  7460. var urlBase = data.url;
  7461. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7462. /* console.log("params.term="+params.term); */
  7463. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7464. saveRemoteData[data.id].url = urlBase + separ + "search_all=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7465. }
  7466. if (!$disableFiltering) {
  7467. $outdelayed .= '
  7468. if(data.text.match(new RegExp(params.term))) {
  7469. return data;
  7470. }
  7471. return null;';
  7472. } else {
  7473. $outdelayed .= '
  7474. return data;';
  7475. }
  7476. $outdelayed .= '
  7477. }
  7478. });
  7479. '.($callurlonselect ? '
  7480. /* Code to execute a GET when we select a value */
  7481. $(".'.$htmlname.'").change(function() {
  7482. var selected = $(".'.$htmlname.'").val();
  7483. console.log("We select "+selected)
  7484. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7485. $.each( saveRemoteData, function( key, value ) {
  7486. if (key == selected)
  7487. {
  7488. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7489. location.assign(value.url);
  7490. }
  7491. });
  7492. });' : '').'
  7493. });
  7494. </script>';
  7495. }
  7496. if ($acceptdelayedhtml) {
  7497. $delayedhtmlcontent .= $outdelayed;
  7498. } else {
  7499. $out .= $outdelayed;
  7500. }
  7501. return $out;
  7502. }
  7503. /**
  7504. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7505. *
  7506. * @param string $htmlname Name of select
  7507. * @param array $array Array(key=>value) or Array(key=>array('id'=> , 'label'=> ))
  7508. * @param array $selected Array of keys preselected
  7509. * @param int $key_in_label 1 to show key like in "[key] value"
  7510. * @param int $value_as_key 1 to use value as key
  7511. * @param string $morecss Add more css style
  7512. * @param int $translate Translate and encode value
  7513. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7514. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7515. * @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.
  7516. * @param string $placeholder String to use as placeholder
  7517. * @param int $addjscombo Add js combo
  7518. * @return string HTML multiselect string
  7519. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7520. */
  7521. 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)
  7522. {
  7523. global $conf, $langs;
  7524. $out = '';
  7525. if ($addjscombo < 0) {
  7526. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7527. $addjscombo = 1;
  7528. } else {
  7529. $addjscombo = 0;
  7530. }
  7531. }
  7532. $useenhancedmultiselect = 0;
  7533. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7534. $useenhancedmultiselect = 1;
  7535. }
  7536. // Output select component
  7537. $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";
  7538. if (is_array($array) && !empty($array)) {
  7539. if ($value_as_key) {
  7540. $array = array_combine($array, $array);
  7541. }
  7542. if (!empty($array)) {
  7543. foreach ($array as $key => $value) {
  7544. $tmpkey = $key;
  7545. $tmpvalue = $value;
  7546. $tmpcolor = '';
  7547. $tmppicto = '';
  7548. if (is_array($value) && array_key_exists('id', $value) && array_key_exists('label', $value)) {
  7549. $tmpkey = $value['id'];
  7550. $tmpvalue = $value['label'];
  7551. $tmpcolor = $value['color'];
  7552. $tmppicto = $value['picto'];
  7553. }
  7554. $newval = ($translate ? $langs->trans($tmpvalue) : $tmpvalue);
  7555. $newval = ($key_in_label ? $tmpkey.' - '.$newval : $newval);
  7556. $out .= '<option value="'.$tmpkey.'"';
  7557. if (is_array($selected) && !empty($selected) && in_array((string) $tmpkey, $selected) && ((string) $tmpkey != '')) {
  7558. $out .= ' selected';
  7559. }
  7560. $out .= ' data-html="'.dol_escape_htmltag(($tmppicto ? img_picto('', $tmppicto, 'class="pictofixedwidth" style="color: #'.$tmpcolor.'"') : '').$newval).'"';
  7561. $out .= '>';
  7562. $out .= dol_htmlentitiesbr($newval);
  7563. $out .= '</option>'."\n";
  7564. }
  7565. }
  7566. }
  7567. $out .= '</select>'."\n";
  7568. // Add code for jquery to use multiselect
  7569. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7570. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7571. $out .= "\n".'<script>'."\n";
  7572. if ($addjscombo == 1) {
  7573. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7574. $out .= 'function formatResult(record, container) {'."\n";
  7575. $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";
  7576. $out .= ' return record.text;';
  7577. $out .= '};'."\n";
  7578. $out .= 'function formatSelection(record) {'."\n";
  7579. if ($elemtype == 'category') {
  7580. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7581. } else {
  7582. $out .= 'return record.text;';
  7583. }
  7584. $out .= '};'."\n";
  7585. $out .= '$(document).ready(function () {
  7586. $(\'#'.$htmlname.'\').'.$tmpplugin.'({';
  7587. if ($placeholder) {
  7588. $out .= '
  7589. placeholder: {
  7590. id: \'-1\',
  7591. text: \''.dol_escape_js($placeholder).'\'
  7592. },';
  7593. }
  7594. $out .= ' dir: \'ltr\',
  7595. // Specify format function for dropdown item
  7596. formatResult: formatResult,
  7597. templateResult: formatResult, /* For 4.0 */
  7598. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7599. // Specify format function for selected item
  7600. formatSelection: formatSelection,
  7601. templateSelection: formatSelection /* For 4.0 */
  7602. });
  7603. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7604. the size only if component is not hidden by default on load */
  7605. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7606. });'."\n";
  7607. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7608. // Add other js lib
  7609. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7610. // ...
  7611. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7612. $out .= '$(document).ready(function () {
  7613. $(\'#'.$htmlname.'\').multiSelect({
  7614. containerHTML: \'<div class="multi-select-container">\',
  7615. menuHTML: \'<div class="multi-select-menu">\',
  7616. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7617. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7618. activeClass: \'multi-select-container--open\',
  7619. noneText: \''.$placeholder.'\'
  7620. });
  7621. })';
  7622. }
  7623. $out .= '</script>';
  7624. }
  7625. return $out;
  7626. }
  7627. /**
  7628. * 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.
  7629. *
  7630. * @param string $htmlname Name of HTML field
  7631. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7632. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7633. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7634. * @return string HTML multiselect string
  7635. * @see selectarray()
  7636. */
  7637. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7638. {
  7639. global $conf, $langs, $user, $extrafields;
  7640. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7641. return '';
  7642. }
  7643. if (empty($array)) {
  7644. return '';
  7645. }
  7646. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7647. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7648. $tmparray = explode(',', $user->conf->$tmpvar);
  7649. foreach ($array as $key => $val) {
  7650. //var_dump($key);
  7651. //var_dump($tmparray);
  7652. if (in_array($key, $tmparray)) {
  7653. $array[$key]['checked'] = 1;
  7654. } else {
  7655. $array[$key]['checked'] = 0;
  7656. }
  7657. }
  7658. } else { // There is no list of fields already customized for user
  7659. foreach ($array as $key => $val) {
  7660. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7661. $array[$key]['checked'] = 0;
  7662. }
  7663. }
  7664. }
  7665. $listoffieldsforselection = '';
  7666. $listcheckedstring = '';
  7667. foreach ($array as $key => $val) {
  7668. // var_dump($val);
  7669. // var_dump(array_key_exists('enabled', $val));
  7670. // var_dump(!$val['enabled']);
  7671. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7672. unset($array[$key]); // We don't want this field
  7673. continue;
  7674. }
  7675. if (!empty($val['type']) && $val['type'] == 'separate') {
  7676. // Field remains in array but we don't add it into $listoffieldsforselection
  7677. //$listoffieldsforselection .= '<li>-----</li>';
  7678. continue;
  7679. }
  7680. if ($val['label']) {
  7681. if (!empty($val['langfile']) && is_object($langs)) {
  7682. $langs->load($val['langfile']);
  7683. }
  7684. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7685. $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>';
  7686. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7687. }
  7688. }
  7689. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7690. <dl class="dropdown">
  7691. <dt>
  7692. <a href="#'.$htmlname.'">
  7693. '.img_picto('', 'list').'
  7694. </a>
  7695. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7696. </dt>
  7697. <dd class="dropdowndd">
  7698. <div class="multiselectcheckbox'.$htmlname.'">
  7699. <ul class="'.$htmlname.($pos == '1' ? 'left' : '').'">
  7700. '.$listoffieldsforselection.'
  7701. </ul>
  7702. </div>
  7703. </dd>
  7704. </dl>
  7705. <script type="text/javascript">
  7706. jQuery(document).ready(function () {
  7707. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7708. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7709. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7710. var title = $(this).val() + ",";
  7711. if ($(this).is(\':checked\')) {
  7712. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7713. }
  7714. else {
  7715. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7716. }
  7717. // Now, we submit page
  7718. //$(this).parents(\'form:first\').submit();
  7719. });
  7720. });
  7721. </script>
  7722. ';
  7723. return $out;
  7724. }
  7725. /**
  7726. * Render list of categories linked to object with id $id and type $type
  7727. *
  7728. * @param int $id Id of object
  7729. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7730. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7731. * @param int $nolink 1=Do not add html links
  7732. * @return string String with categories
  7733. */
  7734. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7735. {
  7736. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7737. $cat = new Categorie($this->db);
  7738. $categories = $cat->containing($id, $type);
  7739. if ($rendermode == 1) {
  7740. $toprint = array();
  7741. foreach ($categories as $c) {
  7742. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7743. foreach ($ways as $way) {
  7744. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7745. }
  7746. }
  7747. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7748. }
  7749. if ($rendermode == 0) {
  7750. $arrayselected = array();
  7751. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7752. foreach ($categories as $c) {
  7753. $arrayselected[] = $c->id;
  7754. }
  7755. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7756. }
  7757. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7758. }
  7759. /**
  7760. * Show linked object block.
  7761. *
  7762. * @param CommonObject $object Object we want to show links to
  7763. * @param string $morehtmlright More html to show on right of title
  7764. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7765. * @param string $title Title
  7766. * @return int <0 if KO, >=0 if OK
  7767. */
  7768. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false, $title = 'RelatedObjects')
  7769. {
  7770. global $conf, $langs, $hookmanager;
  7771. global $bc, $action;
  7772. $object->fetchObjectLinked();
  7773. // Bypass the default method
  7774. $hookmanager->initHooks(array('commonobject'));
  7775. $parameters = array(
  7776. 'morehtmlright' => $morehtmlright,
  7777. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7778. );
  7779. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7780. if (empty($reshook)) {
  7781. $nbofdifferenttypes = count($object->linkedObjects);
  7782. print '<!-- showLinkedObjectBlock -->';
  7783. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7784. print '<div class="div-table-responsive-no-min">';
  7785. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7786. print '<tr class="liste_titre">';
  7787. print '<td>'.$langs->trans("Type").'</td>';
  7788. print '<td>'.$langs->trans("Ref").'</td>';
  7789. print '<td class="center"></td>';
  7790. print '<td class="center">'.$langs->trans("Date").'</td>';
  7791. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7792. print '<td class="right">'.$langs->trans("Status").'</td>';
  7793. print '<td></td>';
  7794. print '</tr>';
  7795. $nboftypesoutput = 0;
  7796. foreach ($object->linkedObjects as $objecttype => $objects) {
  7797. $tplpath = $element = $subelement = $objecttype;
  7798. // to display inport button on tpl
  7799. $showImportButton = false;
  7800. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7801. $showImportButton = true;
  7802. }
  7803. $regs = array();
  7804. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7805. $element = $regs[1];
  7806. $subelement = $regs[2];
  7807. $tplpath = $element.'/'.$subelement;
  7808. }
  7809. $tplname = 'linkedobjectblock';
  7810. // To work with non standard path
  7811. if ($objecttype == 'facture') {
  7812. $tplpath = 'compta/'.$element;
  7813. if (!isModEnabled('facture')) {
  7814. continue; // Do not show if module disabled
  7815. }
  7816. } elseif ($objecttype == 'facturerec') {
  7817. $tplpath = 'compta/facture';
  7818. $tplname = 'linkedobjectblockForRec';
  7819. if (!isModEnabled('facture')) {
  7820. continue; // Do not show if module disabled
  7821. }
  7822. } elseif ($objecttype == 'propal') {
  7823. $tplpath = 'comm/'.$element;
  7824. if (!isModEnabled('propal')) {
  7825. continue; // Do not show if module disabled
  7826. }
  7827. } elseif ($objecttype == 'supplier_proposal') {
  7828. if (!isModEnabled('supplier_proposal')) {
  7829. continue; // Do not show if module disabled
  7830. }
  7831. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment' || $objecttype == 'expedition') {
  7832. $tplpath = 'expedition';
  7833. if (!isModEnabled('expedition')) {
  7834. continue; // Do not show if module disabled
  7835. }
  7836. } elseif ($objecttype == 'reception') {
  7837. $tplpath = 'reception';
  7838. if (!isModEnabled('reception')) {
  7839. continue; // Do not show if module disabled
  7840. }
  7841. } elseif ($objecttype == 'delivery') {
  7842. $tplpath = 'delivery';
  7843. if (!isModEnabled('expedition')) {
  7844. continue; // Do not show if module disabled
  7845. }
  7846. } elseif ($objecttype == 'ficheinter') {
  7847. $tplpath = 'fichinter';
  7848. if (!isModEnabled('ficheinter')) {
  7849. continue; // Do not show if module disabled
  7850. }
  7851. } elseif ($objecttype == 'invoice_supplier') {
  7852. $tplpath = 'fourn/facture';
  7853. } elseif ($objecttype == 'order_supplier') {
  7854. $tplpath = 'fourn/commande';
  7855. } elseif ($objecttype == 'expensereport') {
  7856. $tplpath = 'expensereport';
  7857. } elseif ($objecttype == 'subscription') {
  7858. $tplpath = 'adherents';
  7859. } elseif ($objecttype == 'conferenceorbooth') {
  7860. $tplpath = 'eventorganization';
  7861. } elseif ($objecttype == 'conferenceorboothattendee') {
  7862. $tplpath = 'eventorganization';
  7863. } elseif ($objecttype == 'mo') {
  7864. $tplpath = 'mrp';
  7865. if (!isModEnabled('mrp')) {
  7866. continue; // Do not show if module disabled
  7867. }
  7868. }
  7869. global $linkedObjectBlock;
  7870. $linkedObjectBlock = $objects;
  7871. // Output template part (modules that overwrite templates must declare this into descriptor)
  7872. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7873. foreach ($dirtpls as $reldir) {
  7874. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7875. global $noMoreLinkedObjectBlockAfter;
  7876. $noMoreLinkedObjectBlockAfter = 1;
  7877. }
  7878. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7879. if ($res) {
  7880. $nboftypesoutput++;
  7881. break;
  7882. }
  7883. }
  7884. }
  7885. if (!$nboftypesoutput) {
  7886. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7887. }
  7888. print '</table>';
  7889. if (!empty($compatibleImportElementsList)) {
  7890. $res = @include dol_buildpath('core/tpl/objectlinked_lineimport.tpl.php');
  7891. }
  7892. print '</div>';
  7893. return $nbofdifferenttypes;
  7894. }
  7895. }
  7896. /**
  7897. * Show block with links to link to other objects.
  7898. *
  7899. * @param CommonObject $object Object we want to show links to
  7900. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7901. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7902. * @return string <0 if KO, >0 if OK
  7903. */
  7904. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7905. {
  7906. global $conf, $langs, $hookmanager;
  7907. global $action;
  7908. $linktoelem = '';
  7909. $linktoelemlist = '';
  7910. $listofidcompanytoscan = '';
  7911. if (!is_object($object->thirdparty)) {
  7912. $object->fetch_thirdparty();
  7913. }
  7914. $possiblelinks = array();
  7915. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7916. $listofidcompanytoscan = $object->thirdparty->id;
  7917. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7918. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7919. }
  7920. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7921. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7922. $tmpproject = new Project($this->db);
  7923. $tmpproject->fetch($object->fk_project);
  7924. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7925. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7926. }
  7927. unset($tmpproject);
  7928. }
  7929. $possiblelinks = array(
  7930. 'propal'=>array(
  7931. 'enabled'=>isModEnabled('propal'),
  7932. 'perms'=>1,
  7933. 'label'=>'LinkToProposal',
  7934. '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').')'),
  7935. 'shipping'=>array(
  7936. 'enabled'=>isModEnabled('expedition'),
  7937. 'perms'=>1,
  7938. 'label'=>'LinkToExpedition',
  7939. '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').')'),
  7940. 'order'=>array(
  7941. 'enabled'=>isModEnabled('commande'),
  7942. 'perms'=>1,
  7943. 'label'=>'LinkToOrder',
  7944. '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').')'),
  7945. 'invoice'=>array(
  7946. 'enabled'=>isModEnabled('facture'),
  7947. 'perms'=>1,
  7948. 'label'=>'LinkToInvoice',
  7949. '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').')'),
  7950. 'invoice_template'=>array(
  7951. 'enabled'=>isModEnabled('facture'),
  7952. 'perms'=>1,
  7953. 'label'=>'LinkToTemplateInvoice',
  7954. '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').')'),
  7955. 'contrat'=>array(
  7956. 'enabled'=>isModEnabled('contrat'),
  7957. 'perms'=>1,
  7958. 'label'=>'LinkToContract',
  7959. '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
  7960. 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'),
  7961. 'fichinter'=>array(
  7962. 'enabled'=>isModEnabled('ficheinter'),
  7963. 'perms'=>1,
  7964. 'label'=>'LinkToIntervention',
  7965. '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').')'),
  7966. 'supplier_proposal'=>array(
  7967. 'enabled'=>(isModEnabled('supplier_proposal') ? $conf->supplier_proposal->enabled : 0),
  7968. 'perms'=>1,
  7969. 'label'=>'LinkToSupplierProposal',
  7970. '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').')'),
  7971. 'order_supplier'=>array(
  7972. 'enabled'=>(isModEnabled("supplier_order") ? $conf->supplier_order->enabled : 0),
  7973. 'perms'=>1,
  7974. 'label'=>'LinkToSupplierOrder',
  7975. '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').')'),
  7976. 'invoice_supplier'=>array(
  7977. 'enabled'=>(isModEnabled("supplier_invoice") ? $conf->supplier_invoice->enabled : 0),
  7978. 'perms'=>1, 'label'=>'LinkToSupplierInvoice',
  7979. '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').')'),
  7980. 'ticket'=>array(
  7981. 'enabled'=>isModEnabled('ticket'),
  7982. 'perms'=>1,
  7983. 'label'=>'LinkToTicket',
  7984. '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').')'),
  7985. 'mo'=>array(
  7986. 'enabled'=>isModEnabled('mrp'),
  7987. 'perms'=>1,
  7988. 'label'=>'LinkToMo',
  7989. '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').')')
  7990. );
  7991. }
  7992. if ($object->table_element == 'commande_fournisseur') {
  7993. $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').')';
  7994. } elseif ($object->table_element == 'mrp_mo') {
  7995. $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').')';
  7996. }
  7997. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7998. // Can complete the possiblelink array
  7999. $hookmanager->initHooks(array('commonobject'));
  8000. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  8001. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  8002. }
  8003. if (empty($reshook)) {
  8004. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8005. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  8006. }
  8007. } elseif ($reshook > 0) {
  8008. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  8009. $possiblelinks = $hookmanager->resArray;
  8010. }
  8011. }
  8012. foreach ($possiblelinks as $key => $possiblelink) {
  8013. $num = 0;
  8014. if (empty($possiblelink['enabled'])) {
  8015. continue;
  8016. }
  8017. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  8018. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  8019. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8020. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  8021. print '<input type="hidden" name="id" value="' . $object->id . '">';
  8022. print '<input type="hidden" name="action" value="addlinkbyref">';
  8023. print '<input type="hidden" name="token" value="'.newToken().'">';
  8024. print '<input type="hidden" name="addlink" value="' . $key . '">';
  8025. print '<table class="noborder">';
  8026. print '<tr>';
  8027. print '<td>' . $langs->trans("Ref") . '</td>';
  8028. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;';
  8029. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;';
  8030. print '<input type="submit" class="button smallpaddingimp" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  8031. print '</tr>';
  8032. print '</table>';
  8033. print '</form>';
  8034. }
  8035. $sql = $possiblelink['sql'];
  8036. $resqllist = $this->db->query($sql);
  8037. if ($resqllist) {
  8038. $num = $this->db->num_rows($resqllist);
  8039. $i = 0;
  8040. print '<br>';
  8041. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  8042. print '<input type="hidden" name="action" value="addlink">';
  8043. print '<input type="hidden" name="token" value="'.newToken().'">';
  8044. print '<input type="hidden" name="id" value="'.$object->id.'">';
  8045. print '<input type="hidden" name="addlink" value="'.$key.'">';
  8046. print '<table class="noborder">';
  8047. print '<tr class="liste_titre">';
  8048. print '<td class="nowrap"></td>';
  8049. print '<td class="center">'.$langs->trans("Ref").'</td>';
  8050. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  8051. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  8052. print '<td class="left">'.$langs->trans("Company").'</td>';
  8053. print '</tr>';
  8054. while ($i < $num) {
  8055. $objp = $this->db->fetch_object($resqllist);
  8056. print '<tr class="oddeven">';
  8057. print '<td class="left">';
  8058. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  8059. print '</td>';
  8060. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  8061. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  8062. print '<td class="right">';
  8063. if ($possiblelink['label'] == 'LinkToContract') {
  8064. $form = new Form($this->db);
  8065. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  8066. }
  8067. print '<span class="amount">'.(isset($objp->total_ht) ? price($objp->total_ht) : '').'</span>';
  8068. print '</td>';
  8069. print '<td>'.$objp->name.'</td>';
  8070. print '</tr>';
  8071. $i++;
  8072. }
  8073. print '</table>';
  8074. print '<div class="center">';
  8075. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  8076. if (empty($conf->use_javascript_ajax)) {
  8077. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  8078. } else {
  8079. 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>';
  8080. }
  8081. print '</form>';
  8082. $this->db->free($resqllist);
  8083. } else {
  8084. dol_print_error($this->db);
  8085. }
  8086. print '</div>';
  8087. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  8088. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  8089. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  8090. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  8091. } else {
  8092. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  8093. }
  8094. }
  8095. }
  8096. if ($linktoelemlist) {
  8097. $linktoelem = '
  8098. <dl class="dropdown" id="linktoobjectname">
  8099. ';
  8100. if (!empty($conf->use_javascript_ajax)) {
  8101. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  8102. }
  8103. $linktoelem .= '<dd>
  8104. <div class="multiselectlinkto">
  8105. <ul class="ulselectedfields">'.$linktoelemlist.'
  8106. </ul>
  8107. </div>
  8108. </dd>
  8109. </dl>';
  8110. } else {
  8111. $linktoelem = '';
  8112. }
  8113. if (!empty($conf->use_javascript_ajax)) {
  8114. print '<!-- Add js to show linkto box -->
  8115. <script>
  8116. jQuery(document).ready(function() {
  8117. jQuery(".linkto").click(function() {
  8118. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  8119. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  8120. });
  8121. });
  8122. </script>
  8123. ';
  8124. }
  8125. return $linktoelem;
  8126. }
  8127. /**
  8128. * Return an html string with a select combo box to choose yes or no
  8129. *
  8130. * @param string $htmlname Name of html select field
  8131. * @param string $value Pre-selected value
  8132. * @param int $option 0 return yes/no, 1 return 1/0
  8133. * @param bool $disabled true or false
  8134. * @param int $useempty 1=Add empty line
  8135. * @param int $addjscombo 1=Add js beautifier on combo box
  8136. * @param string $morecss More CSS
  8137. * @param string $labelyes Label for Yes
  8138. * @param string $labelno Label for No
  8139. * @return string See option
  8140. */
  8141. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8142. {
  8143. global $langs;
  8144. $yes = "yes";
  8145. $no = "no";
  8146. if ($option) {
  8147. $yes = "1";
  8148. $no = "0";
  8149. }
  8150. $disabled = ($disabled ? ' disabled' : '');
  8151. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  8152. if ($useempty) {
  8153. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8154. }
  8155. if (("$value" == 'yes') || ($value == 1)) {
  8156. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans($labelyes).'</option>'."\n";
  8157. $resultyesno .= '<option value="'.$no.'">'.$langs->trans($labelno).'</option>'."\n";
  8158. } else {
  8159. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8160. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans($labelyes).'</option>'."\n";
  8161. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans($labelno).'</option>'."\n";
  8162. }
  8163. $resultyesno .= '</select>'."\n";
  8164. if ($addjscombo) {
  8165. $resultyesno .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', ($useempty < 0 ? (string) $useempty : '-1'), $morecss);
  8166. }
  8167. return $resultyesno;
  8168. }
  8169. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8170. /**
  8171. * Return list of export templates
  8172. *
  8173. * @param string $selected Id modele pre-selectionne
  8174. * @param string $htmlname Name of HTML select
  8175. * @param string $type Type of searched templates
  8176. * @param int $useempty Affiche valeur vide dans liste
  8177. * @return void
  8178. */
  8179. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8180. {
  8181. // phpcs:enable
  8182. $sql = "SELECT rowid, label";
  8183. $sql .= " FROM ".$this->db->prefix()."export_model";
  8184. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  8185. $sql .= " ORDER BY rowid";
  8186. $result = $this->db->query($sql);
  8187. if ($result) {
  8188. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  8189. if ($useempty) {
  8190. print '<option value="-1">&nbsp;</option>';
  8191. }
  8192. $num = $this->db->num_rows($result);
  8193. $i = 0;
  8194. while ($i < $num) {
  8195. $obj = $this->db->fetch_object($result);
  8196. if ($selected == $obj->rowid) {
  8197. print '<option value="'.$obj->rowid.'" selected>';
  8198. } else {
  8199. print '<option value="'.$obj->rowid.'">';
  8200. }
  8201. print $obj->label;
  8202. print '</option>';
  8203. $i++;
  8204. }
  8205. print "</select>";
  8206. } else {
  8207. dol_print_error($this->db);
  8208. }
  8209. }
  8210. /**
  8211. * Return a HTML area with the reference of object and a navigation bar for a business object
  8212. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8213. *
  8214. * @param object $object Object to show.
  8215. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8216. * @param string $morehtml More html content to output just before the nav bar.
  8217. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8218. * @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.
  8219. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8220. * @param string $morehtmlref More html to show after ref.
  8221. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8222. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8223. * @param string $morehtmlleft More html code to show before ref.
  8224. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8225. * @param string $morehtmlright More html code to show after ref.
  8226. * @return string Portion HTML with ref + navigation buttons
  8227. */
  8228. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8229. {
  8230. global $conf, $langs, $hookmanager, $extralanguages;
  8231. $ret = '';
  8232. if (empty($fieldid)) {
  8233. $fieldid = 'rowid';
  8234. }
  8235. if (empty($fieldref)) {
  8236. $fieldref = 'ref';
  8237. }
  8238. // Preparing gender's display if there is one
  8239. $addgendertxt = '';
  8240. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8241. $addgendertxt = ' ';
  8242. switch ($object->gender) {
  8243. case 'man':
  8244. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8245. break;
  8246. case 'woman':
  8247. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8248. break;
  8249. case 'other':
  8250. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8251. break;
  8252. }
  8253. }
  8254. /*
  8255. $addadmin = '';
  8256. if (property_exists($object, 'admin')) {
  8257. if (isModEnabled('multicompany') && !empty($object->admin) && empty($object->entity)) {
  8258. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8259. } elseif (!empty($object->admin)) {
  8260. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8261. }
  8262. }*/
  8263. // Add where from hooks
  8264. if (is_object($hookmanager)) {
  8265. $parameters = array('showrefnav' => true);
  8266. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8267. $object->next_prev_filter .= $hookmanager->resPrint;
  8268. }
  8269. $previous_ref = $next_ref = '';
  8270. if ($shownav) {
  8271. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8272. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8273. $navurl = $_SERVER["PHP_SELF"];
  8274. // Special case for project/task page
  8275. if ($paramid == 'project_ref') {
  8276. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8277. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8278. $paramid = 'ref';
  8279. }
  8280. }
  8281. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8282. // accesskey is for Mac: CTRL + key for all browsers
  8283. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8284. if ($conf->browser->name == 'chrome') {
  8285. $stringforfirstkey .= ' ALT +';
  8286. } elseif ($conf->browser->name == 'firefox') {
  8287. $stringforfirstkey .= ' ALT + SHIFT +';
  8288. } else {
  8289. $stringforfirstkey .= ' CTL +';
  8290. }
  8291. $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>';
  8292. $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>';
  8293. }
  8294. //print "xx".$previous_ref."x".$next_ref;
  8295. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8296. // Right part of banner
  8297. if ($morehtmlright) {
  8298. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  8299. }
  8300. if ($previous_ref || $next_ref || $morehtml) {
  8301. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8302. }
  8303. if ($morehtml) {
  8304. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  8305. }
  8306. if ($shownav && ($previous_ref || $next_ref)) {
  8307. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  8308. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  8309. }
  8310. if ($previous_ref || $next_ref || $morehtml) {
  8311. $ret .= '</ul></div>';
  8312. }
  8313. $parameters = array();
  8314. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8315. if (empty($reshook)) {
  8316. $morehtmlstatus .= $hookmanager->resPrint;
  8317. } else {
  8318. $morehtmlstatus = $hookmanager->resPrint;
  8319. }
  8320. if ($morehtmlstatus) {
  8321. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  8322. }
  8323. $parameters = array();
  8324. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8325. if (empty($reshook)) {
  8326. $morehtmlref .= $hookmanager->resPrint;
  8327. } elseif ($reshook > 0) {
  8328. $morehtmlref = $hookmanager->resPrint;
  8329. }
  8330. // Left part of banner
  8331. if ($morehtmlleft) {
  8332. if ($conf->browser->layout == 'phone') {
  8333. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  8334. } else {
  8335. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  8336. }
  8337. }
  8338. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8339. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  8340. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8341. if ($object->element == 'societe') {
  8342. $ret .= dol_htmlentities($object->name);
  8343. // List of extra languages
  8344. $arrayoflangcode = array();
  8345. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8346. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8347. }
  8348. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8349. if (!is_object($extralanguages)) {
  8350. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  8351. $extralanguages = new ExtraLanguages($this->db);
  8352. }
  8353. $extralanguages->fetch_name_extralanguages('societe');
  8354. if (!empty($extralanguages->attributes['societe']['name'])) {
  8355. $object->fetchValuesForExtraLanguages();
  8356. $htmltext = '';
  8357. // If there is extra languages
  8358. foreach ($arrayoflangcode as $extralangcode) {
  8359. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8360. if ($object->array_languages['name'][$extralangcode]) {
  8361. $htmltext .= $object->array_languages['name'][$extralangcode];
  8362. } else {
  8363. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  8364. }
  8365. }
  8366. $ret .= '<!-- Show translations of name -->'."\n";
  8367. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8368. }
  8369. }
  8370. } elseif ($object->element == 'member') {
  8371. $ret .= $object->ref.'<br>';
  8372. $fullname = $object->getFullName($langs);
  8373. if ($object->morphy == 'mor' && $object->societe) {
  8374. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  8375. } else {
  8376. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  8377. }
  8378. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8379. $ret .= dol_htmlentities($object->getFullName($langs)).$addgendertxt;
  8380. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8381. $ret .= $object->ref.'<br>'.$object->label;
  8382. } elseif (in_array($object->element, array('adherent_type'))) {
  8383. $ret .= $object->label;
  8384. } elseif ($object->element == 'ecm_directories') {
  8385. $ret .= '';
  8386. } elseif ($fieldref != 'none') {
  8387. $ret .= dol_htmlentities(!empty($object->$fieldref) ? $object->$fieldref : "");
  8388. }
  8389. if ($morehtmlref) {
  8390. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8391. if (substr($morehtmlref, 0, 4) != '<div') {
  8392. $ret .= ' ';
  8393. }
  8394. $ret .= $morehtmlref;
  8395. }
  8396. $ret .= '</div>';
  8397. $ret .= '</div><!-- End banner content -->';
  8398. return $ret;
  8399. }
  8400. /**
  8401. * Return HTML code to output a barcode
  8402. *
  8403. * @param Object $object Object containing data to retrieve file name
  8404. * @param int $width Width of photo
  8405. * @param string $morecss More CSS on img of barcode
  8406. * @return string HTML code to output barcode
  8407. */
  8408. public function showbarcode(&$object, $width = 100, $morecss = '')
  8409. {
  8410. global $conf;
  8411. //Check if barcode is filled in the card
  8412. if (empty($object->barcode)) {
  8413. return '';
  8414. }
  8415. // Complete object if not complete
  8416. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8417. $result = $object->fetch_barcode();
  8418. //Check if fetch_barcode() failed
  8419. if ($result < 1) {
  8420. return '<!-- ErrorFetchBarcode -->';
  8421. }
  8422. }
  8423. // Barcode image
  8424. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8425. $out = '<!-- url barcode = '.$url.' -->';
  8426. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8427. return $out;
  8428. }
  8429. /**
  8430. * Return HTML code to output a photo
  8431. *
  8432. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8433. * @param object $object Object containing data to retrieve file name
  8434. * @param int $width Width of photo
  8435. * @param int $height Height of photo (auto if 0)
  8436. * @param int $caneditfield Add edit fields
  8437. * @param string $cssclass CSS name to use on img for photo
  8438. * @param string $imagesize 'mini', 'small' or '' (original)
  8439. * @param int $addlinktofullsize Add link to fullsize image
  8440. * @param int $cache 1=Accept to use image in cache
  8441. * @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 ''.
  8442. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8443. * @return string HTML code to output photo
  8444. */
  8445. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8446. {
  8447. global $conf, $langs;
  8448. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8449. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8450. $ret = '';
  8451. $dir = '';
  8452. $file = '';
  8453. $originalfile = '';
  8454. $altfile = '';
  8455. $email = '';
  8456. $capture = '';
  8457. if ($modulepart == 'societe') {
  8458. $dir = $conf->societe->multidir_output[$entity];
  8459. if (!empty($object->logo)) {
  8460. if (dolIsAllowedForPreview($object->logo)) {
  8461. if ((string) $imagesize == 'mini') {
  8462. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8463. } elseif ((string) $imagesize == 'small') {
  8464. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8465. } else {
  8466. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8467. }
  8468. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8469. }
  8470. }
  8471. $email = $object->email;
  8472. } elseif ($modulepart == 'contact') {
  8473. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8474. if (!empty($object->photo)) {
  8475. if (dolIsAllowedForPreview($object->photo)) {
  8476. if ((string) $imagesize == 'mini') {
  8477. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8478. } elseif ((string) $imagesize == 'small') {
  8479. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8480. } else {
  8481. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8482. }
  8483. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8484. }
  8485. }
  8486. $email = $object->email;
  8487. $capture = 'user';
  8488. } elseif ($modulepart == 'userphoto') {
  8489. $dir = $conf->user->dir_output;
  8490. if (!empty($object->photo)) {
  8491. if (dolIsAllowedForPreview($object->photo)) {
  8492. if ((string) $imagesize == 'mini') {
  8493. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8494. } elseif ((string) $imagesize == 'small') {
  8495. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8496. } else {
  8497. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8498. }
  8499. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8500. }
  8501. }
  8502. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8503. $altfile = $object->id.".jpg"; // For backward compatibility
  8504. }
  8505. $email = $object->email;
  8506. $capture = 'user';
  8507. } elseif ($modulepart == 'memberphoto') {
  8508. $dir = $conf->adherent->dir_output;
  8509. if (!empty($object->photo)) {
  8510. if (dolIsAllowedForPreview($object->photo)) {
  8511. if ((string) $imagesize == 'mini') {
  8512. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8513. } elseif ((string) $imagesize == 'small') {
  8514. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8515. } else {
  8516. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8517. }
  8518. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8519. }
  8520. }
  8521. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8522. $altfile = $object->id.".jpg"; // For backward compatibility
  8523. }
  8524. $email = $object->email;
  8525. $capture = 'user';
  8526. } else {
  8527. // Generic case to show photos
  8528. $dir = $conf->$modulepart->dir_output;
  8529. if (!empty($object->photo)) {
  8530. if (dolIsAllowedForPreview($object->photo)) {
  8531. if ((string) $imagesize == 'mini') {
  8532. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8533. } elseif ((string) $imagesize == 'small') {
  8534. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8535. } else {
  8536. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8537. }
  8538. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8539. }
  8540. }
  8541. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8542. $altfile = $object->id.".jpg"; // For backward compatibility
  8543. }
  8544. $email = $object->email;
  8545. }
  8546. if ($forcecapture) {
  8547. $capture = $forcecapture;
  8548. }
  8549. if ($dir) {
  8550. if ($file && file_exists($dir."/".$file)) {
  8551. if ($addlinktofullsize) {
  8552. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8553. if ($urladvanced) {
  8554. $ret .= '<a href="'.$urladvanced.'">';
  8555. } else {
  8556. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8557. }
  8558. }
  8559. $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.'">';
  8560. if ($addlinktofullsize) {
  8561. $ret .= '</a>';
  8562. }
  8563. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8564. if ($addlinktofullsize) {
  8565. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8566. if ($urladvanced) {
  8567. $ret .= '<a href="'.$urladvanced.'">';
  8568. } else {
  8569. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8570. }
  8571. }
  8572. $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.'">';
  8573. if ($addlinktofullsize) {
  8574. $ret .= '</a>';
  8575. }
  8576. } else {
  8577. $nophoto = '/public/theme/common/nophoto.png';
  8578. $defaultimg = 'identicon'; // For gravatar
  8579. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8580. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8581. $nophoto = 'company';
  8582. } else {
  8583. $nophoto = '/public/theme/common/user_anonymous.png';
  8584. if (!empty($object->gender) && $object->gender == 'man') {
  8585. $nophoto = '/public/theme/common/user_man.png';
  8586. }
  8587. if (!empty($object->gender) && $object->gender == 'woman') {
  8588. $nophoto = '/public/theme/common/user_woman.png';
  8589. }
  8590. }
  8591. }
  8592. if (isModEnabled('gravatar') && $email && empty($noexternsourceoverwrite)) {
  8593. // see https://gravatar.com/site/implement/images/php/
  8594. $ret .= '<!-- Put link to gravatar -->';
  8595. $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
  8596. } else {
  8597. if ($nophoto == 'company') {
  8598. $ret .= '<div class="divforspanimg photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'>'.img_picto('', 'company').'</div>';
  8599. $ret .= '<div class="difforspanimgright"></div>';
  8600. } else {
  8601. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8602. }
  8603. }
  8604. }
  8605. if ($caneditfield) {
  8606. if ($object->photo) {
  8607. $ret .= "<br>\n";
  8608. }
  8609. $ret .= '<table class="nobordernopadding centpercent">';
  8610. if ($object->photo) {
  8611. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8612. }
  8613. $ret .= '<tr><td class="tdoverflow">';
  8614. $maxfilesizearray = getMaxFileSizeArray();
  8615. $maxmin = $maxfilesizearray['maxmin'];
  8616. if ($maxmin > 0) {
  8617. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
  8618. }
  8619. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'>';
  8620. $ret .= '</td></tr>';
  8621. $ret .= '</table>';
  8622. }
  8623. } else {
  8624. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8625. }
  8626. return $ret;
  8627. }
  8628. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8629. /**
  8630. * Return select list of groups
  8631. *
  8632. * @param string|object $selected Id group or group preselected
  8633. * @param string $htmlname Field name in form
  8634. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8635. * @param string|array $exclude Array list of groups id to exclude
  8636. * @param int $disabled If select list must be disabled
  8637. * @param string|array $include Array list of groups id to include
  8638. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8639. * @param string $force_entity '0' or Ids of environment to force
  8640. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8641. * @param string $morecss More css to add to html component
  8642. * @return string
  8643. * @see select_dolusers()
  8644. */
  8645. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8646. {
  8647. // phpcs:enable
  8648. global $conf, $user, $langs;
  8649. // Permettre l'exclusion de groupes
  8650. $excludeGroups = null;
  8651. if (is_array($exclude)) {
  8652. $excludeGroups = implode(",", $exclude);
  8653. }
  8654. // Permettre l'inclusion de groupes
  8655. $includeGroups = null;
  8656. if (is_array($include)) {
  8657. $includeGroups = implode(",", $include);
  8658. }
  8659. if (!is_array($selected)) {
  8660. $selected = array($selected);
  8661. }
  8662. $out = '';
  8663. // On recherche les groupes
  8664. $sql = "SELECT ug.rowid, ug.nom as name";
  8665. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8666. $sql .= ", e.label";
  8667. }
  8668. $sql .= " FROM ".$this->db->prefix()."usergroup as ug ";
  8669. if (isModEnabled('multicompany') && $conf->entity == 1 && $user->admin && !$user->entity) {
  8670. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid=ug.entity";
  8671. if ($force_entity) {
  8672. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8673. } else {
  8674. $sql .= " WHERE ug.entity IS NOT NULL";
  8675. }
  8676. } else {
  8677. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8678. }
  8679. if (is_array($exclude) && $excludeGroups) {
  8680. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8681. }
  8682. if (is_array($include) && $includeGroups) {
  8683. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8684. }
  8685. $sql .= " ORDER BY ug.nom ASC";
  8686. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8687. $resql = $this->db->query($sql);
  8688. if ($resql) {
  8689. // Enhance with select2
  8690. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8691. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8692. $num = $this->db->num_rows($resql);
  8693. $i = 0;
  8694. if ($num) {
  8695. if ($show_empty && !$multiple) {
  8696. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8697. }
  8698. while ($i < $num) {
  8699. $obj = $this->db->fetch_object($resql);
  8700. $disableline = 0;
  8701. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8702. $disableline = 1;
  8703. }
  8704. $out .= '<option value="'.$obj->rowid.'"';
  8705. if ($disableline) {
  8706. $out .= ' disabled';
  8707. }
  8708. 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))) {
  8709. $out .= ' selected';
  8710. }
  8711. $out .= '>';
  8712. $out .= $obj->name;
  8713. if (isModEnabled('multicompany') && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8714. $out .= " (".$obj->label.")";
  8715. }
  8716. $out .= '</option>';
  8717. $i++;
  8718. }
  8719. } else {
  8720. if ($show_empty) {
  8721. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8722. }
  8723. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8724. }
  8725. $out .= '</select>';
  8726. $out .= ajax_combobox($htmlname);
  8727. } else {
  8728. dol_print_error($this->db);
  8729. }
  8730. return $out;
  8731. }
  8732. /**
  8733. * Return HTML to show the search and clear seach button
  8734. *
  8735. * @param string $pos position colon on liste value left or right
  8736. * @return string
  8737. */
  8738. public function showFilterButtons($pos = '')
  8739. {
  8740. $out = '<div class="nowraponall">';
  8741. if ($pos == 'left') {
  8742. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8743. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8744. } else {
  8745. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8746. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8747. }
  8748. $out .= '</div>';
  8749. return $out;
  8750. }
  8751. /**
  8752. * Return HTML to show the search and clear search button
  8753. *
  8754. * @param string $cssclass CSS class
  8755. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8756. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8757. * @return string
  8758. */
  8759. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8760. {
  8761. global $conf, $langs;
  8762. $out = '';
  8763. if (!empty($conf->use_javascript_ajax)) {
  8764. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8765. }
  8766. $out .= '<script>
  8767. $(document).ready(function() {
  8768. $("#' . $cssclass.'s").click(function() {
  8769. if($(this).is(\':checked\')){
  8770. console.log("We check all '.$cssclass.' and trigger the change method");
  8771. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8772. }
  8773. else
  8774. {
  8775. console.log("We uncheck all");
  8776. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8777. }'."\n";
  8778. if ($calljsfunction) {
  8779. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8780. }
  8781. $out .= ' });
  8782. $(".' . $cssclass.'").change(function() {
  8783. $(this).closest("tr").toggleClass("highlight", this.checked);
  8784. });
  8785. });
  8786. </script>';
  8787. return $out;
  8788. }
  8789. /**
  8790. * Return HTML to show the search and clear seach button
  8791. *
  8792. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8793. * @param string $cssclass CSS class
  8794. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8795. * @param string $massactionname Mass action name
  8796. * @return string
  8797. */
  8798. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8799. {
  8800. $out = $this->showFilterButtons();
  8801. if ($addcheckuncheckall) {
  8802. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8803. }
  8804. return $out;
  8805. }
  8806. /**
  8807. * Return HTML to show the select of expense categories
  8808. *
  8809. * @param string $selected preselected category
  8810. * @param string $htmlname name of HTML select list
  8811. * @param integer $useempty 1=Add empty line
  8812. * @param array $excludeid id to exclude
  8813. * @param string $target htmlname of target select to bind event
  8814. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8815. * @param array $params param to give
  8816. * @param int $info_admin Show the tooltip help picto to setup list
  8817. * @return string
  8818. */
  8819. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8820. {
  8821. global $langs, $user;
  8822. $out = '';
  8823. $sql = "SELECT rowid, label FROM ".$this->db->prefix()."c_exp_tax_cat WHERE active = 1";
  8824. $sql .= " AND entity IN (0,".getEntity('exp_tax_cat').")";
  8825. if (!empty($excludeid)) {
  8826. $sql .= " AND rowid NOT IN (".$this->db->sanitize(implode(',', $excludeid)).")";
  8827. }
  8828. $sql .= " ORDER BY label";
  8829. $resql = $this->db->query($sql);
  8830. if ($resql) {
  8831. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8832. if ($useempty) {
  8833. $out .= '<option value="0">&nbsp;</option>';
  8834. }
  8835. while ($obj = $this->db->fetch_object($resql)) {
  8836. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8837. }
  8838. $out .= '</select>';
  8839. $out .= ajax_combobox('select_'.$htmlname);
  8840. if (!empty($htmlname) && $user->admin && $info_admin) {
  8841. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8842. }
  8843. if (!empty($target)) {
  8844. $sql = "SELECT c.id FROM ".$this->db->prefix()."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8845. $resql = $this->db->query($sql);
  8846. if ($resql) {
  8847. if ($this->db->num_rows($resql) > 0) {
  8848. $obj = $this->db->fetch_object($resql);
  8849. $out .= '<script>
  8850. $(function() {
  8851. $("select[name='.$target.']").on("change", function() {
  8852. var current_val = $(this).val();
  8853. if (current_val == '.$obj->id.') {';
  8854. if (!empty($default_selected) || !empty($selected)) {
  8855. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8856. }
  8857. $out .= '
  8858. $("select[name='.$htmlname.']").change();
  8859. }
  8860. });
  8861. $("select[name='.$htmlname.']").change(function() {
  8862. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8863. // get price of kilometer to fill the unit price
  8864. $.ajax({
  8865. method: "POST",
  8866. dataType: "json",
  8867. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8868. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.join('&', $params)).'",
  8869. }).done(function( data, textStatus, jqXHR ) {
  8870. console.log(data);
  8871. if (typeof data.up != "undefined") {
  8872. $("input[name=value_unit]").val(data.up);
  8873. $("select[name='.$htmlname.']").attr("title", data.title);
  8874. } else {
  8875. $("input[name=value_unit]").val("");
  8876. $("select[name='.$htmlname.']").attr("title", "");
  8877. }
  8878. });
  8879. }
  8880. });
  8881. });
  8882. </script>';
  8883. }
  8884. }
  8885. }
  8886. } else {
  8887. dol_print_error($this->db);
  8888. }
  8889. return $out;
  8890. }
  8891. /**
  8892. * Return HTML to show the select ranges of expense range
  8893. *
  8894. * @param string $selected preselected category
  8895. * @param string $htmlname name of HTML select list
  8896. * @param integer $useempty 1=Add empty line
  8897. * @return string
  8898. */
  8899. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8900. {
  8901. global $conf, $langs;
  8902. $out = '';
  8903. $sql = "SELECT rowid, range_ik FROM ".$this->db->prefix()."c_exp_tax_range";
  8904. $sql .= " WHERE entity = ".$conf->entity." AND active = 1";
  8905. $resql = $this->db->query($sql);
  8906. if ($resql) {
  8907. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8908. if ($useempty) {
  8909. $out .= '<option value="0"></option>';
  8910. }
  8911. while ($obj = $this->db->fetch_object($resql)) {
  8912. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8913. }
  8914. $out .= '</select>';
  8915. } else {
  8916. dol_print_error($this->db);
  8917. }
  8918. return $out;
  8919. }
  8920. /**
  8921. * Return HTML to show a select of expense
  8922. *
  8923. * @param string $selected preselected category
  8924. * @param string $htmlname name of HTML select list
  8925. * @param integer $useempty 1=Add empty choice
  8926. * @param integer $allchoice 1=Add all choice
  8927. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8928. * @return string
  8929. */
  8930. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8931. {
  8932. global $langs;
  8933. $out = '';
  8934. $sql = "SELECT id, code, label FROM ".$this->db->prefix()."c_type_fees";
  8935. $sql .= " WHERE active = 1";
  8936. $resql = $this->db->query($sql);
  8937. if ($resql) {
  8938. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8939. if ($useempty) {
  8940. $out .= '<option value="0"></option>';
  8941. }
  8942. if ($allchoice) {
  8943. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8944. }
  8945. $field = 'code';
  8946. if ($useid) {
  8947. $field = 'id';
  8948. }
  8949. while ($obj = $this->db->fetch_object($resql)) {
  8950. $key = $langs->trans($obj->code);
  8951. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8952. }
  8953. $out .= '</select>';
  8954. } else {
  8955. dol_print_error($this->db);
  8956. }
  8957. return $out;
  8958. }
  8959. /**
  8960. * Output a combo list with invoices qualified for a third party
  8961. *
  8962. * @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)
  8963. * @param int $selected Id invoice preselected
  8964. * @param string $htmlname Name of HTML select
  8965. * @param int $maxlength Maximum length of label
  8966. * @param int $option_only Return only html options lines without the select tag
  8967. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8968. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8969. * @param int $forcefocus Force focus on field (works with javascript only)
  8970. * @param int $disabled Disabled
  8971. * @param string $morecss More css added to the select component
  8972. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8973. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8974. * @param User $usertofilter User object to use for filtering
  8975. * @return int Nbr of project if OK, <0 if KO
  8976. */
  8977. 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)
  8978. {
  8979. global $user, $conf, $langs;
  8980. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8981. if (is_null($usertofilter)) {
  8982. $usertofilter = $user;
  8983. }
  8984. $out = '';
  8985. $hideunselectables = false;
  8986. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8987. $hideunselectables = true;
  8988. }
  8989. if (empty($projectsListId)) {
  8990. if (empty($usertofilter->rights->projet->all->lire)) {
  8991. $projectstatic = new Project($this->db);
  8992. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8993. }
  8994. }
  8995. // Search all projects
  8996. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8997. p.title, p.fk_soc, p.fk_statut, p.public,";
  8998. $sql .= ' s.nom as name';
  8999. $sql .= ' FROM '.$this->db->prefix().'projet as p';
  9000. $sql .= ' LEFT JOIN '.$this->db->prefix().'societe as s ON s.rowid = p.fk_soc,';
  9001. $sql .= ' '.$this->db->prefix().'facture as f';
  9002. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  9003. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  9004. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  9005. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  9006. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  9007. $sql .= " ORDER BY p.ref, f.ref ASC";
  9008. $resql = $this->db->query($sql);
  9009. if ($resql) {
  9010. // Use select2 selector
  9011. if (!empty($conf->use_javascript_ajax)) {
  9012. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  9013. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9014. $out .= $comboenhancement;
  9015. $morecss = 'minwidth200imp maxwidth500';
  9016. }
  9017. if (empty($option_only)) {
  9018. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  9019. }
  9020. if (!empty($show_empty)) {
  9021. $out .= '<option value="0" class="optiongrey">';
  9022. if (!is_numeric($show_empty)) {
  9023. $out .= $show_empty;
  9024. } else {
  9025. $out .= '&nbsp;';
  9026. }
  9027. $out .= '</option>';
  9028. }
  9029. $num = $this->db->num_rows($resql);
  9030. $i = 0;
  9031. if ($num) {
  9032. while ($i < $num) {
  9033. $obj = $this->db->fetch_object($resql);
  9034. // 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.
  9035. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  9036. // Do nothing
  9037. } else {
  9038. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  9039. $i++;
  9040. continue;
  9041. }
  9042. $labeltoshow = '';
  9043. if ($showproject == 'all') {
  9044. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  9045. if ($obj->name) {
  9046. $labeltoshow .= ' - '.$obj->name; // Soc name
  9047. }
  9048. $disabled = 0;
  9049. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  9050. $disabled = 1;
  9051. $labeltoshow .= ' - '.$langs->trans("Draft");
  9052. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  9053. if ($discard_closed == 2) {
  9054. $disabled = 1;
  9055. }
  9056. $labeltoshow .= ' - '.$langs->trans("Closed");
  9057. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  9058. $disabled = 1;
  9059. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  9060. }
  9061. }
  9062. if (!empty($selected) && $selected == $obj->rowid) {
  9063. $out .= '<option value="'.$obj->rowid.'" selected';
  9064. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9065. $out .= '>'.$labeltoshow.'</option>';
  9066. } else {
  9067. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  9068. $resultat = '';
  9069. } else {
  9070. $resultat = '<option value="'.$obj->rowid.'"';
  9071. if ($disabled) {
  9072. $resultat .= ' disabled';
  9073. }
  9074. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  9075. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  9076. $resultat .= '>';
  9077. $resultat .= $labeltoshow;
  9078. $resultat .= '</option>';
  9079. }
  9080. $out .= $resultat;
  9081. }
  9082. }
  9083. $i++;
  9084. }
  9085. }
  9086. if (empty($option_only)) {
  9087. $out .= '</select>';
  9088. }
  9089. print $out;
  9090. $this->db->free($resql);
  9091. return $num;
  9092. } else {
  9093. dol_print_error($this->db);
  9094. return -1;
  9095. }
  9096. }
  9097. /**
  9098. * Output a combo list with invoices qualified for a third party
  9099. *
  9100. * @param int $selected Id invoice preselected
  9101. * @param string $htmlname Name of HTML select
  9102. * @param int $maxlength Maximum length of label
  9103. * @param int $option_only Return only html options lines without the select tag
  9104. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  9105. * @param int $forcefocus Force focus on field (works with javascript only)
  9106. * @param int $disabled Disabled
  9107. * @param string $morecss More css added to the select component
  9108. * @return int Nbr of project if OK, <0 if KO
  9109. */
  9110. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  9111. {
  9112. global $user, $conf, $langs;
  9113. $out = '';
  9114. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  9115. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  9116. //$sql.= ', el.fk_source';
  9117. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  9118. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  9119. $sql .= " ORDER BY f.titre ASC";
  9120. $resql = $this->db->query($sql);
  9121. if ($resql) {
  9122. // Use select2 selector
  9123. if (!empty($conf->use_javascript_ajax)) {
  9124. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9125. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9126. $out .= $comboenhancement;
  9127. $morecss = 'minwidth200imp maxwidth500';
  9128. }
  9129. if (empty($option_only)) {
  9130. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9131. }
  9132. if (!empty($show_empty)) {
  9133. $out .= '<option value="0" class="optiongrey">';
  9134. if (!is_numeric($show_empty)) {
  9135. $out .= $show_empty;
  9136. } else {
  9137. $out .= '&nbsp;';
  9138. }
  9139. $out .= '</option>';
  9140. }
  9141. $num = $this->db->num_rows($resql);
  9142. if ($num) {
  9143. while ($obj = $this->db->fetch_object($resql)) {
  9144. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9145. $disabled = 0;
  9146. if (!empty($obj->suspended)) {
  9147. $disabled = 1;
  9148. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9149. }
  9150. if (!empty($selected) && $selected == $obj->rowid) {
  9151. $out .= '<option value="' . $obj->rowid . '" selected';
  9152. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9153. $out .= '>' . $labeltoshow . '</option>';
  9154. } else {
  9155. if ($disabled && ($selected != $obj->rowid)) {
  9156. $resultat = '';
  9157. } else {
  9158. $resultat = '<option value="' . $obj->rowid . '"';
  9159. if ($disabled) {
  9160. $resultat .= ' disabled';
  9161. }
  9162. $resultat .= '>';
  9163. $resultat .= $labeltoshow;
  9164. $resultat .= '</option>';
  9165. }
  9166. $out .= $resultat;
  9167. }
  9168. }
  9169. }
  9170. if (empty($option_only)) {
  9171. $out .= '</select>';
  9172. }
  9173. print $out;
  9174. $this->db->free($resql);
  9175. return $num;
  9176. } else {
  9177. $this->errors[]=$this->db->lasterror;
  9178. return -1;
  9179. }
  9180. }
  9181. /**
  9182. * Output the component to make advanced search criteries
  9183. *
  9184. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9185. * @param array $search_component_params Array of selected search criterias
  9186. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9187. * @param string $search_component_params_hidden String with $search_component_params criterias
  9188. * @return string HTML component for advanced search
  9189. */
  9190. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9191. {
  9192. global $langs;
  9193. $ret = '';
  9194. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9195. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  9196. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9197. $ret .= '<span class="fas fa-filter linkobject boxfilter paddingright pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Filters")).'" id="idsubimgproductdistribution"></span>';
  9198. //$ret .= $langs->trans("Filters");
  9199. $ret .= '</a>';
  9200. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9201. // Show select fields as tags.
  9202. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9203. if ($search_component_params_hidden) {
  9204. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9205. $search_component_params_hidden .= '('.$search_component_params_hidden.')';
  9206. }
  9207. $errormessage = '';
  9208. $searchtags = forgeSQLFromUniversalSearchCriteria($search_component_params_hidden, $errormessage);
  9209. if ($errormessage) {
  9210. print 'ERROR in parsing search string: '.dol_escape_htmltag($errormessage);
  9211. }
  9212. //var_dump($searchtags);
  9213. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> '.dol_escape_htmltag($searchtags).'</span>';
  9214. }
  9215. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9216. //$ret .= search_component_params
  9217. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9218. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9219. $show_search_component_params_hidden = 1;
  9220. if ($show_search_component_params_hidden) {
  9221. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9222. }
  9223. $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%')) -->";
  9224. $ret .= '<input type="hidden" name="search_component_params_hidden" value="'.dol_escape_htmltag($search_component_params_hidden).'">';
  9225. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  9226. foreach ($arrayofcriterias as $criterias) {
  9227. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9228. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9229. continue;
  9230. }
  9231. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9232. continue;
  9233. }
  9234. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9235. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  9236. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  9237. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  9238. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  9239. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  9240. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  9241. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  9242. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  9243. } else {
  9244. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  9245. }
  9246. }
  9247. }
  9248. $ret .= '</div>';
  9249. $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";
  9250. $ret .= '<input type="text" placeholder="'.$langs->trans("Search").'" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9251. $ret .= '</div>';
  9252. $ret .= '</div>';
  9253. return $ret;
  9254. }
  9255. /**
  9256. * selectModelMail
  9257. *
  9258. * @param string $prefix Prefix
  9259. * @param string $modelType Model type
  9260. * @param int $default 1=Show also Default mail template
  9261. * @param int $addjscombo Add js combobox
  9262. * @return string HTML select string
  9263. */
  9264. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9265. {
  9266. global $langs, $user;
  9267. $retstring = '';
  9268. $TModels = array();
  9269. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  9270. $formmail = new FormMail($this->db);
  9271. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9272. if ($default) {
  9273. $TModels[0] = $langs->trans('DefaultMailModel');
  9274. }
  9275. if ($result > 0) {
  9276. foreach ($formmail->lines_model as $model) {
  9277. $TModels[$model->id] = $model->label;
  9278. }
  9279. }
  9280. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  9281. foreach ($TModels as $id_model => $label_model) {
  9282. $retstring .= '<option value="'.$id_model.'"';
  9283. $retstring .= ">".$label_model."</option>";
  9284. }
  9285. $retstring .= "</select>";
  9286. if ($addjscombo) {
  9287. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  9288. }
  9289. return $retstring;
  9290. }
  9291. /**
  9292. * Output the buttons to submit a creation/edit form
  9293. *
  9294. * @param string $save_label Alternative label for save button
  9295. * @param string $cancel_label Alternative label for cancel button
  9296. * @param array $morebuttons Add additional buttons between save and cancel
  9297. * @param bool $withoutdiv Option to remove enclosing centered div
  9298. * @param string $morecss More CSS
  9299. * @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.
  9300. * @return string Html code with the buttons
  9301. */
  9302. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9303. {
  9304. global $langs;
  9305. $buttons = array();
  9306. $save = array(
  9307. 'name' => 'save',
  9308. 'label_key' => $save_label,
  9309. );
  9310. if ($save_label == 'Create' || $save_label == 'Add' ) {
  9311. $save['name'] = 'add';
  9312. } elseif ($save_label == 'Modify') {
  9313. $save['name'] = 'edit';
  9314. }
  9315. $cancel = array(
  9316. 'name' => 'cancel',
  9317. 'label_key' => 'Cancel',
  9318. );
  9319. !empty($save_label) ? $buttons[] = $save : '';
  9320. if (!empty($morebuttons)) {
  9321. $buttons[] = $morebuttons;
  9322. }
  9323. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9324. $retstring = $withoutdiv ? '': '<div class="center">';
  9325. foreach ($buttons as $button) {
  9326. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9327. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  9328. }
  9329. $retstring .= $withoutdiv ? '': '</div>';
  9330. if ($dol_openinpopup) {
  9331. $retstring .= '<!-- buttons are shown into a $dol_openinpopup='.$dol_openinpopup.' context, so we enable the close of dialog on cancel -->'."\n";
  9332. $retstring .= '<script>';
  9333. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9334. e.preventDefault(); console.log(\'We click on cancel in iframe popup '.$dol_openinpopup.'\');
  9335. window.parent.jQuery(\'#idfordialog'.$dol_openinpopup.'\').dialog(\'close\');
  9336. });';
  9337. $retstring .= '</script>';
  9338. }
  9339. return $retstring;
  9340. }
  9341. }