html.form.class.php 427 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280
  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" 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';
  199. }
  200. // When option to edit inline is activated
  201. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|day|datepicker|dayhour|datehourpicker/', $typeofdata)) { // TODO add jquery timepicker and support select
  202. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  203. } else {
  204. $editmode = (GETPOST('action', 'aZ09') == 'edit'.$htmlname);
  205. if ($editmode) {
  206. $ret .= "\n";
  207. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  208. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  209. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  210. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  211. if (empty($notabletag)) {
  212. $ret .= '<table class="nobordernopadding centpercent">';
  213. }
  214. if (empty($notabletag)) {
  215. $ret .= '<tr><td>';
  216. }
  217. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata)) {
  218. $tmp = explode(':', $typeofdata);
  219. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
  220. } elseif (preg_match('/^(integer)/', $typeofdata)) {
  221. $tmp = explode(':', $typeofdata);
  222. $valuetoshow = price2num($editvalue ? $editvalue : $value, 0);
  223. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.$valuetoshow.'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
  224. } elseif (preg_match('/^(numeric|amount)/', $typeofdata)) {
  225. $tmp = explode(':', $typeofdata);
  226. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  227. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ? price($valuetoshow) : '').'"'.(empty($tmp[1]) ? '' : ' size="'.$tmp[1].'"').' autofocus>';
  228. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  229. $tmp = explode(':', $typeofdata);
  230. $ret .= '<input type="checkbox" id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . (empty($tmp[1]) ? '' : $tmp[1]) . '/>';
  231. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) { // if wysiwyg is enabled $typeofdata = 'ckeditor'
  232. $tmp = explode(':', $typeofdata);
  233. $cols = (empty($tmp[2]) ? '' : $tmp[2]);
  234. $morealt = '';
  235. if (preg_match('/%/', $cols)) {
  236. $morealt = ' style="width: '.$cols.'"';
  237. $cols = '';
  238. }
  239. $valuetoshow = ($editvalue ? $editvalue : $value);
  240. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.(empty($tmp[1]) ? '20' : $tmp[1]).'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  241. // textarea convert automatically entities chars into simple chars.
  242. // 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.
  243. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  244. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  245. $ret .= '</textarea>';
  246. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  247. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  248. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  249. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0, 0, '', '', '', '', 1, '', '', $gm);
  250. } elseif (preg_match('/^select;/', $typeofdata)) {
  251. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  252. $arraylist = array();
  253. foreach ($arraydata as $val) {
  254. $tmp = explode(':', $val);
  255. $tmpkey = str_replace('|', ':', $tmp[0]);
  256. $arraylist[$tmpkey] = $tmp[1];
  257. }
  258. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  259. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  260. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  261. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  262. $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]));
  263. $ret .= $doleditor->Create(1);
  264. }
  265. if (empty($notabletag)) {
  266. $ret .= '</td>';
  267. }
  268. // Button save-cancel
  269. if (empty($notabletag)) {
  270. $ret .= '<td class="left">';
  271. }
  272. //else $ret.='<div class="clearboth"></div>';
  273. $ret .= '<input type="submit" class="smallpaddingimp button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  274. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) {
  275. $ret .= '<br>'."\n";
  276. }
  277. $ret .= '<input type="submit" class="smallpaddingimp button button-cancel'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  278. if (empty($notabletag)) {
  279. $ret .= '</td>';
  280. }
  281. if (empty($notabletag)) {
  282. $ret .= '</tr></table>'."\n";
  283. }
  284. $ret .= '</form>'."\n";
  285. } else {
  286. if (preg_match('/^(email)/', $typeofdata)) {
  287. $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  288. } elseif (preg_match('/^(amount|numeric)/', $typeofdata)) {
  289. $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  290. } elseif (preg_match('/^(checkbox)/', $typeofdata)) {
  291. $tmp = explode(':', $typeofdata);
  292. $ret .= '<input type="checkbox" disabled id="' . $htmlname . '" name="' . $htmlname . '" value="' . $value . '"' . ($tmp[1] ? $tmp[1] : '') . '/>';
  293. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) {
  294. $ret .= dol_htmlentitiesbr($value);
  295. } elseif (preg_match('/^safehtmlstring/', $typeofdata)) {
  296. $ret .= dol_string_onlythesehtmltags($value);
  297. } elseif (preg_match('/^restricthtml/', $typeofdata)) {
  298. $ret .= dol_string_onlythesehtmltags($value);
  299. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
  300. $ret .= '<span class="valuedate">'.dol_print_date($value, 'day', $gm).'</span>';
  301. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
  302. $ret .= '<span class="valuedate">'.dol_print_date($value, 'dayhour', $gm).'</span>';
  303. } elseif (preg_match('/^select;/', $typeofdata)) {
  304. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  305. $arraylist = array();
  306. foreach ($arraydata as $val) {
  307. $tmp = explode(':', $val);
  308. $arraylist[$tmp[0]] = $tmp[1];
  309. }
  310. $ret .= $arraylist[$value];
  311. if ($htmlname == 'fk_product_type') {
  312. if ($value == 0) {
  313. $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  314. } else {
  315. $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret;
  316. }
  317. }
  318. } elseif (preg_match('/^ckeditor/', $typeofdata)) {
  319. $tmpcontent = dol_htmlentitiesbr($value);
  320. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  321. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  322. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  323. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  324. }
  325. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  326. // clean data from some dangerous html
  327. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  328. } else {
  329. $ret .= dol_escape_htmltag($value);
  330. }
  331. if ($formatfunc && method_exists($object, $formatfunc)) {
  332. $ret = $object->$formatfunc($ret);
  333. }
  334. }
  335. }
  336. return $ret;
  337. }
  338. /**
  339. * Output edit in place form
  340. *
  341. * @param string $fieldname Name of the field
  342. * @param object $object Object
  343. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  344. * @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]'...)
  345. * @param string $check Same coe than $check parameter of GETPOST()
  346. * @param string $morecss More CSS
  347. * @return string HTML code for the edit of alternative language
  348. */
  349. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  350. {
  351. global $conf, $langs, $extralanguages;
  352. $result = '';
  353. // List of extra languages
  354. $arrayoflangcode = array();
  355. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  356. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  357. }
  358. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  359. if (!is_object($extralanguages)) {
  360. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  361. $extralanguages = new ExtraLanguages($this->db);
  362. }
  363. $extralanguages->fetch_name_extralanguages('societe');
  364. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  365. return ''; // No extralang field to show
  366. }
  367. $result .= '<!-- Widget for translation -->'."\n";
  368. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  369. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  370. $result .= $s;
  371. $result .= '</div>';
  372. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  373. $resultforextrlang = '';
  374. foreach ($arrayoflangcode as $langcode) {
  375. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  376. if (empty($valuetoshow)) {
  377. $object->fetchValuesForExtraLanguages();
  378. //var_dump($object->array_languages);
  379. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  380. }
  381. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  382. $resultforextrlang .= $s;
  383. // TODO Use the showInputField() method of ExtraLanguages object
  384. if ($typeofdata == 'textarea') {
  385. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  386. $resultforextrlang .= $valuetoshow;
  387. $resultforextrlang .= '</textarea>';
  388. } else {
  389. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  390. }
  391. }
  392. $result .= $resultforextrlang;
  393. $result .= '</div>';
  394. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  395. }
  396. return $result;
  397. }
  398. /**
  399. * Output edit in place form
  400. *
  401. * @param object $object Object
  402. * @param string $value Value to show/edit
  403. * @param string $htmlname DIV ID (field name)
  404. * @param int $condition Condition to edit
  405. * @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')
  406. * @param string $editvalue When in edit mode, use this value as $value instead of value
  407. * @param object $extObject External object
  408. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  409. * @return string HTML edit in place
  410. */
  411. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  412. {
  413. global $conf;
  414. $out = '';
  415. // Check parameters
  416. if (preg_match('/^text/', $inputType)) {
  417. $value = dol_nl2br($value);
  418. } elseif (preg_match('/^numeric/', $inputType)) {
  419. $value = price($value);
  420. } elseif ($inputType == 'day' || $inputType == 'datepicker') {
  421. $value = dol_print_date($value, 'day');
  422. }
  423. if ($condition) {
  424. $element = false;
  425. $table_element = false;
  426. $fk_element = false;
  427. $loadmethod = false;
  428. $savemethod = false;
  429. $ext_element = false;
  430. $button_only = false;
  431. $inputOption = '';
  432. $rows = '';
  433. $cols = '';
  434. if (is_object($object)) {
  435. $element = $object->element;
  436. $table_element = $object->table_element;
  437. $fk_element = $object->id;
  438. }
  439. if (is_object($extObject)) {
  440. $ext_element = $extObject->element;
  441. }
  442. if (preg_match('/^(string|email|numeric)/', $inputType)) {
  443. $tmp = explode(':', $inputType);
  444. $inputType = $tmp[0];
  445. if (!empty($tmp[1])) {
  446. $inputOption = $tmp[1];
  447. }
  448. if (!empty($tmp[2])) {
  449. $savemethod = $tmp[2];
  450. }
  451. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  452. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType))) {
  453. $tmp = explode(':', $inputType);
  454. $inputType = $tmp[0];
  455. if (!empty($tmp[1])) {
  456. $inputOption = $tmp[1];
  457. }
  458. if (!empty($tmp[2])) {
  459. $savemethod = $tmp[2];
  460. }
  461. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  462. } elseif (preg_match('/^(select|autocomplete)/', $inputType)) {
  463. $tmp = explode(':', $inputType);
  464. $inputType = $tmp[0];
  465. $loadmethod = $tmp[1];
  466. if (!empty($tmp[2])) {
  467. $savemethod = $tmp[2];
  468. }
  469. if (!empty($tmp[3])) {
  470. $button_only = true;
  471. }
  472. } elseif (preg_match('/^textarea/', $inputType)) {
  473. $tmp = explode(':', $inputType);
  474. $inputType = $tmp[0];
  475. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  476. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  477. } elseif (preg_match('/^ckeditor/', $inputType)) {
  478. $tmp = explode(':', $inputType);
  479. $inputType = $tmp[0];
  480. $toolbar = $tmp[1];
  481. if (!empty($tmp[2])) {
  482. $width = $tmp[2];
  483. }
  484. if (!empty($tmp[3])) {
  485. $heigth = $tmp[3];
  486. }
  487. if (!empty($tmp[4])) {
  488. $savemethod = $tmp[4];
  489. }
  490. if (!empty($conf->fckeditor->enabled)) {
  491. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  492. } else {
  493. $inputType = 'textarea';
  494. }
  495. }
  496. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  497. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  498. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  499. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  500. if (!empty($savemethod)) {
  501. $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  502. }
  503. if (!empty($ext_element)) {
  504. $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  505. }
  506. if (!empty($custommsg)) {
  507. if (is_array($custommsg)) {
  508. if (!empty($custommsg['success'])) {
  509. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  510. }
  511. if (!empty($custommsg['error'])) {
  512. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  513. }
  514. } else {
  515. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  516. }
  517. }
  518. if ($inputType == 'textarea') {
  519. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  520. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  521. }
  522. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  523. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  524. } else {
  525. $out = $value;
  526. }
  527. return $out;
  528. }
  529. /**
  530. * Show a text and picto with tooltip on text or picto.
  531. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  532. *
  533. * @param string $text Text to show
  534. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  535. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  536. * @param int $direction -1=image is before, 0=no image, 1=image is after
  537. * @param string $img Html code for image (use img_xxx() function to get it)
  538. * @param string $extracss Add a CSS style to td tags
  539. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  540. * @param string $incbefore Include code before the text
  541. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  542. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  543. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  544. * @return string Code html du tooltip (texte+picto)
  545. * @see textwithpicto() Use thisfunction if you can.
  546. */
  547. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  548. {
  549. if ($incbefore) {
  550. $text = $incbefore.$text;
  551. }
  552. if (!$htmltext) {
  553. return $text;
  554. }
  555. $direction = (int) $direction; // For backward compatibility when $direction was set to '' instead of 0
  556. $tag = 'td';
  557. if ($notabs == 2) {
  558. $tag = 'div';
  559. }
  560. if ($notabs == 3) {
  561. $tag = 'span';
  562. }
  563. // Sanitize tooltip
  564. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  565. $extrastyle = '';
  566. if ($direction < 0) {
  567. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  568. $extrastyle = 'padding: 0px; padding-left: 3px !important;';
  569. }
  570. if ($direction > 0) {
  571. $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : '');
  572. $extrastyle = 'padding: 0px; padding-right: 3px !important;';
  573. }
  574. $classfortooltip = 'classfortooltip';
  575. $s = '';
  576. $textfordialog = '';
  577. if ($tooltiptrigger == '') {
  578. $htmltext = str_replace('"', '&quot;', $htmltext);
  579. } else {
  580. $classfortooltip = 'classfortooltiponclick';
  581. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  582. }
  583. if ($tooltipon == 2 || $tooltipon == 3) {
  584. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  585. if ($tooltiptrigger == '') {
  586. $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  587. } else {
  588. $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  589. }
  590. } else {
  591. $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  592. }
  593. if ($tooltipon == 1 || $tooltipon == 3) {
  594. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  595. if ($tooltiptrigger == '') {
  596. $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  597. } else {
  598. $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  599. }
  600. } else {
  601. $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  602. }
  603. if (empty($notabs)) {
  604. $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  605. } elseif ($notabs == 2) {
  606. $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  607. }
  608. // Define value if value is before
  609. if ($direction < 0) {
  610. $s .= '<'.$tag.$paramfortooltipimg;
  611. if ($tag == 'td') {
  612. $s .= ' class=valigntop" width="14"';
  613. }
  614. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  615. }
  616. // Use another method to help avoid having a space in value in order to use this value with jquery
  617. // Define label
  618. if ((string) $text != '') {
  619. $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  620. }
  621. // Define value if value is after
  622. if ($direction > 0) {
  623. $s .= '<'.$tag.$paramfortooltipimg;
  624. if ($tag == 'td') {
  625. $s .= ' class="valignmiddle" width="14"';
  626. }
  627. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  628. }
  629. if (empty($notabs)) {
  630. $s .= '</tr></table>';
  631. } elseif ($notabs == 2) {
  632. $s .= '</div>';
  633. }
  634. return $s;
  635. }
  636. /**
  637. * Show a text with a picto and a tooltip on picto
  638. *
  639. * @param string $text Text to show
  640. * @param string $htmltext Content of tooltip
  641. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  642. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  643. * @param string $extracss Add a CSS style to td, div or span tag
  644. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  645. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  646. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key, clickable link is on image or on link if param $type='none' or on both if $type='xxxclickable')
  647. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  648. * @return string HTML code of text, picto, tooltip
  649. */
  650. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  651. {
  652. global $conf, $langs;
  653. $alt = '';
  654. if ($tooltiptrigger) {
  655. $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  656. }
  657. //For backwards compatibility
  658. if ($type == '0') {
  659. $type = 'info';
  660. } elseif ($type == '1') {
  661. $type = 'help';
  662. }
  663. // If info or help with no javascript, show only text
  664. if (empty($conf->use_javascript_ajax)) {
  665. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  666. return $text;
  667. } else {
  668. $alt = $htmltext;
  669. $htmltext = '';
  670. }
  671. }
  672. // If info or help with smartphone, show only text (tooltip hover can't works)
  673. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger)) {
  674. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') {
  675. return $text;
  676. }
  677. }
  678. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  679. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  680. //{
  681. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  682. //}
  683. $img = '';
  684. if ($type == 'info') {
  685. $img = img_help(0, $alt);
  686. } elseif ($type == 'help') {
  687. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  688. } elseif ($type == 'helpclickable') {
  689. $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  690. } elseif ($type == 'superadmin') {
  691. $img = img_picto($alt, 'redstar');
  692. } elseif ($type == 'admin') {
  693. $img = img_picto($alt, 'star');
  694. } elseif ($type == 'warning') {
  695. $img = img_warning($alt);
  696. } elseif ($type != 'none') {
  697. $img = img_picto($alt, $type); // $type can be an image path
  698. }
  699. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  700. }
  701. /**
  702. * Generate select HTML to choose massaction
  703. *
  704. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  705. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  706. * @param int $alwaysvisible 1=select button always visible
  707. * @param string $name Name for massaction
  708. * @param string $cssclass CSS class used to check for select
  709. * @return string|void Select list
  710. */
  711. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  712. {
  713. global $conf, $langs, $hookmanager;
  714. $disabled = 0;
  715. $ret = '<div class="centpercent center">';
  716. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' '.$name.' '.$name.'select valignmiddle alignstart" id="'.$name.'" name="'.$name.'"'.($disabled ? ' disabled="disabled"' : '').'>';
  717. // 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.
  718. $parameters = array();
  719. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  720. // check if there is a mass action
  721. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) {
  722. return;
  723. }
  724. if (empty($reshook)) {
  725. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  726. foreach ($arrayofaction as $code => $label) {
  727. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  728. }
  729. }
  730. $ret .= $hookmanager->resPrint;
  731. $ret .= '</select>';
  732. if (empty($conf->dol_optimize_smallscreen)) {
  733. $ret .= ajax_combobox('.'.$name.'select');
  734. }
  735. // 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
  736. $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.
  737. $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")).'">';
  738. $ret .= '</div>';
  739. if (!empty($conf->use_javascript_ajax)) {
  740. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  741. <script>
  742. 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 */
  743. {
  744. atleastoneselected=0;
  745. jQuery("."+cssclass).each(function( index ) {
  746. /* console.log( index + ": " + $( this ).text() ); */
  747. if ($(this).is(\':checked\')) atleastoneselected++;
  748. });
  749. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  750. if (atleastoneselected || '.$alwaysvisible.')
  751. {
  752. jQuery("."+name).show();
  753. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  754. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  755. }
  756. else
  757. {
  758. jQuery("."+name).hide();
  759. jQuery("."+name+"other").hide();
  760. }
  761. }
  762. jQuery(document).ready(function () {
  763. initCheckForSelect(0, "' . $name.'", "'.$cssclass.'");
  764. jQuery(".' . $cssclass.'").click(function() {
  765. initCheckForSelect(1, "'.$name.'", "'.$cssclass.'");
  766. });
  767. jQuery(".' . $name.'select").change(function() {
  768. var massaction = $( this ).val();
  769. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  770. if (massaction == "builddoc")
  771. {
  772. urlform = urlform + "#show_files";
  773. }
  774. $( this ).closest("form").attr("action", urlform);
  775. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  776. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  777. if ($(this).val() != \'0\')
  778. {
  779. jQuery(".' . $name.'confirmed").prop(\'disabled\', false);
  780. jQuery(".' . $name.'other").hide(); /* To disable if another div was open */
  781. jQuery(".' . $name.'"+massaction).show();
  782. }
  783. else
  784. {
  785. jQuery(".' . $name.'confirmed").prop(\'disabled\', true);
  786. jQuery(".' . $name.'other").hide(); /* To disable any div open */
  787. }
  788. });
  789. });
  790. </script>
  791. ';
  792. }
  793. return $ret;
  794. }
  795. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  796. /**
  797. * Return combo list of activated countries, into language of user
  798. *
  799. * @param string $selected Id or Code or Label of preselected country
  800. * @param string $htmlname Name of html select object
  801. * @param string $htmloption More html options on select object
  802. * @param integer $maxlength Max length for labels (0=no limit)
  803. * @param string $morecss More css class
  804. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  805. * @param int|string $showempty Show empty choice
  806. * @param int $disablefavorites 1=Disable favorites,
  807. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  808. * @param array $exclude_country_code Array of country code (iso2) to exclude
  809. * @param int $hideflags Hide flags
  810. * @return string HTML string with select
  811. */
  812. 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)
  813. {
  814. // phpcs:enable
  815. global $conf, $langs, $mysoc;
  816. $langs->load("dict");
  817. $out = '';
  818. $countryArray = array();
  819. $favorite = array();
  820. $label = array();
  821. $atleastonefavorite = 0;
  822. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite, eec";
  823. $sql .= " FROM ".$this->db->prefix()."c_country";
  824. $sql .= " WHERE active > 0";
  825. //$sql.= " ORDER BY code ASC";
  826. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  827. $resql = $this->db->query($sql);
  828. if ($resql) {
  829. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  830. $num = $this->db->num_rows($resql);
  831. $i = 0;
  832. if ($num) {
  833. while ($i < $num) {
  834. $obj = $this->db->fetch_object($resql);
  835. $countryArray[$i]['rowid'] = $obj->rowid;
  836. $countryArray[$i]['code_iso'] = $obj->code_iso;
  837. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  838. $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 : ''));
  839. $countryArray[$i]['favorite'] = $obj->favorite;
  840. $countryArray[$i]['eec'] = $obj->eec;
  841. $favorite[$i] = $obj->favorite;
  842. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  843. $i++;
  844. }
  845. if (empty($disablefavorites)) {
  846. $array1_sort_order = SORT_DESC;
  847. $array2_sort_order = SORT_ASC;
  848. array_multisort($favorite, $array1_sort_order, $label, $array2_sort_order, $countryArray);
  849. } else {
  850. $countryArray = dol_sort_array($countryArray, 'label');
  851. }
  852. if ($showempty) {
  853. if (is_numeric($showempty)) {
  854. $out .= '<option value="">&nbsp;</option>'."\n";
  855. } else {
  856. $out .= '<option value="">'.$langs->trans($showempty).'</option>'."\n";
  857. }
  858. }
  859. if ($addspecialentries) { // Add dedicated entries for groups of countries
  860. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  861. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  862. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  863. if ($mysoc->isInEEC()) {
  864. $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  865. }
  866. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  867. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  868. }
  869. foreach ($countryArray as $row) {
  870. //if (empty($showempty) && empty($row['rowid'])) continue;
  871. if (empty($row['rowid'])) {
  872. continue;
  873. }
  874. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) {
  875. continue; // exclude some countries
  876. }
  877. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
  878. $atleastonefavorite++;
  879. }
  880. if (empty($row['favorite']) && $atleastonefavorite) {
  881. $atleastonefavorite = 0;
  882. $out .= '<option value="" disabled class="selectoptiondisabledwhite">------------</option>';
  883. }
  884. $labeltoshow = '';
  885. if ($row['label']) {
  886. $labeltoshow .= dol_trunc($row['label'], $maxlength, 'middle');
  887. } else {
  888. $labeltoshow .= '&nbsp;';
  889. }
  890. if ($row['code_iso']) {
  891. $labeltoshow .= ' <span class="opacitymedium">('.$row['code_iso'].')</span>';
  892. if (empty($hideflags)) {
  893. $tmpflag = picto_from_langcode($row['code_iso'], 'class="saturatemedium paddingrightonly"', 1);
  894. $labeltoshow = $tmpflag.' '.$labeltoshow;
  895. }
  896. }
  897. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label'])) {
  898. $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']).'">';
  899. } else {
  900. $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']).'">';
  901. }
  902. $out .= $labeltoshow;
  903. $out .= '</option>'."\n";
  904. }
  905. }
  906. $out .= '</select>';
  907. } else {
  908. dol_print_error($this->db);
  909. }
  910. // Make select dynamic
  911. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  912. $out .= ajax_combobox('select'.$htmlname, array(), 0, 0, 'resolve');
  913. return $out;
  914. }
  915. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  916. /**
  917. * Return select list of incoterms
  918. *
  919. * @param string $selected Id or Code of preselected incoterm
  920. * @param string $location_incoterms Value of input location
  921. * @param string $page Defined the form action
  922. * @param string $htmlname Name of html select object
  923. * @param string $htmloption Options html on select object
  924. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  925. * @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')))
  926. * @param array $disableautocomplete Disable autocomplete
  927. * @return string HTML string with select and input
  928. */
  929. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array(), $disableautocomplete = 0)
  930. {
  931. // phpcs:enable
  932. global $conf, $langs;
  933. $langs->load("dict");
  934. $out = '';
  935. $moreattrib = '';
  936. $incotermArray = array();
  937. $sql = "SELECT rowid, code";
  938. $sql .= " FROM ".$this->db->prefix()."c_incoterms";
  939. $sql .= " WHERE active > 0";
  940. $sql .= " ORDER BY code ASC";
  941. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  942. $resql = $this->db->query($sql);
  943. if ($resql) {
  944. if ($conf->use_javascript_ajax && !$forcecombo) {
  945. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  946. $out .= ajax_combobox($htmlname, $events);
  947. }
  948. if (!empty($page)) {
  949. $out .= '<form method="post" action="'.$page.'">';
  950. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  951. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  952. }
  953. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm width75" name="'.$htmlname.'" '.$htmloption.'>';
  954. $out .= '<option value="0">&nbsp;</option>';
  955. $num = $this->db->num_rows($resql);
  956. $i = 0;
  957. if ($num) {
  958. while ($i < $num) {
  959. $obj = $this->db->fetch_object($resql);
  960. $incotermArray[$i]['rowid'] = $obj->rowid;
  961. $incotermArray[$i]['code'] = $obj->code;
  962. $i++;
  963. }
  964. foreach ($incotermArray as $row) {
  965. if ($selected && ($selected == $row['rowid'] || $selected == $row['code'])) {
  966. $out .= '<option value="'.$row['rowid'].'" selected>';
  967. } else {
  968. $out .= '<option value="'.$row['rowid'].'">';
  969. }
  970. if ($row['code']) {
  971. $out .= $row['code'];
  972. }
  973. $out .= '</option>';
  974. }
  975. }
  976. $out .= '</select>';
  977. if ($conf->use_javascript_ajax && empty($disableautocomplete)) {
  978. $out .= ajax_multiautocompleter('location_incoterms', '', DOL_URL_ROOT.'/core/ajax/locationincoterms.php')."\n";
  979. $moreattrib .= ' autocomplete="off"';
  980. }
  981. $out .= '<input id="location_incoterms" class="maxwidthonsmartphone type="text" name="location_incoterms" value="'.$location_incoterms.'">'."\n";
  982. if (!empty($page)) {
  983. $out .= '<input type="submit" class="button valignmiddle smallpaddingimp nomargintop nomarginbottom" value="'.$langs->trans("Modify").'"></form>';
  984. }
  985. } else {
  986. dol_print_error($this->db);
  987. }
  988. return $out;
  989. }
  990. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  991. /**
  992. * Return list of types of lines (product or service)
  993. * Example: 0=product, 1=service, 9=other (for external module)
  994. *
  995. * @param string $selected Preselected type
  996. * @param string $htmlname Name of field in html form
  997. * @param int $showempty Add an empty field
  998. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  999. * @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')
  1000. * @return void
  1001. */
  1002. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  1003. {
  1004. // phpcs:enable
  1005. global $langs, $conf;
  1006. // If product & services are enabled or both disabled.
  1007. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  1008. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled))) {
  1009. if (empty($hidetext)) {
  1010. print $langs->trans("Type").': ';
  1011. }
  1012. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  1013. if ($showempty) {
  1014. print '<option value="-1"';
  1015. if ($selected == -1) {
  1016. print ' selected';
  1017. }
  1018. print '>&nbsp;</option>';
  1019. }
  1020. print '<option value="0"';
  1021. if (0 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'product')) {
  1022. print ' selected';
  1023. }
  1024. print '>'.$langs->trans("Product");
  1025. print '<option value="1"';
  1026. if (1 == $selected || ($selected == -1 && getDolGlobalString('MAIN_FREE_PRODUCT_CHECKED_BY_DEFAULT') == 'service')) {
  1027. print ' selected';
  1028. }
  1029. print '>'.$langs->trans("Service");
  1030. print '</select>';
  1031. print ajax_combobox('select_'.$htmlname);
  1032. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  1033. }
  1034. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3) {
  1035. print $langs->trans("Service");
  1036. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  1037. }
  1038. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2) {
  1039. print $langs->trans("Product");
  1040. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  1041. }
  1042. if ($forceall < 0) { // This should happened only for contracts when both predefined product and service are disabled.
  1043. 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
  1044. }
  1045. }
  1046. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1047. /**
  1048. * Load into cache cache_types_fees, array of types of fees
  1049. *
  1050. * @return int Nb of lines loaded, <0 if KO
  1051. */
  1052. public function load_cache_types_fees()
  1053. {
  1054. // phpcs:enable
  1055. global $langs;
  1056. $num = count($this->cache_types_fees);
  1057. if ($num > 0) {
  1058. return 0; // Cache already loaded
  1059. }
  1060. dol_syslog(__METHOD__, LOG_DEBUG);
  1061. $langs->load("trips");
  1062. $sql = "SELECT c.code, c.label";
  1063. $sql .= " FROM ".$this->db->prefix()."c_type_fees as c";
  1064. $sql .= " WHERE active > 0";
  1065. $resql = $this->db->query($sql);
  1066. if ($resql) {
  1067. $num = $this->db->num_rows($resql);
  1068. $i = 0;
  1069. while ($i < $num) {
  1070. $obj = $this->db->fetch_object($resql);
  1071. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  1072. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  1073. $this->cache_types_fees[$obj->code] = $label;
  1074. $i++;
  1075. }
  1076. asort($this->cache_types_fees);
  1077. return $num;
  1078. } else {
  1079. dol_print_error($this->db);
  1080. return -1;
  1081. }
  1082. }
  1083. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1084. /**
  1085. * Return list of types of notes
  1086. *
  1087. * @param string $selected Preselected type
  1088. * @param string $htmlname Name of field in form
  1089. * @param int $showempty Add an empty field
  1090. * @return void
  1091. */
  1092. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  1093. {
  1094. // phpcs:enable
  1095. global $user, $langs;
  1096. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  1097. $this->load_cache_types_fees();
  1098. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  1099. if ($showempty) {
  1100. print '<option value="-1"';
  1101. if ($selected == -1) {
  1102. print ' selected';
  1103. }
  1104. print '>&nbsp;</option>';
  1105. }
  1106. foreach ($this->cache_types_fees as $key => $value) {
  1107. print '<option value="'.$key.'"';
  1108. if ($key == $selected) {
  1109. print ' selected';
  1110. }
  1111. print '>';
  1112. print $value;
  1113. print '</option>';
  1114. }
  1115. print '</select>';
  1116. if ($user->admin) {
  1117. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  1118. }
  1119. }
  1120. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1121. /**
  1122. * Output html form to select a third party
  1123. *
  1124. * @param string $selected Preselected type
  1125. * @param string $htmlname Name of field in form
  1126. * @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)')
  1127. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  1128. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1129. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  1130. * @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')))
  1131. * @param int $limit Maximum number of elements
  1132. * @param string $morecss Add more css styles to the SELECT component
  1133. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1134. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1135. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1136. * @param array $ajaxoptions Options for ajax_autocompleter
  1137. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1138. * @param array $excludeids Exclude IDs from the select combo
  1139. * @param int $showcode Show code
  1140. * @return string HTML string with select box for thirdparty.
  1141. */
  1142. 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)
  1143. {
  1144. // phpcs:enable
  1145. global $conf, $user, $langs;
  1146. $out = '';
  1147. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo) {
  1148. if (is_null($ajaxoptions)) {
  1149. $ajaxoptions = array();
  1150. }
  1151. require_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1152. // No immediate load of all database
  1153. $placeholder = '';
  1154. if ($selected && empty($selected_input_value)) {
  1155. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1156. $societetmp = new Societe($this->db);
  1157. $societetmp->fetch($selected);
  1158. $selected_input_value = $societetmp->name;
  1159. unset($societetmp);
  1160. }
  1161. // mode 1
  1162. $urloption = 'htmlname='.urlencode(str_replace('.', '_', $htmlname)).'&outjson=1&filter='.urlencode($filter).(empty($excludeids) ? '' : '&excludeids='.join(',', $excludeids)).($showtype ? '&showtype='.urlencode($showtype) : '').($showcode ? '&showcode='.urlencode($showcode) : '');
  1163. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  1164. if (empty($hidelabel)) {
  1165. print $langs->trans("RefOrLabel").' : ';
  1166. } elseif ($hidelabel > 1) {
  1167. $placeholder = $langs->trans("RefOrLabel");
  1168. if ($hidelabel == 2) {
  1169. $out .= img_picto($langs->trans("Search"), 'search');
  1170. }
  1171. }
  1172. $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' : '').' />';
  1173. if ($hidelabel == 3) {
  1174. $out .= img_picto($langs->trans("Search"), 'search');
  1175. }
  1176. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1177. } else {
  1178. // Immediate load of all database
  1179. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple, $excludeids, $showcode);
  1180. }
  1181. return $out;
  1182. }
  1183. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1184. /**
  1185. * Output html form to select a third party.
  1186. * 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.
  1187. *
  1188. * @param string $selected Preselected type
  1189. * @param string $htmlname Name of field in form
  1190. * @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.
  1191. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1192. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1193. * @param int $forcecombo Force to use standard HTML select component without beautification
  1194. * @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')))
  1195. * @param string $filterkey Filter on key value
  1196. * @param int $outputmode 0=HTML select string, 1=Array
  1197. * @param int $limit Limit number of answers
  1198. * @param string $morecss Add more css styles to the SELECT component
  1199. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1200. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1201. * @param array $excludeids Exclude IDs from the select combo
  1202. * @param int $showcode Show code in list
  1203. * @return string HTML string with
  1204. */
  1205. 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)
  1206. {
  1207. // phpcs:enable
  1208. global $conf, $user, $langs;
  1209. global $hookmanager;
  1210. $out = '';
  1211. $num = 0;
  1212. $outarray = array();
  1213. if ($selected === '') {
  1214. $selected = array();
  1215. } elseif (!is_array($selected)) {
  1216. $selected = array($selected);
  1217. }
  1218. // Clean $filter that may contains sql conditions so sql code
  1219. if (function_exists('testSqlAndScriptInject')) {
  1220. if (testSqlAndScriptInject($filter, 3) > 0) {
  1221. $filter = '';
  1222. }
  1223. }
  1224. // We search companies
  1225. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.tva_intra, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1226. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1227. $sql .= ", s.address, s.zip, s.town";
  1228. $sql .= ", dictp.code as country_code";
  1229. }
  1230. $sql .= " FROM ".$this->db->prefix()."societe as s";
  1231. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1232. $sql .= " LEFT JOIN ".$this->db->prefix()."c_country as dictp ON dictp.rowid = s.fk_pays";
  1233. }
  1234. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1235. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  1236. }
  1237. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1238. if (!empty($user->socid)) {
  1239. $sql .= " AND s.rowid = ".((int) $user->socid);
  1240. }
  1241. if ($filter) {
  1242. $sql .= " AND (".$filter.")";
  1243. }
  1244. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  1245. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  1246. }
  1247. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
  1248. $sql .= " AND s.status <> 0";
  1249. }
  1250. if (!empty($excludeids)) {
  1251. $sql .= " AND s.rowid NOT IN (".$this->db->sanitize(join(',', $excludeids)).")";
  1252. }
  1253. // Add where from hooks
  1254. $parameters = array();
  1255. $reshook = $hookmanager->executeHooks('selectThirdpartyListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1256. $sql .= $hookmanager->resPrint;
  1257. // Add criteria
  1258. if ($filterkey && $filterkey != '') {
  1259. $sql .= " AND (";
  1260. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1261. // For natural search
  1262. $scrit = explode(' ', $filterkey);
  1263. $i = 0;
  1264. if (count($scrit) > 1) {
  1265. $sql .= "(";
  1266. }
  1267. foreach ($scrit as $crit) {
  1268. if ($i > 0) {
  1269. $sql .= " AND ";
  1270. }
  1271. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1272. $i++;
  1273. }
  1274. if (count($scrit) > 1) {
  1275. $sql .= ")";
  1276. }
  1277. if (!empty($conf->barcode->enabled)) {
  1278. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1279. }
  1280. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1281. $sql .= " OR s.name_alias LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.tva_intra LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1282. $sql .= ")";
  1283. }
  1284. $sql .= $this->db->order("nom", "ASC");
  1285. $sql .= $this->db->plimit($limit, 0);
  1286. // Build output string
  1287. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1288. $resql = $this->db->query($sql);
  1289. if ($resql) {
  1290. if (!$forcecombo) {
  1291. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1292. $out .= ajax_combobox($htmlname, $events, getDolGlobalString("COMPANY_USE_SEARCH_TO_SELECT"));
  1293. }
  1294. // Construct $out and $outarray
  1295. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1296. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1297. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) {
  1298. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1299. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1300. if ($showempty && !is_numeric($showempty)) {
  1301. $textifempty = $langs->trans($showempty);
  1302. } else {
  1303. $textifempty .= $langs->trans("All");
  1304. }
  1305. }
  1306. if ($showempty) {
  1307. $out .= '<option value="-1" data-html="'.dol_escape_htmltag('<span class="opacitymedium">'.($textifempty ? $textifempty : '&nbsp;').'</span>').'">'.$textifempty.'</option>'."\n";
  1308. }
  1309. $companytemp = new Societe($this->db);
  1310. $num = $this->db->num_rows($resql);
  1311. $i = 0;
  1312. if ($num) {
  1313. while ($i < $num) {
  1314. $obj = $this->db->fetch_object($resql);
  1315. $label = '';
  1316. if ($showcode || !empty($conf->global->SOCIETE_ADD_REF_IN_LIST)) {
  1317. if (($obj->client) && (!empty($obj->code_client))) {
  1318. $label = $obj->code_client.' - ';
  1319. }
  1320. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1321. $label .= $obj->code_fournisseur.' - ';
  1322. }
  1323. $label .= ' '.$obj->name;
  1324. } else {
  1325. $label = $obj->name;
  1326. }
  1327. if (!empty($obj->name_alias)) {
  1328. $label .= ' ('.$obj->name_alias.')';
  1329. }
  1330. if (!empty($conf->global->SOCIETE_SHOW_VAT_IN_LIST) && !empty($obj->tva_intra)) {
  1331. $label .= ' - '.$obj->tva_intra.'';
  1332. }
  1333. $labelhtml = $label;
  1334. if ($showtype) {
  1335. $companytemp->id = $obj->rowid;
  1336. $companytemp->client = $obj->client;
  1337. $companytemp->fournisseur = $obj->fournisseur;
  1338. $tmptype = $companytemp->getTypeUrl(1, '', 0, 'span');
  1339. if ($tmptype) {
  1340. $labelhtml .= ' '.$tmptype;
  1341. }
  1342. if ($obj->client || $obj->fournisseur) {
  1343. $label .= ' (';
  1344. }
  1345. if ($obj->client == 1 || $obj->client == 3) {
  1346. $label .= $langs->trans("Customer");
  1347. }
  1348. if ($obj->client == 2 || $obj->client == 3) {
  1349. $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1350. }
  1351. if ($obj->fournisseur) {
  1352. $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1353. }
  1354. if ($obj->client || $obj->fournisseur) {
  1355. $label .= ')';
  1356. }
  1357. }
  1358. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  1359. $s = ($obj->address ? ' - '.$obj->address : '').($obj->zip ? ' - '.$obj->zip : '').($obj->town ? ' '.$obj->town : '');
  1360. if (!empty($obj->country_code)) {
  1361. $s .= ', '.$langs->trans('Country'.$obj->country_code);
  1362. }
  1363. $label .= $s;
  1364. $labelhtml .= $s;
  1365. }
  1366. if (empty($outputmode)) {
  1367. if (in_array($obj->rowid, $selected)) {
  1368. $out .= '<option value="'.$obj->rowid.'" selected data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
  1369. } else {
  1370. $out .= '<option value="'.$obj->rowid.'" data-html="'.dol_escape_htmltag($labelhtml).'">'.$label.'</option>';
  1371. }
  1372. } else {
  1373. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label, 'labelhtml'=>$labelhtml));
  1374. }
  1375. $i++;
  1376. if (($i % 10) == 0) {
  1377. $out .= "\n";
  1378. }
  1379. }
  1380. }
  1381. $out .= '</select>'."\n";
  1382. } else {
  1383. dol_print_error($this->db);
  1384. }
  1385. $this->result = array('nbofthirdparties'=>$num);
  1386. if ($outputmode) {
  1387. return $outarray;
  1388. }
  1389. return $out;
  1390. }
  1391. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1392. /**
  1393. * Return HTML combo list of absolute discounts
  1394. *
  1395. * @param string $selected Id remise fixe pre-selectionnee
  1396. * @param string $htmlname Nom champ formulaire
  1397. * @param string $filter Criteres optionnels de filtre
  1398. * @param int $socid Id of thirdparty
  1399. * @param int $maxvalue Max value for lines that can be selected
  1400. * @return int Return number of qualifed lines in list
  1401. */
  1402. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1403. {
  1404. // phpcs:enable
  1405. global $langs, $conf;
  1406. // On recherche les remises
  1407. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1408. $sql .= " re.description, re.fk_facture_source";
  1409. $sql .= " FROM ".$this->db->prefix()."societe_remise_except as re";
  1410. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1411. $sql .= " AND re.entity = ".$conf->entity;
  1412. if ($filter) {
  1413. $sql .= " AND ".$filter;
  1414. }
  1415. $sql .= " ORDER BY re.description ASC";
  1416. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1417. $resql = $this->db->query($sql);
  1418. if ($resql) {
  1419. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1420. $num = $this->db->num_rows($resql);
  1421. $qualifiedlines = $num;
  1422. $i = 0;
  1423. if ($num) {
  1424. print '<option value="0">&nbsp;</option>';
  1425. while ($i < $num) {
  1426. $obj = $this->db->fetch_object($resql);
  1427. $desc = dol_trunc($obj->description, 40);
  1428. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
  1429. $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1430. }
  1431. if (preg_match('/\(DEPOSIT\)/', $desc)) {
  1432. $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1433. }
  1434. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
  1435. $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1436. }
  1437. if (preg_match('/\(EXCESS PAID\)/', $desc)) {
  1438. $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1439. }
  1440. $selectstring = '';
  1441. if ($selected > 0 && $selected == $obj->rowid) {
  1442. $selectstring = ' selected';
  1443. }
  1444. $disabled = '';
  1445. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue) {
  1446. $qualifiedlines--;
  1447. $disabled = ' disabled';
  1448. }
  1449. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source)) {
  1450. $tmpfac = new Facture($this->db);
  1451. if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
  1452. $desc = $desc.' - '.$tmpfac->ref;
  1453. }
  1454. }
  1455. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1456. $i++;
  1457. }
  1458. }
  1459. print '</select>';
  1460. print ajax_combobox('select_'.$htmlname);
  1461. return $qualifiedlines;
  1462. } else {
  1463. dol_print_error($this->db);
  1464. return -1;
  1465. }
  1466. }
  1467. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1468. /**
  1469. * Return list of all contacts (for a third party or all)
  1470. *
  1471. * @param int $socid Id ot third party or 0 for all
  1472. * @param string $selected Id contact pre-selectionne
  1473. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1474. * @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
  1475. * @param string $exclude List of contacts id to exclude
  1476. * @param string $limitto Disable answers that are not id in this array list
  1477. * @param integer $showfunction Add function into label
  1478. * @param string $morecss Add more class to class style
  1479. * @param integer $showsoc Add company into label
  1480. * @param int $forcecombo Force to use combo box
  1481. * @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')))
  1482. * @param bool $options_only Return options only (for ajax treatment)
  1483. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1484. * @param string $htmlid Html id to use instead of htmlname
  1485. * @return int <0 if KO, Nb of contact in list if OK
  1486. * @deprecated You can use selectcontacts directly (warning order of param was changed)
  1487. */
  1488. 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 = '')
  1489. {
  1490. // phpcs:enable
  1491. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $morecss, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1492. return $this->num;
  1493. }
  1494. /**
  1495. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1496. * This also set the number of contacts found into $this->num
  1497. *
  1498. * @since 9.0 Add afterSelectContactOptions hook
  1499. *
  1500. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1501. * @param array|int $selected Array of ID of pre-selected contact id
  1502. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1503. * @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
  1504. * @param string $exclude List of contacts id to exclude
  1505. * @param string $limitto Disable answers that are not id in this array list
  1506. * @param integer $showfunction Add function into label
  1507. * @param string $morecss Add more class to class style
  1508. * @param bool $options_only Return options only (for ajax treatment)
  1509. * @param integer $showsoc Add company into label
  1510. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1511. * @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')))
  1512. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1513. * @param string $htmlid Html id to use instead of htmlname
  1514. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1515. * @param integer $disableifempty Set tag 'disabled' on select if there is no choice
  1516. * @return int|string <0 if KO, HTML with select string if OK.
  1517. */
  1518. 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)
  1519. {
  1520. global $conf, $langs, $hookmanager, $action;
  1521. $langs->load('companies');
  1522. if (empty($htmlid)) {
  1523. $htmlid = $htmlname;
  1524. }
  1525. $num = 0;
  1526. if ($selected === '') {
  1527. $selected = array();
  1528. } elseif (!is_array($selected)) {
  1529. $selected = array($selected);
  1530. }
  1531. $out = '';
  1532. if (!is_object($hookmanager)) {
  1533. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1534. $hookmanager = new HookManager($this->db);
  1535. }
  1536. // We search third parties
  1537. $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";
  1538. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1539. $sql .= ", s.nom as company, s.town AS company_town";
  1540. }
  1541. $sql .= " FROM ".$this->db->prefix()."socpeople as sp";
  1542. if ($showsoc > 0 || !empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1543. $sql .= " LEFT OUTER JOIN ".$this->db->prefix()."societe as s ON s.rowid=sp.fk_soc";
  1544. }
  1545. $sql .= " WHERE sp.entity IN (".getEntity('contact').")";
  1546. if ($socid > 0 || $socid == -1) {
  1547. $sql .= " AND sp.fk_soc = ".((int) $socid);
  1548. }
  1549. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
  1550. $sql .= " AND sp.statut <> 0";
  1551. }
  1552. // Add where from hooks
  1553. $parameters = array();
  1554. $reshook = $hookmanager->executeHooks('selectContactListWhere', $parameters); // Note that $action and $object may have been modified by hook
  1555. $sql .= $hookmanager->resPrint;
  1556. $sql .= " ORDER BY sp.lastname ASC";
  1557. dol_syslog(get_class($this)."::selectcontacts", LOG_DEBUG);
  1558. $resql = $this->db->query($sql);
  1559. if ($resql) {
  1560. $num = $this->db->num_rows($resql);
  1561. if ($htmlname != 'none' && !$options_only) {
  1562. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlid.'" name="'.$htmlname.(($num || empty($disableifempty)) ? '' : ' disabled').($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1563. }
  1564. if ($showempty && ! is_numeric($showempty)) {
  1565. $textforempty = $showempty;
  1566. $out .= '<option class="optiongrey" value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>'.$textforempty.'</option>';
  1567. } else {
  1568. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && ! $multiple) {
  1569. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1570. }
  1571. if ($showempty == 2) {
  1572. $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1573. }
  1574. }
  1575. $i = 0;
  1576. if ($num) {
  1577. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1578. $contactstatic = new Contact($this->db);
  1579. while ($i < $num) {
  1580. $obj = $this->db->fetch_object($resql);
  1581. // Set email (or phones) and town extended infos
  1582. $extendedInfos = '';
  1583. if (!empty($conf->global->CONTACT_SHOW_EMAIL_PHONE_TOWN_SELECTLIST)) {
  1584. $extendedInfos = array();
  1585. $email = trim($obj->email);
  1586. if (!empty($email)) {
  1587. $extendedInfos[] = $email;
  1588. } else {
  1589. $phone = trim($obj->phone);
  1590. $phone_perso = trim($obj->phone_perso);
  1591. $phone_mobile = trim($obj->phone_mobile);
  1592. if (!empty($phone)) {
  1593. $extendedInfos[] = $phone;
  1594. }
  1595. if (!empty($phone_perso)) {
  1596. $extendedInfos[] = $phone_perso;
  1597. }
  1598. if (!empty($phone_mobile)) {
  1599. $extendedInfos[] = $phone_mobile;
  1600. }
  1601. }
  1602. $contact_town = trim($obj->contact_town);
  1603. $company_town = trim($obj->company_town);
  1604. if (!empty($contact_town)) {
  1605. $extendedInfos[] = $contact_town;
  1606. } elseif (!empty($company_town)) {
  1607. $extendedInfos[] = $company_town;
  1608. }
  1609. $extendedInfos = implode(' - ', $extendedInfos);
  1610. if (!empty($extendedInfos)) {
  1611. $extendedInfos = ' - '.$extendedInfos;
  1612. }
  1613. }
  1614. $contactstatic->id = $obj->rowid;
  1615. $contactstatic->lastname = $obj->lastname;
  1616. $contactstatic->firstname = $obj->firstname;
  1617. if ($obj->statut == 1) {
  1618. if ($htmlname != 'none') {
  1619. $disabled = 0;
  1620. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) {
  1621. $disabled = 1;
  1622. }
  1623. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) {
  1624. $disabled = 1;
  1625. }
  1626. if (!empty($selected) && in_array($obj->rowid, $selected)) {
  1627. $out .= '<option value="'.$obj->rowid.'"';
  1628. if ($disabled) {
  1629. $out .= ' disabled';
  1630. }
  1631. $out .= ' selected>';
  1632. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1633. if ($showfunction && $obj->poste) {
  1634. $out .= ' ('.$obj->poste.')';
  1635. }
  1636. if (($showsoc > 0) && $obj->company) {
  1637. $out .= ' - ('.$obj->company.')';
  1638. }
  1639. $out .= '</option>';
  1640. } else {
  1641. $out .= '<option value="'.$obj->rowid.'"';
  1642. if ($disabled) {
  1643. $out .= ' disabled';
  1644. }
  1645. $out .= '>';
  1646. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1647. if ($showfunction && $obj->poste) {
  1648. $out .= ' ('.$obj->poste.')';
  1649. }
  1650. if (($showsoc > 0) && $obj->company) {
  1651. $out .= ' - ('.$obj->company.')';
  1652. }
  1653. $out .= '</option>';
  1654. }
  1655. } else {
  1656. if (in_array($obj->rowid, $selected)) {
  1657. $out .= $contactstatic->getFullName($langs).$extendedInfos;
  1658. if ($showfunction && $obj->poste) {
  1659. $out .= ' ('.$obj->poste.')';
  1660. }
  1661. if (($showsoc > 0) && $obj->company) {
  1662. $out .= ' - ('.$obj->company.')';
  1663. }
  1664. }
  1665. }
  1666. }
  1667. $i++;
  1668. }
  1669. } else {
  1670. $labeltoshow = ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1671. $out .= '<option class="disabled" value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled="disabled">';
  1672. $out .= $labeltoshow;
  1673. $out .= '</option>';
  1674. }
  1675. $parameters = array(
  1676. 'socid'=>$socid,
  1677. 'htmlname'=>$htmlname,
  1678. 'resql'=>$resql,
  1679. 'out'=>&$out,
  1680. 'showfunction'=>$showfunction,
  1681. 'showsoc'=>$showsoc,
  1682. );
  1683. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1684. if ($htmlname != 'none' && !$options_only) {
  1685. $out .= '</select>';
  1686. }
  1687. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only) {
  1688. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1689. $out .= ajax_combobox($htmlid, $events, getDolGlobalString("CONTACT_USE_SEARCH_TO_SELECT"));
  1690. }
  1691. $this->num = $num;
  1692. return $out;
  1693. } else {
  1694. dol_print_error($this->db);
  1695. return -1;
  1696. }
  1697. }
  1698. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1699. /**
  1700. * Return the HTML select list of users
  1701. *
  1702. * @param string $selected Id user preselected
  1703. * @param string $htmlname Field name in form
  1704. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1705. * @param array $exclude Array list of users id to exclude
  1706. * @param int $disabled If select list must be disabled
  1707. * @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
  1708. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1709. * @param string $force_entity '0' or Ids of environment to force
  1710. * @return void
  1711. * @deprecated Use select_dolusers instead
  1712. * @see select_dolusers()
  1713. */
  1714. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1715. {
  1716. // phpcs:enable
  1717. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1718. }
  1719. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1720. /**
  1721. * Return select list of users
  1722. *
  1723. * @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)
  1724. * @param string $htmlname Field name in form
  1725. * @param int|string $show_empty 0=list with no empty value, 1=add also an empty value into list
  1726. * @param array $exclude Array list of users id to exclude
  1727. * @param int $disabled If select list must be disabled
  1728. * @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
  1729. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1730. * @param string $force_entity '0' or Ids of environment to force
  1731. * @param int $maxlength Maximum length of string into list (0=no limit)
  1732. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1733. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1'). This value must not come from user input.
  1734. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1735. * @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.
  1736. * @param string $morecss More css
  1737. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1738. * @param int $outputmode 0=HTML select string, 1=Array
  1739. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1740. * @param int $forcecombo Force the component to be a simple combo box without ajax
  1741. * @return string HTML select string
  1742. * @see select_dolgroups()
  1743. */
  1744. public function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $noactive = 0, $outputmode = 0, $multiple = false, $forcecombo = 0)
  1745. {
  1746. // phpcs:enable
  1747. global $conf, $user, $langs, $hookmanager;
  1748. global $action;
  1749. // If no preselected user defined, we take current user
  1750. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
  1751. $selected = $user->id;
  1752. }
  1753. if ($selected === '') {
  1754. $selected = array();
  1755. } elseif (!is_array($selected)) {
  1756. $selected = array($selected);
  1757. }
  1758. $excludeUsers = null;
  1759. $includeUsers = null;
  1760. // Permettre l'exclusion d'utilisateurs
  1761. if (is_array($exclude)) {
  1762. $excludeUsers = implode(",", $exclude);
  1763. }
  1764. // Permettre l'inclusion d'utilisateurs
  1765. if (is_array($include)) {
  1766. $includeUsers = implode(",", $include);
  1767. } elseif ($include == 'hierarchy') {
  1768. // Build list includeUsers to have only hierarchy
  1769. $includeUsers = implode(",", $user->getAllChildIds(0));
  1770. } elseif ($include == 'hierarchyme') {
  1771. // Build list includeUsers to have only hierarchy and current user
  1772. $includeUsers = implode(",", $user->getAllChildIds(1));
  1773. }
  1774. $out = '';
  1775. $outarray = array();
  1776. // Forge request to select users
  1777. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut as status, u.login, u.admin, u.entity, u.photo";
  1778. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1779. $sql .= ", e.label";
  1780. }
  1781. $sql .= " FROM ".$this->db->prefix()."user as u";
  1782. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1783. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid = u.entity";
  1784. if ($force_entity) {
  1785. $sql .= " WHERE u.entity IN (0, ".$this->db->sanitize($force_entity).")";
  1786. } else {
  1787. $sql .= " WHERE u.entity IS NOT NULL";
  1788. }
  1789. } else {
  1790. if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  1791. $sql .= " LEFT JOIN ".$this->db->prefix()."usergroup_user as ug";
  1792. $sql .= " ON ug.fk_user = u.rowid";
  1793. $sql .= " WHERE ug.entity = ".$conf->entity;
  1794. } else {
  1795. $sql .= " WHERE u.entity IN (0, ".$conf->entity.")";
  1796. }
  1797. }
  1798. if (!empty($user->socid)) {
  1799. $sql .= " AND u.fk_soc = ".((int) $user->socid);
  1800. }
  1801. if (is_array($exclude) && $excludeUsers) {
  1802. $sql .= " AND u.rowid NOT IN (".$this->db->sanitize($excludeUsers).")";
  1803. }
  1804. if ($includeUsers) {
  1805. $sql .= " AND u.rowid IN (".$this->db->sanitize($includeUsers).")";
  1806. }
  1807. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
  1808. $sql .= " AND u.statut <> 0";
  1809. }
  1810. if (!empty($morefilter)) {
  1811. $sql .= " ".$morefilter;
  1812. }
  1813. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1814. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1815. if (!empty($reshook)) {
  1816. $sql .= $hookmanager->resPrint;
  1817. }
  1818. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) { // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1819. $sql .= " ORDER BY u.statut DESC, u.firstname ASC, u.lastname ASC";
  1820. } else {
  1821. $sql .= " ORDER BY u.statut DESC, u.lastname ASC, u.firstname ASC";
  1822. }
  1823. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1824. $resql = $this->db->query($sql);
  1825. if ($resql) {
  1826. $num = $this->db->num_rows($resql);
  1827. $i = 0;
  1828. if ($num) {
  1829. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1830. $out .= '<select class="flat'.($morecss ? ' '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1831. if ($show_empty && !$multiple) {
  1832. $textforempty = ' ';
  1833. if (!empty($conf->use_javascript_ajax)) {
  1834. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  1835. }
  1836. if (!is_numeric($show_empty)) {
  1837. $textforempty = $show_empty;
  1838. }
  1839. $out .= '<option class="optiongrey" value="'.($show_empty < 0 ? $show_empty : -1).'"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  1840. }
  1841. if ($show_every) {
  1842. $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1843. }
  1844. $userstatic = new User($this->db);
  1845. while ($i < $num) {
  1846. $obj = $this->db->fetch_object($resql);
  1847. $userstatic->id = $obj->rowid;
  1848. $userstatic->lastname = $obj->lastname;
  1849. $userstatic->firstname = $obj->firstname;
  1850. $userstatic->photo = $obj->photo;
  1851. $userstatic->statut = $obj->status;
  1852. $userstatic->entity = $obj->entity;
  1853. $userstatic->admin = $obj->admin;
  1854. $disableline = '';
  1855. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  1856. $disableline = ($enableonlytext ? $enableonlytext : '1');
  1857. }
  1858. $labeltoshow = '';
  1859. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1860. $fullNameMode = 0;
  1861. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
  1862. $fullNameMode = 1; //Firstname+lastname
  1863. }
  1864. $labeltoshow .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1865. if (empty($obj->firstname) && empty($obj->lastname)) {
  1866. $labeltoshow .= $obj->login;
  1867. }
  1868. // Complete name with more info
  1869. $moreinfo = '';
  1870. if (!empty($conf->global->MAIN_SHOW_LOGIN)) {
  1871. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1872. }
  1873. if ($showstatus >= 0) {
  1874. if ($obj->status == 1 && $showstatus == 1) {
  1875. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1876. }
  1877. if ($obj->status == 0 && $showstatus == 1) {
  1878. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1879. }
  1880. }
  1881. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity) {
  1882. if (!$obj->entity) {
  1883. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1884. } else {
  1885. if ($obj->entity != $conf->entity) {
  1886. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1887. }
  1888. }
  1889. }
  1890. $moreinfo .= ($moreinfo ? ')' : '');
  1891. if ($disableline && $disableline != '1') {
  1892. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1893. }
  1894. $labeltoshow .= $moreinfo;
  1895. $out .= '<option value="'.$obj->rowid.'"';
  1896. if ($disableline) {
  1897. $out .= ' disabled';
  1898. }
  1899. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected))) {
  1900. $out .= ' selected';
  1901. }
  1902. $out .= ' data-html="';
  1903. $outhtml = '';
  1904. // if (!empty($obj->photo)) {
  1905. $outhtml .= $userstatic->getNomUrl(-3, '', 0, 1, 24, 1, 'login', '', 1).' ';
  1906. // }
  1907. if ($showstatus >= 0 && $obj->status == 0) {
  1908. $outhtml .= '<strike class="opacitymediumxxx">';
  1909. }
  1910. $outhtml .= $labeltoshow;
  1911. if ($showstatus >= 0 && $obj->status == 0) {
  1912. $outhtml .= '</strike>';
  1913. }
  1914. $out .= dol_escape_htmltag($outhtml);
  1915. $out .= '">';
  1916. $out .= $labeltoshow;
  1917. $out .= '</option>';
  1918. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1919. $i++;
  1920. }
  1921. } else {
  1922. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1923. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1924. }
  1925. $out .= '</select>';
  1926. if ($num && !$forcecombo) {
  1927. // Enhance with select2
  1928. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1929. $out .= ajax_combobox($htmlname);
  1930. }
  1931. } else {
  1932. dol_print_error($this->db);
  1933. }
  1934. if ($outputmode) {
  1935. return $outarray;
  1936. }
  1937. return $out;
  1938. }
  1939. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1940. /**
  1941. * Return select list of users. Selected users are stored into session.
  1942. * List of users are provided into $_SESSION['assignedtouser'].
  1943. *
  1944. * @param string $action Value for $action
  1945. * @param string $htmlname Field name in form
  1946. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1947. * @param array $exclude Array list of users id to exclude
  1948. * @param int $disabled If select list must be disabled
  1949. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1950. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1951. * @param int $force_entity '0' or Ids of environment to force
  1952. * @param int $maxlength Maximum length of string into list (0=no limit)
  1953. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1954. * @param string $morefilter Add more filters into sql request
  1955. * @param int $showproperties Show properties of each attendees
  1956. * @param array $listofuserid Array with properties of each user
  1957. * @param array $listofcontactid Array with properties of each contact
  1958. * @param array $listofotherid Array with properties of each other contact
  1959. * @return string HTML select string
  1960. * @see select_dolgroups()
  1961. */
  1962. 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())
  1963. {
  1964. // phpcs:enable
  1965. global $conf, $user, $langs;
  1966. $userstatic = new User($this->db);
  1967. $out = '';
  1968. $assignedtouser = array();
  1969. if (!empty($_SESSION['assignedtouser'])) {
  1970. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1971. }
  1972. $nbassignetouser = count($assignedtouser);
  1973. //if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1974. if ($nbassignetouser) {
  1975. $out .= '<ul class="attendees">';
  1976. }
  1977. $i = 0;
  1978. $ownerid = 0;
  1979. foreach ($assignedtouser as $key => $value) {
  1980. if ($value['id'] == $ownerid) {
  1981. continue;
  1982. }
  1983. $out .= '<li>';
  1984. $userstatic->fetch($value['id']);
  1985. $out .= $userstatic->getNomUrl(-1);
  1986. if ($i == 0) {
  1987. $ownerid = $value['id'];
  1988. $out .= ' ('.$langs->trans("Owner").')';
  1989. }
  1990. if ($nbassignetouser > 1 && $action != 'view') {
  1991. $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.'">';
  1992. }
  1993. // Show my availability
  1994. if ($showproperties) {
  1995. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid))) {
  1996. $out .= '<div class="myavailability inline-block">';
  1997. $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>';
  1998. $out .= '</div>';
  1999. }
  2000. }
  2001. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  2002. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  2003. $out .= '</li>';
  2004. $i++;
  2005. }
  2006. if ($nbassignetouser) {
  2007. $out .= '</ul>';
  2008. }
  2009. // Method with no ajax
  2010. if ($action != 'view') {
  2011. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  2012. $out .= '<script type="text/javascript">jQuery(document).ready(function () {';
  2013. $out .= 'jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });';
  2014. $out .= 'jQuery(".assignedtouser").change(function() { console.log(jQuery(".assignedtouser option:selected").val());';
  2015. $out .= ' if (jQuery(".assignedtouser option:selected").val() > 0) { jQuery("#'.$action.'assignedtouser").attr("disabled", false); }';
  2016. $out .= ' else { jQuery("#'.$action.'assignedtouser").attr("disabled", true); }';
  2017. $out .= '});';
  2018. $out .= '})</script>';
  2019. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  2020. $out .= ' <input type="submit" disabled class="button valignmiddle smallpaddingimp reposition" id="'.$action.'assignedtouser" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  2021. $out .= '<br>';
  2022. }
  2023. return $out;
  2024. }
  2025. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2026. /**
  2027. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  2028. *
  2029. * @param int $selected Preselected products
  2030. * @param string $htmlname Name of HTML select field (must be unique in page).
  2031. * @param int|string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2032. * @param int $limit Limit on number of returned lines
  2033. * @param int $price_level Level of price to show
  2034. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2035. * @param int $finished 2=all, 1=finished, 0=raw material
  2036. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  2037. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  2038. * @param array $ajaxoptions Options for ajax_autocompleter
  2039. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2040. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2041. * @param int $forcecombo Force to use combo box
  2042. * @param string $morecss Add more css on select
  2043. * @param int $hidepriceinlabel 1=Hide prices in label
  2044. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  2045. * 'warehouseopen' = count products from open warehouses,
  2046. * 'warehouseclosed' = count products from closed warehouses,
  2047. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2048. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  2049. * @param string $nooutput No print, return the output into a string
  2050. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2051. * @return void|string
  2052. */
  2053. 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)
  2054. {
  2055. // phpcs:enable
  2056. global $langs, $conf;
  2057. $out = '';
  2058. // check parameters
  2059. $price_level = (!empty($price_level) ? $price_level : 0);
  2060. if (is_null($ajaxoptions)) {
  2061. $ajaxoptions = array();
  2062. }
  2063. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  2064. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  2065. $filtertype = '0';
  2066. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  2067. $filtertype = '1';
  2068. }
  2069. }
  2070. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2071. $placeholder = '';
  2072. if ($selected && empty($selected_input_value)) {
  2073. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2074. $producttmpselect = new Product($this->db);
  2075. $producttmpselect->fetch($selected);
  2076. $selected_input_value = $producttmpselect->ref;
  2077. unset($producttmpselect);
  2078. }
  2079. // handle case where product or service module is disabled + no filter specified
  2080. if ($filtertype == '') {
  2081. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2082. $filtertype = 1;
  2083. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2084. $filtertype = 0;
  2085. }
  2086. }
  2087. // mode=1 means customers products
  2088. $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;
  2089. //Price by customer
  2090. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2091. $urloption .= '&socid='.$socid;
  2092. }
  2093. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  2094. if (!empty($conf->variants->enabled) && is_array($selected_combinations)) {
  2095. // Code to automatically insert with javascript the select of attributes under the select of product
  2096. // when a parent of variant has been selected.
  2097. $out .= '
  2098. <!-- script to auto show attributes select tags if a variant was selected -->
  2099. <script>
  2100. // auto show attributes fields
  2101. selected = '.json_encode($selected_combinations).';
  2102. combvalues = {};
  2103. jQuery(document).ready(function () {
  2104. jQuery("input[name=\'prod_entry_mode\']").change(function () {
  2105. if (jQuery(this).val() == \'free\') {
  2106. jQuery(\'div#attributes_box\').empty();
  2107. }
  2108. });
  2109. jQuery("input#'.$htmlname.'").change(function () {
  2110. if (!jQuery(this).val()) {
  2111. jQuery(\'div#attributes_box\').empty();
  2112. return;
  2113. }
  2114. console.log("A change has started. We get variants fields to inject html select");
  2115. jQuery.getJSON("'.DOL_URL_ROOT.'/variants/ajax/getCombinations.php", {
  2116. id: jQuery(this).val()
  2117. }, function (data) {
  2118. jQuery(\'div#attributes_box\').empty();
  2119. jQuery.each(data, function (key, val) {
  2120. combvalues[val.id] = val.values;
  2121. var span = jQuery(document.createElement(\'div\')).css({
  2122. \'display\': \'table-row\'
  2123. });
  2124. span.append(
  2125. jQuery(document.createElement(\'div\')).text(val.label).css({
  2126. \'font-weight\': \'bold\',
  2127. \'display\': \'table-cell\'
  2128. })
  2129. );
  2130. var html = jQuery(document.createElement(\'select\')).attr(\'name\', \'combinations[\' + val.id + \']\').css({
  2131. \'margin-left\': \'15px\',
  2132. \'white-space\': \'pre\'
  2133. }).append(
  2134. jQuery(document.createElement(\'option\')).val(\'\')
  2135. );
  2136. jQuery.each(combvalues[val.id], function (key, val) {
  2137. var tag = jQuery(document.createElement(\'option\')).val(val.id).html(val.value);
  2138. if (selected[val.fk_product_attribute] == val.id) {
  2139. tag.attr(\'selected\', \'selected\');
  2140. }
  2141. html.append(tag);
  2142. });
  2143. span.append(html);
  2144. jQuery(\'div#attributes_box\').append(span);
  2145. });
  2146. })
  2147. });
  2148. '.($selected ? 'jQuery("input#'.$htmlname.'").change();' : '').'
  2149. });
  2150. </script>
  2151. ';
  2152. }
  2153. if (empty($hidelabel)) {
  2154. $out .= $langs->trans("RefOrLabel").' : ';
  2155. } elseif ($hidelabel > 1) {
  2156. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  2157. if ($hidelabel == 2) {
  2158. $out .= img_picto($langs->trans("Search"), 'search');
  2159. }
  2160. }
  2161. $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' : '').' />';
  2162. if ($hidelabel == 3) {
  2163. $out .= img_picto($langs->trans("Search"), 'search');
  2164. }
  2165. } else {
  2166. $out .= $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus, $status_purchase);
  2167. }
  2168. if (empty($nooutput)) {
  2169. print $out;
  2170. } else {
  2171. return $out;
  2172. }
  2173. }
  2174. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2175. /**
  2176. * Return list of BOM for customer in Ajax if Ajax activated or go to select_produits_list
  2177. *
  2178. * @param int $selected Preselected BOM id
  2179. * @param string $htmlname Name of HTML select field (must be unique in page).
  2180. * @param int $limit Limit on number of returned lines
  2181. * @param int $status Sell status -1=Return all bom, 0=Draft BOM, 1=Validated BOM
  2182. * @param int $type type of the BOM (-1=Return all BOM, 0=Return disassemble BOM, 1=Return manufacturing BOM)
  2183. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2184. * @param string $morecss Add more css on select
  2185. * @param string $nooutput No print, return the output into a string
  2186. * @param int $forcecombo Force to use combo box
  2187. * @param array $TProducts Add filter on a defined product
  2188. * @return void|string
  2189. */
  2190. public function select_bom($selected = '', $htmlname = 'bom_id', $limit = 0, $status = 1, $type = 0, $showempty = '1', $morecss = '', $nooutput = '', $forcecombo = 0, $TProducts = [])
  2191. {
  2192. // phpcs:enable
  2193. global $conf, $user, $langs, $db;
  2194. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2195. $error = 0;
  2196. $out = '';
  2197. if (!$forcecombo) {
  2198. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2199. $events = array();
  2200. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2201. }
  2202. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2203. $sql = 'SELECT b.rowid, b.ref, b.label, b.fk_product';
  2204. $sql.= ' FROM '.MAIN_DB_PREFIX.'bom_bom as b';
  2205. $sql.= ' WHERE b.entity IN ('.getEntity('bom').')';
  2206. if (!empty($status)) $sql.= ' AND status = '. (int) $status;
  2207. if (!empty($type)) $sql.= ' AND bomtype = '. (int) $type;
  2208. if (!empty($TProducts)) $sql .= ' AND fk_product IN ('.$this->db->sanitize(implode(',', $TProducts)).')';
  2209. if (!empty($limit)) $sql.= ' LIMIT '. (int) $limit;
  2210. $resql = $db->query($sql);
  2211. if ($resql) {
  2212. if ($showempty) {
  2213. $out .= '<option value="-1"';
  2214. if (empty($selected)) $out .= ' selected';
  2215. $out .= '>&nbsp;</option>';
  2216. }
  2217. while ($obj = $db->fetch_object($resql)) {
  2218. $product = new Product($db);
  2219. $res = $product->fetch($obj->fk_product);
  2220. $out .= '<option value="'.$obj->rowid.'"';
  2221. if ($obj->rowid == $selected) $out .= 'selected';
  2222. $out .= '>'.$obj->ref.' - '.$product->label .' - '. $obj->label.'</option>';
  2223. }
  2224. } else {
  2225. $error++;
  2226. dol_print_error($db);
  2227. }
  2228. if (empty($nooutput)) {
  2229. print $out;
  2230. } else {
  2231. return $out;
  2232. }
  2233. }
  2234. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2235. /**
  2236. * Return list of products for a customer.
  2237. * Called by select_produits.
  2238. *
  2239. * @param int $selected Preselected product
  2240. * @param string $htmlname Name of select html
  2241. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2242. * @param int $limit Limit on number of returned lines
  2243. * @param int $price_level Level of price to show
  2244. * @param string $filterkey Filter on product
  2245. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  2246. * @param int $finished Filter on finished field: 2=No filter
  2247. * @param int $outputmode 0=HTML select string, 1=Array
  2248. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  2249. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  2250. * @param int $forcecombo Force to use combo box
  2251. * @param string $morecss Add more css on select
  2252. * @param int $hidepriceinlabel 1=Hide prices in label
  2253. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  2254. * 'warehouseopen' = count products from open warehouses,
  2255. * 'warehouseclosed' = count products from closed warehouses,
  2256. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  2257. * @param int $status_purchase Purchase status -1=Return all products, 0=Products not on purchase, 1=Products on purchase
  2258. * @return array Array of keys for json
  2259. */
  2260. 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)
  2261. {
  2262. // phpcs:enable
  2263. global $langs, $conf;
  2264. global $hookmanager;
  2265. $out = '';
  2266. $outarray = array();
  2267. // Units
  2268. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2269. $langs->load('other');
  2270. }
  2271. $warehouseStatusArray = array();
  2272. if (!empty($warehouseStatus)) {
  2273. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2274. if (preg_match('/warehouseclosed/', $warehouseStatus)) {
  2275. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  2276. }
  2277. if (preg_match('/warehouseopen/', $warehouseStatus)) {
  2278. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  2279. }
  2280. if (preg_match('/warehouseinternal/', $warehouseStatus)) {
  2281. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  2282. }
  2283. }
  2284. $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";
  2285. if (count($warehouseStatusArray)) {
  2286. $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
  2287. } else {
  2288. $selectFieldsGrouped = ", ".$this->db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  2289. }
  2290. $sql = "SELECT ";
  2291. $sql .= $selectFields.$selectFieldsGrouped;
  2292. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2293. //Product category
  2294. $sql .= ", (SELECT ".$this->db->prefix()."categorie_product.fk_categorie
  2295. FROM ".$this->db->prefix()."categorie_product
  2296. WHERE ".$this->db->prefix()."categorie_product.fk_product=p.rowid
  2297. LIMIT 1
  2298. ) AS categorie_product_id ";
  2299. }
  2300. //Price by customer
  2301. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2302. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  2303. $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';
  2304. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx, custdefault_vat_code, custref";
  2305. }
  2306. // Units
  2307. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2308. $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";
  2309. $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';
  2310. }
  2311. // Multilang : we add translation
  2312. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2313. $sql .= ", pl.label as label_translated";
  2314. $sql .= ", pl.description as description_translated";
  2315. $selectFields .= ", label_translated";
  2316. $selectFields .= ", description_translated";
  2317. }
  2318. // Price by quantity
  2319. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2320. $sql .= ", (SELECT pp.rowid FROM ".$this->db->prefix()."product_price as pp WHERE pp.fk_product = p.rowid";
  2321. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2322. $sql .= " AND price_level = ".((int) $price_level);
  2323. }
  2324. $sql .= " ORDER BY date_price";
  2325. $sql .= " DESC LIMIT 1) as price_rowid";
  2326. $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
  2327. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  2328. $sql .= " AND price_level = ".((int) $price_level);
  2329. }
  2330. $sql .= " ORDER BY date_price";
  2331. $sql .= " DESC LIMIT 1) as price_by_qty";
  2332. $selectFields .= ", price_rowid, price_by_qty";
  2333. }
  2334. $sql .= " FROM ".$this->db->prefix()."product as p";
  2335. if (count($warehouseStatusArray)) {
  2336. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock as ps on ps.fk_product = p.rowid";
  2337. $sql .= " LEFT JOIN ".$this->db->prefix()."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  2338. $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.
  2339. }
  2340. // include search in supplier ref
  2341. // Added by MMI Mathieu Moulin iProspective
  2342. // Hack : include search in supplier name
  2343. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF) || !empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_LABEL)) {
  2344. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2345. }
  2346. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_LABEL)) {
  2347. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as pf ON pfp.fk_soc = pf.rowid";
  2348. }
  2349. //Price by customer
  2350. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  2351. $sql .= " LEFT JOIN ".$this->db->prefix()."product_customer_price as pcp ON pcp.fk_soc=".((int) $socid)." AND pcp.fk_product=p.rowid";
  2352. }
  2353. // Units
  2354. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2355. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2356. }
  2357. // Multilang : we add translation
  2358. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2359. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lang as pl ON pl.fk_product = p.rowid ";
  2360. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && !empty($socid)) {
  2361. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  2362. $soc = new Societe($this->db);
  2363. $result = $soc->fetch($socid);
  2364. if ($result > 0 && !empty($soc->default_lang)) {
  2365. $sql .= " AND pl.lang = '".$this->db->escape($soc->default_lang)."'";
  2366. } else {
  2367. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2368. }
  2369. } else {
  2370. $sql .= " AND pl.lang = '".$this->db->escape($langs->getDefaultLang())."'";
  2371. }
  2372. }
  2373. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2374. $sql .= " LEFT JOIN ".$this->db->prefix()."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  2375. }
  2376. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  2377. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  2378. $sql .= " AND pac.rowid IS NULL";
  2379. }
  2380. if ($finished == 0) {
  2381. $sql .= " AND p.finished = ".((int) $finished);
  2382. } elseif ($finished == 1) {
  2383. $sql .= " AND p.finished = ".((int) $finished);
  2384. if ($status >= 0) {
  2385. $sql .= " AND p.tosell = ".((int) $status);
  2386. }
  2387. } elseif ($status >= 0) {
  2388. $sql .= " AND p.tosell = ".((int) $status);
  2389. }
  2390. if ($status_purchase >= 0) {
  2391. $sql .= " AND p.tobuy = ".((int) $status_purchase);
  2392. }
  2393. // Filter by product type
  2394. if (strval($filtertype) != '') {
  2395. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2396. } elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  2397. $sql .= " AND p.fk_product_type = 1";
  2398. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  2399. $sql .= " AND p.fk_product_type = 0";
  2400. }
  2401. // Add where from hooks
  2402. $parameters = array();
  2403. $reshook = $hookmanager->executeHooks('selectProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2404. $sql .= $hookmanager->resPrint;
  2405. // Add criteria on ref/label
  2406. if ($filterkey != '') {
  2407. $sql .= ' AND (';
  2408. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2409. // For natural search
  2410. $scrit = explode(' ', $filterkey);
  2411. $i = 0;
  2412. if (count($scrit) > 1) {
  2413. $sql .= "(";
  2414. }
  2415. foreach ($scrit as $crit) {
  2416. if ($i > 0) {
  2417. $sql .= " AND ";
  2418. }
  2419. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2420. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2421. $sql .= " OR pl.label LIKE '".$this->db->escape($prefix.$crit)."%'";
  2422. }
  2423. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && ! empty($socid)) {
  2424. $sql .= " OR pcp.ref_customer LIKE '".$this->db->escape($prefix.$crit)."%'";
  2425. }
  2426. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION)) {
  2427. $sql .= " OR p.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2428. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2429. $sql .= " OR pl.description LIKE '".$this->db->escape($prefix.$crit)."%'";
  2430. }
  2431. }
  2432. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
  2433. $sql .= " OR pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2434. }
  2435. // Added by MMI Mathieu Moulin iProspective
  2436. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_LABEL)) {
  2437. $sql .= " OR pf.nom LIKE '".$this->db->escape($prefix.$crit)."%'";
  2438. $sql .= " OR pf.name_alias LIKE '".$this->db->escape($prefix.$crit)."%'";
  2439. }
  2440. $sql .= ")";
  2441. $i++;
  2442. }
  2443. if (count($scrit) > 1) {
  2444. $sql .= ")";
  2445. }
  2446. if (!empty($conf->barcode->enabled)) {
  2447. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2448. }
  2449. $sql .= ')';
  2450. }
  2451. if (count($warehouseStatusArray)) {
  2452. $sql .= " GROUP BY ".$selectFields;
  2453. }
  2454. //Sort by category
  2455. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY)) {
  2456. $sql .= " ORDER BY categorie_product_id ";
  2457. //ASC OR DESC order
  2458. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2459. } else {
  2460. $sql .= $this->db->order("p.ref");
  2461. }
  2462. $sql .= $this->db->plimit($limit, 0);
  2463. // Build output string
  2464. dol_syslog(get_class($this)."::select_produits_list search products", LOG_DEBUG);
  2465. $result = $this->db->query($sql);
  2466. if ($result) {
  2467. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2468. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2469. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2470. $num = $this->db->num_rows($result);
  2471. $events = null;
  2472. if (!$forcecombo) {
  2473. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2474. $out .= ajax_combobox($htmlname, $events, getDolGlobalInt("PRODUIT_USE_SEARCH_TO_SELECT"));
  2475. }
  2476. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2477. $textifempty = '';
  2478. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2479. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2480. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2481. if ($showempty && !is_numeric($showempty)) {
  2482. $textifempty = $langs->trans($showempty);
  2483. } else {
  2484. $textifempty .= $langs->trans("All");
  2485. }
  2486. } else {
  2487. if ($showempty && !is_numeric($showempty)) {
  2488. $textifempty = $langs->trans($showempty);
  2489. }
  2490. }
  2491. if ($showempty) {
  2492. $out .= '<option value="-1" selected>'.($textifempty ? $textifempty : '&nbsp;').'</option>';
  2493. }
  2494. $i = 0;
  2495. while ($num && $i < $num) {
  2496. $opt = '';
  2497. $optJson = array();
  2498. $objp = $this->db->fetch_object($result);
  2499. 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
  2500. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2501. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2502. $sql .= " WHERE fk_product_price = ".((int) $objp->price_rowid);
  2503. $sql .= " ORDER BY quantity ASC";
  2504. dol_syslog(get_class($this)."::select_produits_list search prices by qty", LOG_DEBUG);
  2505. $result2 = $this->db->query($sql);
  2506. if ($result2) {
  2507. $nb_prices = $this->db->num_rows($result2);
  2508. $j = 0;
  2509. while ($nb_prices && $j < $nb_prices) {
  2510. $objp2 = $this->db->fetch_object($result2);
  2511. $objp->price_by_qty_rowid = $objp2->rowid;
  2512. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2513. $objp->price_by_qty_quantity = $objp2->quantity;
  2514. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2515. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2516. // For backward compatibility
  2517. $objp->quantity = $objp2->quantity;
  2518. $objp->price = $objp2->price;
  2519. $objp->unitprice = $objp2->unitprice;
  2520. $objp->remise_percent = $objp2->remise_percent;
  2521. //$objp->tva_tx is not overwritten by $objp2 value
  2522. //$objp->default_vat_code is not overwritten by $objp2 value
  2523. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2524. $j++;
  2525. // Add new entry
  2526. // "key" value of json key array is used by jQuery automatically as selected value
  2527. // "label" value of json key array is used by jQuery automatically as text for combo box
  2528. $out .= $opt;
  2529. array_push($outarray, $optJson);
  2530. }
  2531. }
  2532. } else {
  2533. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2534. $price_product = new Product($this->db);
  2535. $price_product->fetch($objp->rowid, '', '', 1);
  2536. $priceparser = new PriceParser($this->db);
  2537. $price_result = $priceparser->parseProduct($price_product);
  2538. if ($price_result >= 0) {
  2539. $objp->price = $price_result;
  2540. $objp->unitprice = $price_result;
  2541. //Calculate the VAT
  2542. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2543. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2544. }
  2545. }
  2546. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2547. // Add new entry
  2548. // "key" value of json key array is used by jQuery automatically as selected value
  2549. // "label" value of json key array is used by jQuery automatically as text for combo box
  2550. $out .= $opt;
  2551. array_push($outarray, $optJson);
  2552. }
  2553. $i++;
  2554. }
  2555. $out .= '</select>';
  2556. $this->db->free($result);
  2557. if (empty($outputmode)) {
  2558. return $out;
  2559. }
  2560. return $outarray;
  2561. } else {
  2562. dol_print_error($this->db);
  2563. }
  2564. }
  2565. /**
  2566. * Function to forge the string with OPTIONs of SELECT.
  2567. * This define value for &$opt and &$optJson.
  2568. * This function is called by select_produits_list().
  2569. *
  2570. * @param resource $objp Resultset of fetch
  2571. * @param string $opt Option (var used for returned value in string option format)
  2572. * @param string $optJson Option (var used for returned value in json format)
  2573. * @param int $price_level Price level
  2574. * @param string $selected Preselected value
  2575. * @param int $hidepriceinlabel Hide price in label
  2576. * @param string $filterkey Filter key to highlight
  2577. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2578. * @return void
  2579. */
  2580. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2581. {
  2582. global $langs, $conf, $user;
  2583. $outkey = '';
  2584. $outval = '';
  2585. $outref = '';
  2586. $outlabel = '';
  2587. $outlabel_translated = '';
  2588. $outdesc = '';
  2589. $outdesc_translated = '';
  2590. $outbarcode = '';
  2591. $outorigin = '';
  2592. $outtype = '';
  2593. $outprice_ht = '';
  2594. $outprice_ttc = '';
  2595. $outpricebasetype = '';
  2596. $outtva_tx = '';
  2597. $outdefault_vat_code = '';
  2598. $outqty = 1;
  2599. $outdiscount = 0;
  2600. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2601. $label = $objp->label;
  2602. if (!empty($objp->label_translated)) {
  2603. $label = $objp->label_translated;
  2604. }
  2605. if (!empty($filterkey) && $filterkey != '') {
  2606. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2607. }
  2608. $outkey = $objp->rowid;
  2609. $outref = $objp->ref;
  2610. $outrefcust = empty($objp->custref) ? '' : $objp->custref;
  2611. $outlabel = $objp->label;
  2612. $outdesc = $objp->description;
  2613. if (!empty($conf->global->MAIN_MULTILANGS)) {
  2614. $outlabel_translated = $objp->label_translated;
  2615. $outdesc_translated = $objp->description_translated;
  2616. }
  2617. $outbarcode = $objp->barcode;
  2618. $outorigin = $objp->fk_country;
  2619. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2620. $outtype = $objp->fk_product_type;
  2621. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2622. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2623. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2624. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2625. }
  2626. // Units
  2627. $outvalUnits = '';
  2628. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2629. if (!empty($objp->unit_short)) {
  2630. $outvalUnits .= ' - '.$objp->unit_short;
  2631. }
  2632. }
  2633. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2634. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2635. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2636. $outvalUnits .= ' - '.$unitToShow;
  2637. }
  2638. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2639. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2640. $outvalUnits .= ' - '.$unitToShow;
  2641. }
  2642. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2643. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2644. $outvalUnits .= ' - '.$unitToShow;
  2645. }
  2646. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2647. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2648. $outvalUnits .= ' - '.$unitToShow;
  2649. }
  2650. }
  2651. if ($outdurationvalue && $outdurationunit) {
  2652. $da = array(
  2653. 'h' => $langs->trans('Hour'),
  2654. 'd' => $langs->trans('Day'),
  2655. 'w' => $langs->trans('Week'),
  2656. 'm' => $langs->trans('Month'),
  2657. 'y' => $langs->trans('Year')
  2658. );
  2659. if (isset($da[$outdurationunit])) {
  2660. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2661. }
  2662. }
  2663. $opt = '<option value="'.$objp->rowid.'"';
  2664. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2665. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0) {
  2666. $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.'"';
  2667. }
  2668. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2669. if (!empty($user->rights->stock->lire)) {
  2670. if ($objp->stock > 0) {
  2671. $opt .= ' class="product_line_stock_ok"';
  2672. } elseif ($objp->stock <= 0) {
  2673. $opt .= ' class="product_line_stock_too_low"';
  2674. }
  2675. }
  2676. }
  2677. if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  2678. $opt .= ' data-labeltrans="'.$outlabel_translated.'"';
  2679. $opt .= ' data-desctrans="'.dol_escape_htmltag($outdesc_translated).'"';
  2680. }
  2681. $opt .= '>';
  2682. $opt .= $objp->ref;
  2683. if (! empty($objp->custref)) {
  2684. $opt.= ' (' . $objp->custref . ')';
  2685. }
  2686. if ($outbarcode) {
  2687. $opt .= ' ('.$outbarcode.')';
  2688. }
  2689. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2690. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2691. $opt .= ' ('.getCountry($outorigin, 1).')';
  2692. }
  2693. $objRef = $objp->ref;
  2694. if (! empty($objp->custref)) {
  2695. $objRef .= ' (' . $objp->custref . ')';
  2696. }
  2697. if (!empty($filterkey) && $filterkey != '') {
  2698. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2699. }
  2700. $outval .= $objRef;
  2701. if ($outbarcode) {
  2702. $outval .= ' ('.$outbarcode.')';
  2703. }
  2704. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2705. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) {
  2706. $outval .= ' ('.getCountry($outorigin, 1).')';
  2707. }
  2708. // Units
  2709. $opt .= $outvalUnits;
  2710. $outval .= $outvalUnits;
  2711. $found = 0;
  2712. // Multiprice
  2713. // If we need a particular price level (from 1 to n)
  2714. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))) {
  2715. $sql = "SELECT price, price_ttc, price_base_type, tva_tx, default_vat_code";
  2716. $sql .= " FROM ".$this->db->prefix()."product_price";
  2717. $sql .= " WHERE fk_product = ".((int) $objp->rowid);
  2718. $sql .= " AND entity IN (".getEntity('productprice').")";
  2719. $sql .= " AND price_level = ".((int) $price_level);
  2720. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2721. $sql .= " LIMIT 1";
  2722. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2723. $result2 = $this->db->query($sql);
  2724. if ($result2) {
  2725. $objp2 = $this->db->fetch_object($result2);
  2726. if ($objp2) {
  2727. $found = 1;
  2728. if ($objp2->price_base_type == 'HT') {
  2729. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2730. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2731. } else {
  2732. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2733. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2734. }
  2735. $outprice_ht = price($objp2->price);
  2736. $outprice_ttc = price($objp2->price_ttc);
  2737. $outpricebasetype = $objp2->price_base_type;
  2738. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  2739. $outtva_tx = $objp2->tva_tx; // We use the vat rate on line of multiprice
  2740. $outdefault_vat_code = $objp2->default_vat_code; // We use the vat code on line of multiprice
  2741. } else {
  2742. $outtva_tx = $objp->tva_tx; // We use the vat rate of product, not the one on line of multiprice
  2743. $outdefault_vat_code = $objp->default_vat_code; // We use the vat code or product, not the one on line of multiprice
  2744. }
  2745. }
  2746. } else {
  2747. dol_print_error($this->db);
  2748. }
  2749. }
  2750. // Price by quantity
  2751. 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))) {
  2752. $found = 1;
  2753. $outqty = $objp->quantity;
  2754. $outdiscount = $objp->remise_percent;
  2755. if ($objp->quantity == 1) {
  2756. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2757. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2758. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2759. $outval .= $langs->transnoentities("Unit");
  2760. } else {
  2761. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2762. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2763. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2764. $outval .= $langs->transnoentities("Units");
  2765. }
  2766. $outprice_ht = price($objp->unitprice);
  2767. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2768. $outpricebasetype = $objp->price_base_type;
  2769. $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
  2770. $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
  2771. }
  2772. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1) {
  2773. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2774. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2775. }
  2776. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1) {
  2777. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2778. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2779. }
  2780. // Price by customer
  2781. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  2782. if (!empty($objp->idprodcustprice)) {
  2783. $found = 1;
  2784. if ($objp->custprice_base_type == 'HT') {
  2785. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2786. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2787. } else {
  2788. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2789. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2790. }
  2791. $outprice_ht = price($objp->custprice);
  2792. $outprice_ttc = price($objp->custprice_ttc);
  2793. $outpricebasetype = $objp->custprice_base_type;
  2794. $outtva_tx = $objp->custtva_tx;
  2795. $outdefault_vat_code = $objp->custdefault_vat_code;
  2796. }
  2797. }
  2798. // If level no defined or multiprice not found, we used the default price
  2799. if (empty($hidepriceinlabel) && !$found) {
  2800. if ($objp->price_base_type == 'HT') {
  2801. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2802. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2803. } else {
  2804. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2805. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2806. }
  2807. $outprice_ht = price($objp->price);
  2808. $outprice_ttc = price($objp->price_ttc);
  2809. $outpricebasetype = $objp->price_base_type;
  2810. $outtva_tx = $objp->tva_tx;
  2811. $outdefault_vat_code = $objp->default_vat_code;
  2812. }
  2813. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  2814. if (!empty($user->rights->stock->lire)) {
  2815. $opt .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  2816. if ($objp->stock > 0) {
  2817. $outval .= ' - <span class="product_line_stock_ok">';
  2818. } elseif ($objp->stock <= 0) {
  2819. $outval .= ' - <span class="product_line_stock_too_low">';
  2820. }
  2821. $outval .= $langs->transnoentities("Stock").': '.price(price2num($objp->stock, 'MS'));
  2822. $outval .= '</span>';
  2823. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  2824. $langs->load("stocks");
  2825. $tmpproduct = new Product($this->db);
  2826. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2827. $tmpproduct->load_virtual_stock();
  2828. $virtualstock = $tmpproduct->stock_theorique;
  2829. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2830. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2831. if ($virtualstock > 0) {
  2832. $outval .= '<span class="product_line_stock_ok">';
  2833. } elseif ($virtualstock <= 0) {
  2834. $outval .= '<span class="product_line_stock_too_low">';
  2835. }
  2836. $outval .= $virtualstock;
  2837. $outval .= '</span>';
  2838. unset($tmpproduct);
  2839. }
  2840. }
  2841. }
  2842. $opt .= "</option>\n";
  2843. $optJson = array(
  2844. 'key'=>$outkey,
  2845. 'value'=>$outref,
  2846. 'label'=>$outval,
  2847. 'label2'=>$outlabel,
  2848. 'desc'=>$outdesc,
  2849. 'type'=>$outtype,
  2850. 'price_ht'=>price2num($outprice_ht),
  2851. 'price_ttc'=>price2num($outprice_ttc),
  2852. 'price_ht_locale'=>price(price2num($outprice_ht)),
  2853. 'price_ttc_locale'=>price(price2num($outprice_ttc)),
  2854. 'pricebasetype'=>$outpricebasetype,
  2855. 'tva_tx'=>$outtva_tx,
  2856. 'default_vat_code'=>$outdefault_vat_code,
  2857. 'qty'=>$outqty,
  2858. 'discount'=>$outdiscount,
  2859. 'duration_value'=>$outdurationvalue,
  2860. 'duration_unit'=>$outdurationunit,
  2861. 'pbq'=>$outpbq,
  2862. 'labeltrans'=>$outlabel_translated,
  2863. 'desctrans'=>$outdesc_translated,
  2864. 'ref_customer'=>$outrefcust
  2865. );
  2866. }
  2867. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2868. /**
  2869. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2870. *
  2871. * @param int $socid Id third party
  2872. * @param string $selected Preselected product
  2873. * @param string $htmlname Name of HTML Select
  2874. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2875. * @param string $filtre For a SQL filter
  2876. * @param array $ajaxoptions Options for ajax_autocompleter
  2877. * @param int $hidelabel Hide label (0=no, 1=yes)
  2878. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2879. * @param string $morecss More CSS
  2880. * @param string $placeholder Placeholder
  2881. * @return void
  2882. */
  2883. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '', $placeholder = '')
  2884. {
  2885. // phpcs:enable
  2886. global $langs, $conf;
  2887. global $price_level, $status, $finished;
  2888. if (!isset($status)) {
  2889. $status = 1;
  2890. }
  2891. $selected_input_value = '';
  2892. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT)) {
  2893. if ($selected > 0) {
  2894. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2895. $producttmpselect = new Product($this->db);
  2896. $producttmpselect->fetch($selected);
  2897. $selected_input_value = $producttmpselect->ref;
  2898. unset($producttmpselect);
  2899. }
  2900. // mode=2 means suppliers products
  2901. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2902. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2903. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" class="minwidth300" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.($placeholder ? ' placeholder="'.$placeholder.'"' : '').'>';
  2904. } else {
  2905. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', $status, 0, 0, $alsoproductwithnosupplierprice, $morecss, 0, $placeholder);
  2906. }
  2907. }
  2908. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2909. /**
  2910. * Return list of suppliers products
  2911. *
  2912. * @param int $socid Id of supplier thirdparty (0 = no filter)
  2913. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2914. * @param string $htmlname Name of HTML select
  2915. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2916. * @param string $filtre Generic filter. Data must not come from user input.
  2917. * @param string $filterkey Filter of produdts
  2918. * @param int $statut -1=Return all products, 0=Products not on buy, 1=Products on buy
  2919. * @param int $outputmode 0=HTML select string, 1=Array
  2920. * @param int $limit Limit of line number
  2921. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2922. * @param string $morecss Add more CSS
  2923. * @param int $showstockinlist Show stock information (slower).
  2924. * @param string $placeholder Placeholder
  2925. * @return array Array of keys for json
  2926. */
  2927. 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 = '')
  2928. {
  2929. // phpcs:enable
  2930. global $langs, $conf, $user;
  2931. global $hookmanager;
  2932. $out = '';
  2933. $outarray = array();
  2934. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2935. $langs->load('stocks');
  2936. // Units
  2937. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2938. $langs->load('other');
  2939. }
  2940. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type, p.stock,";
  2941. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2942. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.default_vat_code, pfp.fk_soc, s.nom as name,";
  2943. $sql .= " pfp.supplier_reputation";
  2944. // if we use supplier description of the products
  2945. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2946. $sql .= ", pfp.desc_fourn as description";
  2947. } else {
  2948. $sql .= ", p.description";
  2949. }
  2950. // Units
  2951. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2952. $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";
  2953. }
  2954. if (!empty($conf->barcode->enabled)) {
  2955. $sql .= ", pfp.barcode";
  2956. }
  2957. $sql .= " FROM ".$this->db->prefix()."product as p";
  2958. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2959. if ($socid > 0) {
  2960. $sql .= " AND pfp.fk_soc = ".((int) $socid);
  2961. }
  2962. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  2963. // Units
  2964. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2965. $sql .= " LEFT JOIN ".$this->db->prefix()."c_units u ON u.rowid = p.fk_unit";
  2966. }
  2967. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2968. if ($statut != -1) {
  2969. $sql .= " AND p.tobuy = ".((int) $statut);
  2970. }
  2971. if (strval($filtertype) != '') {
  2972. $sql .= " AND p.fk_product_type = ".((int) $filtertype);
  2973. }
  2974. if (!empty($filtre)) {
  2975. $sql .= " ".$filtre;
  2976. }
  2977. // Add where from hooks
  2978. $parameters = array();
  2979. $reshook = $hookmanager->executeHooks('selectSuppliersProductsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  2980. $sql .= $hookmanager->resPrint;
  2981. // Add criteria on ref/label
  2982. if ($filterkey != '') {
  2983. $sql .= ' AND (';
  2984. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2985. // For natural search
  2986. $scrit = explode(' ', $filterkey);
  2987. $i = 0;
  2988. if (count($scrit) > 1) {
  2989. $sql .= "(";
  2990. }
  2991. foreach ($scrit as $crit) {
  2992. if ($i > 0) {
  2993. $sql .= " AND ";
  2994. }
  2995. $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)."%'";
  2996. if (!empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  2997. $sql .= " OR pfp.desc_fourn LIKE '".$this->db->escape($prefix.$crit)."%'";
  2998. }
  2999. $sql .= ")";
  3000. $i++;
  3001. }
  3002. if (count($scrit) > 1) {
  3003. $sql .= ")";
  3004. }
  3005. if (!empty($conf->barcode->enabled)) {
  3006. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  3007. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  3008. }
  3009. $sql .= ')';
  3010. }
  3011. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  3012. $sql .= $this->db->plimit($limit, 0);
  3013. // Build output string
  3014. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  3015. $result = $this->db->query($sql);
  3016. if ($result) {
  3017. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3018. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  3019. $num = $this->db->num_rows($result);
  3020. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  3021. $out .= '<select class="flat '.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  3022. if (!$selected) {
  3023. $out .= '<option value="-1" selected>'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  3024. } else {
  3025. $out .= '<option value="-1">'.($placeholder ? $placeholder : '&nbsp;').'</option>';
  3026. }
  3027. $i = 0;
  3028. while ($i < $num) {
  3029. $objp = $this->db->fetch_object($result);
  3030. $outkey = $objp->idprodfournprice; // id in table of price
  3031. if (!$outkey && $alsoproductwithnosupplierprice) {
  3032. $outkey = 'idprod_'.$objp->rowid; // id of product
  3033. }
  3034. $outref = $objp->ref;
  3035. $outval = '';
  3036. $outbarcode = $objp->barcode;
  3037. $outqty = 1;
  3038. $outdiscount = 0;
  3039. $outtype = $objp->fk_product_type;
  3040. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  3041. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  3042. // Units
  3043. $outvalUnits = '';
  3044. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  3045. if (!empty($objp->unit_short)) {
  3046. $outvalUnits .= ' - '.$objp->unit_short;
  3047. }
  3048. if (!empty($objp->weight) && $objp->weight_units !== null) {
  3049. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  3050. $outvalUnits .= ' - '.$unitToShow;
  3051. }
  3052. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  3053. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  3054. $outvalUnits .= ' - '.$unitToShow;
  3055. }
  3056. if (!empty($objp->surface) && $objp->surface_units !== null) {
  3057. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  3058. $outvalUnits .= ' - '.$unitToShow;
  3059. }
  3060. if (!empty($objp->volume) && $objp->volume_units !== null) {
  3061. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  3062. $outvalUnits .= ' - '.$unitToShow;
  3063. }
  3064. if ($outdurationvalue && $outdurationunit) {
  3065. $da = array(
  3066. 'h' => $langs->trans('Hour'),
  3067. 'd' => $langs->trans('Day'),
  3068. 'w' => $langs->trans('Week'),
  3069. 'm' => $langs->trans('Month'),
  3070. 'y' => $langs->trans('Year')
  3071. );
  3072. if (isset($da[$outdurationunit])) {
  3073. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  3074. }
  3075. }
  3076. }
  3077. $objRef = $objp->ref;
  3078. if ($filterkey && $filterkey != '') {
  3079. $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  3080. }
  3081. $objRefFourn = $objp->ref_fourn;
  3082. if ($filterkey && $filterkey != '') {
  3083. $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  3084. }
  3085. $label = $objp->label;
  3086. if ($filterkey && $filterkey != '') {
  3087. $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  3088. }
  3089. $optlabel = $objp->ref;
  3090. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3091. $optlabel .= ' <span class="opacitymedium">('.$objp->ref_fourn.')</span>';
  3092. }
  3093. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3094. $optlabel .= ' ('.$outbarcode.')';
  3095. }
  3096. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3097. $outvallabel = $objRef;
  3098. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  3099. $outvallabel .= ' ('.$objRefFourn.')';
  3100. }
  3101. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  3102. $outvallabel .= ' ('.$outbarcode.')';
  3103. }
  3104. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  3105. // Units
  3106. $optlabel .= $outvalUnits;
  3107. $outvallabel .= $outvalUnits;
  3108. if (!empty($objp->idprodfournprice)) {
  3109. $outqty = $objp->quantity;
  3110. $outdiscount = $objp->remise_percent;
  3111. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3112. $prod_supplier = new ProductFournisseur($this->db);
  3113. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3114. $prod_supplier->id = $objp->fk_product;
  3115. $prod_supplier->fourn_qty = $objp->quantity;
  3116. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3117. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3118. $priceparser = new PriceParser($this->db);
  3119. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3120. if ($price_result >= 0) {
  3121. $objp->fprice = $price_result;
  3122. if ($objp->quantity >= 1) {
  3123. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  3124. }
  3125. }
  3126. }
  3127. if ($objp->quantity == 1) {
  3128. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3129. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  3130. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  3131. $outvallabel .= $langs->transnoentities("Unit");
  3132. } else {
  3133. $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;
  3134. $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;
  3135. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  3136. $outvallabel .= ' '.$langs->transnoentities("Units");
  3137. }
  3138. if ($objp->quantity > 1) {
  3139. $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
  3140. $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
  3141. }
  3142. if ($objp->remise_percent >= 1) {
  3143. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  3144. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  3145. }
  3146. if ($objp->duration) {
  3147. $optlabel .= " - ".$objp->duration;
  3148. $outvallabel .= " - ".$objp->duration;
  3149. }
  3150. if (!$socid) {
  3151. $optlabel .= " - ".dol_trunc($objp->name, 8);
  3152. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  3153. }
  3154. if ($objp->supplier_reputation) {
  3155. //TODO dictionary
  3156. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  3157. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  3158. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  3159. }
  3160. } else {
  3161. if (empty($alsoproductwithnosupplierprice)) { // No supplier price defined for couple product/supplier
  3162. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3163. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3164. } else // No supplier price defined for product, even on other suppliers
  3165. {
  3166. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  3167. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  3168. }
  3169. }
  3170. if (!empty($conf->stock->enabled) && $showstockinlist && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  3171. $novirtualstock = ($showstockinlist == 2);
  3172. if (!empty($user->rights->stock->lire)) {
  3173. $outvallabel .= ' - '.$langs->trans("Stock").': '.price(price2num($objp->stock, 'MS'));
  3174. if ($objp->stock > 0) {
  3175. $optlabel .= ' - <span class="product_line_stock_ok">';
  3176. } elseif ($objp->stock <= 0) {
  3177. $optlabel .= ' - <span class="product_line_stock_too_low">';
  3178. }
  3179. $optlabel .= $langs->transnoentities("Stock").':'.price(price2num($objp->stock, 'MS'));
  3180. $optlabel .= '</span>';
  3181. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) { // Warning, this option may slow down combo list generation
  3182. $langs->load("stocks");
  3183. $tmpproduct = new Product($this->db);
  3184. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  3185. $tmpproduct->load_virtual_stock();
  3186. $virtualstock = $tmpproduct->stock_theorique;
  3187. $outvallabel .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  3188. $optlabel .= ' - '.$langs->transnoentities("VirtualStock").':';
  3189. if ($virtualstock > 0) {
  3190. $optlabel .= '<span class="product_line_stock_ok">';
  3191. } elseif ($virtualstock <= 0) {
  3192. $optlabel .= '<span class="product_line_stock_too_low">';
  3193. }
  3194. $optlabel .= $virtualstock;
  3195. $optlabel .= '</span>';
  3196. unset($tmpproduct);
  3197. }
  3198. }
  3199. }
  3200. $opt = '<option value="'.$outkey.'"';
  3201. if ($selected && $selected == $objp->idprodfournprice) {
  3202. $opt .= ' selected';
  3203. }
  3204. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
  3205. $opt .= ' disabled';
  3206. }
  3207. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0) {
  3208. $opt .= ' data-product-id="'.dol_escape_htmltag($objp->rowid).'"';
  3209. $opt .= ' data-price-id="'.dol_escape_htmltag($objp->idprodfournprice).'"';
  3210. $opt .= ' data-qty="'.dol_escape_htmltag($objp->quantity).'"';
  3211. $opt .= ' data-up="'.dol_escape_htmltag($objp->unitprice).'"';
  3212. $opt .= ' data-up-locale="'.dol_escape_htmltag(price($objp->unitprice)).'"';
  3213. $opt .= ' data-discount="'.dol_escape_htmltag($outdiscount).'"';
  3214. $opt .= ' data-tvatx="'.dol_escape_htmltag($objp->tva_tx).'"';
  3215. }
  3216. $opt .= ' data-description="'.dol_escape_htmltag($objp->description, 0, 1).'"';
  3217. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  3218. $opt .= '>';
  3219. $opt .= $optlabel;
  3220. $outval .= $outvallabel;
  3221. $opt .= "</option>\n";
  3222. // Add new entry
  3223. // "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
  3224. // "label" value of json key array is used by jQuery automatically as text for combo box
  3225. $out .= $opt;
  3226. array_push(
  3227. $outarray,
  3228. array('key'=>$outkey,
  3229. 'value'=>$outref,
  3230. 'label'=>$outval,
  3231. 'qty'=>$outqty,
  3232. 'price_qty_ht'=>price2num($objp->fprice, 'MU'), // Keep higher resolution for price for the min qty
  3233. 'price_unit_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price
  3234. 'price_ht'=>price2num($objp->unitprice, 'MU'), // This is used to fill the Unit Price (for compatibility)
  3235. 'price_qty_ht_locale'=>price($objp->fprice),
  3236. 'price_unit_ht_locale'=>price($objp->unitprice),
  3237. 'tva_tx'=>$objp->tva_tx,
  3238. 'default_vat_code'=>$objp->default_vat_code,
  3239. 'discount'=>$outdiscount,
  3240. 'type'=>$outtype,
  3241. 'duration_value'=>$outdurationvalue,
  3242. 'duration_unit'=>$outdurationunit,
  3243. 'disabled'=>(empty($objp->idprodfournprice) ? true : false),
  3244. 'description'=>$objp->description
  3245. )
  3246. );
  3247. // Exemple of var_dump $outarray
  3248. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  3249. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  3250. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  3251. //}
  3252. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3253. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  3254. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  3255. $i++;
  3256. }
  3257. $out .= '</select>';
  3258. $this->db->free($result);
  3259. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  3260. $out .= ajax_combobox($htmlname);
  3261. if (empty($outputmode)) {
  3262. return $out;
  3263. }
  3264. return $outarray;
  3265. } else {
  3266. dol_print_error($this->db);
  3267. }
  3268. }
  3269. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3270. /**
  3271. * Return list of suppliers prices for a product
  3272. *
  3273. * @param int $productid Id of product
  3274. * @param string $htmlname Name of HTML field
  3275. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  3276. * @return string
  3277. */
  3278. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  3279. {
  3280. // phpcs:enable
  3281. global $langs, $conf;
  3282. $langs->load('stocks');
  3283. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  3284. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  3285. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  3286. $sql .= " FROM ".$this->db->prefix()."product as p";
  3287. $sql .= " LEFT JOIN ".$this->db->prefix()."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  3288. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON pfp.fk_soc = s.rowid";
  3289. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  3290. $sql .= " AND p.tobuy = 1";
  3291. $sql .= " AND s.fournisseur = 1";
  3292. $sql .= " AND p.rowid = ".((int) $productid);
  3293. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  3294. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  3295. $result = $this->db->query($sql);
  3296. if ($result) {
  3297. $num = $this->db->num_rows($result);
  3298. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3299. if (!$num) {
  3300. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  3301. } else {
  3302. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  3303. $form .= '<option value="0">&nbsp;</option>';
  3304. $i = 0;
  3305. while ($i < $num) {
  3306. $objp = $this->db->fetch_object($result);
  3307. $opt = '<option value="'.$objp->idprodfournprice.'"';
  3308. //if there is only one supplier, preselect it
  3309. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  3310. $opt .= ' selected';
  3311. }
  3312. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  3313. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  3314. $prod_supplier = new ProductFournisseur($this->db);
  3315. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  3316. $prod_supplier->id = $productid;
  3317. $prod_supplier->fourn_qty = $objp->quantity;
  3318. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  3319. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  3320. $priceparser = new PriceParser($this->db);
  3321. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  3322. if ($price_result >= 0) {
  3323. $objp->fprice = $price_result;
  3324. if ($objp->quantity >= 1) {
  3325. $objp->unitprice = $objp->fprice / $objp->quantity;
  3326. }
  3327. }
  3328. }
  3329. if ($objp->quantity == 1) {
  3330. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  3331. }
  3332. $opt .= $objp->quantity.' ';
  3333. if ($objp->quantity == 1) {
  3334. $opt .= $langs->trans("Unit");
  3335. } else {
  3336. $opt .= $langs->trans("Units");
  3337. }
  3338. if ($objp->quantity > 1) {
  3339. $opt .= " - ";
  3340. $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");
  3341. }
  3342. if ($objp->duration) {
  3343. $opt .= " - ".$objp->duration;
  3344. }
  3345. $opt .= "</option>\n";
  3346. $form .= $opt;
  3347. $i++;
  3348. }
  3349. }
  3350. $form .= '</select>';
  3351. $this->db->free($result);
  3352. return $form;
  3353. } else {
  3354. dol_print_error($this->db);
  3355. }
  3356. }
  3357. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3358. /**
  3359. * Return list of delivery address
  3360. *
  3361. * @param string $selected Id contact pre-selectionn
  3362. * @param int $socid Id of company
  3363. * @param string $htmlname Name of HTML field
  3364. * @param int $showempty Add an empty field
  3365. * @return integer|null
  3366. */
  3367. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  3368. {
  3369. // phpcs:enable
  3370. // looking for users
  3371. $sql = "SELECT a.rowid, a.label";
  3372. $sql .= " FROM ".$this->db->prefix()."societe_address as a";
  3373. $sql .= " WHERE a.fk_soc = ".((int) $socid);
  3374. $sql .= " ORDER BY a.label ASC";
  3375. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  3376. $resql = $this->db->query($sql);
  3377. if ($resql) {
  3378. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3379. if ($showempty) {
  3380. print '<option value="0">&nbsp;</option>';
  3381. }
  3382. $num = $this->db->num_rows($resql);
  3383. $i = 0;
  3384. if ($num) {
  3385. while ($i < $num) {
  3386. $obj = $this->db->fetch_object($resql);
  3387. if ($selected && $selected == $obj->rowid) {
  3388. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  3389. } else {
  3390. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  3391. }
  3392. $i++;
  3393. }
  3394. }
  3395. print '</select>';
  3396. return $num;
  3397. } else {
  3398. dol_print_error($this->db);
  3399. }
  3400. }
  3401. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3402. /**
  3403. * Load into cache list of payment terms
  3404. *
  3405. * @return int Nb of lines loaded, <0 if KO
  3406. */
  3407. public function load_cache_conditions_paiements()
  3408. {
  3409. // phpcs:enable
  3410. global $langs;
  3411. $num = count($this->cache_conditions_paiements);
  3412. if ($num > 0) {
  3413. return 0; // Cache already loaded
  3414. }
  3415. dol_syslog(__METHOD__, LOG_DEBUG);
  3416. $sql = "SELECT rowid, code, libelle as label, deposit_percent";
  3417. $sql .= " FROM ".$this->db->prefix().'c_payment_term';
  3418. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  3419. $sql .= " AND active > 0";
  3420. $sql .= " ORDER BY sortorder";
  3421. $resql = $this->db->query($sql);
  3422. if ($resql) {
  3423. $num = $this->db->num_rows($resql);
  3424. $i = 0;
  3425. while ($i < $num) {
  3426. $obj = $this->db->fetch_object($resql);
  3427. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3428. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3429. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  3430. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  3431. $this->cache_conditions_paiements[$obj->rowid]['deposit_percent'] = $obj->deposit_percent;
  3432. $i++;
  3433. }
  3434. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  3435. return $num;
  3436. } else {
  3437. dol_print_error($this->db);
  3438. return -1;
  3439. }
  3440. }
  3441. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3442. /**
  3443. * Load int a cache property th elist of possible delivery delays.
  3444. *
  3445. * @return int Nb of lines loaded, <0 if KO
  3446. */
  3447. public function load_cache_availability()
  3448. {
  3449. // phpcs:enable
  3450. global $langs;
  3451. $num = count($this->cache_availability); // TODO Use $conf->cache['availability'] instead of $this->cache_availability
  3452. if ($num > 0) {
  3453. return 0; // Cache already loaded
  3454. }
  3455. dol_syslog(__METHOD__, LOG_DEBUG);
  3456. $langs->load('propal');
  3457. $sql = "SELECT rowid, code, label, position";
  3458. $sql .= " FROM ".$this->db->prefix().'c_availability';
  3459. $sql .= " WHERE active > 0";
  3460. $resql = $this->db->query($sql);
  3461. if ($resql) {
  3462. $num = $this->db->num_rows($resql);
  3463. $i = 0;
  3464. while ($i < $num) {
  3465. $obj = $this->db->fetch_object($resql);
  3466. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3467. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3468. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  3469. $this->cache_availability[$obj->rowid]['label'] = $label;
  3470. $this->cache_availability[$obj->rowid]['position'] = $obj->position;
  3471. $i++;
  3472. }
  3473. $this->cache_availability = dol_sort_array($this->cache_availability, 'position', 'asc', 0, 0, 1);
  3474. return $num;
  3475. } else {
  3476. dol_print_error($this->db);
  3477. return -1;
  3478. }
  3479. }
  3480. /**
  3481. * Retourne la liste des types de delais de livraison possibles
  3482. *
  3483. * @param int $selected Id du type de delais pre-selectionne
  3484. * @param string $htmlname Nom de la zone select
  3485. * @param string $filtertype To add a filter
  3486. * @param int $addempty Add empty entry
  3487. * @param string $morecss More CSS
  3488. * @return void
  3489. */
  3490. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0, $morecss = '')
  3491. {
  3492. global $langs, $user;
  3493. $this->load_cache_availability();
  3494. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3495. print '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3496. if ($addempty) {
  3497. print '<option value="0">&nbsp;</option>';
  3498. }
  3499. foreach ($this->cache_availability as $id => $arrayavailability) {
  3500. if ($selected == $id) {
  3501. print '<option value="'.$id.'" selected>';
  3502. } else {
  3503. print '<option value="'.$id.'">';
  3504. }
  3505. print dol_escape_htmltag($arrayavailability['label']);
  3506. print '</option>';
  3507. }
  3508. print '</select>';
  3509. if ($user->admin) {
  3510. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3511. }
  3512. print ajax_combobox($htmlname);
  3513. }
  3514. /**
  3515. * Load into cache cache_demand_reason, array of input reasons
  3516. *
  3517. * @return int Nb of lines loaded, <0 if KO
  3518. */
  3519. public function loadCacheInputReason()
  3520. {
  3521. global $langs;
  3522. $num = count($this->cache_demand_reason); // TODO Use $conf->cache['input_reason'] instead of $this->cache_demand_reason
  3523. if ($num > 0) {
  3524. return 0; // Cache already loaded
  3525. }
  3526. $sql = "SELECT rowid, code, label";
  3527. $sql .= " FROM ".$this->db->prefix().'c_input_reason';
  3528. $sql .= " WHERE active > 0";
  3529. $resql = $this->db->query($sql);
  3530. if ($resql) {
  3531. $num = $this->db->num_rows($resql);
  3532. $i = 0;
  3533. $tmparray = array();
  3534. while ($i < $num) {
  3535. $obj = $this->db->fetch_object($resql);
  3536. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3537. $label = ($obj->label != '-' ? $obj->label : '');
  3538. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
  3539. $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  3540. }
  3541. if ($langs->trans($obj->code) != $obj->code) {
  3542. $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  3543. }
  3544. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  3545. $tmparray[$obj->rowid]['code'] = $obj->code;
  3546. $tmparray[$obj->rowid]['label'] = $label;
  3547. $i++;
  3548. }
  3549. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  3550. unset($tmparray);
  3551. return $num;
  3552. } else {
  3553. dol_print_error($this->db);
  3554. return -1;
  3555. }
  3556. }
  3557. /**
  3558. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3559. * List found into table c_input_reason loaded by loadCacheInputReason
  3560. *
  3561. * @param int $selected Id or code of type origin to select by default
  3562. * @param string $htmlname Nom de la zone select
  3563. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  3564. * @param int $addempty Add an empty entry
  3565. * @param string $morecss Add more css to the HTML select component
  3566. * @param int $notooltip Do not show the tooltip for admin
  3567. * @return void
  3568. */
  3569. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0, $morecss = '', $notooltip = 0)
  3570. {
  3571. global $langs, $user;
  3572. $this->loadCacheInputReason();
  3573. print '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3574. if ($addempty) {
  3575. print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  3576. }
  3577. foreach ($this->cache_demand_reason as $id => $arraydemandreason) {
  3578. if ($arraydemandreason['code'] == $exclude) {
  3579. continue;
  3580. }
  3581. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code'])) {
  3582. print '<option value="'.$arraydemandreason['id'].'" selected>';
  3583. } else {
  3584. print '<option value="'.$arraydemandreason['id'].'">';
  3585. }
  3586. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  3587. print $langs->trans($label);
  3588. print '</option>';
  3589. }
  3590. print '</select>';
  3591. if ($user->admin && empty($notooltip)) {
  3592. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3593. }
  3594. print ajax_combobox('select_'.$htmlname);
  3595. }
  3596. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3597. /**
  3598. * Charge dans cache la liste des types de paiements possibles
  3599. *
  3600. * @return int Nb of lines loaded, <0 if KO
  3601. */
  3602. public function load_cache_types_paiements()
  3603. {
  3604. // phpcs:enable
  3605. global $langs;
  3606. $num = count($this->cache_types_paiements); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_types_paiements
  3607. if ($num > 0) {
  3608. return $num; // Cache already loaded
  3609. }
  3610. dol_syslog(__METHOD__, LOG_DEBUG);
  3611. $this->cache_types_paiements = array();
  3612. $sql = "SELECT id, code, libelle as label, type, active";
  3613. $sql .= " FROM ".$this->db->prefix()."c_paiement";
  3614. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3615. $resql = $this->db->query($sql);
  3616. if ($resql) {
  3617. $num = $this->db->num_rows($resql);
  3618. $i = 0;
  3619. while ($i < $num) {
  3620. $obj = $this->db->fetch_object($resql);
  3621. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3622. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3623. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3624. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3625. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3626. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3627. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3628. $i++;
  3629. }
  3630. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3631. return $num;
  3632. } else {
  3633. dol_print_error($this->db);
  3634. return -1;
  3635. }
  3636. }
  3637. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3638. /**
  3639. * print list of payment modes.
  3640. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3641. * See instead to force the default value by the caller.
  3642. *
  3643. * @param int $selected Id of payment term to preselect by default
  3644. * @param string $htmlname Nom de la zone select
  3645. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3646. * @param int $addempty Add an empty entry
  3647. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3648. * @param string $morecss Add more CSS on select tag
  3649. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3650. * 0 : use default deposit percentage from entry
  3651. * > 0 : force deposit percentage (for example, from company object)
  3652. * @return void
  3653. */
  3654. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3655. {
  3656. // phpcs:enable
  3657. print $this->getSelectConditionsPaiements($selected, $htmlname, $filtertype, $addempty, $noinfoadmin, $morecss, $deposit_percent);
  3658. }
  3659. /**
  3660. * Return list of payment modes.
  3661. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3662. * See instead to force the default value by the caller.
  3663. *
  3664. * @param int $selected Id of payment term to preselect by default
  3665. * @param string $htmlname Nom de la zone select
  3666. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  3667. * @param int $addempty Add an empty entry
  3668. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3669. * @param string $morecss Add more CSS on select tag
  3670. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  3671. * 0 : use default deposit percentage from entry
  3672. * > 0 : force deposit percentage (for example, from company object)
  3673. * @return string String for the HTML select component
  3674. */
  3675. public function getSelectConditionsPaiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '', $deposit_percent = -1)
  3676. {
  3677. global $langs, $user, $conf;
  3678. $out = '';
  3679. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3680. $this->load_cache_conditions_paiements();
  3681. // Set default value if not already set by caller
  3682. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
  3683. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3684. }
  3685. $out.= '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3686. if ($addempty) {
  3687. $out.= '<option value="0">&nbsp;</option>';
  3688. }
  3689. $selectedDepositPercent = null;
  3690. foreach ($this->cache_conditions_paiements as $id => $arrayconditions) {
  3691. if ($filtertype <= 0 && ! empty($arrayconditions['deposit_percent'])) {
  3692. continue;
  3693. }
  3694. if ($selected == $id) {
  3695. $selectedDepositPercent = $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'];
  3696. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '" selected>';
  3697. } else {
  3698. $out .= '<option value="'.$id.'" data-deposit_percent="' . $arrayconditions['deposit_percent'] . '">';
  3699. }
  3700. $label = $arrayconditions['label'];
  3701. if (! empty($arrayconditions['deposit_percent'])) {
  3702. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $arrayconditions['deposit_percent'], $label);
  3703. }
  3704. $out.= $label;
  3705. $out.= '</option>';
  3706. }
  3707. $out.= '</select>';
  3708. if ($user->admin && empty($noinfoadmin)) {
  3709. $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3710. }
  3711. $out.= ajax_combobox($htmlname);
  3712. if ($deposit_percent >= 0) {
  3713. $out .= ' <span id="'.$htmlname.'_deposit_percent_container"' . (empty($selectedDepositPercent) ? ' style="display: none"' : '') . '>';
  3714. $out .= $langs->trans('DepositPercent') . ' : ';
  3715. $out .= '<input id="'.$htmlname.'_deposit_percent" name="'.$htmlname.'_deposit_percent" class="maxwidth50" value="' . strval($deposit_percent) . '" />';
  3716. $out .= '</span>';
  3717. $out .= '
  3718. <script>
  3719. $(document).ready(function () {
  3720. $("#' . $htmlname . '").change(function () {
  3721. let $selected = $(this).find("option:selected");
  3722. let depositPercent = $selected.attr("data-deposit_percent");
  3723. if (depositPercent.length > 0) {
  3724. $("#'.$htmlname.'_deposit_percent_container").show().find("#'.$htmlname.'_deposit_percent").val(depositPercent);
  3725. } else {
  3726. $("#'.$htmlname.'_deposit_percent_container").hide();
  3727. }
  3728. return true;
  3729. });
  3730. });
  3731. </script>';
  3732. }
  3733. return $out;
  3734. }
  3735. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3736. /**
  3737. * Return list of payment methods
  3738. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3739. *
  3740. * @param string $selected Id or code or preselected payment mode
  3741. * @param string $htmlname Name of select field
  3742. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3743. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3744. * @param int $empty 1=can be empty, 0 otherwise
  3745. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3746. * @param int $maxlength Max length of label
  3747. * @param int $active Active or not, -1 = all
  3748. * @param string $morecss Add more CSS on select tag
  3749. * @param int $nooutput 1=Return string, do not send to output
  3750. * @return string|void String for the HTML select component
  3751. */
  3752. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '', $nooutput = 0)
  3753. {
  3754. // phpcs:enable
  3755. global $langs, $user, $conf;
  3756. $out = '';
  3757. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3758. $filterarray = array();
  3759. if ($filtertype == 'CRDT') {
  3760. $filterarray = array(0, 2, 3);
  3761. } elseif ($filtertype == 'DBIT') {
  3762. $filterarray = array(1, 2, 3);
  3763. } elseif ($filtertype != '' && $filtertype != '-1') {
  3764. $filterarray = explode(',', $filtertype);
  3765. }
  3766. $this->load_cache_types_paiements();
  3767. // Set default value if not already set by caller
  3768. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) {
  3769. $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3770. }
  3771. $out .= '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3772. if ($empty) {
  3773. $out .= '<option value="">&nbsp;</option>';
  3774. }
  3775. foreach ($this->cache_types_paiements as $id => $arraytypes) {
  3776. // If not good status
  3777. if ($active >= 0 && $arraytypes['active'] != $active) {
  3778. continue;
  3779. }
  3780. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3781. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) {
  3782. continue;
  3783. }
  3784. // We discard empty line if showempty is on because an empty line has already been output.
  3785. if ($empty && empty($arraytypes['code'])) {
  3786. continue;
  3787. }
  3788. if ($format == 0) {
  3789. $out .= '<option value="'.$id.'"';
  3790. } elseif ($format == 1) {
  3791. $out .= '<option value="'.$arraytypes['code'].'"';
  3792. } elseif ($format == 2) {
  3793. $out .= '<option value="'.$arraytypes['code'].'"';
  3794. } elseif ($format == 3) {
  3795. $out .= '<option value="'.$id.'"';
  3796. }
  3797. // Print attribute selected or not
  3798. if ($format == 1 || $format == 2) {
  3799. if ($selected == $arraytypes['code']) {
  3800. $out .= ' selected';
  3801. }
  3802. } else {
  3803. if ($selected == $id) {
  3804. $out .= ' selected';
  3805. }
  3806. }
  3807. $out .= '>';
  3808. $value = '';
  3809. if ($format == 0) {
  3810. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3811. } elseif ($format == 1) {
  3812. $value = $arraytypes['code'];
  3813. } elseif ($format == 2) {
  3814. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3815. } elseif ($format == 3) {
  3816. $value = $arraytypes['code'];
  3817. }
  3818. $out .= $value ? $value : '&nbsp;';
  3819. $out .= '</option>';
  3820. }
  3821. $out .= '</select>';
  3822. if ($user->admin && !$noadmininfo) {
  3823. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3824. }
  3825. $out .= ajax_combobox('select'.$htmlname);
  3826. if (empty($nooutput)) {
  3827. print $out;
  3828. } else {
  3829. return $out;
  3830. }
  3831. }
  3832. /**
  3833. * Selection HT or TTC
  3834. *
  3835. * @param string $selected Id pre-selectionne
  3836. * @param string $htmlname Nom de la zone select
  3837. * @param string $addjscombo Add js combo
  3838. * @return string Code of HTML select to chose tax or not
  3839. */
  3840. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type', $addjscombo = 0)
  3841. {
  3842. global $langs;
  3843. $return = '<select class="flat maxwidth100" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3844. $options = array(
  3845. 'HT'=>$langs->trans("HT"),
  3846. 'TTC'=>$langs->trans("TTC")
  3847. );
  3848. foreach ($options as $id => $value) {
  3849. if ($selected == $id) {
  3850. $return .= '<option value="'.$id.'" selected>'.$value;
  3851. } else {
  3852. $return .= '<option value="'.$id.'">'.$value;
  3853. }
  3854. $return .= '</option>';
  3855. }
  3856. $return .= '</select>';
  3857. if ($addjscombo) {
  3858. $return .= ajax_combobox('select_'.$htmlname);
  3859. }
  3860. return $return;
  3861. }
  3862. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3863. /**
  3864. * Load in cache list of transport mode
  3865. *
  3866. * @return int Nb of lines loaded, <0 if KO
  3867. */
  3868. public function load_cache_transport_mode()
  3869. {
  3870. // phpcs:enable
  3871. global $langs;
  3872. $num = count($this->cache_transport_mode); // TODO Use $conf->cache['payment_mode'] instead of $this->cache_transport_mode
  3873. if ($num > 0) {
  3874. return $num; // Cache already loaded
  3875. }
  3876. dol_syslog(__METHOD__, LOG_DEBUG);
  3877. $this->cache_transport_mode = array();
  3878. $sql = "SELECT rowid, code, label, active";
  3879. $sql .= " FROM ".$this->db->prefix()."c_transport_mode";
  3880. $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")";
  3881. $resql = $this->db->query($sql);
  3882. if ($resql) {
  3883. $num = $this->db->num_rows($resql);
  3884. $i = 0;
  3885. while ($i < $num) {
  3886. $obj = $this->db->fetch_object($resql);
  3887. // If traduction exist, we use it else we take the default label
  3888. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3889. $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid;
  3890. $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code;
  3891. $this->cache_transport_mode[$obj->rowid]['label'] = $label;
  3892. $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active;
  3893. $i++;
  3894. }
  3895. $this->cache_transport_mode = dol_sort_array($this->cache_transport_mode, 'label', 'asc', 0, 0, 1);
  3896. return $num;
  3897. } else {
  3898. dol_print_error($this->db);
  3899. return -1;
  3900. }
  3901. }
  3902. /**
  3903. * Return list of transport mode for intracomm report
  3904. *
  3905. * @param string $selected Id of the transport mode pre-selected
  3906. * @param string $htmlname Name of the select field
  3907. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3908. * @param int $empty 1=can be empty, 0 else
  3909. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3910. * @param int $maxlength Max length of label
  3911. * @param int $active Active or not, -1 = all
  3912. * @param string $morecss Add more CSS on select tag
  3913. * @return void
  3914. */
  3915. public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3916. {
  3917. global $langs, $user;
  3918. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG);
  3919. $this->load_cache_transport_mode();
  3920. print '<select id="select'.$htmlname.'" class="flat selectmodetransport'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3921. if ($empty) {
  3922. print '<option value="">&nbsp;</option>';
  3923. }
  3924. foreach ($this->cache_transport_mode as $id => $arraytypes) {
  3925. // If not good status
  3926. if ($active >= 0 && $arraytypes['active'] != $active) {
  3927. continue;
  3928. }
  3929. // We discard empty line if showempty is on because an empty line has already been output.
  3930. if ($empty && empty($arraytypes['code'])) {
  3931. continue;
  3932. }
  3933. if ($format == 0) {
  3934. print '<option value="'.$id.'"';
  3935. } elseif ($format == 1) {
  3936. print '<option value="'.$arraytypes['code'].'"';
  3937. } elseif ($format == 2) {
  3938. print '<option value="'.$arraytypes['code'].'"';
  3939. } elseif ($format == 3) {
  3940. print '<option value="'.$id.'"';
  3941. }
  3942. // If text is selected, we compare with code, else with id
  3943. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
  3944. print ' selected';
  3945. } elseif ($selected == $id) {
  3946. print ' selected';
  3947. }
  3948. print '>';
  3949. $value = '';
  3950. if ($format == 0) {
  3951. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3952. } elseif ($format == 1) {
  3953. $value = $arraytypes['code'];
  3954. } elseif ($format == 2) {
  3955. $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3956. } elseif ($format == 3) {
  3957. $value = $arraytypes['code'];
  3958. }
  3959. print $value ? $value : '&nbsp;';
  3960. print '</option>';
  3961. }
  3962. print '</select>';
  3963. if ($user->admin && !$noadmininfo) {
  3964. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3965. }
  3966. }
  3967. /**
  3968. * Return a HTML select list of shipping mode
  3969. *
  3970. * @param string $selected Id shipping mode pre-selected
  3971. * @param string $htmlname Name of select zone
  3972. * @param string $filtre To filter list. This parameter must not come from input of users
  3973. * @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.
  3974. * @param string $moreattrib To add more attribute on select
  3975. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3976. * @param string $morecss More CSS
  3977. * @return void
  3978. */
  3979. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '', $noinfoadmin = 0, $morecss = '')
  3980. {
  3981. global $langs, $conf, $user;
  3982. $langs->load("admin");
  3983. $langs->load("deliveries");
  3984. $sql = "SELECT rowid, code, libelle as label";
  3985. $sql .= " FROM ".$this->db->prefix()."c_shipment_mode";
  3986. $sql .= " WHERE active > 0";
  3987. if ($filtre) {
  3988. $sql .= " AND ".$filtre;
  3989. }
  3990. $sql .= " ORDER BY libelle ASC";
  3991. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3992. $result = $this->db->query($sql);
  3993. if ($result) {
  3994. $num = $this->db->num_rows($result);
  3995. $i = 0;
  3996. if ($num) {
  3997. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3998. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3999. print '<option value="-1">&nbsp;</option>';
  4000. }
  4001. while ($i < $num) {
  4002. $obj = $this->db->fetch_object($result);
  4003. if ($selected == $obj->rowid) {
  4004. print '<option value="'.$obj->rowid.'" selected>';
  4005. } else {
  4006. print '<option value="'.$obj->rowid.'">';
  4007. }
  4008. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  4009. print '</option>';
  4010. $i++;
  4011. }
  4012. print "</select>";
  4013. if ($user->admin && empty($noinfoadmin)) {
  4014. print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4015. }
  4016. print ajax_combobox('select'.$htmlname);
  4017. } else {
  4018. print $langs->trans("NoShippingMethodDefined");
  4019. }
  4020. } else {
  4021. dol_print_error($this->db);
  4022. }
  4023. }
  4024. /**
  4025. * Display form to select shipping mode
  4026. *
  4027. * @param string $page Page
  4028. * @param int $selected Id of shipping mode
  4029. * @param string $htmlname Name of select html field
  4030. * @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.
  4031. * @return void
  4032. */
  4033. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  4034. {
  4035. global $langs;
  4036. $langs->load("deliveries");
  4037. if ($htmlname != "none") {
  4038. print '<form method="POST" action="'.$page.'">';
  4039. print '<input type="hidden" name="action" value="setshippingmethod">';
  4040. print '<input type="hidden" name="token" value="'.newToken().'">';
  4041. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  4042. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4043. print '</form>';
  4044. } else {
  4045. if ($selected) {
  4046. $code = $langs->getLabelFromKey($this->db, $selected, 'c_shipment_mode', 'rowid', 'code');
  4047. print $langs->trans("SendingMethod".strtoupper($code));
  4048. } else {
  4049. print "&nbsp;";
  4050. }
  4051. }
  4052. }
  4053. /**
  4054. * Creates HTML last in cycle situation invoices selector
  4055. *
  4056. * @param string $selected Preselected ID
  4057. * @param int $socid Company ID
  4058. *
  4059. * @return string HTML select
  4060. */
  4061. public function selectSituationInvoices($selected = '', $socid = 0)
  4062. {
  4063. global $langs;
  4064. $langs->load('bills');
  4065. $opt = '<option value="" selected></option>';
  4066. $sql = "SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc";
  4067. $sql .= ' FROM '.$this->db->prefix().'facture';
  4068. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  4069. $sql .= ' AND situation_counter >= 1';
  4070. $sql .= ' AND fk_soc = '.(int) $socid;
  4071. $sql .= ' AND type <> 2';
  4072. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  4073. $resql = $this->db->query($sql);
  4074. if ($resql && $this->db->num_rows($resql) > 0) {
  4075. // Last seen cycle
  4076. $ref = 0;
  4077. while ($obj = $this->db->fetch_object($resql)) {
  4078. //Same cycle ?
  4079. if ($obj->situation_cycle_ref != $ref) {
  4080. // Just seen this cycle
  4081. $ref = $obj->situation_cycle_ref;
  4082. //not final ?
  4083. if ($obj->situation_final != 1) {
  4084. //Not prov?
  4085. if (substr($obj->ref, 1, 4) != 'PROV') {
  4086. if ($selected == $obj->rowid) {
  4087. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  4088. } else {
  4089. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  4090. }
  4091. }
  4092. }
  4093. }
  4094. }
  4095. } else {
  4096. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4097. }
  4098. if ($opt == '<option value ="" selected></option>') {
  4099. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  4100. }
  4101. return $opt;
  4102. }
  4103. /**
  4104. * Creates HTML units selector (code => label)
  4105. *
  4106. * @param string $selected Preselected Unit ID
  4107. * @param string $htmlname Select name
  4108. * @param int $showempty Add a nempty line
  4109. * @param string $unit_type Restrict to one given unit type
  4110. * @return string HTML select
  4111. */
  4112. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0, $unit_type = '')
  4113. {
  4114. global $langs;
  4115. $langs->load('products');
  4116. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  4117. $sql = "SELECT rowid, label, code FROM ".$this->db->prefix()."c_units";
  4118. $sql .= ' WHERE active > 0';
  4119. if (!empty($unit_type)) {
  4120. $sql .= " AND unit_type = '".$this->db->escape($unit_type)."'";
  4121. }
  4122. $sql .= " ORDER BY sortorder";
  4123. $resql = $this->db->query($sql);
  4124. if ($resql && $this->db->num_rows($resql) > 0) {
  4125. if ($showempty) {
  4126. $return .= '<option value="none"></option>';
  4127. }
  4128. while ($res = $this->db->fetch_object($resql)) {
  4129. $unitLabel = $res->label;
  4130. if (!empty($langs->tab_translate['unit'.$res->code])) { // check if Translation is available before
  4131. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  4132. }
  4133. if ($selected == $res->rowid) {
  4134. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  4135. } else {
  4136. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  4137. }
  4138. }
  4139. $return .= '</select>';
  4140. }
  4141. return $return;
  4142. }
  4143. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4144. /**
  4145. * Return a HTML select list of bank accounts
  4146. *
  4147. * @param string $selected Id account pre-selected
  4148. * @param string $htmlname Name of select zone
  4149. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  4150. * @param string $filtre To filter list. This parameter must not come from input of users
  4151. * @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.
  4152. * @param string $moreattrib To add more attribute on select
  4153. * @param int $showcurrency Show currency in label
  4154. * @param string $morecss More CSS
  4155. * @param int $nooutput 1=Return string, do not send to output
  4156. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  4157. */
  4158. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '', $nooutput = 0)
  4159. {
  4160. // phpcs:enable
  4161. global $langs, $conf;
  4162. $out = '';
  4163. $langs->load("admin");
  4164. $num = 0;
  4165. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  4166. $sql .= " FROM ".$this->db->prefix()."bank_account";
  4167. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  4168. if ($status != 2) {
  4169. $sql .= " AND clos = ".(int) $status;
  4170. }
  4171. if ($filtre) {
  4172. $sql .= " AND ".$filtre;
  4173. }
  4174. $sql .= " ORDER BY label";
  4175. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  4176. $result = $this->db->query($sql);
  4177. if ($result) {
  4178. $num = $this->db->num_rows($result);
  4179. $i = 0;
  4180. if ($num) {
  4181. $out .= '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4182. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4183. $out .= '<option value="-1">&nbsp;</option>';
  4184. }
  4185. while ($i < $num) {
  4186. $obj = $this->db->fetch_object($result);
  4187. if ($selected == $obj->rowid || ($useempty == 2 && $num == 1 && empty($selected))) {
  4188. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'" selected>';
  4189. } else {
  4190. $out .= '<option value="'.$obj->rowid.'" data-currency-code="'.$obj->currency_code.'">';
  4191. }
  4192. $out .= trim($obj->label);
  4193. if ($showcurrency) {
  4194. $out .= ' ('.$obj->currency_code.')';
  4195. }
  4196. if ($status == 2 && $obj->status == 1) {
  4197. $out .= ' ('.$langs->trans("Closed").')';
  4198. }
  4199. $out .= '</option>';
  4200. $i++;
  4201. }
  4202. $out .= "</select>";
  4203. $out .= ajax_combobox('select'.$htmlname);
  4204. } else {
  4205. if ($status == 0) {
  4206. $out .= '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  4207. } else {
  4208. $out .= '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  4209. }
  4210. }
  4211. } else {
  4212. dol_print_error($this->db);
  4213. }
  4214. // Output or return
  4215. if (empty($nooutput)) {
  4216. print $out;
  4217. } else {
  4218. return $out;
  4219. }
  4220. return $num;
  4221. }
  4222. /**
  4223. * Return a HTML select list of establishment
  4224. *
  4225. * @param string $selected Id establishment pre-selected
  4226. * @param string $htmlname Name of select zone
  4227. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  4228. * @param string $filtre To filter list. This parameter must not come from input of users
  4229. * @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.
  4230. * @param string $moreattrib To add more attribute on select
  4231. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  4232. */
  4233. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  4234. {
  4235. global $langs, $conf;
  4236. $langs->load("admin");
  4237. $num = 0;
  4238. $sql = "SELECT rowid, name, fk_country, status, entity";
  4239. $sql .= " FROM ".$this->db->prefix()."establishment";
  4240. $sql .= " WHERE 1=1";
  4241. if ($status != 2) {
  4242. $sql .= " AND status = ".(int) $status;
  4243. }
  4244. if ($filtre) {
  4245. $sql .= " AND ".$filtre;
  4246. }
  4247. $sql .= " ORDER BY name";
  4248. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  4249. $result = $this->db->query($sql);
  4250. if ($result) {
  4251. $num = $this->db->num_rows($result);
  4252. $i = 0;
  4253. if ($num) {
  4254. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  4255. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  4256. print '<option value="-1">&nbsp;</option>';
  4257. }
  4258. while ($i < $num) {
  4259. $obj = $this->db->fetch_object($result);
  4260. if ($selected == $obj->rowid) {
  4261. print '<option value="'.$obj->rowid.'" selected>';
  4262. } else {
  4263. print '<option value="'.$obj->rowid.'">';
  4264. }
  4265. print trim($obj->name);
  4266. if ($status == 2 && $obj->status == 1) {
  4267. print ' ('.$langs->trans("Closed").')';
  4268. }
  4269. print '</option>';
  4270. $i++;
  4271. }
  4272. print "</select>";
  4273. } else {
  4274. if ($status == 0) {
  4275. print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  4276. } else {
  4277. print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  4278. }
  4279. }
  4280. } else {
  4281. dol_print_error($this->db);
  4282. }
  4283. }
  4284. /**
  4285. * Display form to select bank account
  4286. *
  4287. * @param string $page Page
  4288. * @param int $selected Id of bank account
  4289. * @param string $htmlname Name of select html field
  4290. * @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.
  4291. * @return void
  4292. */
  4293. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  4294. {
  4295. global $langs;
  4296. if ($htmlname != "none") {
  4297. print '<form method="POST" action="'.$page.'">';
  4298. print '<input type="hidden" name="action" value="setbankaccount">';
  4299. print '<input type="hidden" name="token" value="'.newToken().'">';
  4300. print img_picto('', 'bank_account', 'class="pictofixedwidth"');
  4301. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  4302. if ($nbaccountfound > 0) {
  4303. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  4304. }
  4305. print '</form>';
  4306. } else {
  4307. $langs->load('banks');
  4308. if ($selected) {
  4309. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  4310. $bankstatic = new Account($this->db);
  4311. $result = $bankstatic->fetch($selected);
  4312. if ($result) {
  4313. print $bankstatic->getNomUrl(1);
  4314. }
  4315. } else {
  4316. print "&nbsp;";
  4317. }
  4318. }
  4319. }
  4320. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4321. /**
  4322. * Return list of categories having choosed type
  4323. *
  4324. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  4325. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  4326. * @param string $htmlname HTML field name
  4327. * @param int $maxlength Maximum length for labels
  4328. * @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.
  4329. * $markafterid can be an :
  4330. * - int (id of category)
  4331. * - string (categories ids seprated by comma)
  4332. * - array (list of categories ids)
  4333. * @param int $outputmode 0=HTML select string, 1=Array
  4334. * @param int $include [=0] Removed or 1=Keep only
  4335. * @param string $morecss More CSS
  4336. * @return string|array
  4337. * @see select_categories()
  4338. */
  4339. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  4340. {
  4341. // phpcs:enable
  4342. global $conf, $langs;
  4343. $langs->load("categories");
  4344. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4345. // For backward compatibility
  4346. if (is_numeric($type)) {
  4347. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  4348. }
  4349. if ($type === Categorie::TYPE_BANK_LINE) {
  4350. // TODO Move this into common category feature
  4351. $cate_arbo = array();
  4352. $sql = "SELECT c.label, c.rowid";
  4353. $sql .= " FROM ".$this->db->prefix()."bank_categ as c";
  4354. $sql .= " WHERE entity = ".$conf->entity;
  4355. $sql .= " ORDER BY c.label";
  4356. $result = $this->db->query($sql);
  4357. if ($result) {
  4358. $num = $this->db->num_rows($result);
  4359. $i = 0;
  4360. while ($i < $num) {
  4361. $objp = $this->db->fetch_object($result);
  4362. if ($objp) {
  4363. $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  4364. }
  4365. $i++;
  4366. }
  4367. $this->db->free($result);
  4368. } else {
  4369. dol_print_error($this->db);
  4370. }
  4371. } else {
  4372. $cat = new Categorie($this->db);
  4373. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  4374. }
  4375. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  4376. $outarray = array();
  4377. if (is_array($cate_arbo)) {
  4378. if (!count($cate_arbo)) {
  4379. $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  4380. } else {
  4381. $output .= '<option value="-1">&nbsp;</option>';
  4382. foreach ($cate_arbo as $key => $value) {
  4383. if ($cate_arbo[$key]['id'] == $selected || ($selected === 'auto' && count($cate_arbo) == 1)) {
  4384. $add = 'selected ';
  4385. } else {
  4386. $add = '';
  4387. }
  4388. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  4389. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  4390. }
  4391. }
  4392. }
  4393. $output .= '</select>';
  4394. $output .= "\n";
  4395. if ($outputmode) {
  4396. return $outarray;
  4397. }
  4398. return $output;
  4399. }
  4400. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4401. /**
  4402. * Show a confirmation HTML form or AJAX popup
  4403. *
  4404. * @param string $page Url of page to call if confirmation is OK
  4405. * @param string $title Title
  4406. * @param string $question Question
  4407. * @param string $action Action
  4408. * @param array $formquestion An array with forms complementary inputs
  4409. * @param string $selectedchoice "" or "no" or "yes"
  4410. * @param int $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
  4411. * @param int $height Force height of box
  4412. * @param int $width Force width of box
  4413. * @return void
  4414. * @deprecated
  4415. * @see formconfirm()
  4416. */
  4417. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  4418. {
  4419. // phpcs:enable
  4420. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  4421. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  4422. }
  4423. /**
  4424. * Show a confirmation HTML form or AJAX popup.
  4425. * Easiest way to use this is with useajax=1.
  4426. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  4427. * just after calling this method. For example:
  4428. * print '<script type="text/javascript">'."\n";
  4429. * print 'jQuery(document).ready(function() {'."\n";
  4430. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  4431. * print '});'."\n";
  4432. * print '</script>'."\n";
  4433. *
  4434. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  4435. * @param string $title Title
  4436. * @param string $question Question
  4437. * @param string $action Action
  4438. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , 'size'=>, 'morecss'=>, 'moreattr'=>))
  4439. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', 'other' or 'onecolumn'...
  4440. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  4441. * @param int|string $useajax 0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
  4442. * @param int|string $height Force height of box (0 = auto)
  4443. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  4444. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  4445. * @param string $labelbuttonyes Label for Yes
  4446. * @param string $labelbuttonno Label for No
  4447. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  4448. */
  4449. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0, $labelbuttonyes = 'Yes', $labelbuttonno = 'No')
  4450. {
  4451. global $langs, $conf;
  4452. $more = '<!-- formconfirm before calling page='.dol_escape_htmltag($page).' -->';
  4453. $formconfirm = '';
  4454. $inputok = array();
  4455. $inputko = array();
  4456. // Clean parameters
  4457. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  4458. if ($conf->browser->layout == 'phone') {
  4459. $width = '95%';
  4460. }
  4461. // Set height automatically if not defined
  4462. if (empty($height)) {
  4463. $height = 220;
  4464. if (is_array($formquestion) && count($formquestion) > 2) {
  4465. $height += ((count($formquestion) - 2) * 24);
  4466. }
  4467. }
  4468. if (is_array($formquestion) && !empty($formquestion)) {
  4469. // First add hidden fields and value
  4470. foreach ($formquestion as $key => $input) {
  4471. if (is_array($input) && !empty($input)) {
  4472. if ($input['type'] == 'hidden') {
  4473. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4474. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4475. $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";
  4476. }
  4477. }
  4478. }
  4479. // Now add questions
  4480. $moreonecolumn = '';
  4481. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  4482. foreach ($formquestion as $key => $input) {
  4483. if (is_array($input) && !empty($input)) {
  4484. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : ''); // deprecated. Use morecss instead.
  4485. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  4486. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  4487. if ($input['type'] == 'text') {
  4488. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="text" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4489. } elseif ($input['type'] == 'password') {
  4490. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd"><input type="password" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  4491. } elseif ($input['type'] == 'textarea') {
  4492. /*$more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div><div class="tagtd">';
  4493. $more .= '<textarea name="'.$input['name'].'" class="'.$morecss.'"'.$moreattr.'>';
  4494. $more .= $input['value'];
  4495. $more .= '</textarea>';
  4496. $more .= '</div></div>'."\n";*/
  4497. $moreonecolumn .= '<div class="margintoponly">';
  4498. $moreonecolumn .= $input['label'].'<br>';
  4499. $moreonecolumn .= '<textarea name="'.dol_escape_htmltag($input['name']).'" id="'.dol_escape_htmltag($input['name']).'" class="'.$morecss.'"'.$moreattr.'>';
  4500. $moreonecolumn .= $input['value'];
  4501. $moreonecolumn .= '</textarea>';
  4502. $moreonecolumn .= '</div>';
  4503. } elseif ($input['type'] == 'select') {
  4504. if (empty($morecss)) {
  4505. $morecss = 'minwidth100';
  4506. }
  4507. $show_empty = isset($input['select_show_empty']) ? $input['select_show_empty'] : 1;
  4508. $key_in_label = isset($input['select_key_in_label']) ? $input['select_key_in_label'] : 0;
  4509. $value_as_key = isset($input['select_value_as_key']) ? $input['select_value_as_key'] : 0;
  4510. $translate = isset($input['select_translate']) ? $input['select_translate'] : 0;
  4511. $maxlen = isset($input['select_maxlen']) ? $input['select_maxlen'] : 0;
  4512. $disabled = isset($input['select_disabled']) ? $input['select_disabled'] : 0;
  4513. $sort = isset($input['select_sort']) ? $input['select_sort'] : '';
  4514. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4515. if (!empty($input['label'])) {
  4516. $more .= $input['label'].'</div><div class="tagtd left">';
  4517. }
  4518. $more .= $this->selectarray($input['name'], $input['values'], isset($input['default'])?$input['default']:'', $show_empty, $key_in_label, $value_as_key, $moreattr, $translate, $maxlen, $disabled, $sort, $morecss);
  4519. $more .= '</div></div>'."\n";
  4520. } elseif ($input['type'] == 'checkbox') {
  4521. $more .= '<div class="tagtr">';
  4522. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  4523. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.dol_escape_htmltag($input['name']).'" name="'.dol_escape_htmltag($input['name']).'"'.$moreattr;
  4524. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0' && $input['value'] != '') {
  4525. $more .= ' checked';
  4526. }
  4527. if (is_bool($input['value']) && $input['value']) {
  4528. $more .= ' checked';
  4529. }
  4530. if (isset($input['disabled'])) {
  4531. $more .= ' disabled';
  4532. }
  4533. $more .= ' /></div>';
  4534. $more .= '</div>'."\n";
  4535. } elseif ($input['type'] == 'radio') {
  4536. $i = 0;
  4537. foreach ($input['values'] as $selkey => $selval) {
  4538. $more .= '<div class="tagtr">';
  4539. if ($i == 0) {
  4540. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4541. } else {
  4542. $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  4543. }
  4544. $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;
  4545. if (!empty($input['disabled'])) {
  4546. $more .= ' disabled';
  4547. }
  4548. if (isset($input['default']) && $input['default'] === $selkey) {
  4549. $more .= ' checked="checked"';
  4550. }
  4551. $more .= ' /> ';
  4552. $more .= '<label for="'.dol_escape_htmltag($input['name'].$selkey).'" class="valignmiddle">'.$selval.'</label>';
  4553. $more .= '</div></div>'."\n";
  4554. $i++;
  4555. }
  4556. } elseif ($input['type'] == 'date') {
  4557. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  4558. $more .= '<div class="tagtd">';
  4559. $addnowlink = (empty($input['datenow']) ? 0 : 1);
  4560. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, $addnowlink);
  4561. $more .= '</div></div>'."\n";
  4562. $formquestion[] = array('name'=>$input['name'].'day');
  4563. $formquestion[] = array('name'=>$input['name'].'month');
  4564. $formquestion[] = array('name'=>$input['name'].'year');
  4565. $formquestion[] = array('name'=>$input['name'].'hour');
  4566. $formquestion[] = array('name'=>$input['name'].'min');
  4567. } elseif ($input['type'] == 'other') {
  4568. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  4569. if (!empty($input['label'])) {
  4570. $more .= $input['label'].'</div><div class="tagtd">';
  4571. }
  4572. $more .= $input['value'];
  4573. $more .= '</div></div>'."\n";
  4574. } elseif ($input['type'] == 'onecolumn') {
  4575. $moreonecolumn .= '<div class="margintoponly">';
  4576. $moreonecolumn .= $input['value'];
  4577. $moreonecolumn .= '</div>'."\n";
  4578. } elseif ($input['type'] == 'hidden') {
  4579. // Do nothing more, already added by a previous loop
  4580. } elseif ($input['type'] == 'separator') {
  4581. $more .= '<br>';
  4582. } else {
  4583. $more .= 'Error type '.$input['type'].' for the confirm box is not a supported type';
  4584. }
  4585. }
  4586. }
  4587. $more .= '</div>'."\n";
  4588. $more .= $moreonecolumn;
  4589. }
  4590. // JQUERY method dialog is broken with smartphone, we use standard HTML.
  4591. // 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
  4592. // See page product/card.php for example
  4593. if (!empty($conf->dol_use_jmobile)) {
  4594. $useajax = 0;
  4595. }
  4596. if (empty($conf->use_javascript_ajax)) {
  4597. $useajax = 0;
  4598. }
  4599. if ($useajax) {
  4600. $autoOpen = true;
  4601. $dialogconfirm = 'dialog-confirm';
  4602. $button = '';
  4603. if (!is_numeric($useajax)) {
  4604. $button = $useajax;
  4605. $useajax = 1;
  4606. $autoOpen = false;
  4607. $dialogconfirm .= '-'.$button;
  4608. }
  4609. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=yes';
  4610. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.urlencode($action).'&confirm=no' : '');
  4611. // Add input fields into list of fields to read during submit (inputok and inputko)
  4612. if (is_array($formquestion)) {
  4613. foreach ($formquestion as $key => $input) {
  4614. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  4615. // Add name of fields to propagate with the GET when submitting the form with button OK.
  4616. if (is_array($input) && isset($input['name'])) {
  4617. if (strpos($input['name'], ',') > 0) {
  4618. $inputok = array_merge($inputok, explode(',', $input['name']));
  4619. } else {
  4620. array_push($inputok, $input['name']);
  4621. }
  4622. }
  4623. // Add name of fields to propagate with the GET when submitting the form with button KO.
  4624. if (isset($input['inputko']) && $input['inputko'] == 1) {
  4625. array_push($inputko, $input['name']);
  4626. }
  4627. }
  4628. }
  4629. // Show JQuery confirm box.
  4630. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  4631. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4632. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  4633. }
  4634. if (!empty($more)) {
  4635. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  4636. }
  4637. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  4638. $formconfirm .= '</div>'."\n";
  4639. $formconfirm .= "\n<!-- begin code of popup for formconfirm page=".$page." -->\n";
  4640. $formconfirm .= '<script type="text/javascript">'."\n";
  4641. $formconfirm .= "/* Code for the jQuery('#dialogforpopup').dialog() */\n";
  4642. $formconfirm .= 'jQuery(document).ready(function() {
  4643. $(function() {
  4644. $( "#'.$dialogconfirm.'" ).dialog(
  4645. {
  4646. autoOpen: '.($autoOpen ? "true" : "false").',';
  4647. if ($newselectedchoice == 'no') {
  4648. $formconfirm .= '
  4649. open: function() {
  4650. $(this).parent().find("button.ui-button:eq(2)").focus();
  4651. },';
  4652. }
  4653. $jsforcursor = '';
  4654. if (empty($useajax)) {
  4655. $jsforcursor = '// The call to urljump can be slow, so we set the wait cursor'."\n";
  4656. $jsforcursor .= 'jQuery("html,body,#id-container").addClass("cursorwait");'."\n";
  4657. }
  4658. $formconfirm .= '
  4659. resizable: false,
  4660. height: "'.$height.'",
  4661. width: "'.$width.'",
  4662. modal: true,
  4663. closeOnEscape: false,
  4664. buttons: {
  4665. "'.dol_escape_js($langs->transnoentities($labelbuttonyes)).'": function() {
  4666. var options = "&token='.urlencode(newToken()).'";
  4667. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  4668. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  4669. if (inputok.length > 0) {
  4670. $.each(inputok, function(i, inputname) {
  4671. var more = "";
  4672. var inputvalue;
  4673. if ($("input[name=\'" + inputname + "\']").attr("type") == "radio") {
  4674. inputvalue = $("input[name=\'" + inputname + "\']:checked").val();
  4675. } else {
  4676. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4677. inputvalue = $("#" + inputname + more).val();
  4678. }
  4679. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4680. console.log("formconfirm check inputname="+inputname+" inputvalue="+inputvalue);
  4681. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4682. });
  4683. }
  4684. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  4685. if (pageyes.length > 0) {
  4686. '.$jsforcursor.'
  4687. location.href = urljump;
  4688. console.log("after location.href");
  4689. }
  4690. $(this).dialog("close");
  4691. },
  4692. "'.dol_escape_js($langs->transnoentities($labelbuttonno)).'": function() {
  4693. var options = "&token='.urlencode(newToken()).'";
  4694. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  4695. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  4696. if (inputko.length > 0) {
  4697. $.each(inputko, function(i, inputname) {
  4698. var more = "";
  4699. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  4700. var inputvalue = $("#" + inputname + more).val();
  4701. if (typeof inputvalue == "undefined") { inputvalue=""; }
  4702. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  4703. });
  4704. }
  4705. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  4706. //alert(urljump);
  4707. if (pageno.length > 0) {
  4708. '.$jsforcursor.'
  4709. location.href = urljump;
  4710. console.log("after location.href");
  4711. }
  4712. $(this).dialog("close");
  4713. }
  4714. }
  4715. }
  4716. );
  4717. var button = "'.$button.'";
  4718. if (button.length > 0) {
  4719. $( "#" + button ).click(function() {
  4720. $("#'.$dialogconfirm.'").dialog("open");
  4721. });
  4722. }
  4723. });
  4724. });
  4725. </script>';
  4726. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  4727. } else {
  4728. $formconfirm .= "\n<!-- begin formconfirm page=".dol_escape_htmltag($page)." -->\n";
  4729. if (empty($disableformtag)) {
  4730. $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  4731. }
  4732. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  4733. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  4734. $formconfirm .= '<table class="valid centpercent">'."\n";
  4735. // Line title
  4736. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="2">';
  4737. $formconfirm .= img_picto('', 'recent').' '.$title;
  4738. $formconfirm .= '</td></tr>'."\n";
  4739. // Line text
  4740. if (is_array($formquestion) && !empty($formquestion['text'])) {
  4741. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
  4742. }
  4743. // Line form fields
  4744. if ($more) {
  4745. $formconfirm .= '<tr class="valid"><td class="valid" colspan="2">'."\n";
  4746. $formconfirm .= $more;
  4747. $formconfirm .= '</td></tr>'."\n";
  4748. }
  4749. // Line with question
  4750. $formconfirm .= '<tr class="valid">';
  4751. $formconfirm .= '<td class="valid">'.$question.'</td>';
  4752. $formconfirm .= '<td class="valid center">';
  4753. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice, 0, false, 0, 0, 'marginleftonly marginrightonly', $labelbuttonyes, $labelbuttonno);
  4754. $formconfirm .= '<input class="button valignmiddle confirmvalidatebutton small" type="submit" value="'.$langs->trans("Validate").'">';
  4755. $formconfirm .= '</td>';
  4756. $formconfirm .= '</tr>'."\n";
  4757. $formconfirm .= '</table>'."\n";
  4758. if (empty($disableformtag)) {
  4759. $formconfirm .= "</form>\n";
  4760. }
  4761. $formconfirm .= '<br>';
  4762. if (!empty($conf->use_javascript_ajax)) {
  4763. $formconfirm .= '<!-- code to disable button to avoid double clic -->';
  4764. $formconfirm .= '<script type="text/javascript">'."\n";
  4765. $formconfirm .= '
  4766. $(document).ready(function () {
  4767. $(".confirmvalidatebutton").on("click", function() {
  4768. console.log("We click on button");
  4769. $(this).attr("disabled", "disabled");
  4770. setTimeout(\'$(".confirmvalidatebutton").removeAttr("disabled")\', 3000);
  4771. //console.log($(this).closest("form"));
  4772. $(this).closest("form").submit();
  4773. });
  4774. });
  4775. ';
  4776. $formconfirm .= '</script>'."\n";
  4777. }
  4778. $formconfirm .= "<!-- end formconfirm -->\n";
  4779. }
  4780. return $formconfirm;
  4781. }
  4782. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4783. /**
  4784. * Show a form to select a project
  4785. *
  4786. * @param int $page Page
  4787. * @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)
  4788. * @param int $selected Id pre-selected project
  4789. * @param string $htmlname Name of select field
  4790. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  4791. * @param int $maxlength Max length
  4792. * @param int $forcefocus Force focus on field (works with javascript only)
  4793. * @param int $nooutput No print is done. String is returned.
  4794. * @return string Return html content
  4795. */
  4796. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  4797. {
  4798. // phpcs:enable
  4799. global $langs;
  4800. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  4801. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  4802. $out = '';
  4803. $formproject = new FormProjets($this->db);
  4804. $langs->load("project");
  4805. if ($htmlname != "none") {
  4806. $out .= "\n";
  4807. $out .= '<form method="post" action="'.$page.'">';
  4808. $out .= '<input type="hidden" name="action" value="classin">';
  4809. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4810. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  4811. $out .= '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4812. $out .= '</form>';
  4813. } else {
  4814. $out .= '<span class="project_head_block">';
  4815. if ($selected) {
  4816. $projet = new Project($this->db);
  4817. $projet->fetch($selected);
  4818. $out .= $projet->getNomUrl(1, '', 1);
  4819. } else {
  4820. $out .= "&nbsp;";
  4821. }
  4822. $out .= '</span>';
  4823. }
  4824. if (empty($nooutput)) {
  4825. print $out;
  4826. return '';
  4827. }
  4828. return $out;
  4829. }
  4830. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4831. /**
  4832. * Show a form to select payment conditions
  4833. *
  4834. * @param int $page Page
  4835. * @param string $selected Id condition pre-selectionne
  4836. * @param string $htmlname Name of select html field
  4837. * @param int $addempty Add empty entry
  4838. * @param string $type Type ('direct-debit' or 'bank-transfer')
  4839. * @param int $filtertype If > 0, include payment terms with deposit percentage (for objects other than invoices and invoice templates)
  4840. * @param string $deposit_percent < 0 : deposit_percent input makes no sense (for example, in list filters)
  4841. * 0 : use default deposit percentage from entry
  4842. * > 0 : force deposit percentage (for example, from company object)
  4843. * @return void
  4844. */
  4845. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0, $type = '', $filtertype = -1, $deposit_percent = -1)
  4846. {
  4847. // phpcs:enable
  4848. global $langs;
  4849. if ($htmlname != "none") {
  4850. print '<form method="POST" action="'.$page.'">';
  4851. print '<input type="hidden" name="action" value="setconditions">';
  4852. print '<input type="hidden" name="token" value="'.newToken().'">';
  4853. if ($type) {
  4854. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4855. }
  4856. $this->select_conditions_paiements($selected, $htmlname, $filtertype, $addempty, 0, '', $deposit_percent);
  4857. print '<input type="submit" class="button valignmiddle smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4858. print '</form>';
  4859. } else {
  4860. if ($selected) {
  4861. $this->load_cache_conditions_paiements();
  4862. if (isset($this->cache_conditions_paiements[$selected])) {
  4863. $label = $this->cache_conditions_paiements[$selected]['label'];
  4864. if (! empty($this->cache_conditions_paiements[$selected]['deposit_percent'])) {
  4865. $label = str_replace('__DEPOSIT_PERCENT__', $deposit_percent > 0 ? $deposit_percent : $this->cache_conditions_paiements[$selected]['deposit_percent'], $label);
  4866. }
  4867. print $label;
  4868. } else {
  4869. $langs->load('errors');
  4870. print $langs->trans('ErrorNotInDictionaryPaymentConditions');
  4871. }
  4872. } else {
  4873. print "&nbsp;";
  4874. }
  4875. }
  4876. }
  4877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4878. /**
  4879. * Show a form to select a delivery delay
  4880. *
  4881. * @param int $page Page
  4882. * @param string $selected Id condition pre-selectionne
  4883. * @param string $htmlname Name of select html field
  4884. * @param int $addempty Ajoute entree vide
  4885. * @return void
  4886. */
  4887. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  4888. {
  4889. // phpcs:enable
  4890. global $langs;
  4891. if ($htmlname != "none") {
  4892. print '<form method="post" action="'.$page.'">';
  4893. print '<input type="hidden" name="action" value="setavailability">';
  4894. print '<input type="hidden" name="token" value="'.newToken().'">';
  4895. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  4896. print '<input type="submit" name="modify" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4897. print '<input type="submit" name="cancel" class="button smallpaddingimp" value="'.$langs->trans("Cancel").'">';
  4898. print '</form>';
  4899. } else {
  4900. if ($selected) {
  4901. $this->load_cache_availability();
  4902. print $this->cache_availability[$selected]['label'];
  4903. } else {
  4904. print "&nbsp;";
  4905. }
  4906. }
  4907. }
  4908. /**
  4909. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  4910. * List found into table c_input_reason loaded by loadCacheInputReason
  4911. *
  4912. * @param string $page Page
  4913. * @param string $selected Id condition pre-selectionne
  4914. * @param string $htmlname Name of select html field
  4915. * @param int $addempty Add empty entry
  4916. * @return void
  4917. */
  4918. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  4919. {
  4920. global $langs;
  4921. if ($htmlname != "none") {
  4922. print '<form method="post" action="'.$page.'">';
  4923. print '<input type="hidden" name="action" value="setdemandreason">';
  4924. print '<input type="hidden" name="token" value="'.newToken().'">';
  4925. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  4926. print '<input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'">';
  4927. print '</form>';
  4928. } else {
  4929. if ($selected) {
  4930. $this->loadCacheInputReason();
  4931. foreach ($this->cache_demand_reason as $key => $val) {
  4932. if ($val['id'] == $selected) {
  4933. print $val['label'];
  4934. break;
  4935. }
  4936. }
  4937. } else {
  4938. print "&nbsp;";
  4939. }
  4940. }
  4941. }
  4942. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4943. /**
  4944. * Show a form + html select a date
  4945. *
  4946. * @param string $page Page
  4947. * @param string $selected Date preselected
  4948. * @param string $htmlname Html name of date input fields or 'none'
  4949. * @param int $displayhour Display hour selector
  4950. * @param int $displaymin Display minutes selector
  4951. * @param int $nooutput 1=No print output, return string
  4952. * @param string $type 'direct-debit' or 'bank-transfer'
  4953. * @return string
  4954. * @see selectDate()
  4955. */
  4956. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0, $type = '')
  4957. {
  4958. // phpcs:enable
  4959. global $langs;
  4960. $ret = '';
  4961. if ($htmlname != "none") {
  4962. $ret .= '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4963. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4964. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4965. if ($type) {
  4966. $ret .= '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  4967. }
  4968. $ret .= '<table class="nobordernopadding">';
  4969. $ret .= '<tr><td>';
  4970. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4971. $ret .= '</td>';
  4972. $ret .= '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  4973. $ret .= '</tr></table></form>';
  4974. } else {
  4975. if ($displayhour) {
  4976. $ret .= dol_print_date($selected, 'dayhour');
  4977. } else {
  4978. $ret .= dol_print_date($selected, 'day');
  4979. }
  4980. }
  4981. if (empty($nooutput)) {
  4982. print $ret;
  4983. }
  4984. return $ret;
  4985. }
  4986. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4987. /**
  4988. * Show a select form to choose a user
  4989. *
  4990. * @param string $page Page
  4991. * @param string $selected Id of user preselected
  4992. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4993. * @param array $exclude List of users id to exclude
  4994. * @param array $include List of users id to include
  4995. * @return void
  4996. */
  4997. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4998. {
  4999. // phpcs:enable
  5000. global $langs;
  5001. if ($htmlname != "none") {
  5002. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  5003. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  5004. print '<input type="hidden" name="token" value="'.newToken().'">';
  5005. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  5006. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5007. print '</form>';
  5008. } else {
  5009. if ($selected) {
  5010. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  5011. $theuser = new User($this->db);
  5012. $theuser->fetch($selected);
  5013. print $theuser->getNomUrl(1);
  5014. } else {
  5015. print "&nbsp;";
  5016. }
  5017. }
  5018. }
  5019. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5020. /**
  5021. * Show form with payment mode
  5022. *
  5023. * @param string $page Page
  5024. * @param int $selected Id mode pre-selectionne
  5025. * @param string $htmlname Name of select html field
  5026. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  5027. * @param int $active Active or not, -1 = all
  5028. * @param int $addempty 1=Add empty entry
  5029. * @param string $type Type ('direct-debit' or 'bank-transfer')
  5030. * @return void
  5031. */
  5032. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0, $type = '')
  5033. {
  5034. // phpcs:enable
  5035. global $langs;
  5036. if ($htmlname != "none") {
  5037. print '<form method="POST" action="'.$page.'">';
  5038. print '<input type="hidden" name="action" value="setmode">';
  5039. print '<input type="hidden" name="token" value="'.newToken().'">';
  5040. if ($type) {
  5041. print '<input type="hidden" name="type" value="'.dol_escape_htmltag($type).'">';
  5042. }
  5043. print $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active, '', 1);
  5044. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5045. print '</form>';
  5046. } else {
  5047. if ($selected) {
  5048. $this->load_cache_types_paiements();
  5049. print $this->cache_types_paiements[$selected]['label'];
  5050. } else {
  5051. print "&nbsp;";
  5052. }
  5053. }
  5054. }
  5055. /**
  5056. * Show form with transport mode
  5057. *
  5058. * @param string $page Page
  5059. * @param int $selected Id mode pre-select
  5060. * @param string $htmlname Name of select html field
  5061. * @param int $active Active or not, -1 = all
  5062. * @param int $addempty 1=Add empty entry
  5063. * @return void
  5064. */
  5065. public function formSelectTransportMode($page, $selected = '', $htmlname = 'transport_mode_id', $active = 1, $addempty = 0)
  5066. {
  5067. global $langs;
  5068. if ($htmlname != "none") {
  5069. print '<form method="POST" action="'.$page.'">';
  5070. print '<input type="hidden" name="action" value="settransportmode">';
  5071. print '<input type="hidden" name="token" value="'.newToken().'">';
  5072. $this->selectTransportMode($selected, $htmlname, 0, $addempty, 0, 0, $active);
  5073. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5074. print '</form>';
  5075. } else {
  5076. if ($selected) {
  5077. $this->load_cache_transport_mode();
  5078. print $this->cache_transport_mode[$selected]['label'];
  5079. } else {
  5080. print "&nbsp;";
  5081. }
  5082. }
  5083. }
  5084. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5085. /**
  5086. * Show form with multicurrency code
  5087. *
  5088. * @param string $page Page
  5089. * @param string $selected code pre-selectionne
  5090. * @param string $htmlname Name of select html field
  5091. * @return void
  5092. */
  5093. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  5094. {
  5095. // phpcs:enable
  5096. global $langs;
  5097. if ($htmlname != "none") {
  5098. print '<form method="POST" action="'.$page.'">';
  5099. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  5100. print '<input type="hidden" name="token" value="'.newToken().'">';
  5101. print $this->selectMultiCurrency($selected, $htmlname, 0);
  5102. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5103. print '</form>';
  5104. } else {
  5105. dol_include_once('/core/lib/company.lib.php');
  5106. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  5107. }
  5108. }
  5109. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5110. /**
  5111. * Show form with multicurrency rate
  5112. *
  5113. * @param string $page Page
  5114. * @param double $rate Current rate
  5115. * @param string $htmlname Name of select html field
  5116. * @param string $currency Currency code to explain the rate
  5117. * @return void
  5118. */
  5119. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  5120. {
  5121. // phpcs:enable
  5122. global $langs, $mysoc, $conf;
  5123. if ($htmlname != "none") {
  5124. print '<form method="POST" action="'.$page.'">';
  5125. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  5126. print '<input type="hidden" name="token" value="'.newToken().'">';
  5127. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CU')) : 1).'" /> ';
  5128. print '<select name="calculation_mode">';
  5129. print '<option value="1">Change '.$langs->trans("PriceUHT").' of lines</option>';
  5130. print '<option value="2">Change '.$langs->trans("PriceUHTCurrency").' of lines</option>';
  5131. print '</select> ';
  5132. print '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5133. print '</form>';
  5134. } else {
  5135. if (!empty($rate)) {
  5136. print price($rate, 1, $langs, 1, 0);
  5137. if ($currency && $rate != 1) {
  5138. print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  5139. }
  5140. } else {
  5141. print 1;
  5142. }
  5143. }
  5144. }
  5145. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5146. /**
  5147. * Show a select box with available absolute discounts
  5148. *
  5149. * @param string $page Page URL where form is shown
  5150. * @param int $selected Value pre-selected
  5151. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  5152. * @param int $socid Third party id
  5153. * @param float $amount Total amount available
  5154. * @param string $filter SQL filter on discounts
  5155. * @param int $maxvalue Max value for lines that can be selected
  5156. * @param string $more More string to add
  5157. * @param int $hidelist 1=Hide list
  5158. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  5159. * @return void
  5160. */
  5161. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  5162. {
  5163. // phpcs:enable
  5164. global $conf, $langs;
  5165. if ($htmlname != "none") {
  5166. print '<form method="post" action="'.$page.'">';
  5167. print '<input type="hidden" name="action" value="setabsolutediscount">';
  5168. print '<input type="hidden" name="token" value="'.newToken().'">';
  5169. print '<div class="inline-block">';
  5170. if (!empty($discount_type)) {
  5171. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5172. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") {
  5173. $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5174. } else {
  5175. $translationKey = 'HasCreditNoteFromSupplier';
  5176. }
  5177. } else {
  5178. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5179. $translationKey = 'HasAbsoluteDiscountFromSupplier';
  5180. } else {
  5181. $translationKey = 'HasCreditNoteFromSupplier';
  5182. }
  5183. }
  5184. } else {
  5185. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {
  5186. if (!$filter || $filter == "fk_facture_source IS NULL") {
  5187. $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  5188. } else {
  5189. $translationKey = 'CompanyHasCreditNote';
  5190. }
  5191. } else {
  5192. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5193. $translationKey = 'CompanyHasAbsoluteDiscount';
  5194. } else {
  5195. $translationKey = 'CompanyHasCreditNote';
  5196. }
  5197. }
  5198. }
  5199. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  5200. if (empty($hidelist)) {
  5201. print ' ';
  5202. }
  5203. print '</div>';
  5204. if (empty($hidelist)) {
  5205. print '<div class="inline-block" style="padding-right: 10px">';
  5206. $newfilter = 'discount_type='.intval($discount_type);
  5207. if (!empty($discount_type)) {
  5208. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  5209. } else {
  5210. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  5211. }
  5212. if ($filter) {
  5213. $newfilter .= ' AND ('.$filter.')';
  5214. }
  5215. // output the combo of discounts
  5216. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  5217. if ($nbqualifiedlines > 0) {
  5218. print ' &nbsp; <input type="submit" class="button smallpaddingimp" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  5219. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
  5220. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5221. }
  5222. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
  5223. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  5224. }
  5225. print '>';
  5226. }
  5227. print '</div>';
  5228. }
  5229. if ($more) {
  5230. print '<div class="inline-block">';
  5231. print $more;
  5232. print '</div>';
  5233. }
  5234. print '</form>';
  5235. } else {
  5236. if ($selected) {
  5237. print $selected;
  5238. } else {
  5239. print "0";
  5240. }
  5241. }
  5242. }
  5243. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5244. /**
  5245. * Show forms to select a contact
  5246. *
  5247. * @param string $page Page
  5248. * @param Societe $societe Filter on third party
  5249. * @param int $selected Id contact pre-selectionne
  5250. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  5251. * @return void
  5252. */
  5253. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  5254. {
  5255. // phpcs:enable
  5256. global $langs, $conf;
  5257. if ($htmlname != "none") {
  5258. print '<form method="post" action="'.$page.'">';
  5259. print '<input type="hidden" name="action" value="set_contact">';
  5260. print '<input type="hidden" name="token" value="'.newToken().'">';
  5261. print '<table class="nobordernopadding">';
  5262. print '<tr><td>';
  5263. print $this->selectcontacts($societe->id, $selected, $htmlname);
  5264. $num = $this->num;
  5265. if ($num == 0) {
  5266. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  5267. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  5268. }
  5269. print '</td>';
  5270. print '<td class="left"><input type="submit" class="button smallpaddingimp" value="'.$langs->trans("Modify").'"></td>';
  5271. print '</tr></table></form>';
  5272. } else {
  5273. if ($selected) {
  5274. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  5275. $contact = new Contact($this->db);
  5276. $contact->fetch($selected);
  5277. print $contact->getFullName($langs);
  5278. } else {
  5279. print "&nbsp;";
  5280. }
  5281. }
  5282. }
  5283. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5284. /**
  5285. * Output html select to select thirdparty
  5286. *
  5287. * @param string $page Page
  5288. * @param string $selected Id preselected
  5289. * @param string $htmlname Name of HTML select
  5290. * @param string $filter Optional filters criteras. Do not use a filter coming from input of users.
  5291. * @param int $showempty Add an empty field
  5292. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  5293. * @param int $forcecombo Force to use combo box
  5294. * @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')))
  5295. * @param int $nooutput No print output. Return it only.
  5296. * @param array $excludeids Exclude IDs from the select combo
  5297. * @return void|string
  5298. */
  5299. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0, $excludeids = array())
  5300. {
  5301. // phpcs:enable
  5302. global $langs;
  5303. $out = '';
  5304. if ($htmlname != "none") {
  5305. $out .= '<form method="post" action="'.$page.'">';
  5306. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  5307. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  5308. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, 0, 'minwidth100', '', '', 1, array(), false, $excludeids);
  5309. $out .= '<input type="submit" class="button smallpaddingimp valignmiddle" value="'.$langs->trans("Modify").'">';
  5310. $out .= '</form>';
  5311. } else {
  5312. if ($selected) {
  5313. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  5314. $soc = new Societe($this->db);
  5315. $soc->fetch($selected);
  5316. $out .= $soc->getNomUrl($langs);
  5317. } else {
  5318. $out .= "&nbsp;";
  5319. }
  5320. }
  5321. if ($nooutput) {
  5322. return $out;
  5323. } else {
  5324. print $out;
  5325. }
  5326. }
  5327. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5328. /**
  5329. * Retourne la liste des devises, dans la langue de l'utilisateur
  5330. *
  5331. * @param string $selected preselected currency code
  5332. * @param string $htmlname name of HTML select list
  5333. * @deprecated
  5334. * @return void
  5335. */
  5336. public function select_currency($selected = '', $htmlname = 'currency_id')
  5337. {
  5338. // phpcs:enable
  5339. print $this->selectCurrency($selected, $htmlname);
  5340. }
  5341. /**
  5342. * Retourne la liste des devises, dans la langue de l'utilisateur
  5343. *
  5344. * @param string $selected preselected currency code
  5345. * @param string $htmlname name of HTML select list
  5346. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  5347. * @param string $useempty '1'=Allow empty value
  5348. * @return string
  5349. */
  5350. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0, $useempty = '')
  5351. {
  5352. global $conf, $langs, $user;
  5353. $langs->loadCacheCurrencies('');
  5354. $out = '';
  5355. if ($selected == 'euro' || $selected == 'euros') {
  5356. $selected = 'EUR'; // Pour compatibilite
  5357. }
  5358. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  5359. if ($useempty) {
  5360. $out .= '<option value="-1" selected></option>';
  5361. }
  5362. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5363. $labeltoshow = $currency['label'];
  5364. if ($mode == 1) {
  5365. $labeltoshow .= ' <span class="opacitymedium">('.$code_iso.')</span>';
  5366. } else {
  5367. $labeltoshow .= ' <span class="opacitymedium">('.$langs->getCurrencySymbol($code_iso).')</span>';
  5368. }
  5369. if ($selected && $selected == $code_iso) {
  5370. $out .= '<option value="'.$code_iso.'" selected data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5371. } else {
  5372. $out .= '<option value="'.$code_iso.'" data-html="'.dol_escape_htmltag($labeltoshow).'">';
  5373. }
  5374. $out .= $labeltoshow;
  5375. $out .= '</option>';
  5376. }
  5377. $out .= '</select>';
  5378. if ($user->admin) {
  5379. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  5380. }
  5381. // Make select dynamic
  5382. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5383. $out .= ajax_combobox($htmlname);
  5384. return $out;
  5385. }
  5386. /**
  5387. * Return array of currencies in user language
  5388. *
  5389. * @param string $selected Preselected currency code
  5390. * @param string $htmlname Name of HTML select list
  5391. * @param integer $useempty 1=Add empty line
  5392. * @param string $filter Optional filters criteras (example: 'code <> x', ' in (1,3)')
  5393. * @param bool $excludeConfCurrency false = If company current currency not in table, we add it into list. Should always be available.
  5394. * true = we are in currency_rate update , we don't want to see conf->currency in select
  5395. * @param string $morecss More css
  5396. * @return string
  5397. */
  5398. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0, $filter = '', $excludeConfCurrency = false, $morecss = '')
  5399. {
  5400. global $conf, $langs;
  5401. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  5402. $TCurrency = array();
  5403. $sql = "SELECT code FROM ".$this->db->prefix()."multicurrency";
  5404. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  5405. if ($filter) {
  5406. $sql .= " AND ".$filter;
  5407. }
  5408. $resql = $this->db->query($sql);
  5409. if ($resql) {
  5410. while ($obj = $this->db->fetch_object($resql)) {
  5411. $TCurrency[$obj->code] = $obj->code;
  5412. }
  5413. }
  5414. $out = '';
  5415. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  5416. if ($useempty) {
  5417. $out .= '<option value="">&nbsp;</option>';
  5418. }
  5419. // If company current currency not in table, we add it into list. Should always be available.
  5420. if (!in_array($conf->currency, $TCurrency) && !$excludeConfCurrency) {
  5421. $TCurrency[$conf->currency] = $conf->currency;
  5422. }
  5423. if (count($TCurrency) > 0) {
  5424. foreach ($langs->cache_currencies as $code_iso => $currency) {
  5425. if (isset($TCurrency[$code_iso])) {
  5426. if (!empty($selected) && $selected == $code_iso) {
  5427. $out .= '<option value="'.$code_iso.'" selected="selected">';
  5428. } else {
  5429. $out .= '<option value="'.$code_iso.'">';
  5430. }
  5431. $out .= $currency['label'];
  5432. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  5433. $out .= '</option>';
  5434. }
  5435. }
  5436. }
  5437. $out .= '</select>';
  5438. // Make select dynamic
  5439. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5440. $out .= ajax_combobox($htmlname);
  5441. return $out;
  5442. }
  5443. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5444. /**
  5445. * Load into the cache vat rates of a country
  5446. *
  5447. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  5448. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  5449. */
  5450. public function load_cache_vatrates($country_code)
  5451. {
  5452. // phpcs:enable
  5453. global $langs;
  5454. $num = count($this->cache_vatrates);
  5455. if ($num > 0) {
  5456. return $num; // Cache already loaded
  5457. }
  5458. dol_syslog(__METHOD__, LOG_DEBUG);
  5459. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  5460. $sql .= " FROM ".$this->db->prefix()."c_tva as t, ".$this->db->prefix()."c_country as c";
  5461. $sql .= " WHERE t.fk_pays = c.rowid";
  5462. $sql .= " AND t.active > 0";
  5463. $sql .= " AND c.code IN (".$this->db->sanitize($country_code, 1).")";
  5464. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  5465. $resql = $this->db->query($sql);
  5466. if ($resql) {
  5467. $num = $this->db->num_rows($resql);
  5468. if ($num) {
  5469. for ($i = 0; $i < $num; $i++) {
  5470. $obj = $this->db->fetch_object($resql);
  5471. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  5472. $this->cache_vatrates[$i]['code'] = $obj->code;
  5473. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  5474. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  5475. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  5476. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  5477. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  5478. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  5479. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  5480. $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
  5481. $positiverates = '';
  5482. if ($obj->taux) {
  5483. $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  5484. }
  5485. if ($obj->localtax1) {
  5486. $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  5487. }
  5488. if ($obj->localtax2) {
  5489. $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  5490. }
  5491. if (empty($positiverates)) {
  5492. $positiverates = '0';
  5493. }
  5494. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  5495. }
  5496. return $num;
  5497. } else {
  5498. $this->error = '<span class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</span>';
  5499. return -1;
  5500. }
  5501. } else {
  5502. $this->error = '<span class="error">'.$this->db->error().'</span>';
  5503. return -2;
  5504. }
  5505. }
  5506. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5507. /**
  5508. * Output an HTML select vat rate.
  5509. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  5510. *
  5511. * @param string $htmlname Name of HTML select field
  5512. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  5513. * @param Societe $societe_vendeuse Thirdparty seller
  5514. * @param Societe $societe_acheteuse Thirdparty buyer
  5515. * @param int $idprod Id product. O if unknown of NA.
  5516. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  5517. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  5518. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5519. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5520. * 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.
  5521. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  5522. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  5523. * Sinon la TVA proposee par defaut=0. Fin de regle.
  5524. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  5525. * @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
  5526. * @return string
  5527. */
  5528. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  5529. {
  5530. // phpcs:enable
  5531. global $langs, $conf, $mysoc;
  5532. $langs->load('errors');
  5533. $return = '';
  5534. // Define defaultnpr, defaultttx and defaultcode
  5535. $defaultnpr = ($info_bits & 0x01);
  5536. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  5537. $defaulttx = str_replace('*', '', $selectedrate);
  5538. $defaultcode = '';
  5539. $reg = array();
  5540. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5541. $defaultcode = $reg[1];
  5542. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5543. }
  5544. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  5545. // Check parameters
  5546. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code) {
  5547. if ($societe_vendeuse->id == $mysoc->id) {
  5548. $return .= '<span class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</span>';
  5549. } else {
  5550. $return .= '<span class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</span>';
  5551. }
  5552. return $return;
  5553. }
  5554. //var_dump($societe_acheteuse);
  5555. //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";
  5556. //exit;
  5557. // Define list of countries to use to search VAT rates to show
  5558. // First we defined code_country to use to find list
  5559. if (is_object($societe_vendeuse)) {
  5560. $code_country = "'".$societe_vendeuse->country_code."'";
  5561. } else {
  5562. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  5563. }
  5564. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) { // If option to have vat for end customer for services is on
  5565. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5566. if (isInEEC($societe_vendeuse) && (is_object($societe_acheteuse) && (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany()))) {
  5567. //var_dump($type); die();
  5568. // We also add the buyer
  5569. if (is_numeric($type)) {
  5570. if ($type == 1 || $type == 0) { // We know product is a service
  5571. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5572. }
  5573. } elseif (!$idprod) { // We don't know type of product
  5574. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5575. } else {
  5576. $prodstatic = new Product($this->db);
  5577. $prodstatic->fetch($idprod);
  5578. if ($prodstatic->type == Product::TYPE_SERVICE || $prodstatic->type == Product::TYPE_PRODUCT) { // We know product is a service
  5579. $code_country .= ",'".$societe_acheteuse->country_code."'";
  5580. }
  5581. }
  5582. }
  5583. }
  5584. // Now we get list
  5585. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  5586. if ($num > 0) {
  5587. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  5588. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5589. $tmpthirdparty = new Societe($this->db);
  5590. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5591. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  5592. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5593. $defaultcode = $reg[1];
  5594. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5595. }
  5596. if (empty($defaulttx)) {
  5597. $defaultnpr = 0;
  5598. }
  5599. }
  5600. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  5601. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  5602. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0) {
  5603. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5604. $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  5605. } else {
  5606. $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  5607. }
  5608. }
  5609. // Disabled if seller is not subject to VAT
  5610. $disabled = false;
  5611. $title = '';
  5612. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0") {
  5613. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  5614. // of using supplier invoices (this is a very bad idea !)
  5615. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT)) {
  5616. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  5617. $disabled = true;
  5618. }
  5619. }
  5620. if (!$options_only) {
  5621. $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  5622. }
  5623. $selectedfound = false;
  5624. foreach ($this->cache_vatrates as $rate) {
  5625. // Keep only 0 if seller is not subject to VAT
  5626. if ($disabled && $rate['txtva'] != 0) {
  5627. continue;
  5628. }
  5629. // Define key to use into select list
  5630. $key = $rate['txtva'];
  5631. $key .= $rate['nprtva'] ? '*' : '';
  5632. if ($mode > 0 && $rate['code']) {
  5633. $key .= ' ('.$rate['code'].')';
  5634. }
  5635. if ($mode < 0) {
  5636. $key = $rate['rowid'];
  5637. }
  5638. $return .= '<option value="'.$key.'"';
  5639. if (!$selectedfound) {
  5640. if ($defaultcode) { // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  5641. if ($defaultcode == $rate['code']) {
  5642. $return .= ' selected';
  5643. $selectedfound = true;
  5644. }
  5645. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr) {
  5646. $return .= ' selected';
  5647. $selectedfound = true;
  5648. }
  5649. }
  5650. $return .= '>';
  5651. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  5652. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES)) {
  5653. $return .= $rate['labelpositiverates'];
  5654. } else {
  5655. $return .= vatrate($rate['label']);
  5656. }
  5657. //$return.=($rate['code']?' '.$rate['code']:'');
  5658. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  5659. $return .= '</option>';
  5660. }
  5661. if (!$options_only) {
  5662. $return .= '</select>';
  5663. }
  5664. } else {
  5665. $return .= $this->error;
  5666. }
  5667. $this->num = $num;
  5668. return $return;
  5669. }
  5670. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5671. /**
  5672. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5673. * Fields are preselected with :
  5674. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5675. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5676. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5677. *
  5678. * @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).
  5679. * @param string $prefix Prefix for fields name
  5680. * @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
  5681. * @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
  5682. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5683. * @param string $form_name Not used
  5684. * @param int $d 1=Show days, month, years
  5685. * @param int $addnowlink Add a link "Now"
  5686. * @param int $nooutput Do not output html string but return it
  5687. * @param int $disabled Disable input fields
  5688. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  5689. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  5690. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  5691. * @return string|void Nothing or string if nooutput is 1
  5692. * @deprecated
  5693. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  5694. */
  5695. 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 = '')
  5696. {
  5697. // phpcs:enable
  5698. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  5699. if (!empty($nooutput)) {
  5700. return $retstring;
  5701. }
  5702. print $retstring;
  5703. return;
  5704. }
  5705. /**
  5706. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5707. * Fields are preselected with :
  5708. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5709. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5710. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5711. *
  5712. * @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).
  5713. * @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).
  5714. * @param string $prefix Prefix for fields name
  5715. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5716. * @param string $forcenewline Force new line between the 2 dates.
  5717. * @return string Html for selectDate
  5718. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5719. */
  5720. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0, $forcenewline = 0)
  5721. {
  5722. global $langs;
  5723. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("from"), 'tzuserrel');
  5724. if ($forcenewline) {
  5725. $ret .= '<br>';
  5726. }
  5727. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans("to"), 'tzuserrel');
  5728. return $ret;
  5729. }
  5730. /**
  5731. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  5732. * Fields are preselected with :
  5733. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  5734. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  5735. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  5736. *
  5737. * @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).
  5738. * @param string $prefix Prefix for fields name
  5739. * @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
  5740. * @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
  5741. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  5742. * @param string $form_name Not used
  5743. * @param int $d 1=Show days, month, years
  5744. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  5745. * @param int $disabled Disable input fields
  5746. * @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')
  5747. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  5748. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  5749. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  5750. * @param int $stepminutes Specify step for minutes between 1 and 30
  5751. * @param string $labeladddateof Label to use for the $adddateof parameter.
  5752. * @param string $placeholder Placeholder
  5753. * @param mixed $gm 'auto' (for backward compatibility, avoid this), 'gmt' or 'tzserver' or 'tzuserrel'
  5754. * @return string Html for selectDate
  5755. * @see form_date(), select_month(), select_year(), select_dayofweek()
  5756. */
  5757. 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')
  5758. {
  5759. global $conf, $langs;
  5760. if ($gm === 'auto') {
  5761. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  5762. }
  5763. $retstring = '';
  5764. if ($prefix == '') {
  5765. $prefix = 're';
  5766. }
  5767. if ($h == '') {
  5768. $h = 0;
  5769. }
  5770. if ($m == '') {
  5771. $m = 0;
  5772. }
  5773. $emptydate = 0;
  5774. $emptyhours = 0;
  5775. if ($stepminutes <= 0 || $stepminutes > 30) {
  5776. $stepminutes = 1;
  5777. }
  5778. if ($empty == 1) {
  5779. $emptydate = 1;
  5780. $emptyhours = 1;
  5781. }
  5782. if ($empty == 2) {
  5783. $emptydate = 0;
  5784. $emptyhours = 1;
  5785. }
  5786. $orig_set_time = $set_time;
  5787. if ($set_time === '' && $emptydate == 0) {
  5788. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5789. if ($gm == 'tzuser' || $gm == 'tzuserrel') {
  5790. $set_time = dol_now($gm);
  5791. } else {
  5792. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  5793. }
  5794. }
  5795. // Analysis of the pre-selection date
  5796. $reg = array();
  5797. $shour = '';
  5798. $smin = '';
  5799. $ssec = '';
  5800. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) { // deprecated usage
  5801. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  5802. $syear = (!empty($reg[1]) ? $reg[1] : '');
  5803. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  5804. $sday = (!empty($reg[3]) ? $reg[3] : '');
  5805. $shour = (!empty($reg[4]) ? $reg[4] : '');
  5806. $smin = (!empty($reg[5]) ? $reg[5] : '');
  5807. } elseif (strval($set_time) != '' && $set_time != -1) {
  5808. // set_time est un timestamps (0 possible)
  5809. $syear = dol_print_date($set_time, "%Y", $gm);
  5810. $smonth = dol_print_date($set_time, "%m", $gm);
  5811. $sday = dol_print_date($set_time, "%d", $gm);
  5812. if ($orig_set_time != '') {
  5813. $shour = dol_print_date($set_time, "%H", $gm);
  5814. $smin = dol_print_date($set_time, "%M", $gm);
  5815. $ssec = dol_print_date($set_time, "%S", $gm);
  5816. }
  5817. } else {
  5818. // Date est '' ou vaut -1
  5819. $syear = '';
  5820. $smonth = '';
  5821. $sday = '';
  5822. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  5823. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  5824. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  5825. }
  5826. if ($h == 3) {
  5827. $shour = '';
  5828. }
  5829. if ($m == 3) {
  5830. $smin = '';
  5831. }
  5832. $nowgmt = dol_now('gmt');
  5833. //var_dump(dol_print_date($nowgmt, 'dayhourinputnoreduce', 'tzuserrel'));
  5834. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  5835. $usecalendar = 'combo';
  5836. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  5837. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  5838. }
  5839. if ($d) {
  5840. // Show date with popup
  5841. if ($usecalendar != 'combo') {
  5842. $formated_date = '';
  5843. //print "e".$set_time." t ".$conf->format_date_short;
  5844. if (strval($set_time) != '' && $set_time != -1) {
  5845. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  5846. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput"), $gm); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5847. }
  5848. // Calendrier popup version eldy
  5849. if ($usecalendar == "eldy") {
  5850. // Input area to enter date manually
  5851. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5852. $retstring .= ($disabled ? ' disabled' : '');
  5853. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5854. $retstring .= '>';
  5855. // Icon calendar
  5856. $retstringbuttom = '';
  5857. if (!$disabled) {
  5858. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  5859. $base = DOL_URL_ROOT.'/core/';
  5860. $retstringbuttom .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  5861. $retstringbuttom .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  5862. } else {
  5863. $retstringbuttom = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5864. }
  5865. $retstring = $retstringbuttom.$retstring;
  5866. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5867. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5868. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5869. } elseif ($usecalendar == 'jquery') {
  5870. if (!$disabled) {
  5871. // Output javascript for datepicker
  5872. $minYear = getDolGlobalString('MIN_YEAR_SELECT_DATE', date('Y') - 100);
  5873. $maxYear = getDolGlobalString('MAX_YEAR_SELECT_DATE', date('Y') + 100);
  5874. $retstring .= "<script type='text/javascript'>";
  5875. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  5876. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  5877. autoclose: true,
  5878. todayHighlight: true,
  5879. yearRange: '".$minYear.":".$maxYear."',";
  5880. if (!empty($conf->dol_use_jmobile)) {
  5881. $retstring .= "
  5882. beforeShow: function (input, datePicker) {
  5883. input.disabled = true;
  5884. },
  5885. onClose: function (dateText, datePicker) {
  5886. this.disabled = false;
  5887. },
  5888. ";
  5889. }
  5890. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  5891. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS)) {
  5892. $retstring .= "
  5893. showOn: 'button', /* both has problem with autocompletion */
  5894. buttonImage: '".DOL_URL_ROOT."/theme/".dol_escape_js($conf->theme)."/img/object_calendarday.png',
  5895. buttonImageOnly: true";
  5896. }
  5897. $retstring .= "
  5898. }) });";
  5899. $retstring .= "</script>";
  5900. }
  5901. // Zone de saisie manuelle de la date
  5902. $retstring .= '<div class="nowrap inline-block divfordateinput">';
  5903. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  5904. $retstring .= ($disabled ? ' disabled' : '');
  5905. $retstring .= ($placeholder ? ' placeholder="'.dol_escape_htmltag($placeholder).'"' : '');
  5906. $retstring .= ' onChange="dpChangeDay(\''.dol_escape_js($prefix).'\',\''.dol_escape_js($langs->trans("FormatDateShortJavaInput")).'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  5907. $retstring .= '>';
  5908. // Icone calendrier
  5909. if (!$disabled) {
  5910. /* Not required. Managed by option buttonImage of jquery
  5911. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  5912. $retstring.="<script type='text/javascript'>";
  5913. $retstring.="jQuery(document).ready(function() {";
  5914. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  5915. $retstring.=" jQuery('#".$prefix."').focus();";
  5916. $retstring.=' });';
  5917. $retstring.='});';
  5918. $retstring.="</script>";*/
  5919. } else {
  5920. $retstringbutton = '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  5921. $retsring = $retstringbutton.$retstring;
  5922. }
  5923. $retstring .= '</div>';
  5924. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  5925. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  5926. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  5927. } else {
  5928. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  5929. }
  5930. } else {
  5931. // Show date with combo selects
  5932. // Day
  5933. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  5934. if ($emptydate || $set_time == -1) {
  5935. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5936. }
  5937. for ($day = 1; $day <= 31; $day++) {
  5938. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  5939. }
  5940. $retstring .= "</select>";
  5941. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  5942. if ($emptydate || $set_time == -1) {
  5943. $retstring .= '<option value="0" selected>&nbsp;</option>';
  5944. }
  5945. // Month
  5946. for ($month = 1; $month <= 12; $month++) {
  5947. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  5948. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  5949. $retstring .= "</option>";
  5950. }
  5951. $retstring .= "</select>";
  5952. // Year
  5953. if ($emptydate || $set_time == -1) {
  5954. $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.'">';
  5955. } else {
  5956. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  5957. for ($year = $syear - 10; $year < $syear + 10; $year++) {
  5958. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  5959. }
  5960. $retstring .= "</select>\n";
  5961. }
  5962. }
  5963. }
  5964. if ($d && $h) {
  5965. $retstring .= ($h == 2 ? '<br>' : ' ');
  5966. $retstring .= '<span class="nowraponall">';
  5967. }
  5968. if ($h) {
  5969. $hourstart = 0;
  5970. $hourend = 24;
  5971. if ($openinghours != '') {
  5972. $openinghours = explode(',', $openinghours);
  5973. $hourstart = $openinghours[0];
  5974. $hourend = $openinghours[1];
  5975. if ($hourend < $hourstart) {
  5976. $hourend = $hourstart;
  5977. }
  5978. }
  5979. // Show hour
  5980. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  5981. if ($emptyhours) {
  5982. $retstring .= '<option value="-1">&nbsp;</option>';
  5983. }
  5984. for ($hour = $hourstart; $hour < $hourend; $hour++) {
  5985. if (strlen($hour) < 2) {
  5986. $hour = "0".$hour;
  5987. }
  5988. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour;
  5989. //$retstring .= (empty($conf->dol_optimize_smallscreen) ? '' : 'H');
  5990. $retstring .= '</option>';
  5991. }
  5992. $retstring .= '</select>';
  5993. //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  5994. if ($m) {
  5995. $retstring .= ":";
  5996. }
  5997. }
  5998. if ($m) {
  5999. // Show minutes
  6000. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  6001. if ($emptyhours) {
  6002. $retstring .= '<option value="-1">&nbsp;</option>';
  6003. }
  6004. for ($min = 0; $min < 60; $min += $stepminutes) {
  6005. if (strlen($min) < 2) {
  6006. $min = "0".$min;
  6007. }
  6008. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  6009. }
  6010. $retstring .= '</select>';
  6011. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  6012. }
  6013. if ($d && $h) {
  6014. $retstring .= '</span>';
  6015. }
  6016. // Add a "Now" link
  6017. if ($conf->use_javascript_ajax && $addnowlink) {
  6018. // Script which will be inserted in the onClick of the "Now" link
  6019. $reset_scripts = "";
  6020. if ($addnowlink == 2) { // local computer time
  6021. // pad add leading 0 on numbers
  6022. $reset_scripts .= "Number.prototype.pad = function(size) {
  6023. var s = String(this);
  6024. while (s.length < (size || 2)) {s = '0' + s;}
  6025. return s;
  6026. };
  6027. var d = new Date();";
  6028. }
  6029. // Generate the date part, depending on the use or not of the javascript calendar
  6030. if ($addnowlink == 1) { // server time expressed in user time setup
  6031. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  6032. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6033. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6034. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6035. } elseif ($addnowlink == 2) {
  6036. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  6037. * This break application for foreign languages.
  6038. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  6039. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  6040. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  6041. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  6042. */
  6043. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');';
  6044. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6045. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6046. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6047. }
  6048. /*if ($usecalendar == "eldy")
  6049. {
  6050. $base=DOL_URL_ROOT.'/core/';
  6051. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  6052. }
  6053. else
  6054. {
  6055. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  6056. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  6057. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  6058. }*/
  6059. // Update the hour part
  6060. if ($h) {
  6061. if ($fullday) {
  6062. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6063. }
  6064. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  6065. if ($addnowlink == 1) {
  6066. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6067. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  6068. } elseif ($addnowlink == 2) {
  6069. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  6070. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  6071. }
  6072. if ($fullday) {
  6073. $reset_scripts .= ' } ';
  6074. }
  6075. }
  6076. // Update the minute part
  6077. if ($m) {
  6078. if ($fullday) {
  6079. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6080. }
  6081. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  6082. if ($addnowlink == 1) {
  6083. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6084. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6085. } elseif ($addnowlink == 2) {
  6086. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  6087. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  6088. }
  6089. if ($fullday) {
  6090. $reset_scripts .= ' } ';
  6091. }
  6092. }
  6093. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6094. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6095. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  6096. $retstring .= $langs->trans("Now");
  6097. $retstring .= '</button> ';
  6098. }
  6099. }
  6100. // Add a "Plus one hour" link
  6101. if ($conf->use_javascript_ajax && $addplusone) {
  6102. // Script which will be inserted in the onClick of the "Add plusone" link
  6103. $reset_scripts = "";
  6104. // Generate the date part, depending on the use or not of the javascript calendar
  6105. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'dayinputnoreduce', 'tzuserrel').'\');';
  6106. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');';
  6107. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');';
  6108. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');';
  6109. // Update the hour part
  6110. if ($h) {
  6111. if ($fullday) {
  6112. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6113. }
  6114. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');';
  6115. if ($fullday) {
  6116. $reset_scripts .= ' } ';
  6117. }
  6118. }
  6119. // Update the minute part
  6120. if ($m) {
  6121. if ($fullday) {
  6122. $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  6123. }
  6124. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');';
  6125. if ($fullday) {
  6126. $reset_scripts .= ' } ';
  6127. }
  6128. }
  6129. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  6130. if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) {
  6131. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  6132. $retstring .= $langs->trans("DateStartPlusOne");
  6133. $retstring .= '</button> ';
  6134. }
  6135. }
  6136. // Add a link to set data
  6137. if ($conf->use_javascript_ajax && $adddateof) {
  6138. $tmparray = dol_getdate($adddateof);
  6139. if (empty($labeladddateof)) {
  6140. $labeladddateof = $langs->trans("DateInvoice");
  6141. }
  6142. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="console.log(\'Click on now link\'); jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'dayinputnoreduce').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  6143. }
  6144. return $retstring;
  6145. }
  6146. /**
  6147. * selectTypeDuration
  6148. *
  6149. * @param string $prefix Prefix
  6150. * @param string $selected Selected duration type
  6151. * @param array $excludetypes Array of duration types to exclude. Example array('y', 'm')
  6152. * @return string HTML select string
  6153. */
  6154. public function selectTypeDuration($prefix, $selected = 'i', $excludetypes = array())
  6155. {
  6156. global $langs;
  6157. $TDurationTypes = array(
  6158. 'y'=>$langs->trans('Years'),
  6159. 'm'=>$langs->trans('Month'),
  6160. 'w'=>$langs->trans('Weeks'),
  6161. 'd'=>$langs->trans('Days'),
  6162. 'h'=>$langs->trans('Hours'),
  6163. 'i'=>$langs->trans('Minutes')
  6164. );
  6165. // Removed undesired duration types
  6166. foreach ($excludetypes as $value) {
  6167. unset($TDurationTypes[$value]);
  6168. }
  6169. $retstring = '<select class="flat minwidth75 maxwidth100" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  6170. foreach ($TDurationTypes as $key => $typeduration) {
  6171. $retstring .= '<option value="'.$key.'"';
  6172. if ($key == $selected) {
  6173. $retstring .= " selected";
  6174. }
  6175. $retstring .= ">".$typeduration."</option>";
  6176. }
  6177. $retstring .= "</select>";
  6178. $retstring .= ajax_combobox('select_'.$prefix.'type_duration');
  6179. return $retstring;
  6180. }
  6181. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6182. /**
  6183. * Function to show a form to select a duration on a page
  6184. *
  6185. * @param string $prefix Prefix for input fields
  6186. * @param int $iSecond Default preselected duration (number of seconds or '')
  6187. * @param int $disabled Disable the combo box
  6188. * @param string $typehour If 'select' then input hour and input min is a combo,
  6189. * If 'text' input hour is in text and input min is a text,
  6190. * If 'textselect' input hour is in text and input min is a combo
  6191. * @param integer $minunderhours If 1, show minutes selection under the hours
  6192. * @param int $nooutput Do not output html string but return it
  6193. * @return string|void
  6194. */
  6195. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  6196. {
  6197. // phpcs:enable
  6198. global $langs;
  6199. $retstring = '<span class="nowraponall">';
  6200. $hourSelected = 0;
  6201. $minSelected = 0;
  6202. // Hours
  6203. if ($iSecond != '') {
  6204. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6205. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  6206. $minSelected = convertSecondToTime($iSecond, 'min');
  6207. }
  6208. if ($typehour == 'select') {
  6209. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  6210. for ($hour = 0; $hour < 25; $hour++) { // For a duration, we allow 24 hours
  6211. $retstring .= '<option value="'.$hour.'"';
  6212. if ($hourSelected == $hour) {
  6213. $retstring .= " selected";
  6214. }
  6215. $retstring .= ">".$hour."</option>";
  6216. }
  6217. $retstring .= "</select>";
  6218. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  6219. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  6220. } else {
  6221. return 'BadValueForParameterTypeHour';
  6222. }
  6223. if ($typehour != 'text') {
  6224. $retstring .= ' '.$langs->trans('HourShort');
  6225. } else {
  6226. $retstring .= '<span class="">:</span>';
  6227. }
  6228. // Minutes
  6229. if ($minunderhours) {
  6230. $retstring .= '<br>';
  6231. } else {
  6232. $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  6233. }
  6234. if ($typehour == 'select' || $typehour == 'textselect') {
  6235. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  6236. for ($min = 0; $min <= 55; $min = $min + 5) {
  6237. $retstring .= '<option value="'.$min.'"';
  6238. if ($minSelected == $min) {
  6239. $retstring .= ' selected';
  6240. }
  6241. $retstring .= '>'.$min.'</option>';
  6242. }
  6243. $retstring .= "</select>";
  6244. } elseif ($typehour == 'text') {
  6245. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  6246. }
  6247. if ($typehour != 'text') {
  6248. $retstring .= ' '.$langs->trans('MinuteShort');
  6249. }
  6250. $retstring.="</span>";
  6251. if (!empty($nooutput)) {
  6252. return $retstring;
  6253. }
  6254. print $retstring;
  6255. return;
  6256. }
  6257. /**
  6258. * Return list of tickets in Ajax if Ajax activated or go to selectTicketsList
  6259. *
  6260. * @param int $selected Preselected tickets
  6261. * @param string $htmlname Name of HTML select field (must be unique in page).
  6262. * @param string $filtertype To add a filter
  6263. * @param int $limit Limit on number of returned lines
  6264. * @param int $status Ticket status
  6265. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6266. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6267. * @param array $ajaxoptions Options for ajax_autocompleter
  6268. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6269. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6270. * @param int $forcecombo Force to use combo box
  6271. * @param string $morecss Add more css on select
  6272. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6273. * @param string $nooutput No print, return the output into a string
  6274. * @return void|string
  6275. */
  6276. 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)
  6277. {
  6278. global $langs, $conf;
  6279. $out = '';
  6280. // check parameters
  6281. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6282. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6283. $placeholder = '';
  6284. if ($selected && empty($selected_input_value)) {
  6285. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6286. $tickettmpselect = new Ticket($this->db);
  6287. $tickettmpselect->fetch($selected);
  6288. $selected_input_value = $tickettmpselect->ref;
  6289. unset($tickettmpselect);
  6290. }
  6291. $urloption = '';
  6292. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/ticket/ajax/tickets.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6293. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6294. elseif ($hidelabel > 1) {
  6295. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6296. if ($hidelabel == 2) {
  6297. $out .= img_picto($langs->trans("Search"), 'search');
  6298. }
  6299. }
  6300. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6301. if ($hidelabel == 3) {
  6302. $out .= img_picto($langs->trans("Search"), 'search');
  6303. }
  6304. } else {
  6305. $out .= $this->selectTicketsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6306. }
  6307. if (empty($nooutput)) print $out;
  6308. else return $out;
  6309. }
  6310. /**
  6311. * Return list of tickets.
  6312. * Called by selectTickets.
  6313. *
  6314. * @param int $selected Preselected ticket
  6315. * @param string $htmlname Name of select html
  6316. * @param string $filtertype Filter on ticket type
  6317. * @param int $limit Limit on number of returned lines
  6318. * @param string $filterkey Filter on ticket ref or subject
  6319. * @param int $status Ticket status
  6320. * @param int $outputmode 0=HTML select string, 1=Array
  6321. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6322. * @param int $forcecombo Force to use combo box
  6323. * @param string $morecss Add more css on select
  6324. * @return array Array of keys for json
  6325. */
  6326. public function selectTicketsList($selected = '', $htmlname = 'ticketid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6327. {
  6328. global $langs, $conf;
  6329. $out = '';
  6330. $outarray = array();
  6331. $selectFields = " p.rowid, p.ref, p.message";
  6332. $sql = "SELECT ";
  6333. $sql .= $selectFields;
  6334. $sql .= " FROM ".$this->db->prefix()."ticket as p";
  6335. $sql .= ' WHERE p.entity IN ('.getEntity('ticket').')';
  6336. // Add criteria on ref/label
  6337. if ($filterkey != '') {
  6338. $sql .= ' AND (';
  6339. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6340. // For natural search
  6341. $scrit = explode(' ', $filterkey);
  6342. $i = 0;
  6343. if (count($scrit) > 1) $sql .= "(";
  6344. foreach ($scrit as $crit) {
  6345. if ($i > 0) $sql .= " AND ";
  6346. $sql .= "(p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.subject LIKE '".$this->db->escape($prefix.$crit)."%'";
  6347. $sql .= ")";
  6348. $i++;
  6349. }
  6350. if (count($scrit) > 1) $sql .= ")";
  6351. $sql .= ')';
  6352. }
  6353. $sql .= $this->db->plimit($limit, 0);
  6354. // Build output string
  6355. dol_syslog(get_class($this)."::selectTicketsList search tickets", LOG_DEBUG);
  6356. $result = $this->db->query($sql);
  6357. if ($result) {
  6358. require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
  6359. require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php';
  6360. $num = $this->db->num_rows($result);
  6361. $events = null;
  6362. if (!$forcecombo) {
  6363. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6364. $out .= ajax_combobox($htmlname, $events, $conf->global->TICKET_USE_SEARCH_TO_SELECT);
  6365. }
  6366. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6367. $textifempty = '';
  6368. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6369. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6370. if (!empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6371. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6372. else $textifempty .= $langs->trans("All");
  6373. } else {
  6374. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6375. }
  6376. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6377. $i = 0;
  6378. while ($num && $i < $num) {
  6379. $opt = '';
  6380. $optJson = array();
  6381. $objp = $this->db->fetch_object($result);
  6382. $this->constructTicketListOption($objp, $opt, $optJson, $selected, $filterkey);
  6383. // Add new entry
  6384. // "key" value of json key array is used by jQuery automatically as selected value
  6385. // "label" value of json key array is used by jQuery automatically as text for combo box
  6386. $out .= $opt;
  6387. array_push($outarray, $optJson);
  6388. $i++;
  6389. }
  6390. $out .= '</select>';
  6391. $this->db->free($result);
  6392. if (empty($outputmode)) return $out;
  6393. return $outarray;
  6394. } else {
  6395. dol_print_error($this->db);
  6396. }
  6397. }
  6398. /**
  6399. * constructTicketListOption.
  6400. * This define value for &$opt and &$optJson.
  6401. *
  6402. * @param resource $objp Result set of fetch
  6403. * @param string $opt Option (var used for returned value in string option format)
  6404. * @param string $optJson Option (var used for returned value in json format)
  6405. * @param string $selected Preselected value
  6406. * @param string $filterkey Filter key to highlight
  6407. * @return void
  6408. */
  6409. protected function constructTicketListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6410. {
  6411. $outkey = '';
  6412. $outref = '';
  6413. $outtype = '';
  6414. $outkey = $objp->rowid;
  6415. $outref = $objp->ref;
  6416. $outtype = $objp->fk_product_type;
  6417. $opt = '<option value="'.$objp->rowid.'"';
  6418. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6419. $opt .= '>';
  6420. $opt .= $objp->ref;
  6421. $objRef = $objp->ref;
  6422. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6423. $opt .= "</option>\n";
  6424. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6425. }
  6426. /**
  6427. * Return list of projects in Ajax if Ajax activated or go to selectTicketsList
  6428. *
  6429. * @param int $selected Preselected tickets
  6430. * @param string $htmlname Name of HTML select field (must be unique in page).
  6431. * @param string $filtertype To add a filter
  6432. * @param int $limit Limit on number of returned lines
  6433. * @param int $status Ticket status
  6434. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6435. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  6436. * @param array $ajaxoptions Options for ajax_autocompleter
  6437. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6438. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6439. * @param int $forcecombo Force to use combo box
  6440. * @param string $morecss Add more css on select
  6441. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6442. * @param string $nooutput No print, return the output into a string
  6443. * @return void|string
  6444. */
  6445. 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)
  6446. {
  6447. global $langs, $conf;
  6448. $out = '';
  6449. // check parameters
  6450. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6451. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6452. $placeholder = '';
  6453. if ($selected && empty($selected_input_value)) {
  6454. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6455. $projecttmpselect = new Project($this->db);
  6456. $projecttmpselect->fetch($selected);
  6457. $selected_input_value = $projecttmpselect->ref;
  6458. unset($projecttmpselect);
  6459. }
  6460. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6461. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6462. elseif ($hidelabel > 1) {
  6463. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6464. if ($hidelabel == 2) {
  6465. $out .= img_picto($langs->trans("Search"), 'search');
  6466. }
  6467. }
  6468. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6469. if ($hidelabel == 3) {
  6470. $out .= img_picto($langs->trans("Search"), 'search');
  6471. }
  6472. } else {
  6473. $out .= $this->selectProjectsList($selected, $htmlname, $filtertype, $limit, $status, 0, $socid, $showempty, $forcecombo, $morecss);
  6474. }
  6475. if (empty($nooutput)) print $out;
  6476. else return $out;
  6477. }
  6478. /**
  6479. * Return list of projects.
  6480. * Called by selectProjects.
  6481. *
  6482. * @param int $selected Preselected project
  6483. * @param string $htmlname Name of select html
  6484. * @param string $filtertype Filter on project type
  6485. * @param int $limit Limit on number of returned lines
  6486. * @param string $filterkey Filter on project ref or subject
  6487. * @param int $status Ticket status
  6488. * @param int $outputmode 0=HTML select string, 1=Array
  6489. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6490. * @param int $forcecombo Force to use combo box
  6491. * @param string $morecss Add more css on select
  6492. * @return array Array of keys for json
  6493. */
  6494. public function selectProjectsList($selected = '', $htmlname = 'projectid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6495. {
  6496. global $langs, $conf;
  6497. $out = '';
  6498. $outarray = array();
  6499. $selectFields = " p.rowid, p.ref";
  6500. $sql = "SELECT ";
  6501. $sql .= $selectFields;
  6502. $sql .= " FROM ".$this->db->prefix()."projet as p";
  6503. $sql .= ' WHERE p.entity IN ('.getEntity('project').')';
  6504. // Add criteria on ref/label
  6505. if ($filterkey != '') {
  6506. $sql .= ' AND (';
  6507. $prefix = empty($conf->global->TICKET_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6508. // For natural search
  6509. $scrit = explode(' ', $filterkey);
  6510. $i = 0;
  6511. if (count($scrit) > 1) $sql .= "(";
  6512. foreach ($scrit as $crit) {
  6513. if ($i > 0) $sql .= " AND ";
  6514. $sql .= "p.ref LIKE '".$this->db->escape($prefix.$crit)."%'";
  6515. $sql .= "";
  6516. $i++;
  6517. }
  6518. if (count($scrit) > 1) $sql .= ")";
  6519. $sql .= ')';
  6520. }
  6521. $sql .= $this->db->plimit($limit, 0);
  6522. // Build output string
  6523. dol_syslog(get_class($this)."::selectProjectsList search projects", LOG_DEBUG);
  6524. $result = $this->db->query($sql);
  6525. if ($result) {
  6526. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6527. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  6528. $num = $this->db->num_rows($result);
  6529. $events = null;
  6530. if (!$forcecombo) {
  6531. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6532. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6533. }
  6534. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6535. $textifempty = '';
  6536. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6537. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6538. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6539. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6540. else $textifempty .= $langs->trans("All");
  6541. } else {
  6542. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6543. }
  6544. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  6545. $i = 0;
  6546. while ($num && $i < $num) {
  6547. $opt = '';
  6548. $optJson = array();
  6549. $objp = $this->db->fetch_object($result);
  6550. $this->constructProjectListOption($objp, $opt, $optJson, $selected, $filterkey);
  6551. // Add new entry
  6552. // "key" value of json key array is used by jQuery automatically as selected value
  6553. // "label" value of json key array is used by jQuery automatically as text for combo box
  6554. $out .= $opt;
  6555. array_push($outarray, $optJson);
  6556. $i++;
  6557. }
  6558. $out .= '</select>';
  6559. $this->db->free($result);
  6560. if (empty($outputmode)) return $out;
  6561. return $outarray;
  6562. } else {
  6563. dol_print_error($this->db);
  6564. }
  6565. }
  6566. /**
  6567. * constructProjectListOption.
  6568. * This define value for &$opt and &$optJson.
  6569. *
  6570. * @param resource $objp Result set of fetch
  6571. * @param string $opt Option (var used for returned value in string option format)
  6572. * @param string $optJson Option (var used for returned value in json format)
  6573. * @param string $selected Preselected value
  6574. * @param string $filterkey Filter key to highlight
  6575. * @return void
  6576. */
  6577. protected function constructProjectListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6578. {
  6579. $outkey = '';
  6580. $outval = '';
  6581. $outref = '';
  6582. $outlabel = '';
  6583. $outtype = '';
  6584. $label = $objp->label;
  6585. $outkey = $objp->rowid;
  6586. $outref = $objp->ref;
  6587. $outlabel = $objp->label;
  6588. $outtype = $objp->fk_product_type;
  6589. $opt = '<option value="'.$objp->rowid.'"';
  6590. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6591. $opt .= '>';
  6592. $opt .= $objp->ref;
  6593. $objRef = $objp->ref;
  6594. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  6595. $outval .= $objRef;
  6596. $opt .= "</option>\n";
  6597. $optJson = array('key'=>$outkey, 'value'=>$outref, 'type'=>$outtype);
  6598. }
  6599. /**
  6600. * Return list of members in Ajax if Ajax activated or go to selectTicketsList
  6601. *
  6602. * @param int $selected Preselected tickets
  6603. * @param string $htmlname Name of HTML select field (must be unique in page).
  6604. * @param string $filtertype To add a filter
  6605. * @param int $limit Limit on number of returned lines
  6606. * @param int $status Ticket status
  6607. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6608. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon before and placeholder, 3 search icon after)
  6609. * @param array $ajaxoptions Options for ajax_autocompleter
  6610. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  6611. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6612. * @param int $forcecombo Force to use combo box
  6613. * @param string $morecss Add more css on select
  6614. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  6615. * @param string $nooutput No print, return the output into a string
  6616. * @return void|string
  6617. */
  6618. 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)
  6619. {
  6620. global $langs, $conf;
  6621. $out = '';
  6622. // check parameters
  6623. if (is_null($ajaxoptions)) $ajaxoptions = array();
  6624. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->TICKET_USE_SEARCH_TO_SELECT)) {
  6625. $placeholder = '';
  6626. $urloption = '';
  6627. if ($selected && empty($selected_input_value)) {
  6628. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6629. $adherenttmpselect = new Adherent($this->db);
  6630. $adherenttmpselect->fetch($selected);
  6631. $selected_input_value = $adherenttmpselect->ref;
  6632. unset($adherenttmpselect);
  6633. }
  6634. $urloption = '';
  6635. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/adherents/ajax/adherents.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 1, $ajaxoptions);
  6636. if (empty($hidelabel)) $out .= $langs->trans("RefOrLabel").' : ';
  6637. elseif ($hidelabel > 1) {
  6638. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  6639. if ($hidelabel == 2) {
  6640. $out .= img_picto($langs->trans("Search"), 'search');
  6641. }
  6642. }
  6643. $out .= '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  6644. if ($hidelabel == 3) {
  6645. $out .= img_picto($langs->trans("Search"), 'search');
  6646. }
  6647. } else {
  6648. $filterkey = '';
  6649. $out .= $this->selectMembersList($selected, $htmlname, $filtertype, $limit, $filterkey, $status, 0, $showempty, $forcecombo, $morecss);
  6650. }
  6651. if (empty($nooutput)) print $out;
  6652. else return $out;
  6653. }
  6654. /**
  6655. * Return list of adherents.
  6656. * Called by selectMembers.
  6657. *
  6658. * @param int $selected Preselected adherent
  6659. * @param string $htmlname Name of select html
  6660. * @param string $filtertype Filter on adherent type
  6661. * @param int $limit Limit on number of returned lines
  6662. * @param string $filterkey Filter on member status
  6663. * @param int $status Member status
  6664. * @param int $outputmode 0=HTML select string, 1=Array
  6665. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  6666. * @param int $forcecombo Force to use combo box
  6667. * @param string $morecss Add more css on select
  6668. * @return array Array of keys for json
  6669. */
  6670. public function selectMembersList($selected = '', $htmlname = 'adherentid', $filtertype = '', $limit = 20, $filterkey = '', $status = 1, $outputmode = 0, $showempty = '1', $forcecombo = 0, $morecss = '')
  6671. {
  6672. global $langs, $conf;
  6673. $out = '';
  6674. $outarray = array();
  6675. $selectFields = " p.rowid, p.ref, p.firstname, p.lastname";
  6676. $sql = "SELECT ";
  6677. $sql .= $selectFields;
  6678. $sql .= " FROM ".$this->db->prefix()."adherent as p";
  6679. $sql .= ' WHERE p.entity IN ('.getEntity('adherent').')';
  6680. // Add criteria on ref/label
  6681. if ($filterkey != '') {
  6682. $sql .= ' AND (';
  6683. $prefix = empty($conf->global->MEMBER_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  6684. // For natural search
  6685. $scrit = explode(' ', $filterkey);
  6686. $i = 0;
  6687. if (count($scrit) > 1) $sql .= "(";
  6688. foreach ($scrit as $crit) {
  6689. if ($i > 0) $sql .= " AND ";
  6690. $sql .= "(p.firstname LIKE '".$this->db->escape($prefix.$crit)."%'";
  6691. $sql .= " OR p.lastname LIKE '".$this->db->escape($prefix.$crit)."%')";
  6692. $i++;
  6693. }
  6694. if (count($scrit) > 1) $sql .= ")";
  6695. $sql .= ')';
  6696. }
  6697. if ($status != -1) {
  6698. $sql .= ' AND statut = '.((int) $status);
  6699. }
  6700. $sql .= $this->db->plimit($limit, 0);
  6701. // Build output string
  6702. dol_syslog(get_class($this)."::selectMembersList search adherents", LOG_DEBUG);
  6703. $result = $this->db->query($sql);
  6704. if ($result) {
  6705. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  6706. require_once DOL_DOCUMENT_ROOT.'/core/lib/member.lib.php';
  6707. $num = $this->db->num_rows($result);
  6708. $events = null;
  6709. if (!$forcecombo) {
  6710. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6711. $out .= ajax_combobox($htmlname, $events, $conf->global->PROJECT_USE_SEARCH_TO_SELECT);
  6712. }
  6713. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  6714. $textifempty = '';
  6715. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  6716. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  6717. if (!empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT)) {
  6718. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6719. else $textifempty .= $langs->trans("All");
  6720. } else {
  6721. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  6722. }
  6723. if ($showempty) {
  6724. $out .= '<option value="-1" selected>'.$textifempty.'</option>';
  6725. }
  6726. $i = 0;
  6727. while ($num && $i < $num) {
  6728. $opt = '';
  6729. $optJson = array();
  6730. $objp = $this->db->fetch_object($result);
  6731. $this->constructMemberListOption($objp, $opt, $optJson, $selected, $filterkey);
  6732. // Add new entry
  6733. // "key" value of json key array is used by jQuery automatically as selected value
  6734. // "label" value of json key array is used by jQuery automatically as text for combo box
  6735. $out .= $opt;
  6736. array_push($outarray, $optJson);
  6737. $i++;
  6738. }
  6739. $out .= '</select>';
  6740. $this->db->free($result);
  6741. if (empty($outputmode)) return $out;
  6742. return $outarray;
  6743. } else {
  6744. dol_print_error($this->db);
  6745. }
  6746. }
  6747. /**
  6748. * constructMemberListOption.
  6749. * This define value for &$opt and &$optJson.
  6750. *
  6751. * @param resource $objp Result set of fetch
  6752. * @param string $opt Option (var used for returned value in string option format)
  6753. * @param string $optJson Option (var used for returned value in json format)
  6754. * @param string $selected Preselected value
  6755. * @param string $filterkey Filter key to highlight
  6756. * @return void
  6757. */
  6758. protected function constructMemberListOption(&$objp, &$opt, &$optJson, $selected, $filterkey = '')
  6759. {
  6760. $outkey = '';
  6761. $outlabel = '';
  6762. $outtype = '';
  6763. $outkey = $objp->rowid;
  6764. $outlabel = dolGetFirstLastname($objp->firstname, $objp->lastname);
  6765. $outtype = $objp->fk_adherent_type;
  6766. $opt = '<option value="'.$objp->rowid.'"';
  6767. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  6768. $opt .= '>';
  6769. if (!empty($filterkey) && $filterkey != '') {
  6770. $outlabel = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $outlabel, 1);
  6771. }
  6772. $opt .= $outlabel;
  6773. $opt .= "</option>\n";
  6774. $optJson = array('key'=>$outkey, 'value'=>$outlabel, 'type'=>$outtype);
  6775. }
  6776. /**
  6777. * Generic method to select a component from a combo list.
  6778. * Can use autocomplete with ajax after x key pressed or a full combo, depending on setup.
  6779. * This is the generic method that will replace all specific existing methods.
  6780. *
  6781. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]
  6782. * @param string $htmlname Name of HTML select component
  6783. * @param int $preselectedvalue Preselected value (ID of element)
  6784. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6785. * @param string $searchkey Search criteria
  6786. * @param string $placeholder Place holder
  6787. * @param string $morecss More CSS
  6788. * @param string $moreparams More params provided to ajax call
  6789. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6790. * @param int $disabled 1=Html component is disabled
  6791. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  6792. * @return string Return HTML string
  6793. * @see selectForFormsList() select_thirdparty_list()
  6794. */
  6795. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  6796. {
  6797. global $conf, $user;
  6798. $objecttmp = null;
  6799. // Example of value for $objectdec:
  6800. // Bom:bom/class/bom.class.php:0:t.status=1
  6801. // Bom:bom/class/bom.class.php:0:t.status=1:ref
  6802. // Bom:bom/class/bom.class.php:0:(t.status:=:1):ref
  6803. $InfoFieldList = explode(":", $objectdesc, 4);
  6804. $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]);
  6805. $reg = array();
  6806. if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) {
  6807. $InfoFieldList[4] = $reg[1]; // take the sort field
  6808. }
  6809. $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field
  6810. $classname = $InfoFieldList[0];
  6811. $classpath = $InfoFieldList[1];
  6812. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  6813. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  6814. $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4];
  6815. if (!empty($classpath)) {
  6816. dol_include_once($classpath);
  6817. if ($classname && class_exists($classname)) {
  6818. $objecttmp = new $classname($this->db);
  6819. // Make some replacement
  6820. $sharedentities = getEntity(strtolower($classname));
  6821. $objecttmp->filter = str_replace(
  6822. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  6823. array($conf->entity, $sharedentities, $user->id),
  6824. $filter
  6825. );
  6826. }
  6827. }
  6828. if (!is_object($objecttmp)) {
  6829. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  6830. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  6831. }
  6832. //var_dump($objecttmp->filter);
  6833. $prefixforautocompletemode = $objecttmp->element;
  6834. if ($prefixforautocompletemode == 'societe') {
  6835. $prefixforautocompletemode = 'company';
  6836. }
  6837. if ($prefixforautocompletemode == 'product') {
  6838. $prefixforautocompletemode = 'produit';
  6839. }
  6840. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6841. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  6842. $out = '';
  6843. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo) {
  6844. // No immediate load of all database
  6845. $placeholder = '';
  6846. if ($preselectedvalue && empty($selected_input_value)) {
  6847. $objecttmp->fetch($preselectedvalue);
  6848. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  6849. //unset($objecttmp);
  6850. }
  6851. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  6852. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  6853. // No immediate load of all database
  6854. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&objectdesc='.urlencode($objectdesc).'&filter='.urlencode($objecttmp->filter).($sortfield ? '&sortfield='.urlencode($sortfield) : '');
  6855. // Activate the auto complete using ajax call.
  6856. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  6857. $out .= '<style type="text/css">.ui-autocomplete { z-index: 1003; }</style>';
  6858. $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).'"' : '') .' />';
  6859. } else {
  6860. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  6861. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled, $sortfield);
  6862. }
  6863. return $out;
  6864. }
  6865. /**
  6866. * Function to forge a SQL criteria
  6867. *
  6868. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  6869. * @return string Forged criteria. Example: "t.field like 'abc%'"
  6870. */
  6871. protected static function forgeCriteriaCallback($matches)
  6872. {
  6873. global $db;
  6874. //dol_syslog("Convert matches ".$matches[1]);
  6875. if (empty($matches[1])) {
  6876. return '';
  6877. }
  6878. $tmp = explode(':', $matches[1]);
  6879. if (count($tmp) < 3) {
  6880. return '';
  6881. }
  6882. $tmpescaped = $tmp[2];
  6883. $regbis = array();
  6884. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  6885. $tmpescaped = "'".$db->escape($regbis[1])."'";
  6886. } else {
  6887. $tmpescaped = $db->escape($tmpescaped);
  6888. }
  6889. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  6890. }
  6891. /**
  6892. * Output html form to select an object.
  6893. * Note, this function is called by selectForForms or by ajax selectobject.php
  6894. *
  6895. * @param Object $objecttmp Object to knwo the table to scan for combo.
  6896. * @param string $htmlname Name of HTML select component
  6897. * @param int $preselectedvalue Preselected value (ID of element)
  6898. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  6899. * @param string $searchkey Search value
  6900. * @param string $placeholder Place holder
  6901. * @param string $morecss More CSS
  6902. * @param string $moreparams More params provided to ajax call
  6903. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  6904. * @param int $outputmode 0=HTML select string, 1=Array
  6905. * @param int $disabled 1=Html component is disabled
  6906. * @param string $sortfield Sort field
  6907. * @return string|array Return HTML string
  6908. * @see selectForForms()
  6909. */
  6910. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0, $sortfield = '')
  6911. {
  6912. global $conf, $langs, $user, $hookmanager;
  6913. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  6914. $prefixforautocompletemode = $objecttmp->element;
  6915. if ($prefixforautocompletemode == 'societe') {
  6916. $prefixforautocompletemode = 'company';
  6917. }
  6918. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  6919. if (!empty($objecttmp->fields)) { // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  6920. $tmpfieldstoshow = '';
  6921. foreach ($objecttmp->fields as $key => $val) {
  6922. if (!dol_eval($val['enabled'], 1, 1, '1')) {
  6923. continue;
  6924. }
  6925. if (!empty($val['showoncombobox'])) {
  6926. $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  6927. }
  6928. }
  6929. if ($tmpfieldstoshow) {
  6930. $fieldstoshow = $tmpfieldstoshow;
  6931. }
  6932. } else {
  6933. // For backward compatibility
  6934. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  6935. }
  6936. if (empty($fieldstoshow)) {
  6937. if (isset($objecttmp->fields['ref'])) {
  6938. $fieldstoshow = 't.ref';
  6939. } else {
  6940. $langs->load("errors");
  6941. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  6942. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  6943. }
  6944. }
  6945. $out = '';
  6946. $outarray = array();
  6947. $tmparray = array();
  6948. $num = 0;
  6949. // Search data
  6950. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".$this->db->prefix().$objecttmp->table_element." as t";
  6951. if (isset($objecttmp->ismultientitymanaged)) {
  6952. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6953. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  6954. $sql .= " INNER JOIN ".$this->db->prefix().$tmparray[1]." as parenttable ON parenttable.rowid = t.".$tmparray[0];
  6955. }
  6956. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6957. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6958. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  6959. }
  6960. }
  6961. }
  6962. // Add where from hooks
  6963. $parameters = array(
  6964. 'object' => $objecttmp,
  6965. 'htmlname' => $htmlname,
  6966. 'filter' => $filter,
  6967. 'searchkey' => $searchkey
  6968. );
  6969. $reshook = $hookmanager->executeHooks('selectForFormsListWhere', $parameters); // Note that $action and $object may have been modified by hook
  6970. if (!empty($hookmanager->resPrint)) {
  6971. $sql .= $hookmanager->resPrint;
  6972. } else {
  6973. $sql .= " WHERE 1=1";
  6974. if (isset($objecttmp->ismultientitymanaged)) {
  6975. if ($objecttmp->ismultientitymanaged == 1) {
  6976. $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  6977. }
  6978. if (!is_numeric($objecttmp->ismultientitymanaged)) {
  6979. $sql .= " AND parenttable.entity = t.".$tmparray[0];
  6980. }
  6981. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  6982. if ($objecttmp->element == 'societe') {
  6983. $sql .= " AND t.rowid = ".((int) $user->socid);
  6984. } else {
  6985. $sql .= " AND t.fk_soc = ".((int) $user->socid);
  6986. }
  6987. }
  6988. if ($objecttmp->ismultientitymanaged === 'fk_soc@societe') {
  6989. if (empty($user->rights->societe->client->voir) && !$user->socid) {
  6990. $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  6991. }
  6992. }
  6993. }
  6994. if ($searchkey != '') {
  6995. $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  6996. }
  6997. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  6998. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  6999. {
  7000. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  7001. }*/
  7002. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  7003. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  7004. }
  7005. }
  7006. $sql .= $this->db->order($sortfield ? $sortfield : $fieldstoshow, "ASC");
  7007. //$sql.=$this->db->plimit($limit, 0);
  7008. //print $sql;
  7009. // Build output string
  7010. $resql = $this->db->query($sql);
  7011. if ($resql) {
  7012. // Construct $out and $outarray
  7013. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  7014. // 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
  7015. $textifempty = '&nbsp;';
  7016. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  7017. if (!empty($conf->global->$confkeyforautocompletemode)) {
  7018. if ($showempty && !is_numeric($showempty)) {
  7019. $textifempty = $langs->trans($showempty);
  7020. } else {
  7021. $textifempty .= $langs->trans("All");
  7022. }
  7023. }
  7024. if ($showempty) {
  7025. $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  7026. }
  7027. $num = $this->db->num_rows($resql);
  7028. $i = 0;
  7029. if ($num) {
  7030. while ($i < $num) {
  7031. $obj = $this->db->fetch_object($resql);
  7032. $label = '';
  7033. $tmparray = explode(',', $fieldstoshow);
  7034. $oldvalueforshowoncombobox = 0;
  7035. foreach ($tmparray as $key => $val) {
  7036. $val = preg_replace('/t\./', '', $val);
  7037. $label .= (($label && $obj->$val) ? ($oldvalueforshowoncombobox != $objecttmp->fields[$val]['showoncombobox'] ? ' - ' : ' ') : '');
  7038. $label .= $obj->$val;
  7039. $oldvalueforshowoncombobox = !empty($objecttmp->fields[$val]['showoncombobox']) ? $objecttmp->fields[$val]['showoncombobox'] : 0;
  7040. }
  7041. if (empty($outputmode)) {
  7042. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid) {
  7043. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  7044. } else {
  7045. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  7046. }
  7047. } else {
  7048. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  7049. }
  7050. $i++;
  7051. if (($i % 10) == 0) {
  7052. $out .= "\n";
  7053. }
  7054. }
  7055. }
  7056. $out .= '</select>'."\n";
  7057. if (!$forcecombo) {
  7058. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7059. $out .= ajax_combobox($htmlname, null, (!empty($conf->global->$confkeyforautocompletemode) ? $conf->global->$confkeyforautocompletemode : 0));
  7060. }
  7061. } else {
  7062. dol_print_error($this->db);
  7063. }
  7064. $this->result = array('nbofelement'=>$num);
  7065. if ($outputmode) {
  7066. return $outarray;
  7067. }
  7068. return $out;
  7069. }
  7070. /**
  7071. * Return a HTML select string, built from an array of key+value.
  7072. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  7073. *
  7074. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  7075. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>..., 'disabled'=>..., 'css'=>...))
  7076. * @param string|string[] $id Preselected key or preselected keys for multiselect. Use 'ifone' to autoselect record if there is only one record.
  7077. * @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.
  7078. * @param int $key_in_label 1 to show key into label with format "[key] value"
  7079. * @param int $value_as_key 1 to use value as key
  7080. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  7081. * @param int $translate 1=Translate and encode value
  7082. * @param int $maxlen Length maximum for labels
  7083. * @param int $disabled Html select box is disabled
  7084. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  7085. * @param string $morecss Add more class to css styles
  7086. * @param int $addjscombo Add js combo
  7087. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  7088. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  7089. * @param int $nohtmlescape No html escaping.
  7090. * @return string HTML select string.
  7091. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  7092. */
  7093. public static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '', $addjscombo = 1, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  7094. {
  7095. global $conf, $langs;
  7096. // Do we want a multiselect ?
  7097. //$jsbeautify = 0;
  7098. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  7099. $jsbeautify = 1;
  7100. if ($value_as_key) {
  7101. $array = array_combine($array, $array);
  7102. }
  7103. $out = '';
  7104. if ($addjscombo < 0) {
  7105. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7106. $addjscombo = 1;
  7107. } else {
  7108. $addjscombo = 0;
  7109. }
  7110. }
  7111. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  7112. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  7113. $out .= '>';
  7114. if ($show_empty) {
  7115. $textforempty = ' ';
  7116. if (!empty($conf->use_javascript_ajax)) {
  7117. $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  7118. }
  7119. if (!is_numeric($show_empty)) {
  7120. $textforempty = $show_empty;
  7121. }
  7122. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  7123. }
  7124. if (is_array($array)) {
  7125. // Translate
  7126. if ($translate) {
  7127. foreach ($array as $key => $value) {
  7128. if (!is_array($value)) {
  7129. $array[$key] = $langs->trans($value);
  7130. } else {
  7131. $array[$key]['label'] = $langs->trans($value['label']);
  7132. }
  7133. }
  7134. }
  7135. // Sort
  7136. if ($sort == 'ASC') {
  7137. asort($array);
  7138. } elseif ($sort == 'DESC') {
  7139. arsort($array);
  7140. }
  7141. foreach ($array as $key => $tmpvalue) {
  7142. if (is_array($tmpvalue)) {
  7143. $value = $tmpvalue['label'];
  7144. $disabled = empty($tmpvalue['disabled']) ? '' : ' disabled';
  7145. $style = empty($tmpvalue['css']) ? '' : ' class="'.$tmpvalue['css'].'"';
  7146. } else {
  7147. $value = $tmpvalue;
  7148. $disabled = '';
  7149. $style = '';
  7150. }
  7151. if (!empty($disablebademail)) {
  7152. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  7153. || ($disablebademail == 2 && preg_match('/---/', $value))) {
  7154. $disabled = ' disabled';
  7155. $style = ' class="warning"';
  7156. }
  7157. }
  7158. if ($key_in_label) {
  7159. if (empty($nohtmlescape)) {
  7160. $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  7161. } else {
  7162. $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  7163. }
  7164. } else {
  7165. if (empty($nohtmlescape)) {
  7166. $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  7167. } else {
  7168. $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  7169. }
  7170. if ($value == '' || $value == '-') {
  7171. $selectOptionValue = '&nbsp;';
  7172. }
  7173. }
  7174. $out .= '<option value="'.$key.'"';
  7175. $out .= $style.$disabled;
  7176. if (is_array($id)) {
  7177. if (in_array($key, $id) && !$disabled) {
  7178. $out .= ' selected'; // To preselect a value
  7179. }
  7180. } else {
  7181. $id = (string) $id; // if $id = 0, then $id = '0'
  7182. if ($id != '' && ($id == $key || ($id == 'ifone' && count($array) == 1)) && !$disabled) {
  7183. $out .= ' selected'; // To preselect a value
  7184. }
  7185. }
  7186. if ($nohtmlescape) {
  7187. $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  7188. }
  7189. if (is_array($tmpvalue)) {
  7190. foreach ($tmpvalue as $keyforvalue => $valueforvalue) {
  7191. if (preg_match('/^data-/', $keyforvalue)) {
  7192. $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  7193. }
  7194. }
  7195. }
  7196. $out .= '>';
  7197. //var_dump($selectOptionValue);
  7198. $out .= $selectOptionValue;
  7199. $out .= "</option>\n";
  7200. }
  7201. }
  7202. $out .= "</select>";
  7203. // Add code for jquery to use multiselect
  7204. if ($addjscombo && $jsbeautify) {
  7205. // Enhance with select2
  7206. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7207. $out .= ajax_combobox($htmlname, array(), 0, 0, 'resolve', $show_empty < 0 ? (string) $show_empty : '-1');
  7208. }
  7209. return $out;
  7210. }
  7211. /**
  7212. * 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.
  7213. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7214. *
  7215. * @param string $htmlname Name of html select area
  7216. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7217. * @param string $id Preselected key
  7218. * @param string $moreparam Add more parameters onto the select tag
  7219. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  7220. * @param int $disabled Html select box is disabled
  7221. * @param int $minimumInputLength Minimum Input Length
  7222. * @param string $morecss Add more class to css styles
  7223. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7224. * @param string $placeholder String to use as placeholder
  7225. * @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)
  7226. * @return string HTML select string
  7227. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  7228. */
  7229. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7230. {
  7231. global $conf, $langs;
  7232. global $delayedhtmlcontent; // Will be used later outside of this function
  7233. // TODO Use an internal dolibarr component instead of select2
  7234. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7235. return '';
  7236. }
  7237. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  7238. $outdelayed = '';
  7239. if (!empty($conf->use_javascript_ajax)) {
  7240. $tmpplugin = 'select2';
  7241. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7242. <script>
  7243. $(document).ready(function () {
  7244. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  7245. $(".'.$htmlname.'").select2({
  7246. ajax: {
  7247. dir: "ltr",
  7248. url: "'.$url.'",
  7249. dataType: \'json\',
  7250. delay: 250,
  7251. data: function (params) {
  7252. return {
  7253. q: params.term, // search term
  7254. page: params.page
  7255. };
  7256. },
  7257. processResults: function (data) {
  7258. // parse the results into the format expected by Select2.
  7259. // since we are using custom formatting functions we do not need to alter the remote JSON data
  7260. //console.log(data);
  7261. saveRemoteData = data;
  7262. /* format json result for select2 */
  7263. result = []
  7264. $.each( data, function( key, value ) {
  7265. result.push({id: key, text: value.text});
  7266. });
  7267. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  7268. //console.log(result);
  7269. return {results: result, more: false}
  7270. },
  7271. cache: true
  7272. },
  7273. language: select2arrayoflanguage,
  7274. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7275. placeholder: "'.dol_escape_js($placeholder).'",
  7276. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7277. minimumInputLength: '.$minimumInputLength.',
  7278. formatResult: function(result, container, query, escapeMarkup) {
  7279. return escapeMarkup(result.text);
  7280. },
  7281. });
  7282. '.($callurlonselect ? '
  7283. /* Code to execute a GET when we select a value */
  7284. $(".'.$htmlname.'").change(function() {
  7285. var selected = $(".'.$htmlname.'").val();
  7286. console.log("We select in selectArrayAjax the entry "+selected)
  7287. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7288. $.each( saveRemoteData, function( key, value ) {
  7289. if (key == selected)
  7290. {
  7291. console.log("selectArrayAjax - Do a redirect to "+value.url)
  7292. location.assign(value.url);
  7293. }
  7294. });
  7295. });' : '').'
  7296. });
  7297. </script>';
  7298. }
  7299. if ($acceptdelayedhtml) {
  7300. $delayedhtmlcontent .= $outdelayed;
  7301. } else {
  7302. $out .= $outdelayed;
  7303. }
  7304. return $out;
  7305. }
  7306. /**
  7307. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  7308. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  7309. *
  7310. * @param string $htmlname Name of html select area
  7311. * @param array $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  7312. * @param string $id Preselected key
  7313. * @param string $moreparam Add more parameters onto the select tag
  7314. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  7315. * @param int $disabled Html select box is disabled
  7316. * @param int $minimumInputLength Minimum Input Length
  7317. * @param string $morecss Add more class to css styles
  7318. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  7319. * @param string $placeholder String to use as placeholder
  7320. * @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)
  7321. * @return string HTML select string
  7322. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  7323. */
  7324. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  7325. {
  7326. global $conf, $langs;
  7327. global $delayedhtmlcontent; // Will be used later outside of this function
  7328. // TODO Use an internal dolibarr component instead of select2
  7329. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) {
  7330. return '';
  7331. }
  7332. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  7333. $formattedarrayresult = array();
  7334. foreach ($array as $key => $value) {
  7335. $o = new stdClass();
  7336. $o->id = $key;
  7337. $o->text = $value['text'];
  7338. $o->url = $value['url'];
  7339. $formattedarrayresult[] = $o;
  7340. }
  7341. $outdelayed = '';
  7342. if (!empty($conf->use_javascript_ajax)) {
  7343. $tmpplugin = 'select2';
  7344. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  7345. <script>
  7346. $(document).ready(function () {
  7347. var data = '.json_encode($formattedarrayresult).';
  7348. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  7349. $(".'.$htmlname.'").select2({
  7350. data: data,
  7351. language: select2arrayoflanguage,
  7352. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  7353. placeholder: "'.dol_escape_js($placeholder).'",
  7354. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7355. minimumInputLength: '.$minimumInputLength.',
  7356. formatResult: function(result, container, query, escapeMarkup) {
  7357. return escapeMarkup(result.text);
  7358. },
  7359. matcher: function (params, data) {
  7360. if(! data.id) return null;';
  7361. if ($callurlonselect) {
  7362. // We forge the url with 'sall='
  7363. $outdelayed .= '
  7364. var urlBase = data.url;
  7365. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  7366. /* console.log("params.term="+params.term); */
  7367. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  7368. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term.replace(/\"/g, ""));';
  7369. }
  7370. if (!$disableFiltering) {
  7371. $outdelayed .= '
  7372. if(data.text.match(new RegExp(params.term))) {
  7373. return data;
  7374. }
  7375. return null;';
  7376. } else {
  7377. $outdelayed .= '
  7378. return data;';
  7379. }
  7380. $outdelayed .= '
  7381. }
  7382. });
  7383. '.($callurlonselect ? '
  7384. /* Code to execute a GET when we select a value */
  7385. $(".'.$htmlname.'").change(function() {
  7386. var selected = $(".'.$htmlname.'").val();
  7387. console.log("We select "+selected)
  7388. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  7389. $.each( saveRemoteData, function( key, value ) {
  7390. if (key == selected)
  7391. {
  7392. console.log("selectArrayFilter - Do a redirect to "+value.url)
  7393. location.assign(value.url);
  7394. }
  7395. });
  7396. });' : '').'
  7397. });
  7398. </script>';
  7399. }
  7400. if ($acceptdelayedhtml) {
  7401. $delayedhtmlcontent .= $outdelayed;
  7402. } else {
  7403. $out .= $outdelayed;
  7404. }
  7405. return $out;
  7406. }
  7407. /**
  7408. * Show a multiselect form from an array. WARNING: Use this only for short lists.
  7409. *
  7410. * @param string $htmlname Name of select
  7411. * @param array $array Array with key+value
  7412. * @param array $selected Array with key+value preselected
  7413. * @param int $key_in_label 1 to show key like in "[key] value"
  7414. * @param int $value_as_key 1 to use value as key
  7415. * @param string $morecss Add more css style
  7416. * @param int $translate Translate and encode value
  7417. * @param int|string $width Force width of select box. May be used only when using jquery couch. Example: 250, '95%'
  7418. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  7419. * @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.
  7420. * @param string $placeholder String to use as placeholder
  7421. * @param int $addjscombo Add js combo
  7422. * @return string HTML multiselect string
  7423. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  7424. */
  7425. 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)
  7426. {
  7427. global $conf, $langs;
  7428. $out = '';
  7429. if ($addjscombo < 0) {
  7430. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7431. $addjscombo = 1;
  7432. } else {
  7433. $addjscombo = 0;
  7434. }
  7435. }
  7436. // Try also magic suggest
  7437. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  7438. if (is_array($array) && !empty($array)) {
  7439. if ($value_as_key) {
  7440. $array = array_combine($array, $array);
  7441. }
  7442. if (!empty($array)) {
  7443. foreach ($array as $key => $value) {
  7444. $newval = ($translate ? $langs->trans($value) : $value);
  7445. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  7446. $out .= '<option value="'.$key.'"';
  7447. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != '')) {
  7448. $out .= ' selected';
  7449. }
  7450. $out .= ' data-html="'.dol_escape_htmltag($newval).'"';
  7451. $out .= '>';
  7452. $out .= dol_htmlentitiesbr($newval);
  7453. $out .= '</option>'."\n";
  7454. }
  7455. }
  7456. }
  7457. $out .= '</select>'."\n";
  7458. // Add code for jquery to use multiselect
  7459. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')) {
  7460. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.', addjscombo='.$addjscombo.' -->';
  7461. $out .= "\n".'<script>'."\n";
  7462. if ($addjscombo == 1) {
  7463. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  7464. $out .= 'function formatResult(record, container) {'."\n";
  7465. $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";
  7466. $out .= ' return record.text;';
  7467. $out .= '};'."\n";
  7468. $out .= 'function formatSelection(record) {'."\n";
  7469. if ($elemtype == 'category') {
  7470. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  7471. } else {
  7472. $out .= 'return record.text;';
  7473. }
  7474. $out .= '};'."\n";
  7475. $out .= '$(document).ready(function () {
  7476. $(\'#'.$htmlname.'\').'.$tmpplugin.'({';
  7477. if ($placeholder) {
  7478. $out .= '
  7479. placeholder: {
  7480. id: \'-1\',
  7481. text: \''.dol_escape_js($placeholder).'\'
  7482. },';
  7483. }
  7484. $out .= ' dir: \'ltr\',
  7485. // Specify format function for dropdown item
  7486. formatResult: formatResult,
  7487. templateResult: formatResult, /* For 4.0 */
  7488. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  7489. // Specify format function for selected item
  7490. formatSelection: formatSelection,
  7491. templateSelection: formatSelection /* For 4.0 */
  7492. });
  7493. /* Add also morecss to the css .select2 that is after the #htmlname, for component that are show dynamically after load, because select2 set
  7494. the size only if component is not hidden by default on load */
  7495. $(\'#'.$htmlname.' + .select2\').addClass(\''.$morecss.'\');
  7496. });'."\n";
  7497. } elseif ($addjscombo == 2 && !defined('DISABLE_MULTISELECT')) {
  7498. // Add other js lib
  7499. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  7500. // ...
  7501. $out .= 'console.log(\'addjscombo=2 for htmlname='.$htmlname.'\');';
  7502. $out .= '$(document).ready(function () {
  7503. $(\'#'.$htmlname.'\').multiSelect({
  7504. containerHTML: \'<div class="multi-select-container">\',
  7505. menuHTML: \'<div class="multi-select-menu">\',
  7506. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  7507. menuItemHTML: \'<label class="multi-select-menuitem">\',
  7508. activeClass: \'multi-select-container--open\',
  7509. noneText: \''.$placeholder.'\'
  7510. });
  7511. })';
  7512. }
  7513. $out .= '</script>';
  7514. }
  7515. return $out;
  7516. }
  7517. /**
  7518. * 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.
  7519. *
  7520. * @param string $htmlname Name of HTML field
  7521. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  7522. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  7523. * @param string $pos Position colon on liste value 'left' or '' (meaning 'right').
  7524. * @return string HTML multiselect string
  7525. * @see selectarray()
  7526. */
  7527. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage, $pos = '')
  7528. {
  7529. global $conf, $langs, $user, $extrafields;
  7530. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  7531. return '';
  7532. }
  7533. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved selected fields to show
  7534. if (!empty($user->conf->$tmpvar)) { // A list of fields was already customized for user
  7535. $tmparray = explode(',', $user->conf->$tmpvar);
  7536. foreach ($array as $key => $val) {
  7537. //var_dump($key);
  7538. //var_dump($tmparray);
  7539. if (in_array($key, $tmparray)) {
  7540. $array[$key]['checked'] = 1;
  7541. } else {
  7542. $array[$key]['checked'] = 0;
  7543. }
  7544. }
  7545. } else { // There is no list of fields already customized for user
  7546. foreach ($array as $key => $val) {
  7547. if (!empty($array[$key]['checked']) && $array[$key]['checked'] < 0) {
  7548. $array[$key]['checked'] = 0;
  7549. }
  7550. }
  7551. }
  7552. $listoffieldsforselection = '';
  7553. $listcheckedstring = '';
  7554. foreach ($array as $key => $val) {
  7555. // var_dump($val);
  7556. // var_dump(array_key_exists('enabled', $val));
  7557. // var_dump(!$val['enabled']);
  7558. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) {
  7559. unset($array[$key]); // We don't want this field
  7560. continue;
  7561. }
  7562. if (!empty($val['type']) && $val['type'] == 'separate') {
  7563. // Field remains in array but we don't add it into $listoffieldsforselection
  7564. //$listoffieldsforselection .= '<li>-----</li>';
  7565. continue;
  7566. }
  7567. if ($val['label']) {
  7568. if (!empty($val['langfile']) && is_object($langs)) {
  7569. $langs->load($val['langfile']);
  7570. }
  7571. // Note: $val['checked'] <> 0 means we must show the field into the combo list
  7572. $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>';
  7573. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  7574. }
  7575. }
  7576. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  7577. <dl class="dropdown">
  7578. <dt>
  7579. <a href="#'.$htmlname.'">
  7580. '.img_picto('', 'list').'
  7581. </a>
  7582. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  7583. </dt>
  7584. <dd class="dropdowndd">
  7585. <div class="multiselectcheckbox'.$htmlname.'">
  7586. <ul class="ul'.$htmlname.' '.$htmlname.$pos.'">
  7587. '.$listoffieldsforselection.'
  7588. </ul>
  7589. </div>
  7590. </dd>
  7591. </dl>
  7592. <script type="text/javascript">
  7593. jQuery(document).ready(function () {
  7594. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  7595. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  7596. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  7597. var title = $(this).val() + ",";
  7598. if ($(this).is(\':checked\')) {
  7599. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  7600. }
  7601. else {
  7602. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  7603. }
  7604. // Now, we submit page
  7605. //$(this).parents(\'form:first\').submit();
  7606. });
  7607. });
  7608. </script>
  7609. ';
  7610. return $out;
  7611. }
  7612. /**
  7613. * Render list of categories linked to object with id $id and type $type
  7614. *
  7615. * @param int $id Id of object
  7616. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  7617. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  7618. * @param int $nolink 1=Do not add html links
  7619. * @return string String with categories
  7620. */
  7621. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  7622. {
  7623. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  7624. $cat = new Categorie($this->db);
  7625. $categories = $cat->containing($id, $type);
  7626. if ($rendermode == 1) {
  7627. $toprint = array();
  7628. foreach ($categories as $c) {
  7629. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  7630. foreach ($ways as $way) {
  7631. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #bbb"').'>'.$way.'</li>';
  7632. }
  7633. }
  7634. return '<div class="select2-container-multi-dolibarr"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  7635. }
  7636. if ($rendermode == 0) {
  7637. $arrayselected = array();
  7638. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  7639. foreach ($categories as $c) {
  7640. $arrayselected[] = $c->id;
  7641. }
  7642. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  7643. }
  7644. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  7645. }
  7646. /**
  7647. * Show linked object block.
  7648. *
  7649. * @param CommonObject $object Object we want to show links to
  7650. * @param string $morehtmlright More html to show on right of title
  7651. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  7652. * @param string $title Title
  7653. * @return int <0 if KO, >=0 if OK
  7654. */
  7655. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false, $title = 'RelatedObjects')
  7656. {
  7657. global $conf, $langs, $hookmanager;
  7658. global $bc, $action;
  7659. $object->fetchObjectLinked();
  7660. // Bypass the default method
  7661. $hookmanager->initHooks(array('commonobject'));
  7662. $parameters = array(
  7663. 'morehtmlright' => $morehtmlright,
  7664. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  7665. );
  7666. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7667. if (empty($reshook)) {
  7668. $nbofdifferenttypes = count($object->linkedObjects);
  7669. print '<!-- showLinkedObjectBlock -->';
  7670. print load_fiche_titre($langs->trans($title), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  7671. print '<div class="div-table-responsive-no-min">';
  7672. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  7673. print '<tr class="liste_titre">';
  7674. print '<td>'.$langs->trans("Type").'</td>';
  7675. print '<td>'.$langs->trans("Ref").'</td>';
  7676. print '<td class="center"></td>';
  7677. print '<td class="center">'.$langs->trans("Date").'</td>';
  7678. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7679. print '<td class="right">'.$langs->trans("Status").'</td>';
  7680. print '<td></td>';
  7681. print '</tr>';
  7682. $nboftypesoutput = 0;
  7683. foreach ($object->linkedObjects as $objecttype => $objects) {
  7684. $tplpath = $element = $subelement = $objecttype;
  7685. // to display inport button on tpl
  7686. $showImportButton = false;
  7687. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  7688. $showImportButton = true;
  7689. }
  7690. $regs = array();
  7691. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
  7692. $element = $regs[1];
  7693. $subelement = $regs[2];
  7694. $tplpath = $element.'/'.$subelement;
  7695. }
  7696. $tplname = 'linkedobjectblock';
  7697. // To work with non standard path
  7698. if ($objecttype == 'facture') {
  7699. $tplpath = 'compta/'.$element;
  7700. if (!isModEnabled('facture')) {
  7701. continue; // Do not show if module disabled
  7702. }
  7703. } elseif ($objecttype == 'facturerec') {
  7704. $tplpath = 'compta/facture';
  7705. $tplname = 'linkedobjectblockForRec';
  7706. if (!isModEnabled('facture')) {
  7707. continue; // Do not show if module disabled
  7708. }
  7709. } elseif ($objecttype == 'propal') {
  7710. $tplpath = 'comm/'.$element;
  7711. if (empty($conf->propal->enabled)) {
  7712. continue; // Do not show if module disabled
  7713. }
  7714. } elseif ($objecttype == 'supplier_proposal') {
  7715. if (empty($conf->supplier_proposal->enabled)) {
  7716. continue; // Do not show if module disabled
  7717. }
  7718. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  7719. $tplpath = 'expedition';
  7720. if (empty($conf->expedition->enabled)) {
  7721. continue; // Do not show if module disabled
  7722. }
  7723. } elseif ($objecttype == 'reception') {
  7724. $tplpath = 'reception';
  7725. if (empty($conf->reception->enabled)) {
  7726. continue; // Do not show if module disabled
  7727. }
  7728. } elseif ($objecttype == 'delivery') {
  7729. $tplpath = 'delivery';
  7730. if (empty($conf->expedition->enabled)) {
  7731. continue; // Do not show if module disabled
  7732. }
  7733. } elseif ($objecttype == 'ficheinter') {
  7734. $tplpath = 'fichinter';
  7735. if (empty($conf->ficheinter->enabled)) {
  7736. continue; // Do not show if module disabled
  7737. }
  7738. } elseif ($objecttype == 'invoice_supplier') {
  7739. $tplpath = 'fourn/facture';
  7740. } elseif ($objecttype == 'order_supplier') {
  7741. $tplpath = 'fourn/commande';
  7742. } elseif ($objecttype == 'expensereport') {
  7743. $tplpath = 'expensereport';
  7744. } elseif ($objecttype == 'subscription') {
  7745. $tplpath = 'adherents';
  7746. } elseif ($objecttype == 'conferenceorbooth') {
  7747. $tplpath = 'eventorganization';
  7748. } elseif ($objecttype == 'conferenceorboothattendee') {
  7749. $tplpath = 'eventorganization';
  7750. } elseif ($objecttype == 'mo') {
  7751. $tplpath = 'mrp';
  7752. if (empty($conf->mrp->enabled)) {
  7753. continue; // Do not show if module disabled
  7754. }
  7755. }
  7756. global $linkedObjectBlock;
  7757. $linkedObjectBlock = $objects;
  7758. // Output template part (modules that overwrite templates must declare this into descriptor)
  7759. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  7760. foreach ($dirtpls as $reldir) {
  7761. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) { // No more type to show after
  7762. global $noMoreLinkedObjectBlockAfter;
  7763. $noMoreLinkedObjectBlockAfter = 1;
  7764. }
  7765. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  7766. if ($res) {
  7767. $nboftypesoutput++;
  7768. break;
  7769. }
  7770. }
  7771. }
  7772. if (!$nboftypesoutput) {
  7773. print '<tr><td class="impair" colspan="7"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
  7774. }
  7775. print '</table>';
  7776. if (!empty($compatibleImportElementsList)) {
  7777. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  7778. }
  7779. print '</div>';
  7780. return $nbofdifferenttypes;
  7781. }
  7782. }
  7783. /**
  7784. * Show block with links to link to other objects.
  7785. *
  7786. * @param CommonObject $object Object we want to show links to
  7787. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  7788. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  7789. * @return string <0 if KO, >0 if OK
  7790. */
  7791. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  7792. {
  7793. global $conf, $langs, $hookmanager;
  7794. global $action;
  7795. $linktoelem = '';
  7796. $linktoelemlist = '';
  7797. $listofidcompanytoscan = '';
  7798. if (!is_object($object->thirdparty)) {
  7799. $object->fetch_thirdparty();
  7800. }
  7801. $possiblelinks = array();
  7802. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) {
  7803. $listofidcompanytoscan = $object->thirdparty->id;
  7804. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
  7805. $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  7806. }
  7807. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) {
  7808. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  7809. $tmpproject = new Project($this->db);
  7810. $tmpproject->fetch($object->fk_project);
  7811. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
  7812. $listofidcompanytoscan .= ','.$tmpproject->socid;
  7813. }
  7814. unset($tmpproject);
  7815. }
  7816. $possiblelinks = array(
  7817. 'propal'=>array(
  7818. 'enabled'=>(!empty($conf->propal->enabled) ? $conf->propal->enabled : 0),
  7819. 'perms'=>1,
  7820. 'label'=>'LinkToProposal',
  7821. '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').')'),
  7822. 'order'=>array(
  7823. 'enabled'=>(!empty($conf->commande->enabled) ? $conf->commande->enabled : 0),
  7824. 'perms'=>1,
  7825. 'label'=>'LinkToOrder',
  7826. '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').')'),
  7827. 'invoice'=>array(
  7828. 'enabled'=>isModEnabled('facture'),
  7829. 'perms'=>1,
  7830. 'label'=>'LinkToInvoice',
  7831. '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').')'),
  7832. 'invoice_template'=>array(
  7833. 'enabled'=>isModEnabled('facture'),
  7834. 'perms'=>1,
  7835. 'label'=>'LinkToTemplateInvoice',
  7836. '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').')'),
  7837. 'contrat'=>array(
  7838. 'enabled'=>(!empty($conf->contrat->enabled) ? $conf->contrat->enabled : 0),
  7839. 'perms'=>1,
  7840. 'label'=>'LinkToContract',
  7841. '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
  7842. 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'
  7843. ),
  7844. 'fichinter'=>array(
  7845. 'enabled'=>(!empty($conf->ficheinter->enabled) ? $conf->ficheinter->enabled : 0),
  7846. 'perms'=>1,
  7847. 'label'=>'LinkToIntervention',
  7848. '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').')'),
  7849. 'supplier_proposal'=>array(
  7850. 'enabled'=>(!empty($conf->supplier_proposal->enabled) ? $conf->supplier_proposal->enabled : 0),
  7851. 'perms'=>1,
  7852. 'label'=>'LinkToSupplierProposal',
  7853. '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').')'),
  7854. 'order_supplier'=>array(
  7855. 'enabled'=>(!empty($conf->supplier_order->enabled) ? $conf->supplier_order->enabled : 0),
  7856. 'perms'=>1,
  7857. 'label'=>'LinkToSupplierOrder',
  7858. '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').')'),
  7859. 'invoice_supplier'=>array(
  7860. 'enabled'=>(!empty($conf->supplier_invoice->enabled) ? $conf->supplier_invoice->enabled : 0),
  7861. 'perms'=>1, 'label'=>'LinkToSupplierInvoice',
  7862. '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').')'),
  7863. 'ticket'=>array(
  7864. 'enabled'=>(!empty($conf->ticket->enabled) ? $conf->ticket->enabled : 0),
  7865. 'perms'=>1,
  7866. 'label'=>'LinkToTicket',
  7867. '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').')'),
  7868. 'mo'=>array(
  7869. 'enabled'=>(!empty($conf->mrp->enabled) ? $conf->mrp->enabled : 0),
  7870. 'perms'=>1,
  7871. 'label'=>'LinkToMo',
  7872. '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').')')
  7873. );
  7874. }
  7875. if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to
  7876. // Can complete the possiblelink array
  7877. $hookmanager->initHooks(array('commonobject'));
  7878. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan, 'possiblelinks' => $possiblelinks);
  7879. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  7880. }
  7881. if (empty($reshook)) {
  7882. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7883. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  7884. }
  7885. } elseif ($reshook > 0) {
  7886. if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) {
  7887. $possiblelinks = $hookmanager->resArray;
  7888. }
  7889. }
  7890. foreach ($possiblelinks as $key => $possiblelink) {
  7891. $num = 0;
  7892. if (empty($possiblelink['enabled'])) {
  7893. continue;
  7894. }
  7895. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) {
  7896. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  7897. if (!empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7898. print '<br><form action="' . $_SERVER["PHP_SELF"] . '" method="POST" name="formlinkedbyref' . $key . '">';
  7899. print '<input type="hidden" name="id" value="' . $object->id . '">';
  7900. print '<input type="hidden" name="action" value="addlinkbyref">';
  7901. print '<input type="hidden" name="token" value="'.newToken().'">';
  7902. print '<input type="hidden" name="addlink" value="' . $key . '">';
  7903. print '<table class="noborder">';
  7904. print '<tr>';
  7905. print '<td>' . $langs->trans("Ref") . '</td>';
  7906. print '<td><input type="text" name="reftolinkto" value="' . dol_escape_htmltag(GETPOST('reftolinkto', 'alpha')) . '">&nbsp;<input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></td>';
  7907. print '</tr>';
  7908. print '</table>';
  7909. print '</form>';
  7910. }
  7911. $sql = $possiblelink['sql'];
  7912. $resqllist = $this->db->query($sql);
  7913. if ($resqllist) {
  7914. $num = $this->db->num_rows($resqllist);
  7915. $i = 0;
  7916. print '<br>';
  7917. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  7918. print '<input type="hidden" name="action" value="addlink">';
  7919. print '<input type="hidden" name="token" value="'.newToken().'">';
  7920. print '<input type="hidden" name="id" value="'.$object->id.'">';
  7921. print '<input type="hidden" name="addlink" value="'.$key.'">';
  7922. print '<table class="noborder">';
  7923. print '<tr class="liste_titre">';
  7924. print '<td class="nowrap"></td>';
  7925. print '<td class="center">'.$langs->trans("Ref").'</td>';
  7926. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  7927. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  7928. print '<td class="left">'.$langs->trans("Company").'</td>';
  7929. print '</tr>';
  7930. while ($i < $num) {
  7931. $objp = $this->db->fetch_object($resqllist);
  7932. print '<tr class="oddeven">';
  7933. print '<td class="left">';
  7934. print '<input type="radio" name="idtolinkto" id="'.$key.'_'.$objp->rowid.'" value="'.$objp->rowid.'">';
  7935. print '</td>';
  7936. print '<td class="center"><label for="'.$key.'_'.$objp->rowid.'">'.$objp->ref.'</label></td>';
  7937. print '<td>'.(!empty($objp->ref_client) ? $objp->ref_client : (!empty($objp->ref_supplier) ? $objp->ref_supplier : '')).'</td>';
  7938. print '<td class="right">';
  7939. if ($possiblelink['label'] == 'LinkToContract') {
  7940. $form = new Form($this->db);
  7941. print $form->textwithpicto('', $langs->trans("InformationOnLinkToContract")).' ';
  7942. }
  7943. print '<span class="amount">'.price($objp->total_ht).'</span>';
  7944. print '</td>';
  7945. print '<td>'.$objp->name.'</td>';
  7946. print '</tr>';
  7947. $i++;
  7948. }
  7949. print '</table>';
  7950. print '<div class="center">';
  7951. print '<input type="submit" class="button valignmiddle marginleftonly marginrightonly" value="'.$langs->trans('ToLink').'">';
  7952. if (empty($conf->use_javascript_ajax)) {
  7953. print '<input type="submit" class="button button-cancel marginleftonly marginrightonly" name="cancel" value="'.$langs->trans("Cancel").'"></div>';
  7954. } else {
  7955. 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>';
  7956. }
  7957. print '</form>';
  7958. $this->db->free($resqllist);
  7959. } else {
  7960. dol_print_error($this->db);
  7961. }
  7962. print '</div>';
  7963. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  7964. if ($num > 0 || !empty($conf->global->MAIN_LINK_BY_REF_IN_LINKTO)) {
  7965. $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  7966. // } else $linktoelem.=$langs->trans($possiblelink['label']);
  7967. } else {
  7968. $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  7969. }
  7970. }
  7971. }
  7972. if ($linktoelemlist) {
  7973. $linktoelem = '
  7974. <dl class="dropdown" id="linktoobjectname">
  7975. ';
  7976. if (!empty($conf->use_javascript_ajax)) {
  7977. $linktoelem .= '<dt><a href="#linktoobjectname"><span class="fas fa-link paddingrightonly"></span>'.$langs->trans("LinkTo").'...</a></dt>';
  7978. }
  7979. $linktoelem .= '<dd>
  7980. <div class="multiselectlinkto">
  7981. <ul class="ulselectedfields">'.$linktoelemlist.'
  7982. </ul>
  7983. </div>
  7984. </dd>
  7985. </dl>';
  7986. } else {
  7987. $linktoelem = '';
  7988. }
  7989. if (!empty($conf->use_javascript_ajax)) {
  7990. print '<!-- Add js to show linkto box -->
  7991. <script>
  7992. jQuery(document).ready(function() {
  7993. jQuery(".linkto").click(function() {
  7994. console.log("We choose to show/hide links for rel="+jQuery(this).attr(\'rel\')+" so #"+jQuery(this).attr(\'rel\')+"list");
  7995. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  7996. });
  7997. });
  7998. </script>
  7999. ';
  8000. }
  8001. return $linktoelem;
  8002. }
  8003. /**
  8004. * Return an html string with a select combo box to choose yes or no
  8005. *
  8006. * @param string $htmlname Name of html select field
  8007. * @param string $value Pre-selected value
  8008. * @param int $option 0 return yes/no, 1 return 1/0
  8009. * @param bool $disabled true or false
  8010. * @param int $useempty 1=Add empty line
  8011. * @param int $addjscombo 1=Add js beautifier on combo box
  8012. * @param string $morecss More CSS
  8013. * @param string $labelyes Label for Yes
  8014. * @param string $labelno Label for No
  8015. * @return string See option
  8016. */
  8017. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0, $addjscombo = 0, $morecss = '', $labelyes = 'Yes', $labelno = 'No')
  8018. {
  8019. global $langs;
  8020. $yes = "yes";
  8021. $no = "no";
  8022. if ($option) {
  8023. $yes = "1";
  8024. $no = "0";
  8025. }
  8026. $disabled = ($disabled ? ' disabled' : '');
  8027. $resultyesno = '<select class="flat width75'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  8028. if ($useempty) {
  8029. $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8030. }
  8031. if (("$value" == 'yes') || ($value == 1)) {
  8032. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans($labelyes).'</option>'."\n";
  8033. $resultyesno .= '<option value="'.$no.'">'.$langs->trans($labelno).'</option>'."\n";
  8034. } else {
  8035. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  8036. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans($labelyes).'</option>'."\n";
  8037. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans($labelno).'</option>'."\n";
  8038. }
  8039. $resultyesno .= '</select>'."\n";
  8040. if ($addjscombo) {
  8041. $resultyesno .= ajax_combobox($htmlname);
  8042. }
  8043. return $resultyesno;
  8044. }
  8045. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8046. /**
  8047. * Return list of export templates
  8048. *
  8049. * @param string $selected Id modele pre-selectionne
  8050. * @param string $htmlname Name of HTML select
  8051. * @param string $type Type of searched templates
  8052. * @param int $useempty Affiche valeur vide dans liste
  8053. * @return void
  8054. */
  8055. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  8056. {
  8057. // phpcs:enable
  8058. $sql = "SELECT rowid, label";
  8059. $sql .= " FROM ".$this->db->prefix()."export_model";
  8060. $sql .= " WHERE type = '".$this->db->escape($type)."'";
  8061. $sql .= " ORDER BY rowid";
  8062. $result = $this->db->query($sql);
  8063. if ($result) {
  8064. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  8065. if ($useempty) {
  8066. print '<option value="-1">&nbsp;</option>';
  8067. }
  8068. $num = $this->db->num_rows($result);
  8069. $i = 0;
  8070. while ($i < $num) {
  8071. $obj = $this->db->fetch_object($result);
  8072. if ($selected == $obj->rowid) {
  8073. print '<option value="'.$obj->rowid.'" selected>';
  8074. } else {
  8075. print '<option value="'.$obj->rowid.'">';
  8076. }
  8077. print $obj->label;
  8078. print '</option>';
  8079. $i++;
  8080. }
  8081. print "</select>";
  8082. } else {
  8083. dol_print_error($this->db);
  8084. }
  8085. }
  8086. /**
  8087. * Return a HTML area with the reference of object and a navigation bar for a business object
  8088. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  8089. *
  8090. * @param object $object Object to show.
  8091. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  8092. * @param string $morehtml More html content to output just before the nav bar.
  8093. * @param int $shownav Show Condition (navigation is shown if value is 1).
  8094. * @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.
  8095. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  8096. * @param string $morehtmlref More html to show after ref.
  8097. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  8098. * @param int $nodbprefix Do not include DB prefix to forge table name.
  8099. * @param string $morehtmlleft More html code to show before ref.
  8100. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  8101. * @param string $morehtmlright More html code to show after ref.
  8102. * @return string Portion HTML with ref + navigation buttons
  8103. */
  8104. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  8105. {
  8106. global $conf, $langs, $hookmanager, $extralanguages;
  8107. $ret = '';
  8108. if (empty($fieldid)) {
  8109. $fieldid = 'rowid';
  8110. }
  8111. if (empty($fieldref)) {
  8112. $fieldref = 'ref';
  8113. }
  8114. // Preparing gender's display if there is one
  8115. $addgendertxt = '';
  8116. if (property_exists($object, 'gender') && !empty($object->gender)) {
  8117. $addgendertxt = ' ';
  8118. switch ($object->gender) {
  8119. case 'man':
  8120. $addgendertxt .= '<i class="fas fa-mars"></i>';
  8121. break;
  8122. case 'woman':
  8123. $addgendertxt .= '<i class="fas fa-venus"></i>';
  8124. break;
  8125. case 'other':
  8126. $addgendertxt .= '<i class="fas fa-transgender"></i>';
  8127. break;
  8128. }
  8129. }
  8130. /*
  8131. $addadmin = '';
  8132. if (property_exists($object, 'admin')) {
  8133. if (!empty($conf->multicompany->enabled) && !empty($object->admin) && empty($object->entity)) {
  8134. $addadmin .= img_picto($langs->trans("SuperAdministratorDesc"), "redstar", 'class="paddingleft"');
  8135. } elseif (!empty($object->admin)) {
  8136. $addadmin .= img_picto($langs->trans("AdministratorDesc"), "star", 'class="paddingleft"');
  8137. }
  8138. }*/
  8139. // Add where from hooks
  8140. if (is_object($hookmanager)) {
  8141. $parameters = array('showrefnav' => true);
  8142. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  8143. $object->next_prev_filter .= $hookmanager->resPrint;
  8144. }
  8145. $previous_ref = $next_ref = '';
  8146. if ($shownav) {
  8147. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  8148. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  8149. $navurl = $_SERVER["PHP_SELF"];
  8150. // Special case for project/task page
  8151. if ($paramid == 'project_ref') {
  8152. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) { // TODO Remove this when nav with project_ref on task pages are ok
  8153. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  8154. $paramid = 'ref';
  8155. }
  8156. }
  8157. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  8158. // accesskey is for Mac: CTRL + key for all browsers
  8159. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  8160. if ($conf->browser->name == 'chrome') {
  8161. $stringforfirstkey .= ' ALT +';
  8162. } elseif ($conf->browser->name == 'firefox') {
  8163. $stringforfirstkey .= ' ALT + SHIFT +';
  8164. } else {
  8165. $stringforfirstkey .= ' CTL +';
  8166. }
  8167. $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>';
  8168. $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>';
  8169. }
  8170. //print "xx".$previous_ref."x".$next_ref;
  8171. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  8172. // Right part of banner
  8173. if ($morehtmlright) {
  8174. $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  8175. }
  8176. if ($previous_ref || $next_ref || $morehtml) {
  8177. $ret .= '<div class="pagination paginationref"><ul class="right">';
  8178. }
  8179. if ($morehtml) {
  8180. $ret .= '<li class="noborder litext'.(($shownav && $previous_ref && $next_ref) ? ' clearbothonsmartphone' : '').'">'.$morehtml.'</li>';
  8181. }
  8182. if ($shownav && ($previous_ref || $next_ref)) {
  8183. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  8184. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  8185. }
  8186. if ($previous_ref || $next_ref || $morehtml) {
  8187. $ret .= '</ul></div>';
  8188. }
  8189. $parameters = array();
  8190. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  8191. if (empty($reshook)) {
  8192. $morehtmlstatus .= $hookmanager->resPrint;
  8193. } else {
  8194. $morehtmlstatus = $hookmanager->resPrint;
  8195. }
  8196. if ($morehtmlstatus) {
  8197. $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  8198. }
  8199. $parameters = array();
  8200. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  8201. if (empty($reshook)) {
  8202. $morehtmlref .= $hookmanager->resPrint;
  8203. } elseif ($reshook > 0) {
  8204. $morehtmlref = $hookmanager->resPrint;
  8205. }
  8206. // Left part of banner
  8207. if ($morehtmlleft) {
  8208. if ($conf->browser->layout == 'phone') {
  8209. $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  8210. } else {
  8211. $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  8212. }
  8213. }
  8214. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  8215. $ret .= '<div class="inline-block floatleft valignmiddle maxwidth750 marginbottomonly refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  8216. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  8217. if ($object->element == 'societe') {
  8218. $ret .= dol_htmlentities($object->name);
  8219. // List of extra languages
  8220. $arrayoflangcode = array();
  8221. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) {
  8222. $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  8223. }
  8224. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  8225. if (!is_object($extralanguages)) {
  8226. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  8227. $extralanguages = new ExtraLanguages($this->db);
  8228. }
  8229. $extralanguages->fetch_name_extralanguages('societe');
  8230. if (!empty($extralanguages->attributes['societe']['name'])) {
  8231. $object->fetchValuesForExtraLanguages();
  8232. $htmltext = '';
  8233. // If there is extra languages
  8234. foreach ($arrayoflangcode as $extralangcode) {
  8235. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  8236. if ($object->array_languages['name'][$extralangcode]) {
  8237. $htmltext .= $object->array_languages['name'][$extralangcode];
  8238. } else {
  8239. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  8240. }
  8241. }
  8242. $ret .= '<!-- Show translations of name -->'."\n";
  8243. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  8244. }
  8245. }
  8246. } elseif ($object->element == 'member') {
  8247. $ret .= $object->ref.'<br>';
  8248. $fullname = $object->getFullName($langs);
  8249. if ($object->morphy == 'mor' && $object->societe) {
  8250. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).$addgendertxt.')' : '');
  8251. } else {
  8252. $ret .= dol_htmlentities($fullname).$addgendertxt.((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  8253. }
  8254. } elseif (in_array($object->element, array('contact', 'user', 'usergroup'))) {
  8255. $ret .= dol_htmlentities($object->getFullName($langs)).$addgendertxt;
  8256. } elseif (in_array($object->element, array('action', 'agenda'))) {
  8257. $ret .= $object->ref.'<br>'.$object->label;
  8258. } elseif (in_array($object->element, array('adherent_type'))) {
  8259. $ret .= $object->label;
  8260. } elseif ($object->element == 'ecm_directories') {
  8261. $ret .= '';
  8262. } elseif ($fieldref != 'none') {
  8263. $ret .= dol_htmlentities($object->$fieldref);
  8264. }
  8265. if ($morehtmlref) {
  8266. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  8267. if (substr($morehtmlref, 0, 4) != '<div') {
  8268. $ret .= ' ';
  8269. }
  8270. $ret .= $morehtmlref;
  8271. }
  8272. $ret .= '</div>';
  8273. $ret .= '</div><!-- End banner content -->';
  8274. return $ret;
  8275. }
  8276. /**
  8277. * Return HTML code to output a barcode
  8278. *
  8279. * @param Object $object Object containing data to retrieve file name
  8280. * @param int $width Width of photo
  8281. * @param string $morecss More CSS on img of barcode
  8282. * @return string HTML code to output barcode
  8283. */
  8284. public function showbarcode(&$object, $width = 100, $morecss = '')
  8285. {
  8286. global $conf;
  8287. //Check if barcode is filled in the card
  8288. if (empty($object->barcode)) {
  8289. return '';
  8290. }
  8291. // Complete object if not complete
  8292. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder)) {
  8293. $result = $object->fetch_barcode();
  8294. //Check if fetch_barcode() failed
  8295. if ($result < 1) {
  8296. return '<!-- ErrorFetchBarcode -->';
  8297. }
  8298. }
  8299. // Barcode image
  8300. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  8301. $out = '<!-- url barcode = '.$url.' -->';
  8302. $out .= '<img src="'.$url.'"'.($morecss ? ' class="'.$morecss.'"' : '').'>';
  8303. return $out;
  8304. }
  8305. /**
  8306. * Return HTML code to output a photo
  8307. *
  8308. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  8309. * @param object $object Object containing data to retrieve file name
  8310. * @param int $width Width of photo
  8311. * @param int $height Height of photo (auto if 0)
  8312. * @param int $caneditfield Add edit fields
  8313. * @param string $cssclass CSS name to use on img for photo
  8314. * @param string $imagesize 'mini', 'small' or '' (original)
  8315. * @param int $addlinktofullsize Add link to fullsize image
  8316. * @param int $cache 1=Accept to use image in cache
  8317. * @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 ''.
  8318. * @param int $noexternsourceoverwrite No overwrite image with extern source (like 'gravatar' or other module)
  8319. * @return string HTML code to output photo
  8320. */
  8321. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '', $noexternsourceoverwrite = 0)
  8322. {
  8323. global $conf, $langs;
  8324. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  8325. $id = (!empty($object->id) ? $object->id : $object->rowid);
  8326. $ret = '';
  8327. $dir = '';
  8328. $file = '';
  8329. $originalfile = '';
  8330. $altfile = '';
  8331. $email = '';
  8332. $capture = '';
  8333. if ($modulepart == 'societe') {
  8334. $dir = $conf->societe->multidir_output[$entity];
  8335. if (!empty($object->logo)) {
  8336. if (dolIsAllowedForPreview($object->logo)) {
  8337. if ((string) $imagesize == 'mini') {
  8338. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  8339. } elseif ((string) $imagesize == 'small') {
  8340. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.getImageFileNameForSize($object->logo, '_small');
  8341. } else {
  8342. $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8343. }
  8344. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'logos/'.$object->logo;
  8345. }
  8346. }
  8347. $email = $object->email;
  8348. } elseif ($modulepart == 'contact') {
  8349. $dir = $conf->societe->multidir_output[$entity].'/contact';
  8350. if (!empty($object->photo)) {
  8351. if (dolIsAllowedForPreview($object->photo)) {
  8352. if ((string) $imagesize == 'mini') {
  8353. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8354. } elseif ((string) $imagesize == 'small') {
  8355. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8356. } else {
  8357. $file = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8358. }
  8359. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'photos/'.$object->photo;
  8360. }
  8361. }
  8362. $email = $object->email;
  8363. $capture = 'user';
  8364. } elseif ($modulepart == 'userphoto') {
  8365. $dir = $conf->user->dir_output;
  8366. if (!empty($object->photo)) {
  8367. if (dolIsAllowedForPreview($object->photo)) {
  8368. if ((string) $imagesize == 'mini') {
  8369. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8370. } elseif ((string) $imagesize == 'small') {
  8371. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8372. } else {
  8373. $file = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8374. }
  8375. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'photos/'.$object->photo;
  8376. }
  8377. }
  8378. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8379. $altfile = $object->id.".jpg"; // For backward compatibility
  8380. }
  8381. $email = $object->email;
  8382. $capture = 'user';
  8383. } elseif ($modulepart == 'memberphoto') {
  8384. $dir = $conf->adherent->dir_output;
  8385. if (!empty($object->photo)) {
  8386. if (dolIsAllowedForPreview($object->photo)) {
  8387. if ((string) $imagesize == 'mini') {
  8388. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8389. } elseif ((string) $imagesize == 'small') {
  8390. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  8391. } else {
  8392. $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8393. }
  8394. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  8395. }
  8396. }
  8397. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8398. $altfile = $object->id.".jpg"; // For backward compatibility
  8399. }
  8400. $email = $object->email;
  8401. $capture = 'user';
  8402. } else {
  8403. // Generic case to show photos
  8404. $dir = $conf->$modulepart->dir_output;
  8405. if (!empty($object->photo)) {
  8406. if (dolIsAllowedForPreview($object->photo)) {
  8407. if ((string) $imagesize == 'mini') {
  8408. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  8409. } elseif ((string) $imagesize == 'small') {
  8410. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  8411. } else {
  8412. $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8413. }
  8414. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  8415. }
  8416. }
  8417. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
  8418. $altfile = $object->id.".jpg"; // For backward compatibility
  8419. }
  8420. $email = $object->email;
  8421. }
  8422. if ($forcecapture) {
  8423. $capture = $forcecapture;
  8424. }
  8425. if ($dir) {
  8426. if ($file && file_exists($dir."/".$file)) {
  8427. if ($addlinktofullsize) {
  8428. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8429. if ($urladvanced) {
  8430. $ret .= '<a href="'.$urladvanced.'">';
  8431. } else {
  8432. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8433. }
  8434. }
  8435. $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.'">';
  8436. if ($addlinktofullsize) {
  8437. $ret .= '</a>';
  8438. }
  8439. } elseif ($altfile && file_exists($dir."/".$altfile)) {
  8440. if ($addlinktofullsize) {
  8441. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  8442. if ($urladvanced) {
  8443. $ret .= '<a href="'.$urladvanced.'">';
  8444. } else {
  8445. $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  8446. }
  8447. }
  8448. $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.'">';
  8449. if ($addlinktofullsize) {
  8450. $ret .= '</a>';
  8451. }
  8452. } else {
  8453. $nophoto = '/public/theme/common/nophoto.png';
  8454. $defaultimg = 'identicon'; // For gravatar
  8455. if (in_array($modulepart, array('societe', 'userphoto', 'contact', 'memberphoto'))) { // For modules that need a special image when photo not found
  8456. if ($modulepart == 'societe' || ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor')) !== false) {
  8457. $nophoto = 'company';
  8458. } else {
  8459. $nophoto = '/public/theme/common/user_anonymous.png';
  8460. if (!empty($object->gender) && $object->gender == 'man') {
  8461. $nophoto = '/public/theme/common/user_man.png';
  8462. }
  8463. if (!empty($object->gender) && $object->gender == 'woman') {
  8464. $nophoto = '/public/theme/common/user_woman.png';
  8465. }
  8466. }
  8467. }
  8468. if (!empty($conf->gravatar->enabled) && $email && empty($noexternsourceoverwrite)) {
  8469. // see https://gravatar.com/site/implement/images/php/
  8470. $ret .= '<!-- Put link to gravatar -->';
  8471. $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
  8472. } else {
  8473. if ($nophoto == 'company') {
  8474. $ret .= '<div class="divforspanimg photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').'>'.img_picto('', 'company').'</div>';
  8475. $ret .= '<div class="difforspanimgright"></div>';
  8476. } else {
  8477. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  8478. }
  8479. }
  8480. }
  8481. if ($caneditfield) {
  8482. if ($object->photo) {
  8483. $ret .= "<br>\n";
  8484. }
  8485. $ret .= '<table class="nobordernopadding centpercent">';
  8486. if ($object->photo) {
  8487. $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> <label for="photodelete">'.$langs->trans("Delete").'</label><br><br></td></tr>';
  8488. }
  8489. $ret .= '<tr><td class="tdoverflow">';
  8490. $maxfilesizearray = getMaxFileSizeArray();
  8491. $maxmin = $maxfilesizearray['maxmin'];
  8492. if ($maxmin > 0) {
  8493. $ret .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
  8494. }
  8495. $ret .= '<input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'>';
  8496. $ret .= '</td></tr>';
  8497. $ret .= '</table>';
  8498. }
  8499. } else {
  8500. dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  8501. }
  8502. return $ret;
  8503. }
  8504. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  8505. /**
  8506. * Return select list of groups
  8507. *
  8508. * @param string $selected Id group preselected
  8509. * @param string $htmlname Field name in form
  8510. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  8511. * @param string|array $exclude Array list of groups id to exclude
  8512. * @param int $disabled If select list must be disabled
  8513. * @param string|array $include Array list of groups id to include
  8514. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  8515. * @param string $force_entity '0' or Ids of environment to force
  8516. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  8517. * @param string $morecss More css to add to html component
  8518. * @return string
  8519. * @see select_dolusers()
  8520. */
  8521. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  8522. {
  8523. // phpcs:enable
  8524. global $conf, $user, $langs;
  8525. // Permettre l'exclusion de groupes
  8526. $excludeGroups = null;
  8527. if (is_array($exclude)) {
  8528. $excludeGroups = implode(",", $exclude);
  8529. }
  8530. // Permettre l'inclusion de groupes
  8531. $includeGroups = null;
  8532. if (is_array($include)) {
  8533. $includeGroups = implode(",", $include);
  8534. }
  8535. if (!is_array($selected)) {
  8536. $selected = array($selected);
  8537. }
  8538. $out = '';
  8539. // On recherche les groupes
  8540. $sql = "SELECT ug.rowid, ug.nom as name";
  8541. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8542. $sql .= ", e.label";
  8543. }
  8544. $sql .= " FROM ".$this->db->prefix()."usergroup as ug ";
  8545. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity) {
  8546. $sql .= " LEFT JOIN ".$this->db->prefix()."entity as e ON e.rowid=ug.entity";
  8547. if ($force_entity) {
  8548. $sql .= " WHERE ug.entity IN (0, ".$force_entity.")";
  8549. } else {
  8550. $sql .= " WHERE ug.entity IS NOT NULL";
  8551. }
  8552. } else {
  8553. $sql .= " WHERE ug.entity IN (0, ".$conf->entity.")";
  8554. }
  8555. if (is_array($exclude) && $excludeGroups) {
  8556. $sql .= " AND ug.rowid NOT IN (".$this->db->sanitize($excludeGroups).")";
  8557. }
  8558. if (is_array($include) && $includeGroups) {
  8559. $sql .= " AND ug.rowid IN (".$this->db->sanitize($includeGroups).")";
  8560. }
  8561. $sql .= " ORDER BY ug.nom ASC";
  8562. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  8563. $resql = $this->db->query($sql);
  8564. if ($resql) {
  8565. // Enhance with select2
  8566. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8567. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  8568. $num = $this->db->num_rows($resql);
  8569. $i = 0;
  8570. if ($num) {
  8571. if ($show_empty && !$multiple) {
  8572. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  8573. }
  8574. while ($i < $num) {
  8575. $obj = $this->db->fetch_object($resql);
  8576. $disableline = 0;
  8577. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) {
  8578. $disableline = 1;
  8579. }
  8580. $out .= '<option value="'.$obj->rowid.'"';
  8581. if ($disableline) {
  8582. $out .= ' disabled';
  8583. }
  8584. 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))) {
  8585. $out .= ' selected';
  8586. }
  8587. $out .= '>';
  8588. $out .= $obj->name;
  8589. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1) {
  8590. $out .= " (".$obj->label.")";
  8591. }
  8592. $out .= '</option>';
  8593. $i++;
  8594. }
  8595. } else {
  8596. if ($show_empty) {
  8597. $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  8598. }
  8599. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  8600. }
  8601. $out .= '</select>';
  8602. $out .= ajax_combobox($htmlname);
  8603. } else {
  8604. dol_print_error($this->db);
  8605. }
  8606. return $out;
  8607. }
  8608. /**
  8609. * Return HTML to show the search and clear seach button
  8610. *
  8611. * @param string $pos position colon on liste value left or right
  8612. * @return string
  8613. */
  8614. public function showFilterButtons($pos = '')
  8615. {
  8616. $out = '<div class="nowraponall">';
  8617. if ($pos == 'left') {
  8618. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8619. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8620. } else {
  8621. $out .= '<button type="submit" class="liste_titre button_search reposition" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  8622. $out .= '<button type="submit" class="liste_titre button_removefilter reposition" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  8623. }
  8624. $out .= '</div>';
  8625. return $out;
  8626. }
  8627. /**
  8628. * Return HTML to show the search and clear search button
  8629. *
  8630. * @param string $cssclass CSS class
  8631. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8632. * @param string $massactionname Mass action button name that will launch an action on the selected items
  8633. * @return string
  8634. */
  8635. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8636. {
  8637. global $conf, $langs;
  8638. $out = '';
  8639. if (!empty($conf->use_javascript_ajax)) {
  8640. $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="'.$cssclass.'s" name="'.$cssclass.'s" class="checkallactions"></div>';
  8641. }
  8642. $out .= '<script>
  8643. $(document).ready(function() {
  8644. $("#' . $cssclass.'s").click(function() {
  8645. if($(this).is(\':checked\')){
  8646. console.log("We check all '.$cssclass.' and trigger the change method");
  8647. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  8648. }
  8649. else
  8650. {
  8651. console.log("We uncheck all");
  8652. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  8653. }'."\n";
  8654. if ($calljsfunction) {
  8655. $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "'.$massactionname.'", "'.$cssclass.'"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  8656. }
  8657. $out .= ' });
  8658. $(".' . $cssclass.'").change(function() {
  8659. $(this).closest("tr").toggleClass("highlight", this.checked);
  8660. });
  8661. });
  8662. </script>';
  8663. return $out;
  8664. }
  8665. /**
  8666. * Return HTML to show the search and clear seach button
  8667. *
  8668. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  8669. * @param string $cssclass CSS class
  8670. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  8671. * @param string $massactionname Mass action name
  8672. * @return string
  8673. */
  8674. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  8675. {
  8676. $out = $this->showFilterButtons();
  8677. if ($addcheckuncheckall) {
  8678. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  8679. }
  8680. return $out;
  8681. }
  8682. /**
  8683. * Return HTML to show the select of expense categories
  8684. *
  8685. * @param string $selected preselected category
  8686. * @param string $htmlname name of HTML select list
  8687. * @param integer $useempty 1=Add empty line
  8688. * @param array $excludeid id to exclude
  8689. * @param string $target htmlname of target select to bind event
  8690. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  8691. * @param array $params param to give
  8692. * @param int $info_admin Show the tooltip help picto to setup list
  8693. * @return string
  8694. */
  8695. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array(), $info_admin = 1)
  8696. {
  8697. global $langs, $user;
  8698. $out = '';
  8699. $sql = "SELECT rowid, label FROM ".$this->db->prefix()."c_exp_tax_cat WHERE active = 1";
  8700. $sql .= " AND entity IN (0,".getEntity('exp_tax_cat').")";
  8701. if (!empty($excludeid)) {
  8702. $sql .= " AND rowid NOT IN (".$this->db->sanitize(implode(',', $excludeid)).")";
  8703. }
  8704. $sql .= " ORDER BY label";
  8705. $resql = $this->db->query($sql);
  8706. if ($resql) {
  8707. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp maxwidth200">';
  8708. if ($useempty) {
  8709. $out .= '<option value="0">&nbsp;</option>';
  8710. }
  8711. while ($obj = $this->db->fetch_object($resql)) {
  8712. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  8713. }
  8714. $out .= '</select>';
  8715. $out .= ajax_combobox('select_'.$htmlname);
  8716. if (!empty($htmlname) && $user->admin && $info_admin) {
  8717. $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  8718. }
  8719. if (!empty($target)) {
  8720. $sql = "SELECT c.id FROM ".$this->db->prefix()."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  8721. $resql = $this->db->query($sql);
  8722. if ($resql) {
  8723. if ($this->db->num_rows($resql) > 0) {
  8724. $obj = $this->db->fetch_object($resql);
  8725. $out .= '<script>
  8726. $(function() {
  8727. $("select[name='.$target.']").on("change", function() {
  8728. var current_val = $(this).val();
  8729. if (current_val == '.$obj->id.') {';
  8730. if (!empty($default_selected) || !empty($selected)) {
  8731. $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  8732. }
  8733. $out .= '
  8734. $("select[name='.$htmlname.']").change();
  8735. }
  8736. });
  8737. $("select[name='.$htmlname.']").change(function() {
  8738. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  8739. // get price of kilometer to fill the unit price
  8740. $.ajax({
  8741. method: "POST",
  8742. dataType: "json",
  8743. data: { fk_c_exp_tax_cat: $(this).val(), token: \''.currentToken().'\' },
  8744. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php?'.$params).'",
  8745. }).done(function( data, textStatus, jqXHR ) {
  8746. console.log(data);
  8747. if (typeof data.up != "undefined") {
  8748. $("input[name=value_unit]").val(data.up);
  8749. $("select[name='.$htmlname.']").attr("title", data.title);
  8750. } else {
  8751. $("input[name=value_unit]").val("");
  8752. $("select[name='.$htmlname.']").attr("title", "");
  8753. }
  8754. });
  8755. }
  8756. });
  8757. });
  8758. </script>';
  8759. }
  8760. }
  8761. }
  8762. } else {
  8763. dol_print_error($this->db);
  8764. }
  8765. return $out;
  8766. }
  8767. /**
  8768. * Return HTML to show the select ranges of expense range
  8769. *
  8770. * @param string $selected preselected category
  8771. * @param string $htmlname name of HTML select list
  8772. * @param integer $useempty 1=Add empty line
  8773. * @return string
  8774. */
  8775. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  8776. {
  8777. global $conf, $langs;
  8778. $out = '';
  8779. $sql = "SELECT rowid, range_ik FROM ".$this->db->prefix()."c_exp_tax_range";
  8780. $sql .= " WHERE entity = ".$conf->entity." AND active = 1";
  8781. $resql = $this->db->query($sql);
  8782. if ($resql) {
  8783. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8784. if ($useempty) {
  8785. $out .= '<option value="0"></option>';
  8786. }
  8787. while ($obj = $this->db->fetch_object($resql)) {
  8788. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  8789. }
  8790. $out .= '</select>';
  8791. } else {
  8792. dol_print_error($this->db);
  8793. }
  8794. return $out;
  8795. }
  8796. /**
  8797. * Return HTML to show a select of expense
  8798. *
  8799. * @param string $selected preselected category
  8800. * @param string $htmlname name of HTML select list
  8801. * @param integer $useempty 1=Add empty choice
  8802. * @param integer $allchoice 1=Add all choice
  8803. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  8804. * @return string
  8805. */
  8806. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  8807. {
  8808. global $langs;
  8809. $out = '';
  8810. $sql = "SELECT id, code, label FROM ".$this->db->prefix()."c_type_fees";
  8811. $sql .= " WHERE active = 1";
  8812. $resql = $this->db->query($sql);
  8813. if ($resql) {
  8814. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  8815. if ($useempty) {
  8816. $out .= '<option value="0"></option>';
  8817. }
  8818. if ($allchoice) {
  8819. $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  8820. }
  8821. $field = 'code';
  8822. if ($useid) {
  8823. $field = 'id';
  8824. }
  8825. while ($obj = $this->db->fetch_object($resql)) {
  8826. $key = $langs->trans($obj->code);
  8827. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  8828. }
  8829. $out .= '</select>';
  8830. } else {
  8831. dol_print_error($this->db);
  8832. }
  8833. return $out;
  8834. }
  8835. /**
  8836. * Output a combo list with invoices qualified for a third party
  8837. *
  8838. * @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)
  8839. * @param int $selected Id invoice preselected
  8840. * @param string $htmlname Name of HTML select
  8841. * @param int $maxlength Maximum length of label
  8842. * @param int $option_only Return only html options lines without the select tag
  8843. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8844. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  8845. * @param int $forcefocus Force focus on field (works with javascript only)
  8846. * @param int $disabled Disabled
  8847. * @param string $morecss More css added to the select component
  8848. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  8849. * @param string $showproject 'all' = Show project info, ''=Hide project info
  8850. * @param User $usertofilter User object to use for filtering
  8851. * @return int Nbr of project if OK, <0 if KO
  8852. */
  8853. 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)
  8854. {
  8855. global $user, $conf, $langs;
  8856. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  8857. if (is_null($usertofilter)) {
  8858. $usertofilter = $user;
  8859. }
  8860. $out = '';
  8861. $hideunselectables = false;
  8862. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
  8863. $hideunselectables = true;
  8864. }
  8865. if (empty($projectsListId)) {
  8866. if (empty($usertofilter->rights->projet->all->lire)) {
  8867. $projectstatic = new Project($this->db);
  8868. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  8869. }
  8870. }
  8871. // Search all projects
  8872. $sql = "SELECT f.rowid, f.ref as fref, 'nolabel' as flabel, p.rowid as pid, f.ref,
  8873. p.title, p.fk_soc, p.fk_statut, p.public,";
  8874. $sql .= ' s.nom as name';
  8875. $sql .= ' FROM '.$this->db->prefix().'projet as p';
  8876. $sql .= ' LEFT JOIN '.$this->db->prefix().'societe as s ON s.rowid = p.fk_soc,';
  8877. $sql .= ' '.$this->db->prefix().'facture as f';
  8878. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  8879. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  8880. //if ($projectsListId) $sql.= " AND p.rowid IN (".$this->db->sanitize($projectsListId).")";
  8881. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  8882. //if ($socid > 0) $sql.= " AND (p.fk_soc=".((int) $socid)." OR p.fk_soc IS NULL)";
  8883. $sql .= " ORDER BY p.ref, f.ref ASC";
  8884. $resql = $this->db->query($sql);
  8885. if ($resql) {
  8886. // Use select2 selector
  8887. if (!empty($conf->use_javascript_ajax)) {
  8888. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  8889. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  8890. $out .= $comboenhancement;
  8891. $morecss = 'minwidth200imp maxwidth500';
  8892. }
  8893. if (empty($option_only)) {
  8894. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  8895. }
  8896. if (!empty($show_empty)) {
  8897. $out .= '<option value="0" class="optiongrey">';
  8898. if (!is_numeric($show_empty)) {
  8899. $out .= $show_empty;
  8900. } else {
  8901. $out .= '&nbsp;';
  8902. }
  8903. $out .= '</option>';
  8904. }
  8905. $num = $this->db->num_rows($resql);
  8906. $i = 0;
  8907. if ($num) {
  8908. while ($i < $num) {
  8909. $obj = $this->db->fetch_object($resql);
  8910. // 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.
  8911. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire)) {
  8912. // Do nothing
  8913. } else {
  8914. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED) {
  8915. $i++;
  8916. continue;
  8917. }
  8918. $labeltoshow = '';
  8919. if ($showproject == 'all') {
  8920. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  8921. if ($obj->name) {
  8922. $labeltoshow .= ' - '.$obj->name; // Soc name
  8923. }
  8924. $disabled = 0;
  8925. if ($obj->fk_statut == Project::STATUS_DRAFT) {
  8926. $disabled = 1;
  8927. $labeltoshow .= ' - '.$langs->trans("Draft");
  8928. } elseif ($obj->fk_statut == Project::STATUS_CLOSED) {
  8929. if ($discard_closed == 2) {
  8930. $disabled = 1;
  8931. }
  8932. $labeltoshow .= ' - '.$langs->trans("Closed");
  8933. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid)) {
  8934. $disabled = 1;
  8935. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  8936. }
  8937. }
  8938. if (!empty($selected) && $selected == $obj->rowid) {
  8939. $out .= '<option value="'.$obj->rowid.'" selected';
  8940. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  8941. $out .= '>'.$labeltoshow.'</option>';
  8942. } else {
  8943. if ($hideunselectables && $disabled && ($selected != $obj->rowid)) {
  8944. $resultat = '';
  8945. } else {
  8946. $resultat = '<option value="'.$obj->rowid.'"';
  8947. if ($disabled) {
  8948. $resultat .= ' disabled';
  8949. }
  8950. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  8951. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  8952. $resultat .= '>';
  8953. $resultat .= $labeltoshow;
  8954. $resultat .= '</option>';
  8955. }
  8956. $out .= $resultat;
  8957. }
  8958. }
  8959. $i++;
  8960. }
  8961. }
  8962. if (empty($option_only)) {
  8963. $out .= '</select>';
  8964. }
  8965. print $out;
  8966. $this->db->free($resql);
  8967. return $num;
  8968. } else {
  8969. dol_print_error($this->db);
  8970. return -1;
  8971. }
  8972. }
  8973. /**
  8974. * Output a combo list with invoices qualified for a third party
  8975. *
  8976. * @param int $selected Id invoice preselected
  8977. * @param string $htmlname Name of HTML select
  8978. * @param int $maxlength Maximum length of label
  8979. * @param int $option_only Return only html options lines without the select tag
  8980. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  8981. * @param int $forcefocus Force focus on field (works with javascript only)
  8982. * @param int $disabled Disabled
  8983. * @param string $morecss More css added to the select component
  8984. * @return int Nbr of project if OK, <0 if KO
  8985. */
  8986. public function selectInvoiceRec($selected = '', $htmlname = 'facrecid', $maxlength = 24, $option_only = 0, $show_empty = '1', $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500')
  8987. {
  8988. global $user, $conf, $langs;
  8989. $out = '';
  8990. dol_syslog('FactureRec::fetch', LOG_DEBUG);
  8991. $sql = 'SELECT f.rowid, f.entity, f.titre as title, f.suspended, f.fk_soc';
  8992. //$sql.= ', el.fk_source';
  8993. $sql .= ' FROM ' . MAIN_DB_PREFIX . 'facture_rec as f';
  8994. $sql .= " WHERE f.entity IN (" . getEntity('invoice') . ")";
  8995. $sql .= " ORDER BY f.titre ASC";
  8996. $resql = $this->db->query($sql);
  8997. if ($resql) {
  8998. // Use select2 selector
  8999. if (!empty($conf->use_javascript_ajax)) {
  9000. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  9001. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  9002. $out .= $comboenhancement;
  9003. $morecss = 'minwidth200imp maxwidth500';
  9004. }
  9005. if (empty($option_only)) {
  9006. $out .= '<select class="valignmiddle flat' . ($morecss ? ' ' . $morecss : '') . '"' . ($disabled ? ' disabled="disabled"' : '') . ' id="' . $htmlname . '" name="' . $htmlname . '">';
  9007. }
  9008. if (!empty($show_empty)) {
  9009. $out .= '<option value="0" class="optiongrey">';
  9010. if (!is_numeric($show_empty)) {
  9011. $out .= $show_empty;
  9012. } else {
  9013. $out .= '&nbsp;';
  9014. }
  9015. $out .= '</option>';
  9016. }
  9017. $num = $this->db->num_rows($resql);
  9018. if ($num) {
  9019. while ($obj = $this->db->fetch_object($resql)) {
  9020. $labeltoshow = dol_trunc($obj->title, 18); // Invoice ref
  9021. $disabled = 0;
  9022. if (!empty($obj->suspended)) {
  9023. $disabled = 1;
  9024. $labeltoshow .= ' - ' . $langs->trans("Closed");
  9025. }
  9026. if (!empty($selected) && $selected == $obj->rowid) {
  9027. $out .= '<option value="' . $obj->rowid . '" selected';
  9028. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  9029. $out .= '>' . $labeltoshow . '</option>';
  9030. } else {
  9031. if ($disabled && ($selected != $obj->rowid)) {
  9032. $resultat = '';
  9033. } else {
  9034. $resultat = '<option value="' . $obj->rowid . '"';
  9035. if ($disabled) {
  9036. $resultat .= ' disabled';
  9037. }
  9038. $resultat .= '>';
  9039. $resultat .= $labeltoshow;
  9040. $resultat .= '</option>';
  9041. }
  9042. $out .= $resultat;
  9043. }
  9044. }
  9045. }
  9046. if (empty($option_only)) {
  9047. $out .= '</select>';
  9048. }
  9049. print $out;
  9050. $this->db->free($resql);
  9051. return $num;
  9052. } else {
  9053. $this->errors[]=$this->db->lasterror;
  9054. return -1;
  9055. }
  9056. }
  9057. /**
  9058. * Output the component to make advanced search criteries
  9059. *
  9060. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  9061. * @param array $search_component_params Array of selected search criterias
  9062. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  9063. * @param string $search_component_params_hidden String with $search_component_params criterias
  9064. * @return string HTML component for advanced search
  9065. */
  9066. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array(), $search_component_params_hidden = '')
  9067. {
  9068. global $langs;
  9069. $ret = '';
  9070. $ret .= '<div class="divadvancedsearchfieldcomp inline-block">';
  9071. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  9072. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor">';
  9073. $ret .= '<span class="fas fa-filter linkobject boxfilter pictofixedwidth" title="'.dol_escape_htmltag($langs->trans("Filters")).'" id="idsubimgproductdistribution"></span>';
  9074. //$ret .= $langs->trans("Filters");
  9075. $ret .= '</a>';
  9076. $ret .= '<div class="divadvancedsearchfieldcompinput inline-block minwidth500 maxwidth300onsmartphone">';
  9077. // Show select fields as tags.
  9078. $ret .= '<div name="divsearch_component_params" class="noborderbottom search_component_params inline-block valignmiddle">';
  9079. if ($search_component_params_hidden) {
  9080. if (!preg_match('/^\(.*\)$/', $search_component_params_hidden)) { // If $search_component_params_hidden does not start and end with ()
  9081. $search_component_params_hidden .= '('.$search_component_params_hidden.')';
  9082. }
  9083. $errormessage = '';
  9084. if (!dolCheckFilters($search_component_params_hidden, $errormessage)) {
  9085. print 'ERROR in parsing search string';
  9086. }
  9087. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9088. //var_dump($search_component_params_hidden);
  9089. $htmltags = preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $search_component_params_hidden);
  9090. //var_dump($htmltags);
  9091. $ret .= '<span class="marginleftonlyshort valignmiddle tagsearch"><span class="tagsearchdelete select2-selection__choice__remove">x</span> '.$htmltags.'</span>';
  9092. }
  9093. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  9094. //$ret .= search_component_params
  9095. //$texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  9096. //$ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  9097. $show_search_component_params_hidden = 1;
  9098. if ($show_search_component_params_hidden) {
  9099. $ret .= '<input type="hidden" name="show_search_component_params_hidden" value="1">';
  9100. }
  9101. $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%')) -->";
  9102. $ret .= '<input type="hidden" name="search_component_params_hidden" value="'.dol_escape_htmltag($search_component_params_hidden).'">';
  9103. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  9104. foreach ($arrayofcriterias as $criterias) {
  9105. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  9106. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) {
  9107. continue;
  9108. }
  9109. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) {
  9110. continue;
  9111. }
  9112. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  9113. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  9114. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  9115. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  9116. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  9117. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  9118. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  9119. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  9120. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  9121. } else {
  9122. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  9123. }
  9124. }
  9125. }
  9126. $ret .= '</div>';
  9127. $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";
  9128. $ret .= '<input type="text" placeholder="'.$langs->trans("Search").'" name="search_component_params_input" class="noborderbottom search_component_input" value="">';
  9129. $ret .= '</div>';
  9130. $ret .= '</div>';
  9131. return $ret;
  9132. }
  9133. /**
  9134. * selectModelMail
  9135. *
  9136. * @param string $prefix Prefix
  9137. * @param string $modelType Model type
  9138. * @param int $default 1=Show also Default mail template
  9139. * @param int $addjscombo Add js combobox
  9140. * @return string HTML select string
  9141. */
  9142. public function selectModelMail($prefix, $modelType = '', $default = 0, $addjscombo = 0)
  9143. {
  9144. global $langs, $user;
  9145. $retstring = '';
  9146. $TModels = array();
  9147. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  9148. $formmail = new FormMail($this->db);
  9149. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  9150. if ($default) {
  9151. $TModels[0] = $langs->trans('DefaultMailModel');
  9152. }
  9153. if ($result > 0) {
  9154. foreach ($formmail->lines_model as $model) {
  9155. $TModels[$model->id] = $model->label;
  9156. }
  9157. }
  9158. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  9159. foreach ($TModels as $id_model => $label_model) {
  9160. $retstring .= '<option value="'.$id_model.'"';
  9161. $retstring .= ">".$label_model."</option>";
  9162. }
  9163. $retstring .= "</select>";
  9164. if ($addjscombo) {
  9165. $retstring .= ajax_combobox('select_'.$prefix.'model_mail');
  9166. }
  9167. return $retstring;
  9168. }
  9169. /**
  9170. * Output the buttons to submit a creation/edit form
  9171. *
  9172. * @param string $save_label Alternative label for save button
  9173. * @param string $cancel_label Alternative label for cancel button
  9174. * @param array $morebuttons Add additional buttons between save and cancel
  9175. * @param bool $withoutdiv Option to remove enclosing centered div
  9176. * @param string $morecss More CSS
  9177. * @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.
  9178. * @return string Html code with the buttons
  9179. */
  9180. public function buttonsSaveCancel($save_label = 'Save', $cancel_label = 'Cancel', $morebuttons = array(), $withoutdiv = 0, $morecss = '', $dol_openinpopup = '')
  9181. {
  9182. global $langs;
  9183. $buttons = array();
  9184. $save = array(
  9185. 'name' => 'save',
  9186. 'label_key' => $save_label,
  9187. );
  9188. if ($save_label == 'Create' || $save_label == 'Add' ) {
  9189. $save['name'] = 'add';
  9190. } elseif ($save_label == 'Modify') {
  9191. $save['name'] = 'edit';
  9192. }
  9193. $cancel = array(
  9194. 'name' => 'cancel',
  9195. 'label_key' => 'Cancel',
  9196. );
  9197. !empty($save_label) ? $buttons[] = $save : '';
  9198. if (!empty($morebuttons)) {
  9199. $buttons[] = $morebuttons;
  9200. }
  9201. !empty($cancel_label) ? $buttons[] = $cancel : '';
  9202. $retstring = $withoutdiv ? '': '<div class="center">';
  9203. foreach ($buttons as $button) {
  9204. $addclass = empty($button['addclass']) ? '' : $button['addclass'];
  9205. $retstring .= '<input type="submit" class="button button-'.$button['name'].($morecss ? ' '.$morecss : '').' '.$addclass.'" name="'.$button['name'].'" value="'.dol_escape_htmltag($langs->trans($button['label_key'])).'">';
  9206. }
  9207. $retstring .= $withoutdiv ? '': '</div>';
  9208. if ($dol_openinpopup) {
  9209. $retstring .= '<!-- buttons are shown into a $dol_openinpopup='.$dol_openinpopup.' context, so we enable the close of dialog on cancel -->'."\n";
  9210. $retstring .= '<script>';
  9211. $retstring .= 'jQuery(".button-cancel").click(function(e) {
  9212. e.preventDefault(); console.log(\'We click on cancel in iframe popup '.$dol_openinpopup.'\');
  9213. window.parent.jQuery(\'#idfordialog'.$dol_openinpopup.'\').dialog(\'close\');
  9214. });';
  9215. $retstring .= '</script>';
  9216. }
  9217. return $retstring;
  9218. }
  9219. }