html.form.class.php 344 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011
  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-2019 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 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
  20. * Copyright (C) 2018-2019 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_availability = array();
  68. public $cache_demand_reason = array();
  69. public $cache_types_fees = array();
  70. public $cache_vatrates = array();
  71. /**
  72. * Constructor
  73. *
  74. * @param DoliDB $db Database handler
  75. */
  76. public function __construct($db)
  77. {
  78. $this->db = $db;
  79. }
  80. /**
  81. * Output key field for an editable field
  82. *
  83. * @param string $text Text of label or key to translate
  84. * @param string $htmlname Name of select field ('edit' prefix will be added)
  85. * @param string $preselected Value to show/edit (not used in this function)
  86. * @param object $object Object
  87. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  88. * @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]'...)
  89. * @param string $moreparam More param to add on a href URL.
  90. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  91. * @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 ' '
  92. * @param string $paramid Key of parameter for id ('id', 'socid')
  93. * @param string $help Tooltip help
  94. * @return string HTML edit field
  95. */
  96. public function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id', $help = '')
  97. {
  98. global $conf, $langs;
  99. $ret = '';
  100. // TODO change for compatibility
  101. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata))
  102. {
  103. if (!empty($perm))
  104. {
  105. $tmp = explode(':', $typeofdata);
  106. $ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  107. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  108. if ($help) {
  109. $ret .= $this->textwithpicto($langs->trans($text), $help);
  110. } else {
  111. $ret .= $langs->trans($text);
  112. }
  113. if ($fieldrequired) $ret .= '</span>';
  114. $ret .= '</div>'."\n";
  115. } else {
  116. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  117. if ($help) {
  118. $ret .= $this->textwithpicto($langs->trans($text), $help);
  119. } else {
  120. $ret .= $langs->trans($text);
  121. }
  122. if ($fieldrequired) $ret .= '</span>';
  123. }
  124. } else {
  125. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  126. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  127. if ($help) {
  128. $ret .= $this->textwithpicto($langs->trans($text), $help);
  129. } else {
  130. $ret .= $langs->trans($text);
  131. }
  132. if ($fieldrequired) $ret .= '</span>';
  133. if (!empty($notabletag)) $ret .= ' ';
  134. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
  135. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<td class="right">';
  136. if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  137. if (!empty($notabletag) && $notabletag == 1) $ret .= ' : ';
  138. if (!empty($notabletag) && $notabletag == 3) $ret .= ' ';
  139. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
  140. if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</tr></table>';
  141. }
  142. return $ret;
  143. }
  144. /**
  145. * Output value of a field for an editable field
  146. *
  147. * @param string $text Text of label (not used in this function)
  148. * @param string $htmlname Name of select field
  149. * @param string $value Value to show/edit
  150. * @param object $object Object
  151. * @param boolean $perm Permission to allow button to edit parameter
  152. * @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,...')
  153. * @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 value). Use '' to use same than $value
  154. * @param object $extObject External object
  155. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  156. * @param string $moreparam More param to add on the form action href URL
  157. * @param int $notabletag Do no output table tags
  158. * @param string $formatfunc Call a specific function to output field
  159. * @param string $paramid Key of parameter for id ('id', 'socid')
  160. * @return string HTML edit field
  161. */
  162. public function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id')
  163. {
  164. global $conf, $langs, $db;
  165. $ret = '';
  166. // Check parameters
  167. if (empty($typeofdata)) return 'ErrorBadParameter';
  168. // When option to edit inline is activated
  169. if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|datehourpicker/', $typeofdata)) // TODO add jquery timepicker and support select
  170. {
  171. $ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  172. } else {
  173. if (GETPOST('action', 'aZ09') == 'edit'.$htmlname)
  174. {
  175. $ret .= "\n";
  176. $ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
  177. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  178. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  179. $ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
  180. if (empty($notabletag)) $ret .= '<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
  181. if (empty($notabletag)) $ret .= '<tr><td>';
  182. if (preg_match('/^(string|safehtmlstring|email)/', $typeofdata))
  183. {
  184. $tmp = explode(':', $typeofdata);
  185. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  186. } elseif (preg_match('/^(numeric|amount)/', $typeofdata))
  187. {
  188. $tmp = explode(':', $typeofdata);
  189. $valuetoshow = price2num($editvalue ? $editvalue : $value);
  190. $ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ?price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').' autofocus>';
  191. } elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) // if wysiwyg is enabled $typeofdata = 'ckeditor'
  192. {
  193. $tmp = explode(':', $typeofdata);
  194. $cols = $tmp[2];
  195. $morealt = '';
  196. if (preg_match('/%/', $cols))
  197. {
  198. $morealt = ' style="width: '.$cols.'"';
  199. $cols = '';
  200. }
  201. $valuetoshow = ($editvalue ? $editvalue : $value);
  202. $ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'" autofocus>';
  203. // textarea convert automatically entities chars into simple chars.
  204. // 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.
  205. $valuetoshow = str_replace('&', '&amp;', $valuetoshow);
  206. $ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
  207. $ret .= '</textarea>';
  208. } elseif ($typeofdata == 'day' || $typeofdata == 'datepicker')
  209. {
  210. $ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0);
  211. } elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
  212. {
  213. $ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0);
  214. } elseif (preg_match('/^select;/', $typeofdata))
  215. {
  216. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  217. $arraylist = array();
  218. foreach ($arraydata as $val)
  219. {
  220. $tmp = explode(':', $val);
  221. $tmpkey = str_replace('|', ':', $tmp[0]);
  222. $arraylist[$tmpkey] = $tmp[1];
  223. }
  224. $ret .= $this->selectarray($htmlname, $arraylist, $value);
  225. } elseif (preg_match('/^ckeditor/', $typeofdata))
  226. {
  227. $tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols:uselocalbrowser
  228. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  229. $doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), ($tmp[2] ? $tmp[2] : ''), ($tmp[3] ? $tmp[3] : '100'), ($tmp[1] ? $tmp[1] : 'dolibarr_notes'), 'In', ($tmp[5] ? $tmp[5] : 0), (isset($tmp[8]) ? ($tmp[8] ?true:false) : true), true, ($tmp[6] ? $tmp[6] : '20'), ($tmp[7] ? $tmp[7] : '100'));
  230. $ret .= $doleditor->Create(1);
  231. }
  232. if (empty($notabletag)) $ret .= '</td>';
  233. if (empty($notabletag)) $ret .= '<td class="left">';
  234. //else $ret.='<div class="clearboth"></div>';
  235. $ret .= '<input type="submit" class="button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  236. if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) $ret .= '<br>'."\n";
  237. $ret .= '<input type="submit" class="button'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  238. if (empty($notabletag)) $ret .= '</td>';
  239. if (empty($notabletag)) $ret .= '</tr></table>'."\n";
  240. $ret .= '</form>'."\n";
  241. } else {
  242. if (preg_match('/^(email)/', $typeofdata)) $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
  243. elseif (preg_match('/^(amount|numeric)/', $typeofdata)) $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
  244. elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata)) $ret .= dol_htmlentitiesbr($value);
  245. elseif (preg_match('/^safehtmlstring/', $typeofdata)) $ret .= dol_string_onlythesehtmltags($value);
  246. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret .= dol_print_date($value, 'day');
  247. elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret .= dol_print_date($value, 'dayhour');
  248. elseif (preg_match('/^select;/', $typeofdata))
  249. {
  250. $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
  251. $arraylist = array();
  252. foreach ($arraydata as $val)
  253. {
  254. $tmp = explode(':', $val);
  255. $arraylist[$tmp[0]] = $tmp[1];
  256. }
  257. $ret .= $arraylist[$value];
  258. } elseif (preg_match('/^ckeditor/', $typeofdata))
  259. {
  260. $tmpcontent = dol_htmlentitiesbr($value);
  261. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB))
  262. {
  263. $firstline = preg_replace('/<br>.*/', '', $tmpcontent);
  264. $firstline = preg_replace('/[\n\r].*/', '', $firstline);
  265. $tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
  266. }
  267. // We dont use dol_escape_htmltag to get the html formating active, but this need we must also
  268. // clean data from some dangerous html
  269. $ret .= dol_string_onlythesehtmltags(dol_htmlentitiesbr($tmpcontent));
  270. } else {
  271. $ret .= dol_escape_htmltag($value);
  272. }
  273. if ($formatfunc && method_exists($object, $formatfunc))
  274. {
  275. $ret = $object->$formatfunc($ret);
  276. }
  277. }
  278. }
  279. return $ret;
  280. }
  281. /**
  282. * Output edit in place form
  283. *
  284. * @param string $fieldname Name of the field
  285. * @param object $object Object
  286. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  287. * @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]'...)
  288. * @param string $check Same coe than $check parameter of GETPOST()
  289. * @param string $morecss More CSS
  290. * @return string HTML code for the edit of alternative language
  291. */
  292. public function widgetForTranslation($fieldname, $object, $perm, $typeofdata = 'string', $check = '', $morecss = '')
  293. {
  294. global $conf, $langs, $extralanguages;
  295. $result = '';
  296. // List of extra languages
  297. $arrayoflangcode = array();
  298. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  299. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  300. if (!is_object($extralanguages)) {
  301. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  302. $extralanguages = new ExtraLanguages($this->db);
  303. }
  304. $extralanguages->fetch_name_extralanguages('societe');
  305. if (!is_array($extralanguages->attributes[$object->element]) || empty($extralanguages->attributes[$object->element][$fieldname])) {
  306. return ''; // No extralang field to show
  307. }
  308. $result .= '<!-- Widget for translation -->'."\n";
  309. $result .= '<div class="inline-block paddingleft image-'.$object->element.'-'.$fieldname.'">';
  310. $s = img_picto($langs->trans("ShowOtherLanguages"), 'language', '', false, 0, 0, '', 'fa-15 editfieldlang');
  311. $result .= $s;
  312. $result .= '</div>';
  313. $result .= '<div class="inline-block hidden field-'.$object->element.'-'.$fieldname.'">';
  314. $resultforextrlang = '';
  315. foreach ($arrayoflangcode as $langcode)
  316. {
  317. $valuetoshow = GETPOSTISSET('field-'.$object->element."-".$fieldname."-".$langcode) ? GETPOST('field-'.$object->element.'-'.$fieldname."-".$langcode, $check) : '';
  318. if (empty($valuetoshow)) {
  319. $object->fetchValuesForExtraLanguages();
  320. //var_dump($object->array_languages);
  321. $valuetoshow = $object->array_languages[$fieldname][$langcode];
  322. }
  323. $s = picto_from_langcode($langcode, 'class="pictoforlang paddingright"');
  324. $resultforextrlang .= $s;
  325. // TODO Use the showInputField() method of ExtraLanguages object
  326. if ($typeofdata == 'textarea') {
  327. $resultforextrlang .= '<textarea name="field-'.$object->element."-".$fieldname."-".$langcode.'" id="'.$fieldname."-".$langcode.'" class="'.$morecss.'" rows="'.ROWS_2.'" wrap="soft">';
  328. $resultforextrlang .= $valuetoshow;
  329. $resultforextrlang .= '</textarea>';
  330. } else {
  331. $resultforextrlang .= '<input type="text" class="inputfieldforlang '.($morecss ? ' '.$morecss : '').'" name="field-'.$object->element.'-'.$fieldname.'-'.$langcode.'" value="'.$valuetoshow.'">';
  332. }
  333. }
  334. $result .= $resultforextrlang;
  335. $result .= '</div>';
  336. $result .= '<script>$(".image-'.$object->element.'-'.$fieldname.'").click(function() { console.log("Toggle lang widget"); jQuery(".field-'.$object->element.'-'.$fieldname.'").toggle(); });</script>';
  337. }
  338. return $result;
  339. }
  340. /**
  341. * Output edit in place form
  342. *
  343. * @param object $object Object
  344. * @param string $value Value to show/edit
  345. * @param string $htmlname DIV ID (field name)
  346. * @param int $condition Condition to edit
  347. * @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')
  348. * @param string $editvalue When in edit mode, use this value as $value instead of value
  349. * @param object $extObject External object
  350. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  351. * @return string HTML edit in place
  352. */
  353. protected function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
  354. {
  355. global $conf;
  356. $out = '';
  357. // Check parameters
  358. if (preg_match('/^text/', $inputType)) $value = dol_nl2br($value);
  359. elseif (preg_match('/^numeric/', $inputType)) $value = price($value);
  360. elseif ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
  361. if ($condition)
  362. {
  363. $element = false;
  364. $table_element = false;
  365. $fk_element = false;
  366. $loadmethod = false;
  367. $savemethod = false;
  368. $ext_element = false;
  369. $button_only = false;
  370. $inputOption = '';
  371. if (is_object($object))
  372. {
  373. $element = $object->element;
  374. $table_element = $object->table_element;
  375. $fk_element = $object->id;
  376. }
  377. if (is_object($extObject))
  378. {
  379. $ext_element = $extObject->element;
  380. }
  381. if (preg_match('/^(string|email|numeric)/', $inputType))
  382. {
  383. $tmp = explode(':', $inputType);
  384. $inputType = $tmp[0];
  385. if (!empty($tmp[1])) $inputOption = $tmp[1];
  386. if (!empty($tmp[2])) $savemethod = $tmp[2];
  387. $out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  388. } elseif ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType)))
  389. {
  390. $tmp = explode(':', $inputType);
  391. $inputType = $tmp[0];
  392. if (!empty($tmp[1])) $inputOption = $tmp[1];
  393. if (!empty($tmp[2])) $savemethod = $tmp[2];
  394. $out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  395. } elseif (preg_match('/^(select|autocomplete)/', $inputType))
  396. {
  397. $tmp = explode(':', $inputType);
  398. $inputType = $tmp[0]; $loadmethod = $tmp[1];
  399. if (!empty($tmp[2])) $savemethod = $tmp[2];
  400. if (!empty($tmp[3])) $button_only = true;
  401. } elseif (preg_match('/^textarea/', $inputType))
  402. {
  403. $tmp = explode(':', $inputType);
  404. $inputType = $tmp[0];
  405. $rows = (empty($tmp[1]) ? '8' : $tmp[1]);
  406. $cols = (empty($tmp[2]) ? '80' : $tmp[2]);
  407. } elseif (preg_match('/^ckeditor/', $inputType))
  408. {
  409. $tmp = explode(':', $inputType);
  410. $inputType = $tmp[0]; $toolbar = $tmp[1];
  411. if (!empty($tmp[2])) $width = $tmp[2];
  412. if (!empty($tmp[3])) $heigth = $tmp[3];
  413. if (!empty($tmp[4])) $savemethod = $tmp[4];
  414. if (!empty($conf->fckeditor->enabled))
  415. {
  416. $out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  417. } else {
  418. $inputType = 'textarea';
  419. }
  420. }
  421. $out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  422. $out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  423. $out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  424. $out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  425. if (!empty($savemethod)) $out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  426. if (!empty($ext_element)) $out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  427. if (!empty($custommsg))
  428. {
  429. if (is_array($custommsg))
  430. {
  431. if (!empty($custommsg['success']))
  432. $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  433. if (!empty($custommsg['error']))
  434. $out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  435. } else $out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  436. }
  437. if ($inputType == 'textarea') {
  438. $out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  439. $out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  440. }
  441. $out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  442. $out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  443. } else {
  444. $out = $value;
  445. }
  446. return $out;
  447. }
  448. /**
  449. * Show a text and picto with tooltip on text or picto.
  450. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  451. *
  452. * @param string $text Text to show
  453. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  454. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  455. * @param int $direction -1=image is before, 0=no image, 1=image is after
  456. * @param string $img Html code for image (use img_xxx() function to get it)
  457. * @param string $extracss Add a CSS style to td tags
  458. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  459. * @param string $incbefore Include code before the text
  460. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  461. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  462. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  463. * @return string Code html du tooltip (texte+picto)
  464. * @see textwithpicto() Use thisfunction if you can.
  465. * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
  466. */
  467. public function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 3, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
  468. {
  469. if ($incbefore) $text = $incbefore.$text;
  470. if (!$htmltext) return $text;
  471. $tag = 'td';
  472. if ($notabs == 2) $tag = 'div';
  473. if ($notabs == 3) $tag = 'span';
  474. // Sanitize tooltip
  475. $htmltext = str_replace(array("\r", "\n"), '', $htmltext);
  476. $extrastyle = '';
  477. if ($direction < 0) { $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : ''); $extrastyle = 'padding: 0px; padding-left: 3px !important;'; }
  478. if ($direction > 0) { $extracss = ($extracss ? $extracss.' ' : '').($notabs != 3 ? 'inline-block' : ''); $extrastyle = 'padding: 0px; padding-right: 3px !important;'; }
  479. $classfortooltip = 'classfortooltip';
  480. $s = ''; $textfordialog = '';
  481. if ($tooltiptrigger == '')
  482. {
  483. $htmltext = str_replace('"', '&quot;', $htmltext);
  484. } else {
  485. $classfortooltip = 'classfortooltiponclick';
  486. $textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  487. }
  488. if ($tooltipon == 2 || $tooltipon == 3)
  489. {
  490. $paramfortooltipimg = ' class="'.$classfortooltip.($notabs != 3 ? ' inline-block' : '').($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
  491. if ($tooltiptrigger == '') $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
  492. else $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
  493. } else $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  494. if ($tooltipon == 1 || $tooltipon == 3)
  495. {
  496. $paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
  497. if ($tooltiptrigger == '') $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
  498. else $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
  499. } else $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
  500. if (empty($notabs)) $s .= '<table class="nobordernopadding"><tr style="height: auto;">';
  501. elseif ($notabs == 2) $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
  502. // Define value if value is before
  503. if ($direction < 0) {
  504. $s .= '<'.$tag.$paramfortooltipimg;
  505. if ($tag == 'td') {
  506. $s .= ' class=valigntop" width="14"';
  507. }
  508. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  509. }
  510. // Use another method to help avoid having a space in value in order to use this value with jquery
  511. // Define label
  512. if ((string) $text != '') $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  513. // Define value if value is after
  514. if ($direction > 0) {
  515. $s .= '<'.$tag.$paramfortooltipimg;
  516. if ($tag == 'td') $s .= ' class="valignmiddle" width="14"';
  517. $s .= '>'.$textfordialog.$img.'</'.$tag.'>';
  518. }
  519. if (empty($notabs)) $s .= '</tr></table>';
  520. elseif ($notabs == 2) $s .= '</div>';
  521. return $s;
  522. }
  523. /**
  524. * Show a text with a picto and a tooltip on picto
  525. *
  526. * @param string $text Text to show
  527. * @param string $htmltext Content of tooltip
  528. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  529. * @param string $type Type of picto ('info', 'infoclickable', 'help', 'helpclickable', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath or 'none'
  530. * @param string $extracss Add a CSS style to td, div or span tag
  531. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  532. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  533. * @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')
  534. * @param int $forcenowrap Force no wrap between text and picto (works with notabs=2 only)
  535. * @return string HTML code of text, picto, tooltip
  536. */
  537. public function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 3, $tooltiptrigger = '', $forcenowrap = 0)
  538. {
  539. global $conf, $langs;
  540. $alt = '';
  541. if ($tooltiptrigger) $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
  542. //For backwards compatibility
  543. if ($type == '0') $type = 'info';
  544. elseif ($type == '1') $type = 'help';
  545. // If info or help with no javascript, show only text
  546. if (empty($conf->use_javascript_ajax))
  547. {
  548. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') return $text;
  549. else {
  550. $alt = $htmltext;
  551. $htmltext = '';
  552. }
  553. }
  554. // If info or help with smartphone, show only text (tooltip hover can't works)
  555. if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
  556. {
  557. if ($type == 'info' || $type == 'infoclickable' || $type == 'help' || $type == 'helpclickable') return $text;
  558. }
  559. // If info or help with smartphone, show only text (tooltip on click does not works with dialog on smaprtphone)
  560. //if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
  561. //{
  562. //if ($type == 'info' || $type == 'help') return '<a href="'..'">'.$text.''</a>';
  563. //}
  564. $img = '';
  565. if ($type == 'info') $img = img_help(0, $alt);
  566. elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  567. elseif ($type == 'helpclickable') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  568. elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
  569. elseif ($type == 'admin') $img = img_picto($alt, 'star');
  570. elseif ($type == 'warning') $img = img_warning($alt);
  571. elseif ($type != 'none') $img = img_picto($alt, $type); // $type can be an image path
  572. return $this->textwithtooltip($text, $htmltext, ((($tooltiptrigger && !$img) || strpos($type, 'clickable')) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
  573. }
  574. /**
  575. * Generate select HTML to choose massaction
  576. *
  577. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  578. * @param array $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  579. * @param int $alwaysvisible 1=select button always visible
  580. * @param string $name Name for massaction
  581. * @param string $cssclass CSS class used to check for select
  582. * @return string|void Select list
  583. */
  584. public function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0, $name = 'massaction', $cssclass = 'checkforselect')
  585. {
  586. global $conf, $langs, $hookmanager;
  587. $disabled = 0;
  588. $ret = '<div class="centpercent center">';
  589. $ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' ' . $name . ' ' . $name . 'select valignmiddle alignstart" name="' . $name . '"'.($disabled ? ' disabled="disabled"' : '').'>';
  590. // 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.
  591. $parameters = array();
  592. $reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
  593. // check if there is a mass action
  594. if (count($arrayofaction) == 0 && empty($hookmanager->resPrint)) return;
  595. if (empty($reshook))
  596. {
  597. $ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
  598. foreach ($arrayofaction as $code => $label)
  599. {
  600. $ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').' data-html="'.dol_escape_htmltag($label).'">'.$label.'</option>';
  601. }
  602. }
  603. $ret .= $hookmanager->resPrint;
  604. $ret .= '</select>';
  605. if (empty($conf->dol_optimize_smallscreen)) $ret .= ajax_combobox('.' . $name . 'select');
  606. // 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
  607. $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.
  608. $ret .= '<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' ' . $name . ' ' . $name . 'confirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  609. $ret .= '</div>';
  610. if (!empty($conf->use_javascript_ajax))
  611. {
  612. $ret .= '<!-- JS CODE TO ENABLE mass action select -->
  613. <script>
  614. 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 */
  615. {
  616. atleastoneselected=0;
  617. jQuery("."+cssclass).each(function( index ) {
  618. /* console.log( index + ": " + $( this ).text() ); */
  619. if ($(this).is(\':checked\')) atleastoneselected++;
  620. });
  621. console.log("initCheckForSelect mode="+mode+" name="+name+" cssclass="+cssclass+" atleastoneselected="+atleastoneselected);
  622. if (atleastoneselected || '.$alwaysvisible.')
  623. {
  624. jQuery("."+name).show();
  625. '.($selected ? 'if (atleastoneselected) { jQuery("."+name+"select").val("'.$selected.'").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', false); }' : '').'
  626. '.($selected ? 'if (! atleastoneselected) { jQuery("."+name+"select").val("0").trigger(\'change\'); jQuery("."+name+"confirmed").prop(\'disabled\', true); } ' : '').'
  627. }
  628. else
  629. {
  630. jQuery("."+name).hide();
  631. jQuery("."+name+"other").hide();
  632. }
  633. }
  634. jQuery(document).ready(function () {
  635. initCheckForSelect(0, "' . $name . '", "' . $cssclass . '");
  636. jQuery(".' . $cssclass . '").click(function() {
  637. initCheckForSelect(1, "'.$name.'", "' . $cssclass . '");
  638. });
  639. jQuery(".' . $name . 'select").change(function() {
  640. var massaction = $( this ).val();
  641. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  642. if (massaction == "builddoc")
  643. {
  644. urlform = urlform + "#show_files";
  645. }
  646. $( this ).closest("form").attr("action", urlform);
  647. console.log("we select a mass action name='.$name.' massaction="+massaction+" - "+urlform);
  648. /* Warning: if you set submit button to disabled, post using Enter will no more work if there is no other button */
  649. if ($(this).val() != \'0\')
  650. {
  651. jQuery(".' . $name . 'confirmed").prop(\'disabled\', false);
  652. jQuery(".' . $name . 'other").hide(); /* To disable if another div was open */
  653. jQuery(".' . $name . '"+massaction).show();
  654. }
  655. else
  656. {
  657. jQuery(".' . $name . 'confirmed").prop(\'disabled\', true);
  658. jQuery(".' . $name . 'other").hide(); /* To disable any div open */
  659. }
  660. });
  661. });
  662. </script>
  663. ';
  664. }
  665. return $ret;
  666. }
  667. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  668. /**
  669. * Return combo list of activated countries, into language of user
  670. *
  671. * @param string $selected Id or Code or Label of preselected country
  672. * @param string $htmlname Name of html select object
  673. * @param string $htmloption More html options on select object
  674. * @param integer $maxlength Max length for labels (0=no limit)
  675. * @param string $morecss More css class
  676. * @param string $usecodeaskey ''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
  677. * @param int $showempty Show empty choice
  678. * @param int $disablefavorites 1=Disable favorites,
  679. * @param int $addspecialentries 1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
  680. * @param array $exclude_country_code Array of country code (iso2) to exclude
  681. * @return string HTML string with select
  682. */
  683. public function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0, $exclude_country_code = array())
  684. {
  685. // phpcs:enable
  686. global $conf, $langs, $mysoc;
  687. $langs->load("dict");
  688. $out = '';
  689. $countryArray = array();
  690. $favorite = array();
  691. $label = array();
  692. $atleastonefavorite = 0;
  693. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
  694. $sql .= " FROM ".MAIN_DB_PREFIX."c_country";
  695. $sql .= " WHERE active > 0";
  696. //$sql.= " ORDER BY code ASC";
  697. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  698. $resql = $this->db->query($sql);
  699. if ($resql)
  700. {
  701. $out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
  702. $num = $this->db->num_rows($resql);
  703. $i = 0;
  704. if ($num)
  705. {
  706. $foundselected = false;
  707. while ($i < $num)
  708. {
  709. $obj = $this->db->fetch_object($resql);
  710. $countryArray[$i]['rowid'] = $obj->rowid;
  711. $countryArray[$i]['code_iso'] = $obj->code_iso;
  712. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  713. $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 : ''));
  714. $countryArray[$i]['favorite'] = $obj->favorite;
  715. $favorite[$i] = $obj->favorite;
  716. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  717. $i++;
  718. }
  719. if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  720. else $countryArray = dol_sort_array($countryArray, 'label');
  721. if ($showempty)
  722. {
  723. $out .= '<option value="">&nbsp;</option>'."\n";
  724. }
  725. if ($addspecialentries) // Add dedicated entries for groups of countries
  726. {
  727. //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  728. $out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  729. $out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
  730. if ($mysoc->isInEEC()) $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
  731. $out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
  732. $out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  733. }
  734. foreach ($countryArray as $row)
  735. {
  736. //if (empty($showempty) && empty($row['rowid'])) continue;
  737. if (empty($row['rowid'])) continue;
  738. if (is_array($exclude_country_code) && count($exclude_country_code) && in_array($row['code_iso'], $exclude_country_code)) continue; // exclude some countries
  739. if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
  740. if (empty($row['favorite']) && $atleastonefavorite)
  741. {
  742. $atleastonefavorite = 0;
  743. $out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
  744. }
  745. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']))
  746. {
  747. $foundselected = true;
  748. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected>';
  749. } else {
  750. $out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'">';
  751. }
  752. if ($row['label']) $out .= dol_trunc($row['label'], $maxlength, 'middle');
  753. else $out .= '&nbsp;';
  754. if ($row['code_iso']) $out .= ' ('.$row['code_iso'].')';
  755. $out .= '</option>';
  756. }
  757. }
  758. $out .= '</select>';
  759. } else {
  760. dol_print_error($this->db);
  761. }
  762. // Make select dynamic
  763. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  764. $out .= ajax_combobox('select'.$htmlname);
  765. return $out;
  766. }
  767. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  768. /**
  769. * Return select list of incoterms
  770. *
  771. * @param string $selected Id or Code of preselected incoterm
  772. * @param string $location_incoterms Value of input location
  773. * @param string $page Defined the form action
  774. * @param string $htmlname Name of html select object
  775. * @param string $htmloption Options html on select object
  776. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  777. * @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')))
  778. * @return string HTML string with select and input
  779. */
  780. public function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
  781. {
  782. // phpcs:enable
  783. global $conf, $langs;
  784. $langs->load("dict");
  785. $out = '';
  786. $incotermArray = array();
  787. $sql = "SELECT rowid, code";
  788. $sql .= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  789. $sql .= " WHERE active > 0";
  790. $sql .= " ORDER BY code ASC";
  791. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  792. $resql = $this->db->query($sql);
  793. if ($resql)
  794. {
  795. if ($conf->use_javascript_ajax && !$forcecombo)
  796. {
  797. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  798. $out .= ajax_combobox($htmlname, $events);
  799. }
  800. if (!empty($page))
  801. {
  802. $out .= '<form method="post" action="'.$page.'">';
  803. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  804. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  805. }
  806. $out .= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
  807. $out .= '<option value="0">&nbsp;</option>';
  808. $num = $this->db->num_rows($resql);
  809. $i = 0;
  810. if ($num)
  811. {
  812. $foundselected = false;
  813. while ($i < $num)
  814. {
  815. $obj = $this->db->fetch_object($resql);
  816. $incotermArray[$i]['rowid'] = $obj->rowid;
  817. $incotermArray[$i]['code'] = $obj->code;
  818. $i++;
  819. }
  820. foreach ($incotermArray as $row)
  821. {
  822. if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
  823. {
  824. $out .= '<option value="'.$row['rowid'].'" selected>';
  825. } else {
  826. $out .= '<option value="'.$row['rowid'].'">';
  827. }
  828. if ($row['code']) $out .= $row['code'];
  829. $out .= '</option>';
  830. }
  831. }
  832. $out .= '</select>';
  833. $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
  834. if (!empty($page))
  835. {
  836. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
  837. }
  838. } else {
  839. dol_print_error($this->db);
  840. }
  841. return $out;
  842. }
  843. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  844. /**
  845. * Return list of types of lines (product or service)
  846. * Example: 0=product, 1=service, 9=other (for external module)
  847. *
  848. * @param string $selected Preselected type
  849. * @param string $htmlname Name of field in html form
  850. * @param int $showempty Add an empty field
  851. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  852. * @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')
  853. * @return void
  854. */
  855. public function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
  856. {
  857. // phpcs:enable
  858. global $db, $langs, $user, $conf;
  859. // If product & services are enabled or both disabled.
  860. if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
  861. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)))
  862. {
  863. if (empty($hidetext)) print $langs->trans("Type").': ';
  864. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  865. if ($showempty)
  866. {
  867. print '<option value="-1"';
  868. if ($selected == -1) print ' selected';
  869. print '>&nbsp;</option>';
  870. }
  871. print '<option value="0"';
  872. if (0 == $selected) print ' selected';
  873. print '>'.$langs->trans("Product");
  874. print '<option value="1"';
  875. if (1 == $selected) print ' selected';
  876. print '>'.$langs->trans("Service");
  877. print '</select>';
  878. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  879. }
  880. if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3)
  881. {
  882. print $langs->trans("Service");
  883. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  884. }
  885. if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
  886. {
  887. print $langs->trans("Product");
  888. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  889. }
  890. if ($forceall < 0) // This should happened only for contracts when both predefined product and service are disabled.
  891. {
  892. 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
  893. }
  894. }
  895. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  896. /**
  897. * Load into cache cache_types_fees, array of types of fees
  898. *
  899. * @return int Nb of lines loaded, <0 if KO
  900. */
  901. public function load_cache_types_fees()
  902. {
  903. // phpcs:enable
  904. global $langs;
  905. $num = count($this->cache_types_fees);
  906. if ($num > 0) return 0; // Cache already loaded
  907. dol_syslog(__METHOD__, LOG_DEBUG);
  908. $langs->load("trips");
  909. $sql = "SELECT c.code, c.label";
  910. $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  911. $sql .= " WHERE active > 0";
  912. $resql = $this->db->query($sql);
  913. if ($resql)
  914. {
  915. $num = $this->db->num_rows($resql);
  916. $i = 0;
  917. while ($i < $num)
  918. {
  919. $obj = $this->db->fetch_object($resql);
  920. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  921. $label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  922. $this->cache_types_fees[$obj->code] = $label;
  923. $i++;
  924. }
  925. asort($this->cache_types_fees);
  926. return $num;
  927. } else {
  928. dol_print_error($this->db);
  929. return -1;
  930. }
  931. }
  932. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  933. /**
  934. * Return list of types of notes
  935. *
  936. * @param string $selected Preselected type
  937. * @param string $htmlname Name of field in form
  938. * @param int $showempty Add an empty field
  939. * @return void
  940. */
  941. public function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
  942. {
  943. // phpcs:enable
  944. global $user, $langs;
  945. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  946. $this->load_cache_types_fees();
  947. print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  948. if ($showempty)
  949. {
  950. print '<option value="-1"';
  951. if ($selected == -1) print ' selected';
  952. print '>&nbsp;</option>';
  953. }
  954. foreach ($this->cache_types_fees as $key => $value)
  955. {
  956. print '<option value="'.$key.'"';
  957. if ($key == $selected) print ' selected';
  958. print '>';
  959. print $value;
  960. print '</option>';
  961. }
  962. print '</select>';
  963. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  964. }
  965. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  966. /**
  967. * Return HTML code to select a company.
  968. *
  969. * @param int $selected Preselected products
  970. * @param string $htmlname Name of HTML select field (must be unique in page)
  971. * @param int $filter Filter on thirdparty
  972. * @param int $limit Limit on number of returned lines
  973. * @param array $ajaxoptions Options for ajax_autocompleter
  974. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  975. * @return string Return select box for thirdparty.
  976. * @deprecated 3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
  977. */
  978. public function select_thirdparty($selected = '', $htmlname = 'socid', $filter = '', $limit = 20, $ajaxoptions = array(), $forcecombo = 0)
  979. {
  980. // phpcs:enable
  981. return $this->select_thirdparty_list($selected, $htmlname, $filter, 1, 0, $forcecombo, array(), '', 0, $limit);
  982. }
  983. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  984. /**
  985. * Output html form to select a third party
  986. *
  987. * @param string $selected Preselected type
  988. * @param string $htmlname Name of field in form
  989. * @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)')
  990. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  991. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  992. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  993. * @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')))
  994. * @param int $limit Maximum number of elements
  995. * @param string $morecss Add more css styles to the SELECT component
  996. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  997. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  998. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  999. * @param array $ajaxoptions Options for ajax_autocompleter
  1000. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  1001. * @return string HTML string with select box for thirdparty.
  1002. */
  1003. 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)
  1004. {
  1005. // phpcs:enable
  1006. global $conf, $user, $langs;
  1007. $out = '';
  1008. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo)
  1009. {
  1010. // No immediate load of all database
  1011. $placeholder = '';
  1012. if ($selected && empty($selected_input_value))
  1013. {
  1014. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1015. $societetmp = new Societe($this->db);
  1016. $societetmp->fetch($selected);
  1017. $selected_input_value = $societetmp->name;
  1018. unset($societetmp);
  1019. }
  1020. // mode 1
  1021. $urloption = 'htmlname='.urlencode($htmlname).'&outjson=1&filter='.urlencode($filter).($showtype ? '&showtype='.urlencode($showtype) : '');
  1022. $out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1023. $out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  1024. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1025. elseif ($hidelabel > 1) {
  1026. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  1027. if ($hidelabel == 2) {
  1028. $out .= img_picto($langs->trans("Search"), 'search');
  1029. }
  1030. }
  1031. $out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1032. if ($hidelabel == 3) {
  1033. $out .= img_picto($langs->trans("Search"), 'search');
  1034. }
  1035. } else {
  1036. // Immediate load of all database
  1037. $out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
  1038. }
  1039. return $out;
  1040. }
  1041. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1042. /**
  1043. * Output html form to select a third party.
  1044. * 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.
  1045. *
  1046. * @param string $selected Preselected type
  1047. * @param string $htmlname Name of field in form
  1048. * @param string $filter Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
  1049. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  1050. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  1051. * @param int $forcecombo Force to use standard HTML select component without beautification
  1052. * @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')))
  1053. * @param string $filterkey Filter on key value
  1054. * @param int $outputmode 0=HTML select string, 1=Array
  1055. * @param int $limit Limit number of answers
  1056. * @param string $morecss Add more css styles to the SELECT component
  1057. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1058. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1059. * @return string HTML string with
  1060. */
  1061. 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)
  1062. {
  1063. // phpcs:enable
  1064. global $conf, $user, $langs;
  1065. $out = '';
  1066. $num = 0;
  1067. $outarray = array();
  1068. if ($selected === '') $selected = array();
  1069. elseif (!is_array($selected)) $selected = array($selected);
  1070. // Clean $filter that may contains sql conditions so sql code
  1071. if (function_exists('testSqlAndScriptInject')) {
  1072. if (testSqlAndScriptInject($filter, 3) > 0) {
  1073. $filter = '';
  1074. }
  1075. }
  1076. // On recherche les societes
  1077. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  1078. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1079. $sql .= ", s.address, s.zip, s.town";
  1080. $sql .= ", dictp.code as country_code";
  1081. }
  1082. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  1083. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  1084. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1085. $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
  1086. }
  1087. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  1088. if (!empty($user->socid)) $sql .= " AND s.rowid = ".$user->socid;
  1089. if ($filter) $sql .= " AND (".$filter.")";
  1090. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
  1091. if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND s.status <> 0";
  1092. // Add criteria
  1093. if ($filterkey && $filterkey != '')
  1094. {
  1095. $sql .= " AND (";
  1096. $prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  1097. // For natural search
  1098. $scrit = explode(' ', $filterkey);
  1099. $i = 0;
  1100. if (count($scrit) > 1) $sql .= "(";
  1101. foreach ($scrit as $crit) {
  1102. if ($i > 0) $sql .= " AND ";
  1103. $sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  1104. $i++;
  1105. }
  1106. if (count($scrit) > 1) $sql .= ")";
  1107. if (!empty($conf->barcode->enabled))
  1108. {
  1109. $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1110. }
  1111. $sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  1112. $sql .= ")";
  1113. }
  1114. $sql .= $this->db->order("nom", "ASC");
  1115. $sql .= $this->db->plimit($limit, 0);
  1116. // Build output string
  1117. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  1118. $resql = $this->db->query($sql);
  1119. if ($resql)
  1120. {
  1121. if (!$forcecombo)
  1122. {
  1123. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1124. $out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
  1125. }
  1126. // Construct $out and $outarray
  1127. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
  1128. $textifempty = (($showempty && !is_numeric($showempty)) ? $langs->trans($showempty) : '');
  1129. if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
  1130. {
  1131. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1132. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1133. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  1134. else $textifempty .= $langs->trans("All");
  1135. }
  1136. if ($showempty) $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  1137. $num = $this->db->num_rows($resql);
  1138. $i = 0;
  1139. if ($num)
  1140. {
  1141. while ($i < $num)
  1142. {
  1143. $obj = $this->db->fetch_object($resql);
  1144. $label = '';
  1145. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1146. if (($obj->client) && (!empty($obj->code_client))) {
  1147. $label = $obj->code_client.' - ';
  1148. }
  1149. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1150. $label .= $obj->code_fournisseur.' - ';
  1151. }
  1152. $label .= ' '.$obj->name;
  1153. } else {
  1154. $label = $obj->name;
  1155. }
  1156. if (!empty($obj->name_alias)) {
  1157. $label .= ' ('.$obj->name_alias.')';
  1158. }
  1159. if ($showtype)
  1160. {
  1161. if ($obj->client || $obj->fournisseur) $label .= ' (';
  1162. if ($obj->client == 1 || $obj->client == 3) $label .= $langs->trans("Customer");
  1163. if ($obj->client == 2 || $obj->client == 3) $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
  1164. if ($obj->fournisseur) $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
  1165. if ($obj->client || $obj->fournisseur) $label .= ')';
  1166. }
  1167. if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
  1168. $label .= '-'.$obj->address.'-'.$obj->zip.' '.$obj->town;
  1169. if (!empty($obj->country_code)) {
  1170. $label .= ' '.$langs->trans('Country'.$obj->country_code);
  1171. }
  1172. }
  1173. if (empty($outputmode))
  1174. {
  1175. if (in_array($obj->rowid, $selected))
  1176. {
  1177. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1178. } else {
  1179. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1180. }
  1181. } else {
  1182. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1183. }
  1184. $i++;
  1185. if (($i % 10) == 0) $out .= "\n";
  1186. }
  1187. }
  1188. $out .= '</select>'."\n";
  1189. } else {
  1190. dol_print_error($this->db);
  1191. }
  1192. $this->result = array('nbofthirdparties'=>$num);
  1193. if ($outputmode) return $outarray;
  1194. return $out;
  1195. }
  1196. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1197. /**
  1198. * Return HTML combo list of absolute discounts
  1199. *
  1200. * @param string $selected Id remise fixe pre-selectionnee
  1201. * @param string $htmlname Nom champ formulaire
  1202. * @param string $filter Criteres optionnels de filtre
  1203. * @param int $socid Id of thirdparty
  1204. * @param int $maxvalue Max value for lines that can be selected
  1205. * @return int Return number of qualifed lines in list
  1206. */
  1207. public function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
  1208. {
  1209. // phpcs:enable
  1210. global $langs, $conf;
  1211. // On recherche les remises
  1212. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1213. $sql .= " re.description, re.fk_facture_source";
  1214. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  1215. $sql .= " WHERE re.fk_soc = ".(int) $socid;
  1216. $sql .= " AND re.entity = ".$conf->entity;
  1217. if ($filter) $sql .= " AND ".$filter;
  1218. $sql .= " ORDER BY re.description ASC";
  1219. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1220. $resql = $this->db->query($sql);
  1221. if ($resql)
  1222. {
  1223. print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1224. $num = $this->db->num_rows($resql);
  1225. $qualifiedlines = $num;
  1226. $i = 0;
  1227. if ($num)
  1228. {
  1229. print '<option value="0">&nbsp;</option>';
  1230. while ($i < $num)
  1231. {
  1232. $obj = $this->db->fetch_object($resql);
  1233. $desc = dol_trunc($obj->description, 40);
  1234. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1235. if (preg_match('/\(DEPOSIT\)/', $desc)) $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1236. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1237. if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
  1238. $selectstring = '';
  1239. if ($selected > 0 && $selected == $obj->rowid) $selectstring = ' selected';
  1240. $disabled = '';
  1241. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  1242. {
  1243. $qualifiedlines--;
  1244. $disabled = ' disabled';
  1245. }
  1246. if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
  1247. {
  1248. $tmpfac = new Facture($this->db);
  1249. if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc = $desc.' - '.$tmpfac->ref;
  1250. }
  1251. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1252. $i++;
  1253. }
  1254. }
  1255. print '</select>';
  1256. return $qualifiedlines;
  1257. } else {
  1258. dol_print_error($this->db);
  1259. return -1;
  1260. }
  1261. }
  1262. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1263. /**
  1264. * Return list of all contacts (for a third party or all)
  1265. *
  1266. * @param int $socid Id ot third party or 0 for all
  1267. * @param string $selected Id contact pre-selectionne
  1268. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1269. * @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
  1270. * @param string $exclude List of contacts id to exclude
  1271. * @param string $limitto Disable answers that are not id in this array list
  1272. * @param integer $showfunction Add function into label
  1273. * @param string $moreclass Add more class to class style
  1274. * @param integer $showsoc Add company into label
  1275. * @param int $forcecombo Force to use combo box
  1276. * @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')))
  1277. * @param bool $options_only Return options only (for ajax treatment)
  1278. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1279. * @param string $htmlid Html id to use instead of htmlname
  1280. * @return int <0 if KO, Nb of contact in list if OK
  1281. * @deprected You can use selectcontacts directly (warning order of param was changed)
  1282. */
  1283. public function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
  1284. {
  1285. // phpcs:enable
  1286. print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
  1287. return $this->num;
  1288. }
  1289. /**
  1290. * Return HTML code of the SELECT of list of all contacts (for a third party or all).
  1291. * This also set the number of contacts found into $this->num
  1292. *
  1293. * @since 9.0 Add afterSelectContactOptions hook
  1294. *
  1295. * @param int $socid Id ot third party or 0 for all or -1 for empty list
  1296. * @param array|int $selected Array of ID of pre-selected contact id
  1297. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1298. * @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
  1299. * @param string $exclude List of contacts id to exclude
  1300. * @param string $limitto Disable answers that are not id in this array list
  1301. * @param integer $showfunction Add function into label
  1302. * @param string $moreclass Add more class to class style
  1303. * @param bool $options_only Return options only (for ajax treatment)
  1304. * @param integer $showsoc Add company into label
  1305. * @param int $forcecombo Force to use combo box (so no ajax beautify effect)
  1306. * @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')))
  1307. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  1308. * @param string $htmlid Html id to use instead of htmlname
  1309. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1310. * @return int <0 if KO, Nb of contact in list if OK
  1311. */
  1312. public function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false)
  1313. {
  1314. global $conf, $langs, $hookmanager, $action;
  1315. $langs->load('companies');
  1316. if (empty($htmlid)) $htmlid = $htmlname;
  1317. if ($selected === '') $selected = array();
  1318. elseif (!is_array($selected)) $selected = array($selected);
  1319. $out = '';
  1320. if (!is_object($hookmanager))
  1321. {
  1322. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  1323. $hookmanager = new HookManager($this->db);
  1324. }
  1325. // We search third parties
  1326. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
  1327. if ($showsoc > 0) $sql .= " , s.nom as company";
  1328. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
  1329. if ($showsoc > 0) $sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid=sp.fk_soc";
  1330. $sql .= " WHERE sp.entity IN (".getEntity('socpeople').")";
  1331. if ($socid > 0 || $socid == -1) $sql .= " AND sp.fk_soc=".$socid;
  1332. if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND sp.statut <> 0";
  1333. $sql .= " ORDER BY sp.lastname ASC";
  1334. dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
  1335. $resql = $this->db->query($sql);
  1336. if ($resql)
  1337. {
  1338. $num = $this->db->num_rows($resql);
  1339. if ($conf->use_javascript_ajax && !$forcecombo && !$options_only)
  1340. {
  1341. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1342. $out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
  1343. }
  1344. if ($htmlname != 'none' && !$options_only) $out .= '<select class="flat'.($moreclass ? ' '.$moreclass : '').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
  1345. if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
  1346. if ($showempty == 2) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>-- '.$langs->trans("Internal").' --</option>';
  1347. $num = $this->db->num_rows($resql);
  1348. $i = 0;
  1349. if ($num)
  1350. {
  1351. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1352. $contactstatic = new Contact($this->db);
  1353. while ($i < $num)
  1354. {
  1355. $obj = $this->db->fetch_object($resql);
  1356. $contactstatic->id = $obj->rowid;
  1357. $contactstatic->lastname = $obj->lastname;
  1358. $contactstatic->firstname = $obj->firstname;
  1359. if ($obj->statut == 1) {
  1360. if ($htmlname != 'none')
  1361. {
  1362. $disabled = 0;
  1363. if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) $disabled = 1;
  1364. if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) $disabled = 1;
  1365. if (!empty($selected) && in_array($obj->rowid, $selected))
  1366. {
  1367. $out .= '<option value="'.$obj->rowid.'"';
  1368. if ($disabled) $out .= ' disabled';
  1369. $out .= ' selected>';
  1370. $out .= $contactstatic->getFullName($langs);
  1371. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1372. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1373. $out .= '</option>';
  1374. } else {
  1375. $out .= '<option value="'.$obj->rowid.'"';
  1376. if ($disabled) $out .= ' disabled';
  1377. $out .= '>';
  1378. $out .= $contactstatic->getFullName($langs);
  1379. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1380. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1381. $out .= '</option>';
  1382. }
  1383. } else {
  1384. if (in_array($obj->rowid, $selected))
  1385. {
  1386. $out .= $contactstatic->getFullName($langs);
  1387. if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
  1388. if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
  1389. }
  1390. }
  1391. }
  1392. $i++;
  1393. }
  1394. } else {
  1395. $out .= '<option value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled>';
  1396. $out .= ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
  1397. $out .= '</option>';
  1398. }
  1399. $parameters = array(
  1400. 'socid'=>$socid,
  1401. 'htmlname'=>$htmlname,
  1402. 'resql'=>$resql,
  1403. 'out'=>&$out,
  1404. 'showfunction'=>$showfunction,
  1405. 'showsoc'=>$showsoc,
  1406. );
  1407. $reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1408. if ($htmlname != 'none' && !$options_only)
  1409. {
  1410. $out .= '</select>';
  1411. }
  1412. $this->num = $num;
  1413. return $out;
  1414. } else {
  1415. dol_print_error($this->db);
  1416. return -1;
  1417. }
  1418. }
  1419. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1420. /**
  1421. * Return the HTML select list of users
  1422. *
  1423. * @param string $selected Id user preselected
  1424. * @param string $htmlname Field name in form
  1425. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1426. * @param array $exclude Array list of users id to exclude
  1427. * @param int $disabled If select list must be disabled
  1428. * @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
  1429. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1430. * @param string $force_entity '0' or Ids of environment to force
  1431. * @return void
  1432. * @deprecated Use select_dolusers instead
  1433. * @see select_dolusers()
  1434. */
  1435. public function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
  1436. {
  1437. // phpcs:enable
  1438. print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
  1439. }
  1440. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1441. /**
  1442. * Return select list of users
  1443. *
  1444. * @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)
  1445. * @param string $htmlname Field name in form
  1446. * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list
  1447. * @param array $exclude Array list of users id to exclude
  1448. * @param int $disabled If select list must be disabled
  1449. * @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
  1450. * @param array $enableonly Array list of users id to be enabled. If defined, it means that others will be disabled
  1451. * @param string $force_entity '0' or Ids of environment to force
  1452. * @param int $maxlength Maximum length of string into list (0=no limit)
  1453. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1454. * @param string $morefilter Add more filters into sql request (Example: 'employee = 1')
  1455. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1456. * @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.
  1457. * @param string $morecss More css
  1458. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1459. * @param int $outputmode 0=HTML select string, 1=Array
  1460. * @param bool $multiple add [] in the name of element and add 'multiple' attribut
  1461. * @return string HTML select string
  1462. * @see select_dolgroups()
  1463. */
  1464. 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)
  1465. {
  1466. // phpcs:enable
  1467. global $conf, $user, $langs, $hookmanager;
  1468. // If no preselected user defined, we take current user
  1469. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected = $user->id;
  1470. if ($selected === '') $selected = array();
  1471. elseif (!is_array($selected)) $selected = array($selected);
  1472. $excludeUsers = null;
  1473. $includeUsers = null;
  1474. // Permettre l'exclusion d'utilisateurs
  1475. if (is_array($exclude)) $excludeUsers = implode(",", $exclude);
  1476. // Permettre l'inclusion d'utilisateurs
  1477. if (is_array($include)) $includeUsers = implode(",", $include);
  1478. elseif ($include == 'hierarchy')
  1479. {
  1480. // Build list includeUsers to have only hierarchy
  1481. $includeUsers = implode(",", $user->getAllChildIds(0));
  1482. } elseif ($include == 'hierarchyme')
  1483. {
  1484. // Build list includeUsers to have only hierarchy and current user
  1485. $includeUsers = implode(",", $user->getAllChildIds(1));
  1486. }
  1487. $out = '';
  1488. $outarray = array();
  1489. // Forge request to select users
  1490. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
  1491. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  1492. {
  1493. $sql .= ", e.label";
  1494. }
  1495. $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
  1496. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  1497. {
  1498. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=u.entity";
  1499. if ($force_entity) $sql .= " WHERE u.entity IN (0,".$force_entity.")";
  1500. else $sql .= " WHERE u.entity IS NOT NULL";
  1501. } else {
  1502. if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
  1503. {
  1504. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1505. $sql .= " ON ug.fk_user = u.rowid";
  1506. $sql .= " WHERE ug.entity = ".$conf->entity;
  1507. } else {
  1508. $sql .= " WHERE u.entity IN (0,".$conf->entity.")";
  1509. }
  1510. }
  1511. if (!empty($user->socid)) $sql .= " AND u.fk_soc = ".$user->socid;
  1512. if (is_array($exclude) && $excludeUsers) $sql .= " AND u.rowid NOT IN (".$excludeUsers.")";
  1513. if ($includeUsers) $sql .= " AND u.rowid IN (".$includeUsers.")";
  1514. if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql .= " AND u.statut <> 0";
  1515. if (!empty($morefilter)) $sql .= " ".$morefilter;
  1516. //Add hook to filter on user (for exemple on usergroup define in custom modules)
  1517. $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectUsers', array(), $this, $action);
  1518. if (!empty($reshook)) $sql .= $hookmanager->resPrint;
  1519. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
  1520. {
  1521. $sql .= " ORDER BY u.firstname ASC";
  1522. } else {
  1523. $sql .= " ORDER BY u.lastname ASC";
  1524. }
  1525. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1526. $resql = $this->db->query($sql);
  1527. if ($resql)
  1528. {
  1529. $num = $this->db->num_rows($resql);
  1530. $i = 0;
  1531. if ($num)
  1532. {
  1533. // Enhance with select2
  1534. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  1535. $out .= ajax_combobox($htmlname);
  1536. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1537. $out .= '<select class="flat'.($morecss ? ' minwidth100imp '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  1538. if ($show_empty && !$multiple) $out .= '<option value="-1"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>&nbsp;</option>'."\n";
  1539. if ($show_every) $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1540. $userstatic = new User($this->db);
  1541. while ($i < $num)
  1542. {
  1543. $obj = $this->db->fetch_object($resql);
  1544. $userstatic->id = $obj->rowid;
  1545. $userstatic->lastname = $obj->lastname;
  1546. $userstatic->firstname = $obj->firstname;
  1547. $disableline = '';
  1548. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = ($enableonlytext ? $enableonlytext : '1');
  1549. if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected)))
  1550. {
  1551. $out .= '<option value="'.$obj->rowid.'"';
  1552. if ($disableline) $out .= ' disabled';
  1553. $out .= ' selected>';
  1554. } else {
  1555. $out .= '<option value="'.$obj->rowid.'"';
  1556. if ($disableline) $out .= ' disabled';
  1557. $out .= '>';
  1558. }
  1559. // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
  1560. $fullNameMode = 0;
  1561. if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
  1562. {
  1563. $fullNameMode = 1; //Firstname+lastname
  1564. }
  1565. $out .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1566. // Complete name with more info
  1567. $moreinfo = '';
  1568. if (!empty($conf->global->MAIN_SHOW_LOGIN))
  1569. {
  1570. $moreinfo .= ($moreinfo ? ' - ' : ' (').$obj->login;
  1571. }
  1572. if ($showstatus >= 0)
  1573. {
  1574. if ($obj->statut == 1 && $showstatus == 1)
  1575. {
  1576. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
  1577. }
  1578. if ($obj->statut == 0)
  1579. {
  1580. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
  1581. }
  1582. }
  1583. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity)
  1584. {
  1585. if (!$obj->entity)
  1586. {
  1587. $moreinfo .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
  1588. } else {
  1589. $moreinfo .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
  1590. }
  1591. }
  1592. $moreinfo .= ($moreinfo ? ')' : '');
  1593. if ($disableline && $disableline != '1')
  1594. {
  1595. $moreinfo .= ' - '.$disableline; // This is text from $enableonlytext parameter
  1596. }
  1597. $out .= $moreinfo;
  1598. $out .= '</option>';
  1599. $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength).$moreinfo;
  1600. $i++;
  1601. }
  1602. } else {
  1603. $out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1604. $out .= '<option value="">'.$langs->trans("None").'</option>';
  1605. }
  1606. $out .= '</select>';
  1607. } else {
  1608. dol_print_error($this->db);
  1609. }
  1610. if ($outputmode) return $outarray;
  1611. return $out;
  1612. }
  1613. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1614. /**
  1615. * Return select list of users. Selected users are stored into session.
  1616. * List of users are provided into $_SESSION['assignedtouser'].
  1617. *
  1618. * @param string $action Value for $action
  1619. * @param string $htmlname Field name in form
  1620. * @param int $show_empty 0=list without the empty value, 1=add empty value
  1621. * @param array $exclude Array list of users id to exclude
  1622. * @param int $disabled If select list must be disabled
  1623. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1624. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1625. * @param int $force_entity '0' or Ids of environment to force
  1626. * @param int $maxlength Maximum length of string into list (0=no limit)
  1627. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1628. * @param string $morefilter Add more filters into sql request
  1629. * @param int $showproperties Show properties of each attendees
  1630. * @param array $listofuserid Array with properties of each user
  1631. * @param array $listofcontactid Array with properties of each contact
  1632. * @param array $listofotherid Array with properties of each other contact
  1633. * @return string HTML select string
  1634. * @see select_dolgroups()
  1635. */
  1636. 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())
  1637. {
  1638. // phpcs:enable
  1639. global $conf, $user, $langs;
  1640. $userstatic = new User($this->db);
  1641. $out = '';
  1642. // Method with no ajax
  1643. //$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  1644. if ($action == 'view')
  1645. {
  1646. $out .= '';
  1647. } else {
  1648. $out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1649. $out .= '<script type="text/javascript" language="javascript">jQuery(document).ready(function () { jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });})</script>';
  1650. $out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1651. $out .= ' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1652. $out .= '<br>';
  1653. }
  1654. $assignedtouser = array();
  1655. if (!empty($_SESSION['assignedtouser']))
  1656. {
  1657. $assignedtouser = json_decode($_SESSION['assignedtouser'], true);
  1658. }
  1659. $nbassignetouser = count($assignedtouser);
  1660. if ($nbassignetouser && $action != 'view') $out .= '<br>';
  1661. if ($nbassignetouser) $out .= '<ul class="attendees">';
  1662. $i = 0; $ownerid = 0;
  1663. foreach ($assignedtouser as $key => $value)
  1664. {
  1665. if ($value['id'] == $ownerid) continue;
  1666. $out .= '<li>';
  1667. $userstatic->fetch($value['id']);
  1668. $out .= $userstatic->getNomUrl(-1);
  1669. if ($i == 0) { $ownerid = $value['id']; $out .= ' ('.$langs->trans("Owner").')'; }
  1670. if ($nbassignetouser > 1 && $action != 'view')
  1671. {
  1672. $out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
  1673. }
  1674. // Show my availability
  1675. if ($showproperties)
  1676. {
  1677. if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
  1678. {
  1679. $out .= '<div class="myavailability inline-block">';
  1680. $out .= '&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span> <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view' ? 'disabled' : '').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency'] ? ' checked' : '').'>'.$langs->trans("Busy");
  1681. $out .= '</div>';
  1682. }
  1683. }
  1684. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1685. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1686. $out .= '</li>';
  1687. $i++;
  1688. }
  1689. if ($nbassignetouser) $out .= '</ul>';
  1690. //$out.='</form>';
  1691. return $out;
  1692. }
  1693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1694. /**
  1695. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1696. *
  1697. * @param int $selected Preselected products
  1698. * @param string $htmlname Name of HTML select field (must be unique in page)
  1699. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1700. * @param int $limit Limit on number of returned lines
  1701. * @param int $price_level Level of price to show
  1702. * @param int $status Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1703. * @param int $finished 2=all, 1=finished, 0=raw material
  1704. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1705. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1706. * @param array $ajaxoptions Options for ajax_autocompleter
  1707. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1708. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1709. * @param int $forcecombo Force to use combo box
  1710. * @param string $morecss Add more css on select
  1711. * @param int $hidepriceinlabel 1=Hide prices in label
  1712. * @param string $warehouseStatus Warehouse status filter to count the quantity in stock. Following comma separated filter options can be used
  1713. * 'warehouseopen' = count products from open warehouses,
  1714. * 'warehouseclosed' = count products from closed warehouses,
  1715. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  1716. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  1717. * @return void
  1718. */
  1719. public function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $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 = array())
  1720. {
  1721. // phpcs:enable
  1722. global $langs, $conf;
  1723. // check parameters
  1724. $price_level = (!empty($price_level) ? $price_level : 0);
  1725. if (is_null($ajaxoptions)) $ajaxoptions = array();
  1726. if (strval($filtertype) === '' && (!empty($conf->product->enabled) || !empty($conf->service->enabled))) {
  1727. if (!empty($conf->product->enabled) && empty($conf->service->enabled)) {
  1728. $filtertype = '0';
  1729. } elseif (empty($conf->product->enabled) && !empty($conf->service->enabled)) {
  1730. $filtertype = '1';
  1731. }
  1732. }
  1733. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1734. {
  1735. $placeholder = '';
  1736. if ($selected && empty($selected_input_value))
  1737. {
  1738. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1739. $producttmpselect = new Product($this->db);
  1740. $producttmpselect->fetch($selected);
  1741. $selected_input_value = $producttmpselect->ref;
  1742. unset($producttmpselect);
  1743. }
  1744. // handle case where product or service module is disabled + no filter specified
  1745. if ($filtertype == '')
  1746. {
  1747. if (empty($conf->product->enabled)) { // when product module is disabled, show services only
  1748. $filtertype = 1;
  1749. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  1750. $filtertype = 0;
  1751. }
  1752. }
  1753. // mode=1 means customers products
  1754. $urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
  1755. //Price by customer
  1756. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1757. $urloption .= '&socid='.$socid;
  1758. }
  1759. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1760. if (!empty($conf->variants->enabled)) {
  1761. ?>
  1762. <script>
  1763. selected = <?php echo json_encode($selected_combinations) ?>;
  1764. combvalues = {};
  1765. jQuery(document).ready(function () {
  1766. jQuery("input[name='prod_entry_mode']").change(function () {
  1767. if (jQuery(this).val() == 'free') {
  1768. jQuery('div#attributes_box').empty();
  1769. }
  1770. });
  1771. jQuery("input#<?php echo $htmlname ?>").change(function () {
  1772. if (!jQuery(this).val()) {
  1773. jQuery('div#attributes_box').empty();
  1774. return;
  1775. }
  1776. jQuery.getJSON("<?php echo dol_buildpath('/variants/ajax/getCombinations.php', 2) ?>", {
  1777. id: jQuery(this).val()
  1778. }, function (data) {
  1779. jQuery('div#attributes_box').empty();
  1780. jQuery.each(data, function (key, val) {
  1781. combvalues[val.id] = val.values;
  1782. var span = jQuery(document.createElement('div')).css({
  1783. 'display': 'table-row'
  1784. });
  1785. span.append(
  1786. jQuery(document.createElement('div')).text(val.label).css({
  1787. 'font-weight': 'bold',
  1788. 'display': 'table-cell',
  1789. 'text-align': 'right'
  1790. })
  1791. );
  1792. var html = jQuery(document.createElement('select')).attr('name', 'combinations[' + val.id + ']').css({
  1793. 'margin-left': '15px',
  1794. 'white-space': 'pre'
  1795. }).append(
  1796. jQuery(document.createElement('option')).val('')
  1797. );
  1798. jQuery.each(combvalues[val.id], function (key, val) {
  1799. var tag = jQuery(document.createElement('option')).val(val.id).html(val.value);
  1800. if (selected[val.fk_product_attribute] == val.id) {
  1801. tag.attr('selected', 'selected');
  1802. }
  1803. html.append(tag);
  1804. });
  1805. span.append(html);
  1806. jQuery('div#attributes_box').append(span);
  1807. });
  1808. })
  1809. });
  1810. <?php if ($selected): ?>
  1811. jQuery("input#<?php echo $htmlname ?>").change();
  1812. <?php endif ?>
  1813. });
  1814. </script>
  1815. <?php
  1816. }
  1817. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1818. elseif ($hidelabel > 1) {
  1819. $placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
  1820. if ($hidelabel == 2) {
  1821. print img_picto($langs->trans("Search"), 'search');
  1822. }
  1823. }
  1824. print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1825. if ($hidelabel == 3) {
  1826. print img_picto($langs->trans("Search"), 'search');
  1827. }
  1828. } else {
  1829. print $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus);
  1830. }
  1831. }
  1832. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1833. /**
  1834. * Return list of products for a customer
  1835. *
  1836. * @param int $selected Preselected product
  1837. * @param string $htmlname Name of select html
  1838. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1839. * @param int $limit Limit on number of returned lines
  1840. * @param int $price_level Level of price to show
  1841. * @param string $filterkey Filter on product
  1842. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1843. * @param int $finished Filter on finished field: 2=No filter
  1844. * @param int $outputmode 0=HTML select string, 1=Array
  1845. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1846. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1847. * @param int $forcecombo Force to use combo box
  1848. * @param string $morecss Add more css on select
  1849. * @param int $hidepriceinlabel 1=Hide prices in label
  1850. * @param string $warehouseStatus Warehouse status filter to group/count stock. Following comma separated filter options can be used.
  1851. * 'warehouseopen' = count products from open warehouses,
  1852. * 'warehouseclosed' = count products from closed warehouses,
  1853. * 'warehouseinternal' = count products from warehouses for internal correct/transfer only
  1854. * @return array Array of keys for json
  1855. */
  1856. 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 = '')
  1857. {
  1858. // phpcs:enable
  1859. global $langs, $conf, $user, $db;
  1860. $out = '';
  1861. $outarray = array();
  1862. // Units
  1863. if ($conf->global->PRODUCT_USE_UNITS) {
  1864. $langs->load('other');
  1865. }
  1866. $warehouseStatusArray = array();
  1867. if (!empty($warehouseStatus))
  1868. {
  1869. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  1870. if (preg_match('/warehouseclosed/', $warehouseStatus))
  1871. {
  1872. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  1873. }
  1874. if (preg_match('/warehouseopen/', $warehouseStatus))
  1875. {
  1876. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  1877. }
  1878. if (preg_match('/warehouseinternal/', $warehouseStatus))
  1879. {
  1880. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  1881. }
  1882. }
  1883. $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.duration, p.fk_price_expression";
  1884. if (count($warehouseStatusArray))
  1885. {
  1886. $selectFieldsGrouped = ", sum(".$db->ifsql("e.statut IS NULL", "0", "ps.reel").") as stock"; // e.statut is null if there is no record in stock
  1887. } else {
  1888. $selectFieldsGrouped = ", ".$db->ifsql("p.stock IS NULL", 0, "p.stock")." AS stock";
  1889. }
  1890. $sql = "SELECT ";
  1891. $sql .= $selectFields.$selectFieldsGrouped;
  1892. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
  1893. {
  1894. //Product category
  1895. $sql .= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
  1896. FROM ".MAIN_DB_PREFIX."categorie_product
  1897. WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
  1898. LIMIT 1
  1899. ) AS categorie_product_id ";
  1900. }
  1901. //Price by customer
  1902. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
  1903. {
  1904. $sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  1905. $sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
  1906. $selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
  1907. }
  1908. // Units
  1909. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1910. $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";
  1911. $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';
  1912. }
  1913. // Multilang : we add translation
  1914. if (!empty($conf->global->MAIN_MULTILANGS))
  1915. {
  1916. $sql .= ", pl.label as label_translated";
  1917. $selectFields .= ", label_translated";
  1918. }
  1919. // Price by quantity
  1920. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
  1921. {
  1922. $sql .= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1923. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
  1924. $sql .= " ORDER BY date_price";
  1925. $sql .= " DESC LIMIT 1) as price_rowid";
  1926. $sql .= ", (SELECT pp.price_by_qty FROM ".MAIN_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
  1927. if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
  1928. $sql .= " ORDER BY date_price";
  1929. $sql .= " DESC LIMIT 1) as price_by_qty";
  1930. $selectFields .= ", price_rowid, price_by_qty";
  1931. }
  1932. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  1933. if (count($warehouseStatusArray))
  1934. {
  1935. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  1936. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid AND e.entity IN (".getEntity('stock').")";
  1937. $sql .= ' AND e.statut IN ('.$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.
  1938. }
  1939. // include search in supplier ref
  1940. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
  1941. {
  1942. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  1943. }
  1944. //Price by customer
  1945. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1946. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
  1947. }
  1948. // Units
  1949. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  1950. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  1951. }
  1952. // Multilang : we add translation
  1953. if (!empty($conf->global->MAIN_MULTILANGS))
  1954. {
  1955. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='".$langs->getDefaultLang()."'";
  1956. }
  1957. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1958. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  1959. }
  1960. $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
  1961. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1962. $sql .= " AND pac.rowid IS NULL";
  1963. }
  1964. if ($finished == 0)
  1965. {
  1966. $sql .= " AND p.finished = ".$finished;
  1967. } elseif ($finished == 1)
  1968. {
  1969. $sql .= " AND p.finished = ".$finished;
  1970. if ($status >= 0) $sql .= " AND p.tosell = ".$status;
  1971. } elseif ($status >= 0)
  1972. {
  1973. $sql .= " AND p.tosell = ".$status;
  1974. }
  1975. // Filter by product type
  1976. if (strval($filtertype) != '') $sql .= " AND p.fk_product_type = ".$filtertype;
  1977. elseif (empty($conf->product->enabled)) { // when product module is disabled, show services only
  1978. $sql .= " AND p.fk_product_type = 1";
  1979. } elseif (empty($conf->service->enabled)) { // when service module is disabled, show products only
  1980. $sql .= " AND p.fk_product_type = 0";
  1981. }
  1982. // Add criteria on ref/label
  1983. if ($filterkey != '')
  1984. {
  1985. $sql .= ' AND (';
  1986. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  1987. // For natural search
  1988. $scrit = explode(' ', $filterkey);
  1989. $i = 0;
  1990. if (count($scrit) > 1) $sql .= "(";
  1991. foreach ($scrit as $crit)
  1992. {
  1993. if ($i > 0) $sql .= " AND ";
  1994. $sql .= "(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
  1995. if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
  1996. if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
  1997. {
  1998. $sql .= " OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
  1999. if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
  2000. }
  2001. if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql .= " OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
  2002. $sql .= ")";
  2003. $i++;
  2004. }
  2005. if (count($scrit) > 1) $sql .= ")";
  2006. if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
  2007. $sql .= ')';
  2008. }
  2009. if (count($warehouseStatusArray))
  2010. {
  2011. $sql .= ' GROUP BY'.$selectFields;
  2012. }
  2013. //Sort by category
  2014. if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
  2015. {
  2016. $sql .= " ORDER BY categorie_product_id ";
  2017. //ASC OR DESC order
  2018. ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
  2019. } else {
  2020. $sql .= $db->order("p.ref");
  2021. }
  2022. $sql .= $db->plimit($limit, 0);
  2023. // Build output string
  2024. dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
  2025. $result = $this->db->query($sql);
  2026. if ($result)
  2027. {
  2028. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2029. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2030. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2031. $num = $this->db->num_rows($result);
  2032. $events = null;
  2033. if (!$forcecombo)
  2034. {
  2035. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2036. $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  2037. }
  2038. $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  2039. $textifempty = '';
  2040. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  2041. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  2042. if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2043. {
  2044. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  2045. else $textifempty .= $langs->trans("All");
  2046. } else {
  2047. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  2048. }
  2049. if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
  2050. $i = 0;
  2051. while ($num && $i < $num)
  2052. {
  2053. $opt = '';
  2054. $optJson = array();
  2055. $objp = $this->db->fetch_object($result);
  2056. 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)
  2057. { // Price by quantity will return many prices for the same product
  2058. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
  2059. $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  2060. $sql .= " WHERE fk_product_price=".$objp->price_rowid;
  2061. $sql .= " ORDER BY quantity ASC";
  2062. dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
  2063. $result2 = $this->db->query($sql);
  2064. if ($result2)
  2065. {
  2066. $nb_prices = $this->db->num_rows($result2);
  2067. $j = 0;
  2068. while ($nb_prices && $j < $nb_prices) {
  2069. $objp2 = $this->db->fetch_object($result2);
  2070. $objp->price_by_qty_rowid = $objp2->rowid;
  2071. $objp->price_by_qty_price_base_type = $objp2->price_base_type;
  2072. $objp->price_by_qty_quantity = $objp2->quantity;
  2073. $objp->price_by_qty_unitprice = $objp2->unitprice;
  2074. $objp->price_by_qty_remise_percent = $objp2->remise_percent;
  2075. // For backward compatibility
  2076. $objp->quantity = $objp2->quantity;
  2077. $objp->price = $objp2->price;
  2078. $objp->unitprice = $objp2->unitprice;
  2079. $objp->remise_percent = $objp2->remise_percent;
  2080. $objp->remise = $objp2->remise;
  2081. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel, $filterkey);
  2082. $j++;
  2083. // Add new entry
  2084. // "key" value of json key array is used by jQuery automatically as selected value
  2085. // "label" value of json key array is used by jQuery automatically as text for combo box
  2086. $out .= $opt;
  2087. array_push($outarray, $optJson);
  2088. }
  2089. }
  2090. } else {
  2091. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  2092. $price_product = new Product($this->db);
  2093. $price_product->fetch($objp->rowid, '', '', 1);
  2094. $priceparser = new PriceParser($this->db);
  2095. $price_result = $priceparser->parseProduct($price_product);
  2096. if ($price_result >= 0) {
  2097. $objp->price = $price_result;
  2098. $objp->unitprice = $price_result;
  2099. //Calculate the VAT
  2100. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  2101. $objp->price_ttc = price2num($objp->price_ttc, 'MU');
  2102. }
  2103. }
  2104. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel, $filterkey);
  2105. // Add new entry
  2106. // "key" value of json key array is used by jQuery automatically as selected value
  2107. // "label" value of json key array is used by jQuery automatically as text for combo box
  2108. $out .= $opt;
  2109. array_push($outarray, $optJson);
  2110. }
  2111. $i++;
  2112. }
  2113. $out .= '</select>';
  2114. $this->db->free($result);
  2115. if (empty($outputmode)) return $out;
  2116. return $outarray;
  2117. } else {
  2118. dol_print_error($db);
  2119. }
  2120. }
  2121. /**
  2122. * constructProductListOption.
  2123. * This define value for &$opt and &$optJson.
  2124. *
  2125. * @param resource $objp Resultset of fetch
  2126. * @param string $opt Option (var used for returned value in string option format)
  2127. * @param string $optJson Option (var used for returned value in json format)
  2128. * @param int $price_level Price level
  2129. * @param string $selected Preselected value
  2130. * @param int $hidepriceinlabel Hide price in label
  2131. * @param string $filterkey Filter key to highlight
  2132. * @param int $novirtualstock Do not load virtual stock, even if slow option STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO is on.
  2133. * @return void
  2134. */
  2135. protected function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0, $filterkey = '', $novirtualstock = 0)
  2136. {
  2137. global $langs, $conf, $user, $db;
  2138. $outkey = '';
  2139. $outval = '';
  2140. $outref = '';
  2141. $outlabel = '';
  2142. $outdesc = '';
  2143. $outbarcode = '';
  2144. $outorigin = '';
  2145. $outtype = '';
  2146. $outprice_ht = '';
  2147. $outprice_ttc = '';
  2148. $outpricebasetype = '';
  2149. $outtva_tx = '';
  2150. $outqty = 1;
  2151. $outdiscount = 0;
  2152. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2153. $label = $objp->label;
  2154. if (!empty($objp->label_translated)) $label = $objp->label_translated;
  2155. if (!empty($filterkey) && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2156. $outkey = $objp->rowid;
  2157. $outref = $objp->ref;
  2158. $outlabel = $objp->label;
  2159. $outdesc = $objp->description;
  2160. $outbarcode = $objp->barcode;
  2161. $outorigin = $objp->fk_country;
  2162. $outpbq = empty($objp->price_by_qty_rowid) ? '' : $objp->price_by_qty_rowid;
  2163. $outtype = $objp->fk_product_type;
  2164. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2165. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2166. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2167. // Units
  2168. $outvalUnits = '';
  2169. if (!empty($conf->global->PRODUCT_USE_UNITS)) {
  2170. if (!empty($objp->unit_short)) {
  2171. $outvalUnits .= ' - '.$objp->unit_short;
  2172. }
  2173. }
  2174. if (!empty($conf->global->PRODUCT_SHOW_DIMENSIONS_IN_COMBO)) {
  2175. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2176. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2177. $outvalUnits .= ' - '.$unitToShow;
  2178. }
  2179. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2180. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2181. $outvalUnits .= ' - '.$unitToShow;
  2182. }
  2183. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2184. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2185. $outvalUnits .= ' - '.$unitToShow;
  2186. }
  2187. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2188. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2189. $outvalUnits .= ' - '.$unitToShow;
  2190. }
  2191. }
  2192. if ($outdurationvalue && $outdurationunit) {
  2193. $da = array(
  2194. 'h' => $langs->trans('Hour'),
  2195. 'd' => $langs->trans('Day'),
  2196. 'w' => $langs->trans('Week'),
  2197. 'm' => $langs->trans('Month'),
  2198. 'y' => $langs->trans('Year')
  2199. );
  2200. if (isset($da[$outdurationunit])) {
  2201. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2202. }
  2203. }
  2204. $opt = '<option value="'.$objp->rowid.'"';
  2205. $opt .= ($objp->rowid == $selected) ? ' selected' : '';
  2206. if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
  2207. {
  2208. $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.'"';
  2209. }
  2210. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)))
  2211. {
  2212. if (!empty($user->rights->stock->lire)) {
  2213. if ($objp->stock > 0) $opt .= ' class="product_line_stock_ok"';
  2214. elseif ($objp->stock <= 0) $opt .= ' class="product_line_stock_too_low"';
  2215. }
  2216. }
  2217. $opt .= '>';
  2218. $opt .= $objp->ref;
  2219. if ($outbarcode) $opt .= ' ('.$outbarcode.')';
  2220. $opt .= ' - '.dol_trunc($label, $maxlengtharticle);
  2221. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) $opt .= ' ('.getCountry($outorigin, 1).')';
  2222. $objRef = $objp->ref;
  2223. if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2224. $outval .= $objRef;
  2225. if ($outbarcode) $outval .= ' ('.$outbarcode.')';
  2226. $outval .= ' - '.dol_trunc($label, $maxlengtharticle);
  2227. if ($outorigin && !empty($conf->global->PRODUCT_SHOW_ORIGIN_IN_COMBO)) $outval .= ' ('.getCountry($outorigin, 1).')';
  2228. // Units
  2229. $opt .= $outvalUnits;
  2230. $outval .= $outvalUnits;
  2231. $found = 0;
  2232. // Multiprice
  2233. // If we need a particular price level (from 1 to 6)
  2234. if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
  2235. {
  2236. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  2237. $sql .= " FROM ".MAIN_DB_PREFIX."product_price";
  2238. $sql .= " WHERE fk_product='".$objp->rowid."'";
  2239. $sql .= " AND entity IN (".getEntity('productprice').")";
  2240. $sql .= " AND price_level=".$price_level;
  2241. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  2242. $sql .= " LIMIT 1";
  2243. dol_syslog(get_class($this).'::constructProductListOption search price for product '.$objp->rowid.' AND level '.$price_level.'', LOG_DEBUG);
  2244. $result2 = $this->db->query($sql);
  2245. if ($result2)
  2246. {
  2247. $objp2 = $this->db->fetch_object($result2);
  2248. if ($objp2)
  2249. {
  2250. $found = 1;
  2251. if ($objp2->price_base_type == 'HT')
  2252. {
  2253. $opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2254. $outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2255. } else {
  2256. $opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2257. $outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2258. }
  2259. $outprice_ht = price($objp2->price);
  2260. $outprice_ttc = price($objp2->price_ttc);
  2261. $outpricebasetype = $objp2->price_base_type;
  2262. $outtva_tx = $objp2->tva_tx;
  2263. }
  2264. } else {
  2265. dol_print_error($this->db);
  2266. }
  2267. }
  2268. // Price by quantity
  2269. 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)))
  2270. {
  2271. $found = 1;
  2272. $outqty = $objp->quantity;
  2273. $outdiscount = $objp->remise_percent;
  2274. if ($objp->quantity == 1)
  2275. {
  2276. $opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
  2277. $outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
  2278. $opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2279. $outval .= $langs->transnoentities("Unit");
  2280. } else {
  2281. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2282. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
  2283. $opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2284. $outval .= $langs->transnoentities("Units");
  2285. }
  2286. $outprice_ht = price($objp->unitprice);
  2287. $outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  2288. $outpricebasetype = $objp->price_base_type;
  2289. $outtva_tx = $objp->tva_tx;
  2290. }
  2291. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
  2292. {
  2293. $opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2294. $outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2295. }
  2296. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
  2297. {
  2298. $opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2299. $outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2300. }
  2301. // Price by customer
  2302. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  2303. {
  2304. if (!empty($objp->idprodcustprice))
  2305. {
  2306. $found = 1;
  2307. if ($objp->custprice_base_type == 'HT')
  2308. {
  2309. $opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2310. $outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2311. } else {
  2312. $opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2313. $outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2314. }
  2315. $outprice_ht = price($objp->custprice);
  2316. $outprice_ttc = price($objp->custprice_ttc);
  2317. $outpricebasetype = $objp->custprice_base_type;
  2318. $outtva_tx = $objp->custtva_tx;
  2319. }
  2320. }
  2321. // If level no defined or multiprice not found, we used the default price
  2322. if (empty($hidepriceinlabel) && !$found)
  2323. {
  2324. if ($objp->price_base_type == 'HT')
  2325. {
  2326. $opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
  2327. $outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
  2328. } else {
  2329. $opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
  2330. $outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
  2331. }
  2332. $outprice_ht = price($objp->price);
  2333. $outprice_ttc = price($objp->price_ttc);
  2334. $outpricebasetype = $objp->price_base_type;
  2335. $outtva_tx = $objp->tva_tx;
  2336. }
  2337. if (!empty($conf->stock->enabled) && isset($objp->stock) && ($objp->fk_product_type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)))
  2338. {
  2339. if (!empty($user->rights->stock->lire)) {
  2340. $opt .= ' - '.$langs->trans("Stock").':'.$objp->stock;
  2341. if ($objp->stock > 0) {
  2342. $outval .= ' - <span class="product_line_stock_ok">';
  2343. } elseif ($objp->stock <= 0) {
  2344. $outval .= ' - <span class="product_line_stock_too_low">';
  2345. }
  2346. $outval .= $langs->transnoentities("Stock").':'.$objp->stock;
  2347. $outval .= '</span>';
  2348. if (empty($novirtualstock) && !empty($conf->global->STOCK_SHOW_VIRTUAL_STOCK_IN_PRODUCTS_COMBO)) // Warning, this option may slow down combo list generation
  2349. {
  2350. $langs->load("stocks");
  2351. $tmpproduct = new Product($this->db);
  2352. $tmpproduct->fetch($objp->rowid, '', '', '', 1, 1, 1); // Load product without lang and prices arrays (we just need to make ->virtual_stock() after)
  2353. $tmpproduct->load_virtual_stock();
  2354. $virtualstock = $tmpproduct->stock_theorique;
  2355. $opt .= ' - '.$langs->trans("VirtualStock").':'.$virtualstock;
  2356. $outval .= ' - '.$langs->transnoentities("VirtualStock").':';
  2357. if ($virtualstock > 0) {
  2358. $outval .= '<span class="product_line_stock_ok">';
  2359. } elseif ($virtualstock <= 0) {
  2360. $outval .= '<span class="product_line_stock_too_low">';
  2361. }
  2362. $outval .= $virtualstock;
  2363. $outval .= '</span>';
  2364. unset($tmpproduct);
  2365. }
  2366. }
  2367. }
  2368. $opt .= "</option>\n";
  2369. $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>price2num($outprice_ht), 'price_ttc'=>price2num($outprice_ttc), 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'pbq'=>$outpbq);
  2370. }
  2371. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2372. /**
  2373. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2374. *
  2375. * @param int $socid Id third party
  2376. * @param string $selected Preselected product
  2377. * @param string $htmlname Name of HTML Select
  2378. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2379. * @param string $filtre For a SQL filter
  2380. * @param array $ajaxoptions Options for ajax_autocompleter
  2381. * @param int $hidelabel Hide label (0=no, 1=yes)
  2382. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2383. * @param string $morecss More CSS
  2384. * @return void
  2385. */
  2386. public function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0, $morecss = '')
  2387. {
  2388. // phpcs:enable
  2389. global $langs, $conf;
  2390. global $price_level, $status, $finished;
  2391. $selected_input_value = '';
  2392. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2393. {
  2394. if ($selected > 0)
  2395. {
  2396. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2397. $producttmpselect = new Product($this->db);
  2398. $producttmpselect->fetch($selected);
  2399. $selected_input_value = $producttmpselect->ref;
  2400. unset($producttmpselect);
  2401. }
  2402. // mode=2 means suppliers products
  2403. $urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2404. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2405. print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
  2406. } else {
  2407. print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', -1, 0, 0, $alsoproductwithnosupplierprice, $morecss);
  2408. }
  2409. }
  2410. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2411. /**
  2412. * Return list of suppliers products
  2413. *
  2414. * @param int $socid Id societe fournisseur (0 pour aucun filtre)
  2415. * @param int $selected Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
  2416. * @param string $htmlname Nom de la zone select
  2417. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2418. * @param string $filtre Pour filtre sql
  2419. * @param string $filterkey Filtre des produits
  2420. * @param int $statut -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
  2421. * @param int $outputmode 0=HTML select string, 1=Array
  2422. * @param int $limit Limit of line number
  2423. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2424. * @param string $morecss Add more CSS
  2425. * @return array Array of keys for json
  2426. */
  2427. public function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0, $morecss = '')
  2428. {
  2429. // phpcs:enable
  2430. global $langs, $conf, $db;
  2431. $out = '';
  2432. $outarray = array();
  2433. $maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
  2434. $langs->load('stocks');
  2435. // Units
  2436. if ($conf->global->PRODUCT_USE_UNITS) {
  2437. $langs->load('other');
  2438. }
  2439. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, p.fk_product_type,";
  2440. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2441. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  2442. $sql .= " pfp.supplier_reputation";
  2443. // Units
  2444. if ($conf->global->PRODUCT_USE_UNITS) {
  2445. $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";
  2446. }
  2447. if (!empty($conf->barcode->enabled)) $sql .= ", pfp.barcode";
  2448. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2449. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON ( p.rowid = pfp.fk_product AND pfp.entity IN (".getEntity('product').") )";
  2450. if ($socid) $sql .= " AND pfp.fk_soc = ".$socid;
  2451. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2452. // Units
  2453. if ($conf->global->PRODUCT_USE_UNITS) {
  2454. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_units u ON u.rowid = p.fk_unit";
  2455. }
  2456. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  2457. $sql .= " AND p.tobuy = 1";
  2458. if (strval($filtertype) != '') $sql .= " AND p.fk_product_type=".$this->db->escape($filtertype);
  2459. if (!empty($filtre)) $sql .= " ".$filtre;
  2460. // Add criteria on ref/label
  2461. if ($filterkey != '')
  2462. {
  2463. $sql .= ' AND (';
  2464. $prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2465. // For natural search
  2466. $scrit = explode(' ', $filterkey);
  2467. $i = 0;
  2468. if (count($scrit) > 1) $sql .= "(";
  2469. foreach ($scrit as $crit)
  2470. {
  2471. if ($i > 0) $sql .= " AND ";
  2472. $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)."%')";
  2473. $i++;
  2474. }
  2475. if (count($scrit) > 1) $sql .= ")";
  2476. if (!empty($conf->barcode->enabled)) {
  2477. $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2478. $sql .= " OR pfp.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2479. }
  2480. $sql .= ')';
  2481. }
  2482. $sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2483. $sql .= $db->plimit($limit, 0);
  2484. // Build output string
  2485. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2486. $result = $this->db->query($sql);
  2487. if ($result)
  2488. {
  2489. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2490. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  2491. $num = $this->db->num_rows($result);
  2492. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2493. $out .= '<select class="flat maxwidthonsmartphone'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  2494. if (!$selected) $out .= '<option value="0" selected>&nbsp;</option>';
  2495. else $out .= '<option value="0">&nbsp;</option>';
  2496. $i = 0;
  2497. while ($i < $num)
  2498. {
  2499. $objp = $this->db->fetch_object($result);
  2500. $outkey = $objp->idprodfournprice; // id in table of price
  2501. if (!$outkey && $alsoproductwithnosupplierprice) $outkey = 'idprod_'.$objp->rowid; // id of product
  2502. $outref = $objp->ref;
  2503. $outval = '';
  2504. $outbarcode = $objp->barcode;
  2505. $outqty = 1;
  2506. $outdiscount = 0;
  2507. $outtype = $objp->fk_product_type;
  2508. $outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
  2509. $outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
  2510. // Units
  2511. $outvalUnits = '';
  2512. if ($conf->global->PRODUCT_USE_UNITS) {
  2513. if (!empty($objp->unit_short)) {
  2514. $outvalUnits .= ' - '.$objp->unit_short;
  2515. }
  2516. if (!empty($objp->weight) && $objp->weight_units !== null) {
  2517. $unitToShow = showDimensionInBestUnit($objp->weight, $objp->weight_units, 'weight', $langs);
  2518. $outvalUnits .= ' - '.$unitToShow;
  2519. }
  2520. if ((!empty($objp->length) || !empty($objp->width) || !empty($objp->height)) && $objp->length_units !== null) {
  2521. $unitToShow = $objp->length.' x '.$objp->width.' x '.$objp->height.' '.measuringUnitString(0, 'size', $objp->length_units);
  2522. $outvalUnits .= ' - '.$unitToShow;
  2523. }
  2524. if (!empty($objp->surface) && $objp->surface_units !== null) {
  2525. $unitToShow = showDimensionInBestUnit($objp->surface, $objp->surface_units, 'surface', $langs);
  2526. $outvalUnits .= ' - '.$unitToShow;
  2527. }
  2528. if (!empty($objp->volume) && $objp->volume_units !== null) {
  2529. $unitToShow = showDimensionInBestUnit($objp->volume, $objp->volume_units, 'volume', $langs);
  2530. $outvalUnits .= ' - '.$unitToShow;
  2531. }
  2532. if ($outdurationvalue && $outdurationunit) {
  2533. $da = array(
  2534. 'h' => $langs->trans('Hour'),
  2535. 'd' => $langs->trans('Day'),
  2536. 'w' => $langs->trans('Week'),
  2537. 'm' => $langs->trans('Month'),
  2538. 'y' => $langs->trans('Year')
  2539. );
  2540. if (isset($da[$outdurationunit])) {
  2541. $outvalUnits .= ' - '.$outdurationvalue.' '.$langs->transnoentities($da[$outdurationunit].($outdurationvalue > 1 ? 's' : ''));
  2542. }
  2543. }
  2544. }
  2545. $objRef = $objp->ref;
  2546. if ($filterkey && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRef, 1);
  2547. $objRefFourn = $objp->ref_fourn;
  2548. if ($filterkey && $filterkey != '') $objRefFourn = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $objRefFourn, 1);
  2549. $label = $objp->label;
  2550. if ($filterkey && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey, '/').')/i', '<strong>$1</strong>', $label, 1);
  2551. $optlabel = $objp->ref;
  2552. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2553. $optlabel .= ' <span class=\'opacitymedium\'>('.$objp->ref_fourn.')</span>';
  2554. }
  2555. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2556. $optlabel .= ' ('.$outbarcode.')';
  2557. }
  2558. $optlabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2559. $outvallabel = $objRef;
  2560. if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
  2561. $outvallabel .= ' ('.$objRefFourn.')';
  2562. }
  2563. if (!empty($conf->barcode->enabled) && !empty($objp->barcode)) {
  2564. $outvallabel .= ' ('.$outbarcode.')';
  2565. }
  2566. $outvallabel .= ' - '.dol_trunc($label, $maxlengtharticle);
  2567. // Units
  2568. $optlabel .= $outvalUnits;
  2569. $outvallabel .= $outvalUnits;
  2570. if (!empty($objp->idprodfournprice))
  2571. {
  2572. $outqty = $objp->quantity;
  2573. $outdiscount = $objp->remise_percent;
  2574. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2575. $prod_supplier = new ProductFournisseur($this->db);
  2576. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2577. $prod_supplier->id = $objp->fk_product;
  2578. $prod_supplier->fourn_qty = $objp->quantity;
  2579. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2580. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2581. $priceparser = new PriceParser($this->db);
  2582. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2583. if ($price_result >= 0) {
  2584. $objp->fprice = $price_result;
  2585. if ($objp->quantity >= 1)
  2586. {
  2587. $objp->unitprice = $objp->fprice / $objp->quantity; // Replace dynamically unitprice
  2588. }
  2589. }
  2590. }
  2591. if ($objp->quantity == 1)
  2592. {
  2593. $optlabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2594. $outvallabel .= ' - '.price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 0, $langs, 0, 0, -1, $conf->currency)."/";
  2595. $optlabel .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2596. $outvallabel .= $langs->transnoentities("Unit");
  2597. } else {
  2598. $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;
  2599. $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;
  2600. $optlabel .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2601. $outvallabel .= ' '.$langs->transnoentities("Units");
  2602. }
  2603. if ($objp->quantity > 1)
  2604. {
  2605. $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
  2606. $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
  2607. }
  2608. if ($objp->remise_percent >= 1)
  2609. {
  2610. $optlabel .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2611. $outvallabel .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2612. }
  2613. if ($objp->duration)
  2614. {
  2615. $optlabel .= " - ".$objp->duration;
  2616. $outvallabel .= " - ".$objp->duration;
  2617. }
  2618. if (!$socid)
  2619. {
  2620. $optlabel .= " - ".dol_trunc($objp->name, 8);
  2621. $outvallabel .= " - ".dol_trunc($objp->name, 8);
  2622. }
  2623. if ($objp->supplier_reputation)
  2624. {
  2625. //TODO dictionary
  2626. $reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  2627. $optlabel .= " - ".$reputations[$objp->supplier_reputation];
  2628. $outvallabel .= " - ".$reputations[$objp->supplier_reputation];
  2629. }
  2630. } else {
  2631. if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier
  2632. {
  2633. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  2634. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2635. } else // No supplier price defined for product, even on other suppliers
  2636. {
  2637. $optlabel .= " - <span class='opacitymedium'>".$langs->trans("NoPriceDefinedForThisSupplier").'</span>';
  2638. $outvallabel .= ' - '.$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2639. }
  2640. }
  2641. $opt = '<option value="'.$outkey.'"';
  2642. if ($selected && $selected == $objp->idprodfournprice) $opt .= ' selected';
  2643. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt .= ' disabled';
  2644. if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
  2645. {
  2646. $opt .= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqup="'.$objp->unitprice.'" data-pbqpercent="'.$objp->remise_percent.'"';
  2647. }
  2648. $opt .= ' data-html="'.dol_escape_htmltag($optlabel).'"';
  2649. $opt .= '>';
  2650. $opt .= $optlabel;
  2651. $outval .= $outvallabel;
  2652. $opt .= "</option>\n";
  2653. // Add new entry
  2654. // "key" value of json key array is used by jQuery automatically as selected value
  2655. // "label" value of json key array is used by jQuery automatically as text for combo box
  2656. $out .= $opt;
  2657. array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'up'=>$objp->unitprice, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false)));
  2658. // Exemple of var_dump $outarray
  2659. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  2660. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  2661. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  2662. //}
  2663. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2664. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  2665. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2666. $i++;
  2667. }
  2668. $out .= '</select>';
  2669. $this->db->free($result);
  2670. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2671. $out .= ajax_combobox($htmlname);
  2672. if (empty($outputmode)) return $out;
  2673. return $outarray;
  2674. } else {
  2675. dol_print_error($this->db);
  2676. }
  2677. }
  2678. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2679. /**
  2680. * Return list of suppliers prices for a product
  2681. *
  2682. * @param int $productid Id of product
  2683. * @param string $htmlname Name of HTML field
  2684. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  2685. * @return string
  2686. */
  2687. public function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
  2688. {
  2689. // phpcs:enable
  2690. global $langs, $conf;
  2691. $langs->load('stocks');
  2692. $sql = "SELECT p.rowid, p.ref, p.label, p.price, p.duration, pfp.fk_soc,";
  2693. $sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.remise_percent, pfp.quantity, pfp.unitprice,";
  2694. $sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  2695. $sql .= " FROM ".MAIN_DB_PREFIX."product as p";
  2696. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2697. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2698. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  2699. $sql .= " AND p.tobuy = 1";
  2700. $sql .= " AND s.fournisseur = 1";
  2701. $sql .= " AND p.rowid = ".$productid;
  2702. $sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
  2703. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  2704. $result = $this->db->query($sql);
  2705. if ($result)
  2706. {
  2707. $num = $this->db->num_rows($result);
  2708. $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2709. if (!$num)
  2710. {
  2711. $form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  2712. } else {
  2713. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2714. $form .= '<option value="0">&nbsp;</option>';
  2715. $i = 0;
  2716. while ($i < $num)
  2717. {
  2718. $objp = $this->db->fetch_object($result);
  2719. $opt = '<option value="'.$objp->idprodfournprice.'"';
  2720. //if there is only one supplier, preselect it
  2721. if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  2722. $opt .= ' selected';
  2723. }
  2724. $opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  2725. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2726. $prod_supplier = new ProductFournisseur($this->db);
  2727. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2728. $prod_supplier->id = $productid;
  2729. $prod_supplier->fourn_qty = $objp->quantity;
  2730. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2731. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2732. $priceparser = new PriceParser($this->db);
  2733. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2734. if ($price_result >= 0) {
  2735. $objp->fprice = $price_result;
  2736. if ($objp->quantity >= 1)
  2737. {
  2738. $objp->unitprice = $objp->fprice / $objp->quantity;
  2739. }
  2740. }
  2741. }
  2742. if ($objp->quantity == 1)
  2743. {
  2744. $opt .= price($objp->fprice * (!empty($conf->global->DISPLAY_DISCOUNTED_SUPPLIER_PRICE) ? (1 - $objp->remise_percent / 100) : 1), 1, $langs, 0, 0, -1, $conf->currency)."/";
  2745. }
  2746. $opt .= $objp->quantity.' ';
  2747. if ($objp->quantity == 1)
  2748. {
  2749. $opt .= $langs->trans("Unit");
  2750. } else {
  2751. $opt .= $langs->trans("Units");
  2752. }
  2753. if ($objp->quantity > 1)
  2754. {
  2755. $opt .= " - ";
  2756. $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");
  2757. }
  2758. if ($objp->duration) $opt .= " - ".$objp->duration;
  2759. $opt .= "</option>\n";
  2760. $form .= $opt;
  2761. $i++;
  2762. }
  2763. }
  2764. $form .= '</select>';
  2765. $this->db->free($result);
  2766. return $form;
  2767. } else {
  2768. dol_print_error($this->db);
  2769. }
  2770. }
  2771. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2772. /**
  2773. * Return list of delivery address
  2774. *
  2775. * @param string $selected Id contact pre-selectionn
  2776. * @param int $socid Id of company
  2777. * @param string $htmlname Name of HTML field
  2778. * @param int $showempty Add an empty field
  2779. * @return integer|null
  2780. */
  2781. public function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
  2782. {
  2783. // phpcs:enable
  2784. // looking for users
  2785. $sql = "SELECT a.rowid, a.label";
  2786. $sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a";
  2787. $sql .= " WHERE a.fk_soc = ".$socid;
  2788. $sql .= " ORDER BY a.label ASC";
  2789. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  2790. $resql = $this->db->query($sql);
  2791. if ($resql)
  2792. {
  2793. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2794. if ($showempty) print '<option value="0">&nbsp;</option>';
  2795. $num = $this->db->num_rows($resql);
  2796. $i = 0;
  2797. if ($num)
  2798. {
  2799. while ($i < $num)
  2800. {
  2801. $obj = $this->db->fetch_object($resql);
  2802. if ($selected && $selected == $obj->rowid)
  2803. {
  2804. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  2805. } else {
  2806. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  2807. }
  2808. $i++;
  2809. }
  2810. }
  2811. print '</select>';
  2812. return $num;
  2813. } else {
  2814. dol_print_error($this->db);
  2815. }
  2816. }
  2817. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2818. /**
  2819. * Load into cache list of payment terms
  2820. *
  2821. * @return int Nb of lines loaded, <0 if KO
  2822. */
  2823. public function load_cache_conditions_paiements()
  2824. {
  2825. // phpcs:enable
  2826. global $langs;
  2827. $num = count($this->cache_conditions_paiements);
  2828. if ($num > 0) return 0; // Cache already loaded
  2829. dol_syslog(__METHOD__, LOG_DEBUG);
  2830. $sql = "SELECT rowid, code, libelle as label";
  2831. $sql .= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  2832. $sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
  2833. $sql .= " AND active > 0";
  2834. $sql .= " ORDER BY sortorder";
  2835. $resql = $this->db->query($sql);
  2836. if ($resql)
  2837. {
  2838. $num = $this->db->num_rows($resql);
  2839. $i = 0;
  2840. while ($i < $num)
  2841. {
  2842. $obj = $this->db->fetch_object($resql);
  2843. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2844. $label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  2845. $this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
  2846. $this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
  2847. $i++;
  2848. }
  2849. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  2850. return $num;
  2851. } else {
  2852. dol_print_error($this->db);
  2853. return -1;
  2854. }
  2855. }
  2856. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2857. /**
  2858. * Charge dans cache la liste des délais de livraison possibles
  2859. *
  2860. * @return int Nb of lines loaded, <0 if KO
  2861. */
  2862. public function load_cache_availability()
  2863. {
  2864. // phpcs:enable
  2865. global $langs;
  2866. $num = count($this->cache_availability);
  2867. if ($num > 0) return 0; // Cache already loaded
  2868. dol_syslog(__METHOD__, LOG_DEBUG);
  2869. $langs->load('propal');
  2870. $sql = "SELECT rowid, code, label";
  2871. $sql .= " FROM ".MAIN_DB_PREFIX.'c_availability';
  2872. $sql .= " WHERE active > 0";
  2873. $resql = $this->db->query($sql);
  2874. if ($resql)
  2875. {
  2876. $num = $this->db->num_rows($resql);
  2877. $i = 0;
  2878. while ($i < $num)
  2879. {
  2880. $obj = $this->db->fetch_object($resql);
  2881. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2882. $label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  2883. $this->cache_availability[$obj->rowid]['code'] = $obj->code;
  2884. $this->cache_availability[$obj->rowid]['label'] = $label;
  2885. $i++;
  2886. }
  2887. $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
  2888. return $num;
  2889. } else {
  2890. dol_print_error($this->db);
  2891. return -1;
  2892. }
  2893. }
  2894. /**
  2895. * Retourne la liste des types de delais de livraison possibles
  2896. *
  2897. * @param int $selected Id du type de delais pre-selectionne
  2898. * @param string $htmlname Nom de la zone select
  2899. * @param string $filtertype To add a filter
  2900. * @param int $addempty Add empty entry
  2901. * @return void
  2902. */
  2903. public function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0)
  2904. {
  2905. global $langs, $user;
  2906. $this->load_cache_availability();
  2907. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2908. print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
  2909. if ($addempty) print '<option value="0">&nbsp;</option>';
  2910. foreach ($this->cache_availability as $id => $arrayavailability)
  2911. {
  2912. if ($selected == $id)
  2913. {
  2914. print '<option value="'.$id.'" selected>';
  2915. } else {
  2916. print '<option value="'.$id.'">';
  2917. }
  2918. print $arrayavailability['label'];
  2919. print '</option>';
  2920. }
  2921. print '</select>';
  2922. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  2923. }
  2924. /**
  2925. * Load into cache cache_demand_reason, array of input reasons
  2926. *
  2927. * @return int Nb of lines loaded, <0 if KO
  2928. */
  2929. public function loadCacheInputReason()
  2930. {
  2931. global $langs;
  2932. $num = count($this->cache_demand_reason);
  2933. if ($num > 0) return 0; // Cache already loaded
  2934. $sql = "SELECT rowid, code, label";
  2935. $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  2936. $sql .= " WHERE active > 0";
  2937. $resql = $this->db->query($sql);
  2938. if ($resql)
  2939. {
  2940. $num = $this->db->num_rows($resql);
  2941. $i = 0;
  2942. $tmparray = array();
  2943. while ($i < $num)
  2944. {
  2945. $obj = $this->db->fetch_object($resql);
  2946. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2947. $label = ($obj->label != '-' ? $obj->label : '');
  2948. if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
  2949. if ($langs->trans($obj->code) != $obj->code) $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
  2950. $tmparray[$obj->rowid]['id'] = $obj->rowid;
  2951. $tmparray[$obj->rowid]['code'] = $obj->code;
  2952. $tmparray[$obj->rowid]['label'] = $label;
  2953. $i++;
  2954. }
  2955. $this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  2956. unset($tmparray);
  2957. return $num;
  2958. } else {
  2959. dol_print_error($this->db);
  2960. return -1;
  2961. }
  2962. }
  2963. /**
  2964. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  2965. * List found into table c_input_reason loaded by loadCacheInputReason
  2966. *
  2967. * @param int $selected Id or code of type origin to select by default
  2968. * @param string $htmlname Nom de la zone select
  2969. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  2970. * @param int $addempty Add an empty entry
  2971. * @return void
  2972. */
  2973. public function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0)
  2974. {
  2975. global $langs, $user;
  2976. $this->loadCacheInputReason();
  2977. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  2978. if ($addempty) print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
  2979. foreach ($this->cache_demand_reason as $id => $arraydemandreason)
  2980. {
  2981. if ($arraydemandreason['code'] == $exclude) continue;
  2982. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
  2983. {
  2984. print '<option value="'.$arraydemandreason['id'].'" selected>';
  2985. } else {
  2986. print '<option value="'.$arraydemandreason['id'].'">';
  2987. }
  2988. $label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
  2989. print $langs->trans($label);
  2990. print '</option>';
  2991. }
  2992. print '</select>';
  2993. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  2994. }
  2995. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2996. /**
  2997. * Charge dans cache la liste des types de paiements possibles
  2998. *
  2999. * @return int Nb of lines loaded, <0 if KO
  3000. */
  3001. public function load_cache_types_paiements()
  3002. {
  3003. // phpcs:enable
  3004. global $langs;
  3005. $num = count($this->cache_types_paiements);
  3006. if ($num > 0) return $num; // Cache already loaded
  3007. dol_syslog(__METHOD__, LOG_DEBUG);
  3008. $this->cache_types_paiements = array();
  3009. $sql = "SELECT id, code, libelle as label, type, active";
  3010. $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement";
  3011. $sql .= " WHERE entity IN (".getEntity('c_paiement').")";
  3012. //if ($active >= 0) $sql.= " AND active = ".$active;
  3013. $resql = $this->db->query($sql);
  3014. if ($resql)
  3015. {
  3016. $num = $this->db->num_rows($resql);
  3017. $i = 0;
  3018. while ($i < $num)
  3019. {
  3020. $obj = $this->db->fetch_object($resql);
  3021. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  3022. $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
  3023. $this->cache_types_paiements[$obj->id]['id'] = $obj->id;
  3024. $this->cache_types_paiements[$obj->id]['code'] = $obj->code;
  3025. $this->cache_types_paiements[$obj->id]['label'] = $label;
  3026. $this->cache_types_paiements[$obj->id]['type'] = $obj->type;
  3027. $this->cache_types_paiements[$obj->id]['active'] = $obj->active;
  3028. $i++;
  3029. }
  3030. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  3031. return $num;
  3032. } else {
  3033. dol_print_error($this->db);
  3034. return -1;
  3035. }
  3036. }
  3037. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3038. /**
  3039. * Return list of payment modes.
  3040. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  3041. * See instead to force the default value by the caller.
  3042. *
  3043. * @param int $selected Id of payment term to preselect by default
  3044. * @param string $htmlname Nom de la zone select
  3045. * @param int $filtertype Not used
  3046. * @param int $addempty Add an empty entry
  3047. * @param int $noinfoadmin 0=Add admin info, 1=Disable admin info
  3048. * @param string $morecss Add more CSS on select tag
  3049. * @return void
  3050. */
  3051. public function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
  3052. {
  3053. // phpcs:enable
  3054. global $langs, $user, $conf;
  3055. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  3056. $this->load_cache_conditions_paiements();
  3057. // Set default value if not already set by caller
  3058. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  3059. print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3060. if ($addempty) print '<option value="0">&nbsp;</option>';
  3061. foreach ($this->cache_conditions_paiements as $id => $arrayconditions)
  3062. {
  3063. if ($selected == $id)
  3064. {
  3065. print '<option value="'.$id.'" selected>';
  3066. } else {
  3067. print '<option value="'.$id.'">';
  3068. }
  3069. print $arrayconditions['label'];
  3070. print '</option>';
  3071. }
  3072. print '</select>';
  3073. if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3074. }
  3075. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3076. /**
  3077. * Return list of payment methods
  3078. * Constant MAIN_DEFAULT_PAYMENT_TYPE_ID can used to set default value but scope is all application, probably not what you want.
  3079. *
  3080. * @param string $selected Id or code or preselected payment mode
  3081. * @param string $htmlname Name of select field
  3082. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  3083. * @param int $format 0=id+label, 1=code+code, 2=code+label, 3=id+code
  3084. * @param int $empty 1=can be empty, 0 otherwise
  3085. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  3086. * @param int $maxlength Max length of label
  3087. * @param int $active Active or not, -1 = all
  3088. * @param string $morecss Add more CSS on select tag
  3089. * @return void
  3090. */
  3091. public function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
  3092. {
  3093. // phpcs:enable
  3094. global $langs, $user, $conf;
  3095. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  3096. $filterarray = array();
  3097. if ($filtertype == 'CRDT') $filterarray = array(0, 2, 3);
  3098. elseif ($filtertype == 'DBIT') $filterarray = array(1, 2, 3);
  3099. elseif ($filtertype != '' && $filtertype != '-1') $filterarray = explode(',', $filtertype);
  3100. $this->load_cache_types_paiements();
  3101. // Set default value if not already set by caller
  3102. if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TYPE_ID;
  3103. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
  3104. if ($empty) print '<option value="">&nbsp;</option>';
  3105. foreach ($this->cache_types_paiements as $id => $arraytypes)
  3106. {
  3107. // If not good status
  3108. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  3109. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  3110. if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) continue;
  3111. // We discard empty line if showempty is on because an empty line has already been output.
  3112. if ($empty && empty($arraytypes['code'])) continue;
  3113. if ($format == 0) print '<option value="'.$id.'"';
  3114. elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  3115. elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  3116. elseif ($format == 3) print '<option value="'.$id.'"';
  3117. // Print attribute selected or not
  3118. if ($format == 1 || $format == 2) {
  3119. if ($selected == $arraytypes['code']) print ' selected';
  3120. } else {
  3121. if ($selected == $id) print ' selected';
  3122. }
  3123. print '>';
  3124. if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3125. elseif ($format == 1) $value = $arraytypes['code'];
  3126. elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
  3127. elseif ($format == 3) $value = $arraytypes['code'];
  3128. print $value ? $value : '&nbsp;';
  3129. print '</option>';
  3130. }
  3131. print '</select>';
  3132. if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3133. }
  3134. /**
  3135. * Selection HT or TTC
  3136. *
  3137. * @param string $selected Id pre-selectionne
  3138. * @param string $htmlname Nom de la zone select
  3139. * @return string Code of HTML select to chose tax or not
  3140. */
  3141. public function selectPriceBaseType($selected = '', $htmlname = 'price_base_type')
  3142. {
  3143. global $langs;
  3144. $return = '';
  3145. $return .= '<select class="flat maxwidth75" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  3146. $options = array(
  3147. 'HT'=>$langs->trans("HT"),
  3148. 'TTC'=>$langs->trans("TTC")
  3149. );
  3150. foreach ($options as $id => $value)
  3151. {
  3152. if ($selected == $id)
  3153. {
  3154. $return .= '<option value="'.$id.'" selected>'.$value;
  3155. } else {
  3156. $return .= '<option value="'.$id.'">'.$value;
  3157. }
  3158. $return .= '</option>';
  3159. }
  3160. $return .= '</select>';
  3161. return $return;
  3162. }
  3163. /**
  3164. * Return a HTML select list of shipping mode
  3165. *
  3166. * @param string $selected Id shipping mode pre-selected
  3167. * @param string $htmlname Name of select zone
  3168. * @param string $filtre To filter list
  3169. * @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.
  3170. * @param string $moreattrib To add more attribute on select
  3171. * @return void
  3172. */
  3173. public function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '')
  3174. {
  3175. global $langs, $conf, $user;
  3176. $langs->load("admin");
  3177. $langs->load("deliveries");
  3178. $sql = "SELECT rowid, code, libelle as label";
  3179. $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  3180. $sql .= " WHERE active > 0";
  3181. if ($filtre) $sql .= " AND ".$filtre;
  3182. $sql .= " ORDER BY libelle ASC";
  3183. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  3184. $result = $this->db->query($sql);
  3185. if ($result) {
  3186. $num = $this->db->num_rows($result);
  3187. $i = 0;
  3188. if ($num) {
  3189. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3190. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  3191. print '<option value="-1">&nbsp;</option>';
  3192. }
  3193. while ($i < $num) {
  3194. $obj = $this->db->fetch_object($result);
  3195. if ($selected == $obj->rowid) {
  3196. print '<option value="'.$obj->rowid.'" selected>';
  3197. } else {
  3198. print '<option value="'.$obj->rowid.'">';
  3199. }
  3200. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  3201. print '</option>';
  3202. $i++;
  3203. }
  3204. print "</select>";
  3205. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  3206. } else {
  3207. print $langs->trans("NoShippingMethodDefined");
  3208. }
  3209. } else {
  3210. dol_print_error($this->db);
  3211. }
  3212. }
  3213. /**
  3214. * Display form to select shipping mode
  3215. *
  3216. * @param string $page Page
  3217. * @param int $selected Id of shipping mode
  3218. * @param string $htmlname Name of select html field
  3219. * @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.
  3220. * @return void
  3221. */
  3222. public function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
  3223. {
  3224. global $langs, $db;
  3225. $langs->load("deliveries");
  3226. if ($htmlname != "none") {
  3227. print '<form method="POST" action="'.$page.'">';
  3228. print '<input type="hidden" name="action" value="setshippingmethod">';
  3229. print '<input type="hidden" name="token" value="'.newToken().'">';
  3230. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  3231. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3232. print '</form>';
  3233. } else {
  3234. if ($selected) {
  3235. $code = $langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  3236. print $langs->trans("SendingMethod".strtoupper($code));
  3237. } else {
  3238. print "&nbsp;";
  3239. }
  3240. }
  3241. }
  3242. /**
  3243. * Creates HTML last in cycle situation invoices selector
  3244. *
  3245. * @param string $selected Preselected ID
  3246. * @param int $socid Company ID
  3247. *
  3248. * @return string HTML select
  3249. */
  3250. public function selectSituationInvoices($selected = '', $socid = 0)
  3251. {
  3252. global $langs;
  3253. $langs->load('bills');
  3254. $opt = '<option value ="" selected></option>';
  3255. $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc';
  3256. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture';
  3257. $sql .= ' WHERE entity IN ('.getEntity('invoice').')';
  3258. $sql .= ' AND situation_counter >= 1';
  3259. $sql .= ' AND fk_soc = '.(int) $socid;
  3260. $sql .= ' AND type <> 2';
  3261. $sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
  3262. $resql = $this->db->query($sql);
  3263. if ($resql && $this->db->num_rows($resql) > 0) {
  3264. // Last seen cycle
  3265. $ref = 0;
  3266. while ($obj = $this->db->fetch_object($resql)) {
  3267. //Same cycle ?
  3268. if ($obj->situation_cycle_ref != $ref) {
  3269. // Just seen this cycle
  3270. $ref = $obj->situation_cycle_ref;
  3271. //not final ?
  3272. if ($obj->situation_final != 1) {
  3273. //Not prov?
  3274. if (substr($obj->ref, 1, 4) != 'PROV') {
  3275. if ($selected == $obj->rowid) {
  3276. $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
  3277. } else {
  3278. $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
  3279. }
  3280. }
  3281. }
  3282. }
  3283. }
  3284. } else {
  3285. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  3286. }
  3287. if ($opt == '<option value ="" selected></option>')
  3288. {
  3289. $opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
  3290. }
  3291. return $opt;
  3292. }
  3293. /**
  3294. * Creates HTML units selector (code => label)
  3295. *
  3296. * @param string $selected Preselected Unit ID
  3297. * @param string $htmlname Select name
  3298. * @param int $showempty Add a nempty line
  3299. * @return string HTML select
  3300. */
  3301. public function selectUnits($selected = '', $htmlname = 'units', $showempty = 0)
  3302. {
  3303. global $langs;
  3304. $langs->load('products');
  3305. $return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  3306. $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
  3307. $sql .= ' WHERE active > 0';
  3308. $resql = $this->db->query($sql);
  3309. if ($resql && $this->db->num_rows($resql) > 0)
  3310. {
  3311. if ($showempty) $return .= '<option value="none"></option>';
  3312. while ($res = $this->db->fetch_object($resql))
  3313. {
  3314. $unitLabel = $res->label;
  3315. if (!empty($langs->tab_translate['unit'.$res->code])) // check if Translation is available before
  3316. {
  3317. $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
  3318. }
  3319. if ($selected == $res->rowid)
  3320. {
  3321. $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
  3322. } else {
  3323. $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
  3324. }
  3325. }
  3326. $return .= '</select>';
  3327. }
  3328. return $return;
  3329. }
  3330. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3331. /**
  3332. * Return a HTML select list of bank accounts
  3333. *
  3334. * @param string $selected Id account pre-selected
  3335. * @param string $htmlname Name of select zone
  3336. * @param int $status Status of searched accounts (0=open, 1=closed, 2=both)
  3337. * @param string $filtre To filter list
  3338. * @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.
  3339. * @param string $moreattrib To add more attribute on select
  3340. * @param int $showcurrency Show currency in label
  3341. * @param string $morecss More CSS
  3342. * @return int <0 if error, Num of bank account found if OK (0, 1, 2, ...)
  3343. */
  3344. public function select_comptes($selected = '', $htmlname = 'accountid', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0, $morecss = '')
  3345. {
  3346. // phpcs:enable
  3347. global $langs, $conf;
  3348. $langs->load("admin");
  3349. $num = 0;
  3350. $sql = "SELECT rowid, label, bank, clos as status, currency_code";
  3351. $sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
  3352. $sql .= " WHERE entity IN (".getEntity('bank_account').")";
  3353. if ($status != 2) $sql .= " AND clos = ".(int) $status;
  3354. if ($filtre) $sql .= " AND ".$filtre;
  3355. $sql .= " ORDER BY label";
  3356. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  3357. $result = $this->db->query($sql);
  3358. if ($result)
  3359. {
  3360. $num = $this->db->num_rows($result);
  3361. $i = 0;
  3362. if ($num)
  3363. {
  3364. print '<select id="select'.$htmlname.'" class="flat selectbankaccount'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3365. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  3366. {
  3367. print '<option value="-1">&nbsp;</option>';
  3368. }
  3369. while ($i < $num)
  3370. {
  3371. $obj = $this->db->fetch_object($result);
  3372. if ($selected == $obj->rowid)
  3373. {
  3374. print '<option value="'.$obj->rowid.'" selected>';
  3375. } else {
  3376. print '<option value="'.$obj->rowid.'">';
  3377. }
  3378. print trim($obj->label);
  3379. if ($showcurrency) print ' ('.$obj->currency_code.')';
  3380. if ($status == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3381. print '</option>';
  3382. $i++;
  3383. }
  3384. print "</select>";
  3385. } else {
  3386. if ($status == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
  3387. else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
  3388. }
  3389. } else {
  3390. dol_print_error($this->db);
  3391. }
  3392. return $num;
  3393. }
  3394. /**
  3395. * Return a HTML select list of establishment
  3396. *
  3397. * @param string $selected Id establishment pre-selected
  3398. * @param string $htmlname Name of select zone
  3399. * @param int $status Status of searched establishment (0=open, 1=closed, 2=both)
  3400. * @param string $filtre To filter list
  3401. * @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.
  3402. * @param string $moreattrib To add more attribute on select
  3403. * @return int <0 if error, Num of establishment found if OK (0, 1, 2, ...)
  3404. */
  3405. public function selectEstablishments($selected = '', $htmlname = 'entity', $status = 0, $filtre = '', $useempty = 0, $moreattrib = '')
  3406. {
  3407. // phpcs:enable
  3408. global $langs, $conf;
  3409. $langs->load("admin");
  3410. $num = 0;
  3411. $sql = "SELECT rowid, name, fk_country, status, entity";
  3412. $sql .= " FROM ".MAIN_DB_PREFIX."establishment";
  3413. $sql .= " WHERE 1=1";
  3414. if ($status != 2) $sql .= " AND status = ".(int) $status;
  3415. if ($filtre) $sql .= " AND ".$filtre;
  3416. $sql .= " ORDER BY name";
  3417. dol_syslog(get_class($this)."::select_establishment", LOG_DEBUG);
  3418. $result = $this->db->query($sql);
  3419. if ($result)
  3420. {
  3421. $num = $this->db->num_rows($result);
  3422. $i = 0;
  3423. if ($num)
  3424. {
  3425. print '<select id="select'.$htmlname.'" class="flat selectestablishment" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
  3426. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  3427. {
  3428. print '<option value="-1">&nbsp;</option>';
  3429. }
  3430. while ($i < $num)
  3431. {
  3432. $obj = $this->db->fetch_object($result);
  3433. if ($selected == $obj->rowid)
  3434. {
  3435. print '<option value="'.$obj->rowid.'" selected>';
  3436. } else {
  3437. print '<option value="'.$obj->rowid.'">';
  3438. }
  3439. print trim($obj->name);
  3440. if ($status == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  3441. print '</option>';
  3442. $i++;
  3443. }
  3444. print "</select>";
  3445. } else {
  3446. if ($status == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveEstablishmentDefined").'</span>';
  3447. else print '<span class="opacitymedium">'.$langs->trans("NoEstablishmentFound").'</span>';
  3448. }
  3449. } else {
  3450. dol_print_error($this->db);
  3451. }
  3452. }
  3453. /**
  3454. * Display form to select bank account
  3455. *
  3456. * @param string $page Page
  3457. * @param int $selected Id of bank account
  3458. * @param string $htmlname Name of select html field
  3459. * @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.
  3460. * @return void
  3461. */
  3462. public function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
  3463. {
  3464. global $langs;
  3465. if ($htmlname != "none") {
  3466. print '<form method="POST" action="'.$page.'">';
  3467. print '<input type="hidden" name="action" value="setbankaccount">';
  3468. print '<input type="hidden" name="token" value="'.newToken().'">';
  3469. $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  3470. if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3471. print '</form>';
  3472. } else {
  3473. $langs->load('banks');
  3474. if ($selected) {
  3475. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  3476. $bankstatic = new Account($this->db);
  3477. $result = $bankstatic->fetch($selected);
  3478. if ($result) print $bankstatic->getNomUrl(1);
  3479. } else {
  3480. print "&nbsp;";
  3481. }
  3482. }
  3483. }
  3484. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3485. /**
  3486. * Return list of categories having choosed type
  3487. *
  3488. * @param string|int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  3489. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element). Not used if $outputmode = 1.
  3490. * @param string $htmlname HTML field name
  3491. * @param int $maxlength Maximum length for labels
  3492. * @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.
  3493. * $markafterid can be an :
  3494. * - int (id of category)
  3495. * - string (categories ids seprated by comma)
  3496. * - array (list of categories ids)
  3497. * @param int $outputmode 0=HTML select string, 1=Array
  3498. * @param int $include [=0] Removed or 1=Keep only
  3499. * @param string $morecss More CSS
  3500. * @return string
  3501. * @see select_categories()
  3502. */
  3503. public function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $markafterid = 0, $outputmode = 0, $include = 0, $morecss = '')
  3504. {
  3505. // phpcs:enable
  3506. global $conf, $langs;
  3507. $langs->load("categories");
  3508. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  3509. // For backward compatibility
  3510. if (is_numeric($type))
  3511. {
  3512. dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  3513. }
  3514. if ($type === Categorie::TYPE_BANK_LINE)
  3515. {
  3516. // TODO Move this into common category feature
  3517. $cate_arbo = array();
  3518. $sql = "SELECT c.label, c.rowid";
  3519. $sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  3520. $sql .= " WHERE entity = ".$conf->entity;
  3521. $sql .= " ORDER BY c.label";
  3522. $result = $this->db->query($sql);
  3523. if ($result)
  3524. {
  3525. $num = $this->db->num_rows($result);
  3526. $i = 0;
  3527. while ($i < $num)
  3528. {
  3529. $objp = $this->db->fetch_object($result);
  3530. if ($objp) $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  3531. $i++;
  3532. }
  3533. $this->db->free($result);
  3534. } else dol_print_error($this->db);
  3535. } else {
  3536. $cat = new Categorie($this->db);
  3537. $cate_arbo = $cat->get_full_arbo($type, $markafterid, $include);
  3538. }
  3539. $output = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  3540. $outarray = array();
  3541. if (is_array($cate_arbo))
  3542. {
  3543. if (!count($cate_arbo)) $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  3544. else {
  3545. $output .= '<option value="-1">&nbsp;</option>';
  3546. foreach ($cate_arbo as $key => $value)
  3547. {
  3548. if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
  3549. {
  3550. $add = 'selected ';
  3551. } else {
  3552. $add = '';
  3553. }
  3554. $output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
  3555. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  3556. }
  3557. }
  3558. }
  3559. $output .= '</select>';
  3560. $output .= "\n";
  3561. if ($outputmode) return $outarray;
  3562. return $output;
  3563. }
  3564. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3565. /**
  3566. * Show a confirmation HTML form or AJAX popup
  3567. *
  3568. * @param string $page Url of page to call if confirmation is OK
  3569. * @param string $title Title
  3570. * @param string $question Question
  3571. * @param string $action Action
  3572. * @param array $formquestion An array with forms complementary inputs
  3573. * @param string $selectedchoice "" or "no" or "yes"
  3574. * @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
  3575. * @param int $height Force height of box
  3576. * @param int $width Force width of box
  3577. * @return void
  3578. * @deprecated
  3579. * @see formconfirm()
  3580. */
  3581. public function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
  3582. {
  3583. // phpcs:enable
  3584. dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
  3585. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  3586. }
  3587. /**
  3588. * Show a confirmation HTML form or AJAX popup.
  3589. * Easiest way to use this is with useajax=1.
  3590. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  3591. * just after calling this method. For example:
  3592. * print '<script type="text/javascript">'."\n";
  3593. * print 'jQuery(document).ready(function() {'."\n";
  3594. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  3595. * print '});'."\n";
  3596. * print '</script>'."\n";
  3597. *
  3598. * @param string $page Url of page to call if confirmation is OK. Can contains parameters (param 'action' and 'confirm' will be reformated)
  3599. * @param string $title Title
  3600. * @param string $question Question
  3601. * @param string $action Action
  3602. * @param array|string $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  3603. * type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
  3604. * @param string $selectedchoice '' or 'no', or 'yes' or '1' or '0'
  3605. * @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
  3606. * @param int $height Force height of box (0 = auto)
  3607. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  3608. * @param int $disableformtag 1=Disable form tag. Can be used if we are already inside a <form> section.
  3609. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  3610. */
  3611. public function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 0, $width = 500, $disableformtag = 0)
  3612. {
  3613. global $langs, $conf;
  3614. $more = '<!-- formconfirm -->';
  3615. $formconfirm = '';
  3616. $inputok = array();
  3617. $inputko = array();
  3618. // Clean parameters
  3619. $newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
  3620. if ($conf->browser->layout == 'phone') $width = '95%';
  3621. // Set height automatically if not defined
  3622. if (empty($height)) {
  3623. $height = 210;
  3624. if (is_array($formquestion) && count($formquestion) > 2) {
  3625. $height += ((count($formquestion) - 2) * 24);
  3626. }
  3627. }
  3628. if (is_array($formquestion) && !empty($formquestion))
  3629. {
  3630. // First add hidden fields and value
  3631. foreach ($formquestion as $key => $input)
  3632. {
  3633. if (is_array($input) && !empty($input))
  3634. {
  3635. if ($input['type'] == 'hidden')
  3636. {
  3637. $more .= '<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  3638. }
  3639. }
  3640. }
  3641. // Now add questions
  3642. $moreonecolumn = '';
  3643. $more .= '<div class="tagtable paddingtopbottomonly centpercent noborderspacing">'."\n";
  3644. foreach ($formquestion as $key => $input)
  3645. {
  3646. if (is_array($input) && !empty($input))
  3647. {
  3648. $size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : '');
  3649. $moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
  3650. $morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
  3651. if ($input['type'] == 'text')
  3652. {
  3653. $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="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  3654. } elseif ($input['type'] == 'password')
  3655. {
  3656. $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="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></div></div>'."\n";
  3657. } elseif ($input['type'] == 'select')
  3658. {
  3659. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  3660. if (!empty($input['label'])) $more .= $input['label'].'</div><div class="tagtd left">';
  3661. $more .= $this->selectarray($input['name'], $input['values'], $input['default'], 1, 0, 0, $moreattr, 0, 0, 0, '', $morecss);
  3662. $more .= '</div></div>'."\n";
  3663. } elseif ($input['type'] == 'checkbox')
  3664. {
  3665. $more .= '<div class="tagtr">';
  3666. $more .= '<div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].' </div><div class="tagtd">';
  3667. $more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
  3668. if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more .= ' checked';
  3669. if (is_bool($input['value']) && $input['value']) $more .= ' checked';
  3670. if (isset($input['disabled'])) $more .= ' disabled';
  3671. $more .= ' /></div>';
  3672. $more .= '</div>'."\n";
  3673. } elseif ($input['type'] == 'radio')
  3674. {
  3675. $i = 0;
  3676. foreach ($input['values'] as $selkey => $selval)
  3677. {
  3678. $more .= '<div class="tagtr">';
  3679. if ($i == 0) $more .= '<div class="tagtd'.(empty($input['tdclass']) ? ' tdtop' : (' tdtop '.$input['tdclass'])).'">'.$input['label'].'</div>';
  3680. else $more .= '<div clas="tagtd'.(empty($input['tdclass']) ? '' : (' "'.$input['tdclass'])).'">&nbsp;</div>';
  3681. $more .= '<div class="tagtd"><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
  3682. if ($input['disabled']) $more .= ' disabled';
  3683. $more .= ' /> ';
  3684. $more .= $selval;
  3685. $more .= '</div></div>'."\n";
  3686. $i++;
  3687. }
  3688. } elseif ($input['type'] == 'date')
  3689. {
  3690. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">'.$input['label'].'</div>';
  3691. $more .= '<div class="tagtd">';
  3692. $more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, 0);
  3693. $more .= '</div></div>'."\n";
  3694. $formquestion[] = array('name'=>$input['name'].'day');
  3695. $formquestion[] = array('name'=>$input['name'].'month');
  3696. $formquestion[] = array('name'=>$input['name'].'year');
  3697. $formquestion[] = array('name'=>$input['name'].'hour');
  3698. $formquestion[] = array('name'=>$input['name'].'min');
  3699. } elseif ($input['type'] == 'other')
  3700. {
  3701. $more .= '<div class="tagtr"><div class="tagtd'.(empty($input['tdclass']) ? '' : (' '.$input['tdclass'])).'">';
  3702. if (!empty($input['label'])) $more .= $input['label'].'</div><div class="tagtd">';
  3703. $more .= $input['value'];
  3704. $more .= '</div></div>'."\n";
  3705. } elseif ($input['type'] == 'onecolumn')
  3706. {
  3707. $moreonecolumn .= '<div class="margintoponly">';
  3708. $moreonecolumn .= $input['value'];
  3709. $moreonecolumn .= '</div>'."\n";
  3710. }
  3711. }
  3712. }
  3713. $more .= '</div>'."\n";
  3714. $more .= $moreonecolumn;
  3715. }
  3716. // JQUI method dialog is broken with jmobile, we use standard HTML.
  3717. // 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
  3718. // See page product/card.php for example
  3719. if (!empty($conf->dol_use_jmobile)) $useajax = 0;
  3720. if (empty($conf->use_javascript_ajax)) $useajax = 0;
  3721. if ($useajax)
  3722. {
  3723. $autoOpen = true;
  3724. $dialogconfirm = 'dialog-confirm';
  3725. $button = '';
  3726. if (!is_numeric($useajax))
  3727. {
  3728. $button = $useajax;
  3729. $useajax = 1;
  3730. $autoOpen = false;
  3731. $dialogconfirm .= '-'.$button;
  3732. }
  3733. $pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes';
  3734. $pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : '');
  3735. // Add input fields into list of fields to read during submit (inputok and inputko)
  3736. if (is_array($formquestion))
  3737. {
  3738. foreach ($formquestion as $key => $input)
  3739. {
  3740. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  3741. if (is_array($input) && isset($input['name'])) array_push($inputok, $input['name']);
  3742. if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko, $input['name']);
  3743. }
  3744. }
  3745. // Show JQuery confirm box.
  3746. $formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  3747. if (is_array($formquestion) && !empty($formquestion['text'])) {
  3748. $formconfirm .= '<div class="confirmtext">'.$formquestion['text'].'</div>'."\n";
  3749. }
  3750. if (!empty($more)) {
  3751. $formconfirm .= '<div class="confirmquestions">'.$more.'</div>'."\n";
  3752. }
  3753. $formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
  3754. $formconfirm .= '</div>'."\n";
  3755. $formconfirm .= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
  3756. $formconfirm .= '<script type="text/javascript">'."\n";
  3757. $formconfirm .= 'jQuery(document).ready(function() {
  3758. $(function() {
  3759. $( "#'.$dialogconfirm.'" ).dialog(
  3760. {
  3761. autoOpen: '.($autoOpen ? "true" : "false").',';
  3762. if ($newselectedchoice == 'no')
  3763. {
  3764. $formconfirm .= '
  3765. open: function() {
  3766. $(this).parent().find("button.ui-button:eq(2)").focus();
  3767. },';
  3768. }
  3769. $formconfirm .= '
  3770. resizable: false,
  3771. height: "'.$height.'",
  3772. width: "'.$width.'",
  3773. modal: true,
  3774. closeOnEscape: false,
  3775. buttons: {
  3776. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  3777. var options = "&token='.urlencode(newToken()).'";
  3778. var inputok = '.json_encode($inputok).'; /* List of fields into form */
  3779. var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
  3780. if (inputok.length>0) {
  3781. $.each(inputok, function(i, inputname) {
  3782. var more = "";
  3783. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3784. if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
  3785. var inputvalue = $("#" + inputname + more).val();
  3786. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3787. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3788. });
  3789. }
  3790. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  3791. //alert(urljump);
  3792. if (pageyes.length > 0) { location.href = urljump; }
  3793. $(this).dialog("close");
  3794. },
  3795. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  3796. var options = "&token='.urlencode(newToken()).'";
  3797. var inputko = '.json_encode($inputko).'; /* List of fields into form */
  3798. var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
  3799. if (inputko.length>0) {
  3800. $.each(inputko, function(i, inputname) {
  3801. var more = "";
  3802. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3803. var inputvalue = $("#" + inputname + more).val();
  3804. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3805. options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
  3806. });
  3807. }
  3808. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  3809. //alert(urljump);
  3810. if (pageno.length > 0) { location.href = urljump; }
  3811. $(this).dialog("close");
  3812. }
  3813. }
  3814. }
  3815. );
  3816. var button = "'.$button.'";
  3817. if (button.length > 0) {
  3818. $( "#" + button ).click(function() {
  3819. $("#'.$dialogconfirm.'").dialog("open");
  3820. });
  3821. }
  3822. });
  3823. });
  3824. </script>';
  3825. $formconfirm .= "<!-- end ajax formconfirm -->\n";
  3826. } else {
  3827. $formconfirm .= "\n<!-- begin formconfirm page=".$page." -->\n";
  3828. if (empty($disableformtag)) $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  3829. $formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  3830. $formconfirm .= '<input type="hidden" name="token" value="'.newToken().'">'."\n";
  3831. $formconfirm .= '<table class="valid centpercent">'."\n";
  3832. // Line title
  3833. $formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('', 'recent').' '.$title.'</td></tr>'."\n";
  3834. // Line text
  3835. if (is_array($formquestion) && !empty($formquestion['text'])) {
  3836. $formconfirm .= '<tr class="valid"><td class="valid" colspan="3">'.$formquestion['text'].'</td></tr>'."\n";
  3837. }
  3838. // Line form fields
  3839. if ($more)
  3840. {
  3841. $formconfirm .= '<tr class="valid"><td class="valid" colspan="3">'."\n";
  3842. $formconfirm .= $more;
  3843. $formconfirm .= '</td></tr>'."\n";
  3844. }
  3845. // Line with question
  3846. $formconfirm .= '<tr class="valid">';
  3847. $formconfirm .= '<td class="valid">'.$question.'</td>';
  3848. $formconfirm .= '<td class="valid">';
  3849. $formconfirm .= $this->selectyesno("confirm", $newselectedchoice);
  3850. $formconfirm .= '</td>';
  3851. $formconfirm .= '<td class="valid center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
  3852. $formconfirm .= '</tr>'."\n";
  3853. $formconfirm .= '</table>'."\n";
  3854. if (empty($disableformtag)) $formconfirm .= "</form>\n";
  3855. $formconfirm .= '<br>';
  3856. $formconfirm .= "<!-- end formconfirm -->\n";
  3857. }
  3858. return $formconfirm;
  3859. }
  3860. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3861. /**
  3862. * Show a form to select a project
  3863. *
  3864. * @param int $page Page
  3865. * @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)
  3866. * @param int $selected Id pre-selected project
  3867. * @param string $htmlname Name of select field
  3868. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  3869. * @param int $maxlength Max length
  3870. * @param int $forcefocus Force focus on field (works with javascript only)
  3871. * @param int $nooutput No print is done. String is returned.
  3872. * @return string Return html content
  3873. */
  3874. public function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
  3875. {
  3876. // phpcs:enable
  3877. global $langs;
  3878. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  3879. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  3880. $out = '';
  3881. $formproject = new FormProjets($this->db);
  3882. $langs->load("project");
  3883. if ($htmlname != "none")
  3884. {
  3885. $out .= "\n";
  3886. $out .= '<form method="post" action="'.$page.'">';
  3887. $out .= '<input type="hidden" name="action" value="classin">';
  3888. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  3889. $out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  3890. $out .= '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3891. $out .= '</form>';
  3892. } else {
  3893. if ($selected)
  3894. {
  3895. $projet = new Project($this->db);
  3896. $projet->fetch($selected);
  3897. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  3898. $out .= $projet->getNomUrl(0, '', 1);
  3899. } else {
  3900. $out .= "&nbsp;";
  3901. }
  3902. }
  3903. if (empty($nooutput))
  3904. {
  3905. print $out;
  3906. return '';
  3907. }
  3908. return $out;
  3909. }
  3910. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3911. /**
  3912. * Show a form to select payment conditions
  3913. *
  3914. * @param int $page Page
  3915. * @param string $selected Id condition pre-selectionne
  3916. * @param string $htmlname Name of select html field
  3917. * @param int $addempty Add empty entry
  3918. * @return void
  3919. */
  3920. public function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0)
  3921. {
  3922. // phpcs:enable
  3923. global $langs;
  3924. if ($htmlname != "none")
  3925. {
  3926. print '<form method="post" action="'.$page.'">';
  3927. print '<input type="hidden" name="action" value="setconditions">';
  3928. print '<input type="hidden" name="token" value="'.newToken().'">';
  3929. $this->select_conditions_paiements($selected, $htmlname, -1, $addempty);
  3930. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3931. print '</form>';
  3932. } else {
  3933. if ($selected)
  3934. {
  3935. $this->load_cache_conditions_paiements();
  3936. print $this->cache_conditions_paiements[$selected]['label'];
  3937. } else {
  3938. print "&nbsp;";
  3939. }
  3940. }
  3941. }
  3942. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3943. /**
  3944. * Show a form to select a delivery delay
  3945. *
  3946. * @param int $page Page
  3947. * @param string $selected Id condition pre-selectionne
  3948. * @param string $htmlname Name of select html field
  3949. * @param int $addempty Ajoute entree vide
  3950. * @return void
  3951. */
  3952. public function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
  3953. {
  3954. // phpcs:enable
  3955. global $langs;
  3956. if ($htmlname != "none")
  3957. {
  3958. print '<form method="post" action="'.$page.'">';
  3959. print '<input type="hidden" name="action" value="setavailability">';
  3960. print '<input type="hidden" name="token" value="'.newToken().'">';
  3961. $this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
  3962. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3963. print '</form>';
  3964. } else {
  3965. if ($selected)
  3966. {
  3967. $this->load_cache_availability();
  3968. print $this->cache_availability[$selected]['label'];
  3969. } else {
  3970. print "&nbsp;";
  3971. }
  3972. }
  3973. }
  3974. /**
  3975. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3976. * List found into table c_input_reason loaded by loadCacheInputReason
  3977. *
  3978. * @param string $page Page
  3979. * @param string $selected Id condition pre-selectionne
  3980. * @param string $htmlname Name of select html field
  3981. * @param int $addempty Add empty entry
  3982. * @return void
  3983. */
  3984. public function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
  3985. {
  3986. global $langs;
  3987. if ($htmlname != "none")
  3988. {
  3989. print '<form method="post" action="'.$page.'">';
  3990. print '<input type="hidden" name="action" value="setdemandreason">';
  3991. print '<input type="hidden" name="token" value="'.newToken().'">';
  3992. $this->selectInputReason($selected, $htmlname, -1, $addempty);
  3993. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3994. print '</form>';
  3995. } else {
  3996. if ($selected)
  3997. {
  3998. $this->loadCacheInputReason();
  3999. foreach ($this->cache_demand_reason as $key => $val)
  4000. {
  4001. if ($val['id'] == $selected)
  4002. {
  4003. print $val['label'];
  4004. break;
  4005. }
  4006. }
  4007. } else {
  4008. print "&nbsp;";
  4009. }
  4010. }
  4011. }
  4012. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4013. /**
  4014. * Show a form + html select a date
  4015. *
  4016. * @param string $page Page
  4017. * @param string $selected Date preselected
  4018. * @param string $htmlname Html name of date input fields or 'none'
  4019. * @param int $displayhour Display hour selector
  4020. * @param int $displaymin Display minutes selector
  4021. * @param int $nooutput 1=No print output, return string
  4022. * @return string
  4023. * @see selectDate()
  4024. */
  4025. public function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0)
  4026. {
  4027. // phpcs:enable
  4028. global $langs;
  4029. $ret = '';
  4030. if ($htmlname != "none")
  4031. {
  4032. $ret .= '<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  4033. $ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4034. $ret .= '<input type="hidden" name="token" value="'.newToken().'">';
  4035. $ret .= '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  4036. $ret .= '<tr><td>';
  4037. $ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
  4038. $ret .= '</td>';
  4039. $ret .= '<td class="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  4040. $ret .= '</tr></table></form>';
  4041. } else {
  4042. if ($displayhour) $ret .= dol_print_date($selected, 'dayhour');
  4043. else $ret .= dol_print_date($selected, 'day');
  4044. }
  4045. if (empty($nooutput)) print $ret;
  4046. return $ret;
  4047. }
  4048. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4049. /**
  4050. * Show a select form to choose a user
  4051. *
  4052. * @param string $page Page
  4053. * @param string $selected Id of user preselected
  4054. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  4055. * @param array $exclude List of users id to exclude
  4056. * @param array $include List of users id to include
  4057. * @return void
  4058. */
  4059. public function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
  4060. {
  4061. // phpcs:enable
  4062. global $langs;
  4063. if ($htmlname != "none")
  4064. {
  4065. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  4066. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  4067. print '<input type="hidden" name="token" value="'.newToken().'">';
  4068. print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
  4069. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4070. print '</form>';
  4071. } else {
  4072. if ($selected)
  4073. {
  4074. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  4075. $theuser = new User($this->db);
  4076. $theuser->fetch($selected);
  4077. print $theuser->getNomUrl(1);
  4078. } else {
  4079. print "&nbsp;";
  4080. }
  4081. }
  4082. }
  4083. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4084. /**
  4085. * Show form with payment mode
  4086. *
  4087. * @param string $page Page
  4088. * @param int $selected Id mode pre-selectionne
  4089. * @param string $htmlname Name of select html field
  4090. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  4091. * @param int $active Active or not, -1 = all
  4092. * @param int $addempty 1=Add empty entry
  4093. * @return void
  4094. */
  4095. public function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1, $addempty = 0)
  4096. {
  4097. // phpcs:enable
  4098. global $langs;
  4099. if ($htmlname != "none")
  4100. {
  4101. print '<form method="POST" action="'.$page.'">';
  4102. print '<input type="hidden" name="action" value="setmode">';
  4103. print '<input type="hidden" name="token" value="'.newToken().'">';
  4104. $this->select_types_paiements($selected, $htmlname, $filtertype, 0, $addempty, 0, 0, $active);
  4105. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4106. print '</form>';
  4107. } else {
  4108. if ($selected)
  4109. {
  4110. $this->load_cache_types_paiements();
  4111. print $this->cache_types_paiements[$selected]['label'];
  4112. } else {
  4113. print "&nbsp;";
  4114. }
  4115. }
  4116. }
  4117. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4118. /**
  4119. * Show form with multicurrency code
  4120. *
  4121. * @param string $page Page
  4122. * @param string $selected code pre-selectionne
  4123. * @param string $htmlname Name of select html field
  4124. * @return void
  4125. */
  4126. public function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
  4127. {
  4128. // phpcs:enable
  4129. global $langs;
  4130. if ($htmlname != "none")
  4131. {
  4132. print '<form method="POST" action="'.$page.'">';
  4133. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  4134. print '<input type="hidden" name="token" value="'.newToken().'">';
  4135. print $this->selectMultiCurrency($selected, $htmlname, 0);
  4136. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4137. print '</form>';
  4138. } else {
  4139. dol_include_once('/core/lib/company.lib.php');
  4140. print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
  4141. }
  4142. }
  4143. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4144. /**
  4145. * Show form with multicurrency rate
  4146. *
  4147. * @param string $page Page
  4148. * @param double $rate Current rate
  4149. * @param string $htmlname Name of select html field
  4150. * @param string $currency Currency code to explain the rate
  4151. * @return void
  4152. */
  4153. public function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
  4154. {
  4155. // phpcs:enable
  4156. global $langs, $mysoc, $conf;
  4157. if ($htmlname != "none")
  4158. {
  4159. print '<form method="POST" action="'.$page.'">';
  4160. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  4161. print '<input type="hidden" name="token" value="'.newToken().'">';
  4162. print '<input type="text" class="maxwidth100" name="'.$htmlname.'" value="'.(!empty($rate) ? price(price2num($rate, 'CR')) : 1).'" /> ';
  4163. print '<select name="calculation_mode">';
  4164. print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
  4165. print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
  4166. print '</select> ';
  4167. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4168. print '</form>';
  4169. } else {
  4170. if (!empty($rate))
  4171. {
  4172. print price($rate, 1, $langs, 1, 0);
  4173. if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  4174. } else {
  4175. print 1;
  4176. }
  4177. }
  4178. }
  4179. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4180. /**
  4181. * Show a select box with available absolute discounts
  4182. *
  4183. * @param string $page Page URL where form is shown
  4184. * @param int $selected Value pre-selected
  4185. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  4186. * @param int $socid Third party id
  4187. * @param float $amount Total amount available
  4188. * @param string $filter SQL filter on discounts
  4189. * @param int $maxvalue Max value for lines that can be selected
  4190. * @param string $more More string to add
  4191. * @param int $hidelist 1=Hide list
  4192. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  4193. * @return void
  4194. */
  4195. public function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
  4196. {
  4197. // phpcs:enable
  4198. global $conf, $langs;
  4199. if ($htmlname != "none")
  4200. {
  4201. print '<form method="post" action="'.$page.'">';
  4202. print '<input type="hidden" name="action" value="setabsolutediscount">';
  4203. print '<input type="hidden" name="token" value="'.newToken().'">';
  4204. print '<div class="inline-block">';
  4205. if (!empty($discount_type)) {
  4206. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  4207. {
  4208. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4209. else $translationKey = 'HasCreditNoteFromSupplier';
  4210. } else {
  4211. if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
  4212. else $translationKey = 'HasCreditNoteFromSupplier';
  4213. }
  4214. } else {
  4215. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  4216. {
  4217. if (!$filter || $filter == "fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
  4218. else $translationKey = 'CompanyHasCreditNote';
  4219. } else {
  4220. if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
  4221. else $translationKey = 'CompanyHasCreditNote';
  4222. }
  4223. }
  4224. print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
  4225. if (empty($hidelist)) print ': ';
  4226. print '</div>';
  4227. if (empty($hidelist))
  4228. {
  4229. print '<div class="inline-block" style="padding-right: 10px">';
  4230. $newfilter = 'discount_type='.intval($discount_type);
  4231. if (!empty($discount_type)) {
  4232. $newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
  4233. } else {
  4234. $newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
  4235. }
  4236. if ($filter) $newfilter .= ' AND ('.$filter.')';
  4237. $nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
  4238. if ($nbqualifiedlines > 0)
  4239. {
  4240. print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  4241. if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
  4242. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4243. if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
  4244. print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  4245. print '>';
  4246. }
  4247. print '</div>';
  4248. }
  4249. if ($more)
  4250. {
  4251. print '<div class="inline-block">';
  4252. print $more;
  4253. print '</div>';
  4254. }
  4255. print '</form>';
  4256. } else {
  4257. if ($selected)
  4258. {
  4259. print $selected;
  4260. } else {
  4261. print "0";
  4262. }
  4263. }
  4264. }
  4265. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4266. /**
  4267. * Show forms to select a contact
  4268. *
  4269. * @param string $page Page
  4270. * @param Societe $societe Filter on third party
  4271. * @param int $selected Id contact pre-selectionne
  4272. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  4273. * @return void
  4274. */
  4275. public function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
  4276. {
  4277. // phpcs:enable
  4278. global $langs, $conf;
  4279. if ($htmlname != "none")
  4280. {
  4281. print '<form method="post" action="'.$page.'">';
  4282. print '<input type="hidden" name="action" value="set_contact">';
  4283. print '<input type="hidden" name="token" value="'.newToken().'">';
  4284. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  4285. print '<tr><td>';
  4286. $num = $this->select_contacts($societe->id, $selected, $htmlname);
  4287. if ($num == 0)
  4288. {
  4289. $addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  4290. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  4291. }
  4292. print '</td>';
  4293. print '<td class="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  4294. print '</tr></table></form>';
  4295. } else {
  4296. if ($selected)
  4297. {
  4298. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  4299. $contact = new Contact($this->db);
  4300. $contact->fetch($selected);
  4301. print $contact->getFullName($langs);
  4302. } else {
  4303. print "&nbsp;";
  4304. }
  4305. }
  4306. }
  4307. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4308. /**
  4309. * Output html select to select thirdparty
  4310. *
  4311. * @param string $page Page
  4312. * @param string $selected Id preselected
  4313. * @param string $htmlname Name of HTML select
  4314. * @param string $filter optional filters criteras
  4315. * @param int $showempty Add an empty field
  4316. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  4317. * @param int $forcecombo Force to use combo box
  4318. * @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')))
  4319. * @param int $nooutput No print output. Return it only.
  4320. * @return void|string
  4321. */
  4322. public function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0)
  4323. {
  4324. // phpcs:enable
  4325. global $langs;
  4326. $out = '';
  4327. if ($htmlname != "none")
  4328. {
  4329. $out .= '<form method="post" action="'.$page.'">';
  4330. $out .= '<input type="hidden" name="action" value="set_thirdparty">';
  4331. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  4332. $out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
  4333. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4334. $out .= '</form>';
  4335. } else {
  4336. if ($selected)
  4337. {
  4338. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  4339. $soc = new Societe($this->db);
  4340. $soc->fetch($selected);
  4341. $out .= $soc->getNomUrl($langs);
  4342. } else {
  4343. $out .= "&nbsp;";
  4344. }
  4345. }
  4346. if ($nooutput) return $out;
  4347. else print $out;
  4348. }
  4349. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4350. /**
  4351. * Retourne la liste des devises, dans la langue de l'utilisateur
  4352. *
  4353. * @param string $selected preselected currency code
  4354. * @param string $htmlname name of HTML select list
  4355. * @deprecated
  4356. * @return void
  4357. */
  4358. public function select_currency($selected = '', $htmlname = 'currency_id')
  4359. {
  4360. // phpcs:enable
  4361. print $this->selectCurrency($selected, $htmlname);
  4362. }
  4363. /**
  4364. * Retourne la liste des devises, dans la langue de l'utilisateur
  4365. *
  4366. * @param string $selected preselected currency code
  4367. * @param string $htmlname name of HTML select list
  4368. * @param string $mode 0 = Add currency symbol into label, 1 = Add 3 letter iso code
  4369. * @return string
  4370. */
  4371. public function selectCurrency($selected = '', $htmlname = 'currency_id', $mode = 0)
  4372. {
  4373. global $conf, $langs, $user;
  4374. $langs->loadCacheCurrencies('');
  4375. $out = '';
  4376. if ($selected == 'euro' || $selected == 'euros') $selected = 'EUR'; // Pour compatibilite
  4377. $out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
  4378. foreach ($langs->cache_currencies as $code_iso => $currency)
  4379. {
  4380. if ($selected && $selected == $code_iso)
  4381. {
  4382. $out .= '<option value="'.$code_iso.'" selected>';
  4383. } else {
  4384. $out .= '<option value="'.$code_iso.'">';
  4385. }
  4386. $out .= $currency['label'];
  4387. if ($mode == 1)
  4388. {
  4389. $out .= ' ('.$code_iso.')';
  4390. } else {
  4391. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  4392. }
  4393. $out .= '</option>';
  4394. }
  4395. $out .= '</select>';
  4396. if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  4397. // Make select dynamic
  4398. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  4399. $out .= ajax_combobox($htmlname);
  4400. return $out;
  4401. }
  4402. /**
  4403. * Return array of currencies in user language
  4404. *
  4405. * @param string $selected preselected currency code
  4406. * @param string $htmlname name of HTML select list
  4407. * @param integer $useempty 1=Add empty line
  4408. * @return string
  4409. */
  4410. public function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0)
  4411. {
  4412. global $db, $conf, $langs, $user;
  4413. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  4414. $TCurrency = array();
  4415. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  4416. $sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  4417. $resql = $db->query($sql);
  4418. if ($resql)
  4419. {
  4420. while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
  4421. }
  4422. $out = '';
  4423. $out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  4424. if ($useempty) $out .= '<option value="">&nbsp;</option>';
  4425. // If company current currency not in table, we add it into list. Should always be available.
  4426. if (!in_array($conf->currency, $TCurrency))
  4427. {
  4428. $TCurrency[$conf->currency] = $conf->currency;
  4429. }
  4430. if (count($TCurrency) > 0)
  4431. {
  4432. foreach ($langs->cache_currencies as $code_iso => $currency)
  4433. {
  4434. if (isset($TCurrency[$code_iso]))
  4435. {
  4436. if (!empty($selected) && $selected == $code_iso) $out .= '<option value="'.$code_iso.'" selected="selected">';
  4437. else $out .= '<option value="'.$code_iso.'">';
  4438. $out .= $currency['label'];
  4439. $out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
  4440. $out .= '</option>';
  4441. }
  4442. }
  4443. }
  4444. $out .= '</select>';
  4445. // Make select dynamic
  4446. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  4447. $out .= ajax_combobox($htmlname);
  4448. return $out;
  4449. }
  4450. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4451. /**
  4452. * Load into the cache vat rates of a country
  4453. *
  4454. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  4455. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  4456. */
  4457. public function load_cache_vatrates($country_code)
  4458. {
  4459. // phpcs:enable
  4460. global $langs;
  4461. $num = count($this->cache_vatrates);
  4462. if ($num > 0) return $num; // Cache already loaded
  4463. dol_syslog(__METHOD__, LOG_DEBUG);
  4464. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
  4465. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4466. $sql .= " WHERE t.fk_pays = c.rowid";
  4467. $sql .= " AND t.active > 0";
  4468. $sql .= " AND c.code IN (".$country_code.")";
  4469. $sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  4470. $resql = $this->db->query($sql);
  4471. if ($resql)
  4472. {
  4473. $num = $this->db->num_rows($resql);
  4474. if ($num)
  4475. {
  4476. for ($i = 0; $i < $num; $i++)
  4477. {
  4478. $obj = $this->db->fetch_object($resql);
  4479. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  4480. $this->cache_vatrates[$i]['code'] = $obj->code;
  4481. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  4482. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  4483. $this->cache_vatrates[$i]['localtax1'] = $obj->localtax1;
  4484. $this->cache_vatrates[$i]['localtax1_type'] = $obj->localtax1_type;
  4485. $this->cache_vatrates[$i]['localtax2'] = $obj->localtax2;
  4486. $this->cache_vatrates[$i]['localtax2_type'] = $obj->localtax1_type;
  4487. $this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
  4488. $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
  4489. $positiverates = '';
  4490. if ($obj->taux) $positiverates .= ($positiverates ? '/' : '').$obj->taux;
  4491. if ($obj->localtax1) $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
  4492. if ($obj->localtax2) $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
  4493. if (empty($positiverates)) $positiverates = '0';
  4494. $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
  4495. }
  4496. return $num;
  4497. } else {
  4498. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</font>';
  4499. return -1;
  4500. }
  4501. } else {
  4502. $this->error = '<font class="error">'.$this->db->error().'</font>';
  4503. return -2;
  4504. }
  4505. }
  4506. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4507. /**
  4508. * Output an HTML select vat rate.
  4509. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  4510. *
  4511. * @param string $htmlname Name of HTML select field
  4512. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  4513. * @param Societe $societe_vendeuse Thirdparty seller
  4514. * @param Societe $societe_acheteuse Thirdparty buyer
  4515. * @param int $idprod Id product. O if unknown of NA.
  4516. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  4517. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  4518. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4519. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4520. * 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.
  4521. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  4522. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  4523. * Sinon la TVA proposee par defaut=0. Fin de regle.
  4524. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  4525. * @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
  4526. * @return string
  4527. */
  4528. public function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
  4529. {
  4530. // phpcs:enable
  4531. global $langs, $conf, $mysoc;
  4532. $langs->load('errors');
  4533. $return = '';
  4534. // Define defaultnpr, defaultttx and defaultcode
  4535. $defaultnpr = ($info_bits & 0x01);
  4536. $defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
  4537. $defaulttx = str_replace('*', '', $selectedrate);
  4538. $defaultcode = '';
  4539. if (preg_match('/\((.*)\)/', $defaulttx, $reg))
  4540. {
  4541. $defaultcode = $reg[1];
  4542. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  4543. }
  4544. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  4545. // Check parameters
  4546. if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code)
  4547. {
  4548. if ($societe_vendeuse->id == $mysoc->id)
  4549. {
  4550. $return .= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</font>';
  4551. } else {
  4552. $return .= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</font>';
  4553. }
  4554. return $return;
  4555. }
  4556. //var_dump($societe_acheteuse);
  4557. //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";
  4558. //exit;
  4559. // Define list of countries to use to search VAT rates to show
  4560. // First we defined code_country to use to find list
  4561. if (is_object($societe_vendeuse))
  4562. {
  4563. $code_country = "'".$societe_vendeuse->country_code."'";
  4564. } else {
  4565. $code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  4566. }
  4567. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  4568. {
  4569. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4570. if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany())))
  4571. {
  4572. // We also add the buyer
  4573. if (is_numeric($type))
  4574. {
  4575. if ($type == 1) // We know product is a service
  4576. {
  4577. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4578. }
  4579. } elseif (!$idprod) // We don't know type of product
  4580. {
  4581. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4582. } else {
  4583. $prodstatic = new Product($this->db);
  4584. $prodstatic->fetch($idprod);
  4585. if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service
  4586. {
  4587. $code_country .= ",'".$societe_acheteuse->country_code."'";
  4588. }
  4589. }
  4590. }
  4591. }
  4592. // Now we get list
  4593. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  4594. if ($num > 0)
  4595. {
  4596. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  4597. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4598. {
  4599. $tmpthirdparty = new Societe($this->db);
  4600. $defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  4601. $defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
  4602. if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  4603. $defaultcode = $reg[1];
  4604. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  4605. }
  4606. if (empty($defaulttx)) $defaultnpr = 0;
  4607. }
  4608. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  4609. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  4610. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4611. {
  4612. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
  4613. else $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  4614. }
  4615. // Disabled if seller is not subject to VAT
  4616. $disabled = false; $title = '';
  4617. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
  4618. {
  4619. // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses instead
  4620. // of using supplier invoices (this is a very bad idea !)
  4621. if (empty($conf->global->EXPENSEREPORT_OVERRIDE_VAT))
  4622. {
  4623. $title = ' title="'.$langs->trans('VATIsNotUsed').'"';
  4624. $disabled = true;
  4625. }
  4626. }
  4627. if (!$options_only) $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
  4628. $selectedfound = false;
  4629. foreach ($this->cache_vatrates as $rate)
  4630. {
  4631. // Keep only 0 if seller is not subject to VAT
  4632. if ($disabled && $rate['txtva'] != 0) continue;
  4633. // Define key to use into select list
  4634. $key = $rate['txtva'];
  4635. $key .= $rate['nprtva'] ? '*' : '';
  4636. if ($mode > 0 && $rate['code']) $key .= ' ('.$rate['code'].')';
  4637. if ($mode < 0) $key = $rate['rowid'];
  4638. $return .= '<option value="'.$key.'"';
  4639. if (!$selectedfound)
  4640. {
  4641. if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  4642. {
  4643. if ($defaultcode == $rate['code'])
  4644. {
  4645. $return .= ' selected';
  4646. $selectedfound = true;
  4647. }
  4648. } elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
  4649. {
  4650. $return .= ' selected';
  4651. $selectedfound = true;
  4652. }
  4653. }
  4654. $return .= '>';
  4655. //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
  4656. if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
  4657. {
  4658. $return .= $rate['labelpositiverates'];
  4659. } else {
  4660. $return .= vatrate($rate['label']);
  4661. }
  4662. //$return.=($rate['code']?' '.$rate['code']:'');
  4663. $return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the * (old behaviour only if new vat code is not used)
  4664. $return .= '</option>';
  4665. }
  4666. if (!$options_only) $return .= '</select>';
  4667. } else {
  4668. $return .= $this->error;
  4669. }
  4670. $this->num = $num;
  4671. return $return;
  4672. }
  4673. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4674. /**
  4675. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4676. * Fields are preselected with :
  4677. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4678. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4679. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4680. *
  4681. * @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).
  4682. * @param string $prefix Prefix for fields name
  4683. * @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
  4684. * @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
  4685. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4686. * @param string $form_name Not used
  4687. * @param int $d 1=Show days, month, years
  4688. * @param int $addnowlink Add a link "Now"
  4689. * @param int $nooutput Do not output html string but return it
  4690. * @param int $disabled Disable input fields
  4691. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  4692. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  4693. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  4694. * @return string|void Nothing or string if nooutput is 1
  4695. * @deprecated
  4696. * @see selectDate(), form_date(), select_month(), select_year(), select_dayofweek()
  4697. */
  4698. 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 = '')
  4699. {
  4700. // phpcs:enable
  4701. $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
  4702. if (!empty($nooutput)) {
  4703. return $retstring;
  4704. }
  4705. print $retstring;
  4706. return;
  4707. }
  4708. /**
  4709. * Show 2 HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4710. * Fields are preselected with :
  4711. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4712. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4713. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4714. *
  4715. * @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).
  4716. * @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).
  4717. * @param string $prefix Prefix for fields name
  4718. * @param string $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4719. * @return string Html for selectDate
  4720. * @see form_date(), select_month(), select_year(), select_dayofweek()
  4721. */
  4722. public function selectDateToDate($set_time = '', $set_time_end = '', $prefix = 're', $empty = 0)
  4723. {
  4724. $ret = $this->selectDate($set_time, $prefix.'_start', 0, 0, $empty);
  4725. $ret .= '<br/>';
  4726. $ret .= $this->selectDate($set_time_end, $prefix.'_end', 0, 0, $empty);
  4727. return $ret;
  4728. }
  4729. /**
  4730. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4731. * Fields are preselected with :
  4732. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4733. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4734. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4735. *
  4736. * @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).
  4737. * @param string $prefix Prefix for fields name
  4738. * @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
  4739. * @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
  4740. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4741. * @param string $form_name Not used
  4742. * @param int $d 1=Show days, month, years
  4743. * @param int $addnowlink Add a link "Now", 1 with server time, 2 with local computer time
  4744. * @param int $disabled Disable input fields
  4745. * @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')
  4746. * @param string $addplusone Add a link "+1 hour". Value must be name of another selectDate field.
  4747. * @param datetime $adddateof Add a link "Date of ..." using the following date. See also $labeladddateof for the label used.
  4748. * @param string $openinghours Specify hour start and hour end for the select ex 8,20
  4749. * @param int $stepminutes Specify step for minutes between 1 and 30
  4750. * @param string $labeladddateof Label to use for the $adddateof parameter.
  4751. * @return string Html for selectDate
  4752. * @see form_date(), select_month(), select_year(), select_dayofweek()
  4753. */
  4754. 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 = '')
  4755. {
  4756. global $conf, $langs;
  4757. $retstring = '';
  4758. if ($prefix == '') $prefix = 're';
  4759. if ($h == '') $h = 0;
  4760. if ($m == '') $m = 0;
  4761. $emptydate = 0;
  4762. $emptyhours = 0;
  4763. if ($stepminutes <= 0 || $stepminutes > 30) $stepminutes = 1;
  4764. if ($empty == 1) { $emptydate = 1; $emptyhours = 1; }
  4765. if ($empty == 2) { $emptydate = 0; $emptyhours = 1; }
  4766. $orig_set_time = $set_time;
  4767. if ($set_time === '' && $emptydate == 0)
  4768. {
  4769. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4770. $set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
  4771. }
  4772. // Analysis of the pre-selection date
  4773. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) // deprecated usage
  4774. {
  4775. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  4776. $syear = (!empty($reg[1]) ? $reg[1] : '');
  4777. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  4778. $sday = (!empty($reg[3]) ? $reg[3] : '');
  4779. $shour = (!empty($reg[4]) ? $reg[4] : '');
  4780. $smin = (!empty($reg[5]) ? $reg[5] : '');
  4781. } elseif (strval($set_time) != '' && $set_time != -1)
  4782. {
  4783. // set_time est un timestamps (0 possible)
  4784. $syear = dol_print_date($set_time, "%Y");
  4785. $smonth = dol_print_date($set_time, "%m");
  4786. $sday = dol_print_date($set_time, "%d");
  4787. if ($orig_set_time != '')
  4788. {
  4789. $shour = dol_print_date($set_time, "%H");
  4790. $smin = dol_print_date($set_time, "%M");
  4791. $ssec = dol_print_date($set_time, "%S");
  4792. } else {
  4793. $shour = '';
  4794. $smin = '';
  4795. $ssec = '';
  4796. }
  4797. } else {
  4798. // Date est '' ou vaut -1
  4799. $syear = '';
  4800. $smonth = '';
  4801. $sday = '';
  4802. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  4803. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
  4804. $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
  4805. }
  4806. if ($h == 3) $shour = '';
  4807. if ($m == 3) $smin = '';
  4808. // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
  4809. $usecalendar = 'combo';
  4810. if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
  4811. $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
  4812. }
  4813. if ($d)
  4814. {
  4815. // Show date with popup
  4816. if ($usecalendar != 'combo')
  4817. {
  4818. $formated_date = '';
  4819. //print "e".$set_time." t ".$conf->format_date_short;
  4820. if (strval($set_time) != '' && $set_time != -1)
  4821. {
  4822. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  4823. $formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4824. }
  4825. // Calendrier popup version eldy
  4826. if ($usecalendar == "eldy")
  4827. {
  4828. // Zone de saisie manuelle de la date
  4829. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  4830. $retstring .= ($disabled ? ' disabled' : '');
  4831. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4832. $retstring .= '>';
  4833. // Icone calendrier
  4834. if (!$disabled)
  4835. {
  4836. $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  4837. $base = DOL_URL_ROOT.'/core/';
  4838. $retstring .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
  4839. $retstring .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
  4840. } else $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  4841. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4842. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4843. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4844. } elseif ($usecalendar == 'jquery')
  4845. {
  4846. if (!$disabled)
  4847. {
  4848. // Output javascript for datepicker
  4849. $retstring .= "<script type='text/javascript'>";
  4850. $retstring .= "$(function(){ $('#".$prefix."').datepicker({
  4851. dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
  4852. autoclose: true,
  4853. todayHighlight: true,";
  4854. if (!empty($conf->dol_use_jmobile))
  4855. {
  4856. $retstring .= "
  4857. beforeShow: function (input, datePicker) {
  4858. input.disabled = true;
  4859. },
  4860. onClose: function (dateText, datePicker) {
  4861. this.disabled = false;
  4862. },
  4863. ";
  4864. }
  4865. // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
  4866. if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
  4867. {
  4868. $retstring .= "
  4869. showOn: 'button',
  4870. buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
  4871. buttonImageOnly: true";
  4872. }
  4873. $retstring .= "
  4874. }) });";
  4875. $retstring .= "</script>";
  4876. }
  4877. // Zone de saisie manuelle de la date
  4878. $retstring .= '<div class="nowrap inline-block">';
  4879. $retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidthdate" maxlength="11" value="'.$formated_date.'"';
  4880. $retstring .= ($disabled ? ' disabled' : '');
  4881. $retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4882. $retstring .= '>';
  4883. // Icone calendrier
  4884. if (!$disabled)
  4885. {
  4886. /* Not required. Managed by option buttonImage of jquery
  4887. $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
  4888. $retstring.="<script type='text/javascript'>";
  4889. $retstring.="jQuery(document).ready(function() {";
  4890. $retstring.=' jQuery("#'.$prefix.'id").click(function() {';
  4891. $retstring.=" jQuery('#".$prefix."').focus();";
  4892. $retstring.=' });';
  4893. $retstring.='});';
  4894. $retstring.="</script>";*/
  4895. } else {
  4896. $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
  4897. }
  4898. $retstring .= '</div>';
  4899. $retstring .= '<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4900. $retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4901. $retstring .= '<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4902. } else {
  4903. $retstring .= "Bad value of MAIN_POPUP_CALENDAR";
  4904. }
  4905. }
  4906. // Show date with combo selects
  4907. else {
  4908. //$retstring.='<div class="inline-block">';
  4909. // Day
  4910. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  4911. if ($emptydate || $set_time == -1)
  4912. {
  4913. $retstring .= '<option value="0" selected>&nbsp;</option>';
  4914. }
  4915. for ($day = 1; $day <= 31; $day++)
  4916. {
  4917. $retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
  4918. }
  4919. $retstring .= "</select>";
  4920. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  4921. if ($emptydate || $set_time == -1)
  4922. {
  4923. $retstring .= '<option value="0" selected>&nbsp;</option>';
  4924. }
  4925. // Month
  4926. for ($month = 1; $month <= 12; $month++)
  4927. {
  4928. $retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
  4929. $retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
  4930. $retstring .= "</option>";
  4931. }
  4932. $retstring .= "</select>";
  4933. // Year
  4934. if ($emptydate || $set_time == -1)
  4935. {
  4936. $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.'">';
  4937. } else {
  4938. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  4939. for ($year = $syear - 10; $year < $syear + 10; $year++)
  4940. {
  4941. $retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
  4942. }
  4943. $retstring .= "</select>\n";
  4944. }
  4945. //$retstring.='</div>';
  4946. }
  4947. }
  4948. if ($d && $h) $retstring .= ($h == 2 ? '<br>' : ' ');
  4949. if ($h)
  4950. {
  4951. $hourstart = 0;
  4952. $hourend = 24;
  4953. if ($openinghours != '') {
  4954. $openinghours = explode(',', $openinghours);
  4955. $hourstart = $openinghours[0];
  4956. $hourend = $openinghours[1];
  4957. if ($hourend < $hourstart) $hourend = $hourstart;
  4958. }
  4959. // Show hour
  4960. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  4961. if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
  4962. for ($hour = $hourstart; $hour < $hourend; $hour++)
  4963. {
  4964. if (strlen($hour) < 2) $hour = "0".$hour;
  4965. $retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour.(empty($conf->dol_optimize_smallscreen) ? '' : 'H').'</option>';
  4966. }
  4967. $retstring .= '</select>';
  4968. if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
  4969. }
  4970. if ($m)
  4971. {
  4972. // Show minutes
  4973. $retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  4974. if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
  4975. for ($min = 0; $min < 60; $min += $stepminutes)
  4976. {
  4977. if (strlen($min) < 2) $min = "0".$min;
  4978. $retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
  4979. }
  4980. $retstring .= '</select>';
  4981. $retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
  4982. }
  4983. // Add a "Now" link
  4984. if ($conf->use_javascript_ajax && $addnowlink)
  4985. {
  4986. // Script which will be inserted in the onClick of the "Now" link
  4987. $reset_scripts = "";
  4988. if ($addnowlink == 2) // local computer time
  4989. {
  4990. // pad add leading 0 on numbers
  4991. $reset_scripts .= "Number.prototype.pad = function(size) {
  4992. var s = String(this);
  4993. while (s.length < (size || 2)) {s = '0' + s;}
  4994. return s;
  4995. };
  4996. var d = new Date();";
  4997. }
  4998. // Generate the date part, depending on the use or not of the javascript calendar
  4999. if ($addnowlink == 1) // server time expressed in user time setup
  5000. {
  5001. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');';
  5002. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');';
  5003. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');';
  5004. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');';
  5005. } elseif ($addnowlink == 2)
  5006. {
  5007. /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix.
  5008. * This break application for foreign languages.
  5009. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));';
  5010. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());';
  5011. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);';
  5012. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());';
  5013. */
  5014. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day', 'tzuser').'\');';
  5015. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d', 'tzuser').'\');';
  5016. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m', 'tzuser').'\');';
  5017. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y', 'tzuser').'\');';
  5018. }
  5019. /*if ($usecalendar == "eldy")
  5020. {
  5021. $base=DOL_URL_ROOT.'/core/';
  5022. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  5023. }
  5024. else
  5025. {
  5026. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  5027. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  5028. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  5029. }*/
  5030. // Update the hour part
  5031. if ($h)
  5032. {
  5033. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5034. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  5035. if ($addnowlink == 1)
  5036. {
  5037. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H', 'tzuser').'\');';
  5038. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5039. } elseif ($addnowlink == 2)
  5040. {
  5041. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());';
  5042. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();';
  5043. }
  5044. if ($fullday) $reset_scripts .= ' } ';
  5045. }
  5046. // Update the minute part
  5047. if ($m)
  5048. {
  5049. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5050. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  5051. if ($addnowlink == 1)
  5052. {
  5053. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M', 'tzuser').'\');';
  5054. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5055. } elseif ($addnowlink == 2)
  5056. {
  5057. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());';
  5058. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();';
  5059. }
  5060. if ($fullday) $reset_scripts .= ' } ';
  5061. }
  5062. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5063. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  5064. {
  5065. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  5066. $retstring .= $langs->trans("Now");
  5067. $retstring .= '</button> ';
  5068. }
  5069. }
  5070. // Add a "Plus one hour" link
  5071. if ($conf->use_javascript_ajax && $addplusone)
  5072. {
  5073. // Script which will be inserted in the onClick of the "Add plusone" link
  5074. $reset_scripts = "";
  5075. // Generate the date part, depending on the use or not of the javascript calendar
  5076. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day').'\');';
  5077. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d').'\');';
  5078. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m').'\');';
  5079. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y').'\');';
  5080. // Update the hour part
  5081. if ($h)
  5082. {
  5083. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5084. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H').'\');';
  5085. if ($fullday) $reset_scripts .= ' } ';
  5086. }
  5087. // Update the minute part
  5088. if ($m)
  5089. {
  5090. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  5091. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M').'\');';
  5092. if ($fullday) $reset_scripts .= ' } ';
  5093. }
  5094. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  5095. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  5096. {
  5097. $retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  5098. $retstring .= $langs->trans("DateStartPlusOne");
  5099. $retstring .= '</button> ';
  5100. }
  5101. }
  5102. // Add a "Plus one hour" link
  5103. if ($conf->use_javascript_ajax && $adddateof)
  5104. {
  5105. $tmparray = dol_getdate($adddateof);
  5106. if (empty($labeladddateof)) $labeladddateof = $langs->trans("DateInvoice");
  5107. $retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$labeladddateof.'</a>';
  5108. }
  5109. return $retstring;
  5110. }
  5111. /**
  5112. * selectTypeDuration
  5113. *
  5114. * @param string $prefix Prefix
  5115. * @param string $selected Selected type
  5116. * @return string HTML select string
  5117. */
  5118. public function selectTypeDuration($prefix, $selected = 'minute')
  5119. {
  5120. global $langs;
  5121. $TDurationTypes = array('year'=>$langs->trans('Years'), 'month'=>$langs->trans('Month'), 'week'=>$langs->trans('Weeks'), 'day'=>$langs->trans('Days'), 'hour'=>$langs->trans('Hours'), 'minute'=>$langs->trans('Minutes'));
  5122. $retstring = '<select class="flat" id="select_'.$prefix.'type_duration" name="'.$prefix.'type_duration">';
  5123. foreach ($TDurationTypes as $key=>$typeduration) {
  5124. $retstring .= '<option value="'.$key.'"';
  5125. if ($key == $selected) {
  5126. $retstring .= " selected";
  5127. }
  5128. $retstring .= ">".$typeduration."</option>";
  5129. }
  5130. $retstring .= "</select>";
  5131. return $retstring;
  5132. }
  5133. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5134. /**
  5135. * Function to show a form to select a duration on a page
  5136. *
  5137. * @param string $prefix Prefix for input fields
  5138. * @param int $iSecond Default preselected duration (number of seconds or '')
  5139. * @param int $disabled Disable the combo box
  5140. * @param string $typehour If 'select' then input hour and input min is a combo,
  5141. * If 'text' input hour is in text and input min is a text,
  5142. * If 'textselect' input hour is in text and input min is a combo
  5143. * @param integer $minunderhours If 1, show minutes selection under the hours
  5144. * @param int $nooutput Do not output html string but return it
  5145. * @return string|void
  5146. */
  5147. public function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
  5148. {
  5149. // phpcs:enable
  5150. global $langs;
  5151. $retstring = '';
  5152. $hourSelected = 0; $minSelected = 0;
  5153. // Hours
  5154. if ($iSecond != '')
  5155. {
  5156. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5157. $hourSelected = convertSecondToTime($iSecond, 'allhour');
  5158. $minSelected = convertSecondToTime($iSecond, 'min');
  5159. }
  5160. if ($typehour == 'select') {
  5161. $retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
  5162. for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours
  5163. {
  5164. $retstring .= '<option value="'.$hour.'"';
  5165. if ($hourSelected == $hour)
  5166. {
  5167. $retstring .= " selected";
  5168. }
  5169. $retstring .= ">".$hour."</option>";
  5170. }
  5171. $retstring .= "</select>";
  5172. } elseif ($typehour == 'text' || $typehour == 'textselect') {
  5173. $retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
  5174. } else {
  5175. return 'BadValueForParameterTypeHour';
  5176. }
  5177. if ($typehour != 'text') $retstring .= ' '.$langs->trans('HourShort');
  5178. else $retstring .= '<span class="hideonsmartphone">:</span>';
  5179. // Minutes
  5180. if ($minunderhours) $retstring .= '<br>';
  5181. else $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
  5182. if ($typehour == 'select' || $typehour == 'textselect')
  5183. {
  5184. $retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
  5185. for ($min = 0; $min <= 55; $min = $min + 5)
  5186. {
  5187. $retstring .= '<option value="'.$min.'"';
  5188. if ($minSelected == $min) $retstring .= ' selected';
  5189. $retstring .= '>'.$min.'</option>';
  5190. }
  5191. $retstring .= "</select>";
  5192. } elseif ($typehour == 'text')
  5193. {
  5194. $retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
  5195. }
  5196. if ($typehour != 'text') $retstring .= ' '.$langs->trans('MinuteShort');
  5197. //$retstring.="&nbsp;";
  5198. if (!empty($nooutput)) return $retstring;
  5199. print $retstring;
  5200. return;
  5201. }
  5202. /**
  5203. * Generic method to select a component from a combo list.
  5204. * This is the generic method that will replace all specific existing methods.
  5205. *
  5206. * @param string $objectdesc ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]
  5207. * @param string $htmlname Name of HTML select component
  5208. * @param int $preselectedvalue Preselected value (ID of element)
  5209. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  5210. * @param string $searchkey Search criteria
  5211. * @param string $placeholder Place holder
  5212. * @param string $morecss More CSS
  5213. * @param string $moreparams More params provided to ajax call
  5214. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  5215. * @param int $disabled 1=Html component is disabled
  5216. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  5217. * @return string Return HTML string
  5218. * @see selectForFormsList() select_thirdparty()
  5219. */
  5220. public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '')
  5221. {
  5222. global $conf, $user;
  5223. $objecttmp = null;
  5224. $InfoFieldList = explode(":", $objectdesc);
  5225. $classname = $InfoFieldList[0];
  5226. $classpath = $InfoFieldList[1];
  5227. $addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2];
  5228. $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3];
  5229. if (!empty($classpath))
  5230. {
  5231. dol_include_once($classpath);
  5232. if ($classname && class_exists($classname))
  5233. {
  5234. $objecttmp = new $classname($this->db);
  5235. // Make some replacement
  5236. $sharedentities = getEntity(strtolower($classname));
  5237. $objecttmp->filter = str_replace(
  5238. array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__'),
  5239. array($conf->entity, $sharedentities, $user->id),
  5240. $filter);
  5241. }
  5242. }
  5243. if (!is_object($objecttmp))
  5244. {
  5245. dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
  5246. return 'Error bad setup of type for field '.join(',', $InfoFieldList);
  5247. }
  5248. //var_dump($objecttmp->filter);
  5249. $prefixforautocompletemode = $objecttmp->element;
  5250. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
  5251. if ($prefixforautocompletemode == 'product') $prefixforautocompletemode = 'produit';
  5252. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  5253. dol_syslog(get_class($this)."::selectForForms object->filter=".$objecttmp->filter, LOG_DEBUG);
  5254. $out = '';
  5255. if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo)
  5256. {
  5257. // No immediate load of all database
  5258. $placeholder = '';
  5259. if ($preselectedvalue && empty($selected_input_value))
  5260. {
  5261. $objecttmp->fetch($preselectedvalue);
  5262. $selected_input_value = ($prefixforautocompletemode == 'company' ? $objecttmp->name : $objecttmp->ref);
  5263. //unset($objecttmp);
  5264. }
  5265. $objectdesc = $classname.':'.$classpath.':'.$addcreatebuttonornot.':'.$filter;
  5266. $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
  5267. // No immediate load of all database
  5268. $urloption = 'htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.'&filter='.urlencode($objecttmp->filter);
  5269. // Activate the auto complete using ajax call.
  5270. $out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
  5271. $out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
  5272. if ($placeholder) $placeholder = ' placeholder="'.$placeholder.'"';
  5273. $out .= '<input type="text" class="'.$morecss.'"'.($disabled ? ' disabled="disabled"' : '').' name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
  5274. } else {
  5275. // Immediate load of table record. Note: filter is inside $objecttmp->filter
  5276. $out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo, 0, $disabled);
  5277. }
  5278. return $out;
  5279. }
  5280. /**
  5281. * Function to forge a SQL criteria
  5282. *
  5283. * @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"
  5284. * @return string Forged criteria. Example: "t.field like 'abc%'"
  5285. */
  5286. protected static function forgeCriteriaCallback($matches)
  5287. {
  5288. global $db;
  5289. //dol_syslog("Convert matches ".$matches[1]);
  5290. if (empty($matches[1])) return '';
  5291. $tmp = explode(':', $matches[1]);
  5292. if (count($tmp) < 3) return '';
  5293. $tmpescaped = $tmp[2];
  5294. $regbis = array();
  5295. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis))
  5296. {
  5297. $tmpescaped = "'".$db->escape($regbis[1])."'";
  5298. } else {
  5299. $tmpescaped = $db->escape($tmpescaped);
  5300. }
  5301. return $db->escape($tmp[0]).' '.strtoupper($db->escape($tmp[1]))." ".$tmpescaped;
  5302. }
  5303. /**
  5304. * Output html form to select an object.
  5305. * Note, this function is called by selectForForms or by ajax selectobject.php
  5306. *
  5307. * @param Object $objecttmp Object to knwo the table to scan for combo.
  5308. * @param string $htmlname Name of HTML select component
  5309. * @param int $preselectedvalue Preselected value (ID of element)
  5310. * @param string $showempty ''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
  5311. * @param string $searchkey Search value
  5312. * @param string $placeholder Place holder
  5313. * @param string $morecss More CSS
  5314. * @param string $moreparams More params provided to ajax call
  5315. * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification)
  5316. * @param int $outputmode 0=HTML select string, 1=Array
  5317. * @param int $disabled 1=Html component is disabled
  5318. * @return string|array Return HTML string
  5319. * @see selectForForms()
  5320. */
  5321. public function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled = 0)
  5322. {
  5323. global $conf, $langs, $user;
  5324. //print "$objecttmp->filter, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0, $disabled";
  5325. $prefixforautocompletemode = $objecttmp->element;
  5326. if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
  5327. $confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
  5328. if (!empty($objecttmp->fields)) // For object that declare it, it is better to use declared fields (like societe, contact, ...)
  5329. {
  5330. $tmpfieldstoshow = '';
  5331. foreach ($objecttmp->fields as $key => $val)
  5332. {
  5333. if ($val['showoncombobox']) $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
  5334. }
  5335. if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
  5336. } else {
  5337. // For backward compatibility
  5338. $objecttmp->fields['ref'] = array('type'=>'varchar(30)', 'label'=>'Ref', 'showoncombobox'=>1);
  5339. }
  5340. if (empty($fieldstoshow))
  5341. {
  5342. if (isset($objecttmp->fields['ref'])) {
  5343. $fieldstoshow = 't.ref';
  5344. } else {
  5345. $langs->load("errors");
  5346. $this->error = $langs->trans("ErrorNoFieldWithAttributeShowoncombobox");
  5347. return $langs->trans('ErrorNoFieldWithAttributeShowoncombobox');
  5348. }
  5349. }
  5350. $out = '';
  5351. $outarray = array();
  5352. $num = 0;
  5353. // Search data
  5354. $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX.$objecttmp->table_element." as t";
  5355. if (isset($objecttmp->ismultientitymanaged) && !is_numeric($objecttmp->ismultientitymanaged)) {
  5356. $tmparray = explode('@', $objecttmp->ismultientitymanaged);
  5357. $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.$tmparray[1].' as parenttable ON parenttable.rowid = t.'.$tmparray[0];
  5358. }
  5359. if ($objecttmp->ismultientitymanaged == 'fk_soc@societe')
  5360. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  5361. $sql .= " WHERE 1=1";
  5362. if (isset($objecttmp->ismultientitymanaged) && $objecttmp->ismultientitymanaged == 1) $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
  5363. if (isset($objecttmp->ismultientitymanaged) && !is_numeric($objecttmp->ismultientitymanaged)) {
  5364. $sql .= ' AND parenttable.entity = t.'.$tmparray[0];
  5365. }
  5366. if ($objecttmp->ismultientitymanaged == 1 && !empty($user->socid)) {
  5367. if ($objecttmp->element == 'societe') $sql .= " AND t.rowid = ".$user->socid;
  5368. else $sql .= " AND t.fk_soc = ".$user->socid;
  5369. }
  5370. if ($searchkey != '') $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
  5371. if ($objecttmp->ismultientitymanaged == 'fk_soc@societe') {
  5372. if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
  5373. }
  5374. if ($objecttmp->filter) { // Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
  5375. /*if (! DolibarrApi::_checkFilters($objecttmp->filter))
  5376. {
  5377. throw new RestException(503, 'Error when validating parameter sqlfilters '.$objecttmp->filter);
  5378. }*/
  5379. $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  5380. $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'Form::forgeCriteriaCallback', $objecttmp->filter).")";
  5381. }
  5382. $sql .= $this->db->order($fieldstoshow, "ASC");
  5383. //$sql.=$this->db->plimit($limit, 0);
  5384. //print $sql;
  5385. // Build output string
  5386. $resql = $this->db->query($sql);
  5387. if ($resql)
  5388. {
  5389. if (!$forcecombo)
  5390. {
  5391. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5392. $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
  5393. }
  5394. // Construct $out and $outarray
  5395. $out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
  5396. // 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
  5397. $textifempty = '&nbsp;';
  5398. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  5399. if (!empty($conf->global->$confkeyforautocompletemode))
  5400. {
  5401. if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
  5402. else $textifempty .= $langs->trans("All");
  5403. }
  5404. if ($showempty) $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
  5405. $num = $this->db->num_rows($resql);
  5406. $i = 0;
  5407. if ($num)
  5408. {
  5409. while ($i < $num)
  5410. {
  5411. $obj = $this->db->fetch_object($resql);
  5412. $label = '';
  5413. $tmparray = explode(',', $fieldstoshow);
  5414. foreach ($tmparray as $key => $val)
  5415. {
  5416. $val = preg_replace('/t\./', '', $val);
  5417. $label .= (($label && $obj->$val) ? ' - ' : '').$obj->$val;
  5418. }
  5419. if (empty($outputmode))
  5420. {
  5421. if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
  5422. {
  5423. $out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  5424. } else {
  5425. $out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  5426. }
  5427. } else {
  5428. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  5429. }
  5430. $i++;
  5431. if (($i % 10) == 0) $out .= "\n";
  5432. }
  5433. }
  5434. $out .= '</select>'."\n";
  5435. } else {
  5436. dol_print_error($this->db);
  5437. }
  5438. $this->result = array('nbofelement'=>$num);
  5439. if ($outputmode) return $outarray;
  5440. return $out;
  5441. }
  5442. /**
  5443. * Return a HTML select string, built from an array of key+value.
  5444. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  5445. *
  5446. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  5447. * @param array $array Array like array(key => value) or array(key=>array('label'=>..., 'data-...'=>...))
  5448. * @param string|string[] $id Preselected key or preselected keys for multiselect
  5449. * @param int|string $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
  5450. * @param int $key_in_label 1 to show key into label with format "[key] value"
  5451. * @param int $value_as_key 1 to use value as key
  5452. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  5453. * @param int $translate 1=Translate and encode value
  5454. * @param int $maxlen Length maximum for labels
  5455. * @param int $disabled Html select box is disabled
  5456. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  5457. * @param string $morecss Add more class to css styles
  5458. * @param int $addjscombo Add js combo
  5459. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  5460. * @param int $disablebademail 1=Check if a not valid email, 2=Check string '---', and if found into value, disable and colorize entry
  5461. * @param int $nohtmlescape No html escaping.
  5462. * @return string HTML select string.
  5463. * @see multiselectarray(), selectArrayAjax(), selectArrayFilter()
  5464. */
  5465. 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 = 0, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
  5466. {
  5467. global $conf, $langs;
  5468. // Do we want a multiselect ?
  5469. //$jsbeautify = 0;
  5470. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  5471. $jsbeautify = 1;
  5472. if ($value_as_key) $array = array_combine($array, $array);
  5473. $out = '';
  5474. // Add code for jquery to use multiselect
  5475. if ($addjscombo && $jsbeautify)
  5476. {
  5477. $minLengthToAutocomplete = 0;
  5478. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? (constant('REQUIRE_JQUERY_MULTISELECT') ?constant('REQUIRE_JQUERY_MULTISELECT') : 'select2') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5479. // Enhance with select2
  5480. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  5481. $out .= ajax_combobox($htmlname);
  5482. }
  5483. $out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled="disabled" ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
  5484. $out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
  5485. $out .= '>';
  5486. if ($show_empty)
  5487. {
  5488. $textforempty = ' ';
  5489. if (!empty($conf->use_javascript_ajax)) $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
  5490. if (!is_numeric($show_empty)) $textforempty = $show_empty;
  5491. $out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
  5492. }
  5493. if (is_array($array))
  5494. {
  5495. // Translate
  5496. if ($translate)
  5497. {
  5498. foreach ($array as $key => $value)
  5499. {
  5500. if (!is_array($value)) $array[$key] = $langs->trans($value);
  5501. else $array[$key]['label'] = $langs->trans($value['label']);
  5502. }
  5503. }
  5504. // Sort
  5505. if ($sort == 'ASC') asort($array);
  5506. elseif ($sort == 'DESC') arsort($array);
  5507. foreach ($array as $key => $tmpvalue)
  5508. {
  5509. if (is_array($tmpvalue)) $value = $tmpvalue['label'];
  5510. else $value = $tmpvalue;
  5511. $disabled = ''; $style = '';
  5512. if (!empty($disablebademail))
  5513. {
  5514. if (($disablebademail == 1 && !preg_match('/&lt;.+@.+&gt;/', $value))
  5515. || ($disablebademail == 2 && preg_match('/---/', $value)))
  5516. {
  5517. $disabled = ' disabled';
  5518. $style = ' class="warning"';
  5519. }
  5520. }
  5521. if ($key_in_label)
  5522. {
  5523. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
  5524. else $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
  5525. } else {
  5526. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
  5527. else $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
  5528. if ($value == '' || $value == '-') $selectOptionValue = '&nbsp;';
  5529. }
  5530. $out .= '<option value="'.$key.'"';
  5531. $out .= $style.$disabled;
  5532. if (is_array($id)) {
  5533. if (in_array($key, $id) && !$disabled) $out .= ' selected'; // To preselect a value
  5534. } else {
  5535. $id = (string) $id; // if $id = 0, then $id = '0'
  5536. if ($id != '' && $id == $key && !$disabled) $out .= ' selected'; // To preselect a value
  5537. }
  5538. if ($nohtmlescape) $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
  5539. if (is_array($tmpvalue))
  5540. {
  5541. foreach ($tmpvalue as $keyforvalue => $valueforvalue)
  5542. {
  5543. if (preg_match('/^data-/', $keyforvalue)) $out .= ' '.$keyforvalue.'="'.$valueforvalue.'"';
  5544. }
  5545. }
  5546. $out .= '>';
  5547. //var_dump($selectOptionValue);
  5548. $out .= $selectOptionValue;
  5549. $out .= "</option>\n";
  5550. }
  5551. }
  5552. $out .= "</select>";
  5553. return $out;
  5554. }
  5555. /**
  5556. * 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.
  5557. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5558. *
  5559. * @param string $htmlname Name of html select area
  5560. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5561. * @param string $id Preselected key
  5562. * @param string $moreparam Add more parameters onto the select tag
  5563. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  5564. * @param int $disabled Html select box is disabled
  5565. * @param int $minimumInputLength Minimum Input Length
  5566. * @param string $morecss Add more class to css styles
  5567. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5568. * @param string $placeholder String to use as placeholder
  5569. * @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)
  5570. * @return string HTML select string
  5571. * @see selectArrayFilter(), ajax_combobox() in ajax.lib.php
  5572. */
  5573. public static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  5574. {
  5575. global $conf, $langs;
  5576. global $delayedhtmlcontent;
  5577. // TODO Use an internal dolibarr component instead of select2
  5578. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5579. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
  5580. $tmpplugin = 'select2';
  5581. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5582. <script>
  5583. $(document).ready(function () {
  5584. '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
  5585. $(".'.$htmlname.'").select2({
  5586. ajax: {
  5587. dir: "ltr",
  5588. url: "'.$url.'",
  5589. dataType: \'json\',
  5590. delay: 250,
  5591. data: function (params) {
  5592. return {
  5593. q: params.term, // search term
  5594. page: params.page
  5595. };
  5596. },
  5597. processResults: function (data) {
  5598. // parse the results into the format expected by Select2.
  5599. // since we are using custom formatting functions we do not need to alter the remote JSON data
  5600. //console.log(data);
  5601. saveRemoteData = data;
  5602. /* format json result for select2 */
  5603. result = []
  5604. $.each( data, function( key, value ) {
  5605. result.push({id: key, text: value.text});
  5606. });
  5607. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  5608. //console.log(result);
  5609. return {results: result, more: false}
  5610. },
  5611. cache: true
  5612. },
  5613. language: select2arrayoflanguage,
  5614. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5615. placeholder: "'.dol_escape_js($placeholder).'",
  5616. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5617. minimumInputLength: '.$minimumInputLength.',
  5618. formatResult: function(result, container, query, escapeMarkup) {
  5619. return escapeMarkup(result.text);
  5620. },
  5621. });
  5622. '.($callurlonselect ? '
  5623. /* Code to execute a GET when we select a value */
  5624. $(".'.$htmlname.'").change(function() {
  5625. var selected = $(".'.$htmlname.'").val();
  5626. console.log("We select in selectArrayAjax the entry "+selected)
  5627. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5628. $.each( saveRemoteData, function( key, value ) {
  5629. if (key == selected)
  5630. {
  5631. console.log("selectArrayAjax - Do a redirect to "+value.url)
  5632. location.assign(value.url);
  5633. }
  5634. });
  5635. });' : '').'
  5636. });
  5637. </script>';
  5638. if ($acceptdelayedhtml)
  5639. {
  5640. $delayedhtmlcontent .= $outdelayed;
  5641. } else {
  5642. $out .= $outdelayed;
  5643. }
  5644. return $out;
  5645. }
  5646. /**
  5647. * Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
  5648. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  5649. *
  5650. * @param string $htmlname Name of html select area
  5651. * @param string $array Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
  5652. * @param string $id Preselected key
  5653. * @param string $moreparam Add more parameters onto the select tag
  5654. * @param int $disableFiltering If set to 1, results are not filtered with searched string
  5655. * @param int $disabled Html select box is disabled
  5656. * @param int $minimumInputLength Minimum Input Length
  5657. * @param string $morecss Add more class to css styles
  5658. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  5659. * @param string $placeholder String to use as placeholder
  5660. * @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)
  5661. * @return string HTML select string
  5662. * @see selectArrayAjax(), ajax_combobox() in ajax.lib.php
  5663. */
  5664. public static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
  5665. {
  5666. global $conf, $langs;
  5667. global $delayedhtmlcontent;
  5668. // TODO Use an internal dolibarr component instead of select2
  5669. if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
  5670. $out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
  5671. $formattedarrayresult = array();
  5672. foreach ($array as $key => $value) {
  5673. $o = new stdClass();
  5674. $o->id = $key;
  5675. $o->text = $value['text'];
  5676. $o->url = $value['url'];
  5677. $formattedarrayresult[] = $o;
  5678. }
  5679. $tmpplugin = 'select2';
  5680. $outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  5681. <script>
  5682. $(document).ready(function () {
  5683. var data = '.json_encode($formattedarrayresult).';
  5684. '.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
  5685. $(".'.$htmlname.'").select2({
  5686. data: data,
  5687. language: select2arrayoflanguage,
  5688. containerCssClass: \':all:\', /* Line to add class of origin SELECT propagated to the new <span class="select2-selection...> tag */
  5689. placeholder: "'.dol_escape_js($placeholder).'",
  5690. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  5691. minimumInputLength: '.$minimumInputLength.',
  5692. formatResult: function(result, container, query, escapeMarkup) {
  5693. return escapeMarkup(result.text);
  5694. },
  5695. matcher: function (params, data) {
  5696. if(! data.id) return null;';
  5697. if ($callurlonselect) {
  5698. $outdelayed .= '
  5699. var urlBase = data.url;
  5700. var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
  5701. /* console.log("params.term="+params.term); */
  5702. /* console.log("params.term encoded="+encodeURIComponent(params.term)); */
  5703. saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term);';
  5704. }
  5705. if (!$disableFiltering) {
  5706. $outdelayed .= '
  5707. if(data.text.match(new RegExp(params.term))) {
  5708. return data;
  5709. }
  5710. return null;';
  5711. } else {
  5712. $outdelayed .= '
  5713. return data;';
  5714. }
  5715. $outdelayed .= '
  5716. }
  5717. });
  5718. '.($callurlonselect ? '
  5719. /* Code to execute a GET when we select a value */
  5720. $(".'.$htmlname.'").change(function() {
  5721. var selected = $(".'.$htmlname.'").val();
  5722. console.log("We select "+selected)
  5723. $(".'.$htmlname.'").val(""); /* reset visible combo value */
  5724. $.each( saveRemoteData, function( key, value ) {
  5725. if (key == selected)
  5726. {
  5727. console.log("selectArrayAjax - Do a redirect to "+value.url)
  5728. location.assign(value.url);
  5729. }
  5730. });
  5731. });' : '').'
  5732. });
  5733. </script>';
  5734. if ($acceptdelayedhtml)
  5735. {
  5736. $delayedhtmlcontent .= $outdelayed;
  5737. } else {
  5738. $out .= $outdelayed;
  5739. }
  5740. return $out;
  5741. }
  5742. /**
  5743. * Show a multiselect form from an array.
  5744. *
  5745. * @param string $htmlname Name of select
  5746. * @param array $array Array with key+value
  5747. * @param array $selected Array with key+value preselected
  5748. * @param int $key_in_label 1 to show key like in "[key] value"
  5749. * @param int $value_as_key 1 to use value as key
  5750. * @param string $morecss Add more css style
  5751. * @param int $translate Translate and encode value
  5752. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  5753. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  5754. * @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.
  5755. * @param string $placeholder String to use as placeholder
  5756. * @param int $addjscombo Add js combo
  5757. * @return string HTML multiselect string
  5758. * @see selectarray(), selectArrayAjax(), selectArrayFilter()
  5759. */
  5760. 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)
  5761. {
  5762. global $conf, $langs;
  5763. $out = '';
  5764. if ($addjscombo < 0) {
  5765. if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $addjscombo = 1;
  5766. else $addjscombo = 0;
  5767. }
  5768. // Add code for jquery to use multiselect
  5769. if (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
  5770. {
  5771. $out .= "\n".'<!-- JS CODE TO ENABLE select for id '.$htmlname.' -->
  5772. <script>'."\n";
  5773. if ($addjscombo == 1)
  5774. {
  5775. $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
  5776. $out .= 'function formatResult(record) {'."\n";
  5777. if ($elemtype == 'category')
  5778. {
  5779. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  5780. } else {
  5781. $out .= 'return record.text;';
  5782. }
  5783. $out .= '};'."\n";
  5784. $out .= 'function formatSelection(record) {'."\n";
  5785. if ($elemtype == 'category')
  5786. {
  5787. $out .= 'return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png"> \'+record.text+\'</span>\';';
  5788. } else {
  5789. $out .= 'return record.text;';
  5790. }
  5791. $out .= '};'."\n";
  5792. $out .= '$(document).ready(function () {
  5793. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  5794. dir: \'ltr\',
  5795. // Specify format function for dropdown item
  5796. formatResult: formatResult,
  5797. templateResult: formatResult, /* For 4.0 */
  5798. // Specify format function for selected item
  5799. formatSelection: formatSelection,
  5800. templateSelection: formatSelection /* For 4.0 */
  5801. });
  5802. });'."\n";
  5803. } elseif ($addjscombo == 2)
  5804. {
  5805. // Add other js lib
  5806. // TODO external lib multiselect/jquery.multi-select.js must have been loaded to use this multiselect plugin
  5807. // ...
  5808. $out .= '$(document).ready(function () {
  5809. $(\'#'.$htmlname.'\').multiSelect({
  5810. containerHTML: \'<div class="multi-select-container">\',
  5811. menuHTML: \'<div class="multi-select-menu">\',
  5812. buttonHTML: \'<span class="multi-select-button '.$morecss.'">\',
  5813. menuItemHTML: \'<label class="multi-select-menuitem">\',
  5814. activeClass: \'multi-select-container--open\',
  5815. noneText: \''.$placeholder.'\'
  5816. });
  5817. })';
  5818. }
  5819. $out .= '</script>';
  5820. }
  5821. // Try also magic suggest
  5822. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
  5823. if (is_array($array) && !empty($array))
  5824. {
  5825. if ($value_as_key) $array = array_combine($array, $array);
  5826. if (!empty($array))
  5827. {
  5828. foreach ($array as $key => $value)
  5829. {
  5830. $newval = ($translate ? $langs->trans($value) : $value);
  5831. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  5832. $out .= '<option value="'.$key.'"';
  5833. if (is_array($selected) && !empty($selected) && in_array((string) $key, $selected) && ((string) $key != ''))
  5834. {
  5835. $out .= ' selected';
  5836. }
  5837. $out .= ' data-html="'.$newval.'"';
  5838. $out .= '>';
  5839. $out .= dol_htmlentitiesbr($newval);
  5840. $out .= '</option>'."\n";
  5841. }
  5842. }
  5843. }
  5844. $out .= '</select>'."\n";
  5845. return $out;
  5846. }
  5847. /**
  5848. * Show a multiselect dropbox from an array.
  5849. *
  5850. * @param string $htmlname Name of HTML field
  5851. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  5852. * @param string $varpage Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
  5853. * @return string HTML multiselect string
  5854. * @see selectarray()
  5855. */
  5856. public static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  5857. {
  5858. global $conf, $langs, $user, $extrafields;
  5859. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
  5860. $tmpvar = "MAIN_SELECTEDFIELDS_".$varpage; // To get list of saved seleteced properties
  5861. if (!empty($user->conf->$tmpvar))
  5862. {
  5863. $tmparray = explode(',', $user->conf->$tmpvar);
  5864. foreach ($array as $key => $val)
  5865. {
  5866. //var_dump($key);
  5867. //var_dump($tmparray);
  5868. if (in_array($key, $tmparray)) $array[$key]['checked'] = 1;
  5869. else $array[$key]['checked'] = 0;
  5870. }
  5871. }
  5872. $lis = '';
  5873. $listcheckedstring = '';
  5874. foreach ($array as $key => $val)
  5875. {
  5876. /* var_dump($val);
  5877. var_dump(array_key_exists('enabled', $val));
  5878. var_dump(!$val['enabled']);*/
  5879. if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled'])
  5880. {
  5881. unset($array[$key]); // We don't want this field
  5882. continue;
  5883. }
  5884. if ($val['label'])
  5885. {
  5886. if (! empty($val['langfile']) && is_object($langs)) {
  5887. $langs->load($val['langfile']);
  5888. }
  5889. $lis .= '<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked']) ? '' : ' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
  5890. $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
  5891. }
  5892. }
  5893. $out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  5894. <dl class="dropdown">
  5895. <dt>
  5896. <a href="#'.$htmlname.'">
  5897. '.img_picto('', 'list').'
  5898. </a>
  5899. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  5900. </dt>
  5901. <dd class="dropdowndd">
  5902. <div class="multiselectcheckbox'.$htmlname.'">
  5903. <ul class="ul'.$htmlname.'">
  5904. '.$lis.'
  5905. </ul>
  5906. </div>
  5907. </dd>
  5908. </dl>
  5909. <script type="text/javascript">
  5910. jQuery(document).ready(function () {
  5911. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  5912. console.log("A new field was added/removed, we edit field input[name=formfilteraction]");
  5913. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\'); // Update field so we know we changed something on selected fields after POST
  5914. var title = $(this).val() + ",";
  5915. if ($(this).is(\':checked\')) {
  5916. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  5917. }
  5918. else {
  5919. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  5920. }
  5921. // Now, we submit page
  5922. //$(this).parents(\'form:first\').submit();
  5923. });
  5924. });
  5925. </script>
  5926. ';
  5927. return $out;
  5928. }
  5929. /**
  5930. * Render list of categories linked to object with id $id and type $type
  5931. *
  5932. * @param int $id Id of object
  5933. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  5934. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  5935. * @param int $nolink 1=Do not add html links
  5936. * @return string String with categories
  5937. */
  5938. public function showCategories($id, $type, $rendermode = 0, $nolink = 0)
  5939. {
  5940. global $db;
  5941. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  5942. $cat = new Categorie($db);
  5943. $categories = $cat->containing($id, $type);
  5944. if ($rendermode == 1)
  5945. {
  5946. $toprint = array();
  5947. foreach ($categories as $c)
  5948. {
  5949. $ways = $c->print_all_ways(' &gt;&gt; ', ($nolink ? 'none' : ''), 0, 1); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  5950. foreach ($ways as $way)
  5951. {
  5952. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #aaa"').'>'.$way.'</li>';
  5953. }
  5954. }
  5955. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  5956. }
  5957. if ($rendermode == 0)
  5958. {
  5959. $arrayselected = array();
  5960. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  5961. foreach ($categories as $c) {
  5962. $arrayselected[] = $c->id;
  5963. }
  5964. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  5965. }
  5966. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  5967. }
  5968. /**
  5969. * Show linked object block.
  5970. *
  5971. * @param CommonObject $object Object we want to show links to
  5972. * @param string $morehtmlright More html to show on right of title
  5973. * @param array $compatibleImportElementsList Array of compatibles elements object for "import from" action
  5974. * @return int <0 if KO, >=0 if OK
  5975. */
  5976. public function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
  5977. {
  5978. global $conf, $langs, $hookmanager;
  5979. global $bc, $action;
  5980. $object->fetchObjectLinked();
  5981. // Bypass the default method
  5982. $hookmanager->initHooks(array('commonobject'));
  5983. $parameters = array(
  5984. 'morehtmlright' => $morehtmlright,
  5985. 'compatibleImportElementsList' => &$compatibleImportElementsList,
  5986. );
  5987. $reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  5988. if (empty($reshook))
  5989. {
  5990. $nbofdifferenttypes = count($object->linkedObjects);
  5991. print '<!-- showLinkedObjectBlock -->';
  5992. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
  5993. print '<div class="div-table-responsive-no-min">';
  5994. print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'" data-elementid="'.$object->id.'" >';
  5995. print '<tr class="liste_titre">';
  5996. print '<td>'.$langs->trans("Type").'</td>';
  5997. print '<td>'.$langs->trans("Ref").'</td>';
  5998. print '<td class="center"></td>';
  5999. print '<td class="center">'.$langs->trans("Date").'</td>';
  6000. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  6001. print '<td class="right">'.$langs->trans("Status").'</td>';
  6002. print '<td></td>';
  6003. print '</tr>';
  6004. $nboftypesoutput = 0;
  6005. foreach ($object->linkedObjects as $objecttype => $objects)
  6006. {
  6007. $tplpath = $element = $subelement = $objecttype;
  6008. // to display inport button on tpl
  6009. $showImportButton = false;
  6010. if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
  6011. $showImportButton = true;
  6012. }
  6013. $regs = array();
  6014. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
  6015. {
  6016. $element = $regs[1];
  6017. $subelement = $regs[2];
  6018. $tplpath = $element.'/'.$subelement;
  6019. }
  6020. $tplname = 'linkedobjectblock';
  6021. // To work with non standard path
  6022. if ($objecttype == 'facture') {
  6023. $tplpath = 'compta/'.$element;
  6024. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  6025. } elseif ($objecttype == 'facturerec') {
  6026. $tplpath = 'compta/facture';
  6027. $tplname = 'linkedobjectblockForRec';
  6028. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  6029. } elseif ($objecttype == 'propal') {
  6030. $tplpath = 'comm/'.$element;
  6031. if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
  6032. } elseif ($objecttype == 'supplier_proposal') {
  6033. if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
  6034. } elseif ($objecttype == 'shipping' || $objecttype == 'shipment') {
  6035. $tplpath = 'expedition';
  6036. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  6037. } elseif ($objecttype == 'reception') {
  6038. $tplpath = 'reception';
  6039. if (empty($conf->reception->enabled)) continue; // Do not show if module disabled
  6040. } elseif ($objecttype == 'delivery') {
  6041. $tplpath = 'livraison';
  6042. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  6043. } elseif ($objecttype == 'invoice_supplier') {
  6044. $tplpath = 'fourn/facture';
  6045. } elseif ($objecttype == 'order_supplier') {
  6046. $tplpath = 'fourn/commande';
  6047. } elseif ($objecttype == 'expensereport') {
  6048. $tplpath = 'expensereport';
  6049. } elseif ($objecttype == 'subscription') {
  6050. $tplpath = 'adherents';
  6051. }
  6052. global $linkedObjectBlock;
  6053. $linkedObjectBlock = $objects;
  6054. // Output template part (modules that overwrite templates must declare this into descriptor)
  6055. $dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
  6056. foreach ($dirtpls as $reldir)
  6057. {
  6058. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after
  6059. {
  6060. global $noMoreLinkedObjectBlockAfter;
  6061. $noMoreLinkedObjectBlockAfter = 1;
  6062. }
  6063. $res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  6064. if ($res)
  6065. {
  6066. $nboftypesoutput++;
  6067. break;
  6068. }
  6069. }
  6070. }
  6071. if (!$nboftypesoutput)
  6072. {
  6073. print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
  6074. }
  6075. print '</table>';
  6076. if (!empty($compatibleImportElementsList))
  6077. {
  6078. $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
  6079. }
  6080. print '</div>';
  6081. return $nbofdifferenttypes;
  6082. }
  6083. }
  6084. /**
  6085. * Show block with links to link to other objects.
  6086. *
  6087. * @param CommonObject $object Object we want to show links to
  6088. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  6089. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  6090. * @return string <0 if KO, >0 if OK
  6091. */
  6092. public function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
  6093. {
  6094. global $conf, $langs, $hookmanager;
  6095. global $bc, $action;
  6096. $linktoelem = '';
  6097. $linktoelemlist = '';
  6098. $listofidcompanytoscan = '';
  6099. if (!is_object($object->thirdparty)) $object->fetch_thirdparty();
  6100. $possiblelinks = array();
  6101. if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0)
  6102. {
  6103. $listofidcompanytoscan = $object->thirdparty->id;
  6104. if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan .= ','.$object->thirdparty->parent;
  6105. if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
  6106. {
  6107. include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6108. $tmpproject = new Project($this->db);
  6109. $tmpproject->fetch($object->fk_project);
  6110. if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan .= ','.$tmpproject->socid;
  6111. unset($tmpproject);
  6112. }
  6113. $possiblelinks = array(
  6114. 'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
  6115. 'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
  6116. 'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
  6117. 'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
  6118. 'contrat'=>array('enabled'=>$conf->contrat->enabled, 'perms'=>1, 'label'=>'LinkToContract',
  6119. '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, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
  6120. 'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
  6121. 'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
  6122. 'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
  6123. 'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled, 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')'),
  6124. 'ticket'=>array('enabled'=>$conf->ticket->enabled, 'perms'=>1, 'label'=>'LinkToTicket', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.track_id, '0' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."ticket as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('ticket').')')
  6125. );
  6126. }
  6127. // Can complete the possiblelink array
  6128. $hookmanager->initHooks(array('commonobject'));
  6129. $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan);
  6130. if (!empty($listofidcompanytoscan)) // If empty, we don't have criteria to scan the object we can link to
  6131. {
  6132. $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  6133. }
  6134. if (empty($reshook))
  6135. {
  6136. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  6137. {
  6138. $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
  6139. }
  6140. } elseif ($reshook > 0)
  6141. {
  6142. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  6143. {
  6144. $possiblelinks = $hookmanager->resArray;
  6145. }
  6146. }
  6147. foreach ($possiblelinks as $key => $possiblelink)
  6148. {
  6149. $num = 0;
  6150. if (empty($possiblelink['enabled'])) continue;
  6151. if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto)))
  6152. {
  6153. print '<div id="'.$key.'list"'.(empty($conf->use_javascript_ajax) ? '' : ' style="display:none"').'>';
  6154. $sql = $possiblelink['sql'];
  6155. $resqllist = $this->db->query($sql);
  6156. if ($resqllist)
  6157. {
  6158. $num = $this->db->num_rows($resqllist);
  6159. $i = 0;
  6160. print '<br>';
  6161. print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  6162. print '<input type="hidden" name="action" value="addlink">';
  6163. print '<input type="hidden" name="token" value="'.newToken().'">';
  6164. print '<input type="hidden" name="id" value="'.$object->id.'">';
  6165. print '<input type="hidden" name="addlink" value="'.$key.'">';
  6166. print '<table class="noborder">';
  6167. print '<tr class="liste_titre">';
  6168. print '<td class="nowrap"></td>';
  6169. print '<td class="center">'.$langs->trans("Ref").'</td>';
  6170. print '<td class="left">'.$langs->trans("RefCustomer").'</td>';
  6171. print '<td class="right">'.$langs->trans("AmountHTShort").'</td>';
  6172. print '<td class="left">'.$langs->trans("Company").'</td>';
  6173. print '</tr>';
  6174. while ($i < $num)
  6175. {
  6176. $objp = $this->db->fetch_object($resqllist);
  6177. print '<tr class="oddeven">';
  6178. print '<td class="left">';
  6179. print '<input type="radio" name="idtolinkto" value='.$objp->rowid.'>';
  6180. print '</td>';
  6181. print '<td class="center">'.$objp->ref.'</td>';
  6182. print '<td>'.$objp->ref_client.'</td>';
  6183. print '<td class="right">'.price($objp->total_ht).'</td>';
  6184. print '<td>'.$objp->name.'</td>';
  6185. print '</tr>';
  6186. $i++;
  6187. }
  6188. print '</table>';
  6189. print '<div class="center"><input type="submit" class="button valignmiddle" value="'.$langs->trans('ToLink').'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="'.$langs->trans('Cancel').'"></div>';
  6190. print '</form>';
  6191. $this->db->free($resqllist);
  6192. } else {
  6193. dol_print_error($this->db);
  6194. }
  6195. print '</div>';
  6196. if ($num > 0)
  6197. {
  6198. }
  6199. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  6200. if ($num > 0) $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
  6201. //else $linktoelem.=$langs->trans($possiblelink['label']);
  6202. else $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
  6203. }
  6204. }
  6205. if ($linktoelemlist)
  6206. {
  6207. $linktoelem = '
  6208. <dl class="dropdown" id="linktoobjectname">
  6209. ';
  6210. if (!empty($conf->use_javascript_ajax)) $linktoelem .= '<dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>';
  6211. $linktoelem .= '<dd>
  6212. <div class="multiselectlinkto">
  6213. <ul class="ulselectedfields">'.$linktoelemlist.'
  6214. </ul>
  6215. </div>
  6216. </dd>
  6217. </dl>';
  6218. } else {
  6219. $linktoelem = '';
  6220. }
  6221. if (!empty($conf->use_javascript_ajax))
  6222. {
  6223. print '<!-- Add js to show linkto box -->
  6224. <script>
  6225. jQuery(document).ready(function() {
  6226. jQuery(".linkto").click(function() {
  6227. console.log("We choose to show/hide link for rel="+jQuery(this).attr(\'rel\'));
  6228. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  6229. });
  6230. });
  6231. </script>
  6232. ';
  6233. }
  6234. return $linktoelem;
  6235. }
  6236. /**
  6237. * Return an html string with a select combo box to choose yes or no
  6238. *
  6239. * @param string $htmlname Name of html select field
  6240. * @param string $value Pre-selected value
  6241. * @param int $option 0 return yes/no, 1 return 1/0
  6242. * @param bool $disabled true or false
  6243. * @param int $useempty 1=Add empty line
  6244. * @return string See option
  6245. */
  6246. public function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0)
  6247. {
  6248. global $langs;
  6249. $yes = "yes"; $no = "no";
  6250. if ($option)
  6251. {
  6252. $yes = "1";
  6253. $no = "0";
  6254. }
  6255. $disabled = ($disabled ? ' disabled' : '');
  6256. $resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  6257. if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
  6258. if (("$value" == 'yes') || ($value == 1))
  6259. {
  6260. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  6261. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  6262. } else {
  6263. $selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
  6264. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  6265. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  6266. }
  6267. $resultyesno .= '</select>'."\n";
  6268. return $resultyesno;
  6269. }
  6270. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6271. /**
  6272. * Return list of export templates
  6273. *
  6274. * @param string $selected Id modele pre-selectionne
  6275. * @param string $htmlname Name of HTML select
  6276. * @param string $type Type of searched templates
  6277. * @param int $useempty Affiche valeur vide dans liste
  6278. * @return void
  6279. */
  6280. public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
  6281. {
  6282. // phpcs:enable
  6283. $sql = "SELECT rowid, label";
  6284. $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
  6285. $sql .= " WHERE type = '".$type."'";
  6286. $sql .= " ORDER BY rowid";
  6287. $result = $this->db->query($sql);
  6288. if ($result)
  6289. {
  6290. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  6291. if ($useempty)
  6292. {
  6293. print '<option value="-1">&nbsp;</option>';
  6294. }
  6295. $num = $this->db->num_rows($result);
  6296. $i = 0;
  6297. while ($i < $num)
  6298. {
  6299. $obj = $this->db->fetch_object($result);
  6300. if ($selected == $obj->rowid)
  6301. {
  6302. print '<option value="'.$obj->rowid.'" selected>';
  6303. } else {
  6304. print '<option value="'.$obj->rowid.'">';
  6305. }
  6306. print $obj->label;
  6307. print '</option>';
  6308. $i++;
  6309. }
  6310. print "</select>";
  6311. } else {
  6312. dol_print_error($this->db);
  6313. }
  6314. }
  6315. /**
  6316. * Return a HTML area with the reference of object and a navigation bar for a business object
  6317. * Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
  6318. *
  6319. * @param object $object Object to show.
  6320. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  6321. * @param string $morehtml More html content to output just before the nav bar.
  6322. * @param int $shownav Show Condition (navigation is shown if value is 1).
  6323. * @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.
  6324. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  6325. * @param string $morehtmlref More html to show after ref.
  6326. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  6327. * @param int $nodbprefix Do not include DB prefix to forge table name.
  6328. * @param string $morehtmlleft More html code to show before ref.
  6329. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  6330. * @param string $morehtmlright More html code to show after ref.
  6331. * @return string Portion HTML with ref + navigation buttons
  6332. */
  6333. public function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
  6334. {
  6335. global $langs, $conf, $hookmanager, $extralanguages;
  6336. $ret = '';
  6337. if (empty($fieldid)) $fieldid = 'rowid';
  6338. if (empty($fieldref)) $fieldref = 'ref';
  6339. // Add where from hooks
  6340. if (is_object($hookmanager))
  6341. {
  6342. $parameters = array();
  6343. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
  6344. $object->next_prev_filter .= $hookmanager->resPrint;
  6345. }
  6346. $previous_ref = $next_ref = '';
  6347. if ($shownav)
  6348. {
  6349. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  6350. $object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
  6351. $navurl = $_SERVER["PHP_SELF"];
  6352. // Special case for project/task page
  6353. if ($paramid == 'project_ref')
  6354. {
  6355. if (preg_match('/\/tasks\/(task|contact|note|document)\.php/', $navurl)) // TODO Remove this when nav with project_ref on task pages are ok
  6356. {
  6357. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
  6358. $paramid = 'ref';
  6359. }
  6360. }
  6361. // accesskey is for Windows or Linux: ALT + key for chrome, ALT + SHIFT + KEY for firefox
  6362. // accesskey is for Mac: CTRL + key for all browsers
  6363. $stringforfirstkey = $langs->trans("KeyboardShortcut");
  6364. if ($conf->browser->name == 'chrome')
  6365. {
  6366. $stringforfirstkey .= ' ALT +';
  6367. } elseif ($conf->browser->name == 'firefox')
  6368. {
  6369. $stringforfirstkey .= ' ALT + SHIFT +';
  6370. } else {
  6371. $stringforfirstkey .= ' CTL +';
  6372. }
  6373. $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>';
  6374. $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>';
  6375. }
  6376. //print "xx".$previous_ref."x".$next_ref;
  6377. $ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
  6378. // Right part of banner
  6379. if ($morehtmlright) $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  6380. if ($previous_ref || $next_ref || $morehtml)
  6381. {
  6382. $ret .= '<div class="pagination paginationref"><ul class="right">';
  6383. }
  6384. if ($morehtml)
  6385. {
  6386. $ret .= '<li class="noborder litext">'.$morehtml.'</li>';
  6387. }
  6388. if ($shownav && ($previous_ref || $next_ref))
  6389. {
  6390. $ret .= '<li class="pagination">'.$previous_ref.'</li>';
  6391. $ret .= '<li class="pagination">'.$next_ref.'</li>';
  6392. }
  6393. if ($previous_ref || $next_ref || $morehtml)
  6394. {
  6395. $ret .= '</ul></div>';
  6396. }
  6397. $parameters = array();
  6398. $reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
  6399. if (empty($reshook)) $morehtmlstatus .= $hookmanager->resPrint;
  6400. else $morehtmlstatus = $hookmanager->resPrint;
  6401. if ($morehtmlstatus) $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
  6402. $parameters = array();
  6403. $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
  6404. if (empty($reshook)) $morehtmlref .= $hookmanager->resPrint;
  6405. elseif ($reshook > 0) $morehtmlref = $hookmanager->resPrint;
  6406. // Left part of banner
  6407. if ($morehtmlleft)
  6408. {
  6409. if ($conf->browser->layout == 'phone') $ret .= '<!-- morehtmlleft --><div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  6410. else $ret .= '<!-- morehtmlleft --><div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  6411. }
  6412. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  6413. $ret .= '<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
  6414. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  6415. if ($object->element == 'societe')
  6416. {
  6417. $ret .= dol_htmlentities($object->name);
  6418. // List of extra languages
  6419. $arrayoflangcode = array();
  6420. if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE)) $arrayoflangcode[] = $conf->global->PDF_USE_ALSO_LANGUAGE_CODE;
  6421. if (is_array($arrayoflangcode) && count($arrayoflangcode)) {
  6422. if (!is_object($extralanguages)) {
  6423. include_once DOL_DOCUMENT_ROOT.'/core/class/extralanguages.class.php';
  6424. $extralanguages = new ExtraLanguages($this->db);
  6425. }
  6426. $extralanguages->fetch_name_extralanguages('societe');
  6427. if (!empty($extralanguages->attributes['societe']['name']))
  6428. {
  6429. $object->fetchValuesForExtraLanguages();
  6430. $htmltext = '';
  6431. // If there is extra languages
  6432. foreach ($arrayoflangcode as $extralangcode) {
  6433. $htmltext .= picto_from_langcode($extralangcode, 'class="pictoforlang paddingright"');
  6434. if ($object->array_languages['name'][$extralangcode]) {
  6435. $htmltext .= $object->array_languages['name'][$extralangcode];
  6436. } else {
  6437. $htmltext .= '<span class="opacitymedium">'.$langs->trans("SwitchInEditModeToAddTranslation").'</span>';
  6438. }
  6439. }
  6440. $ret .= '<!-- Show translations of name -->'."\n";
  6441. $ret .= $this->textwithpicto('', $htmltext, -1, 'language', 'opacitymedium paddingleft');
  6442. }
  6443. }
  6444. } elseif ($object->element == 'member')
  6445. {
  6446. $ret .= $object->ref.'<br>';
  6447. $fullname = $object->getFullName($langs);
  6448. if ($object->morphy == 'mor' && $object->societe) {
  6449. $ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).')' : '');
  6450. } else {
  6451. $ret .= dol_htmlentities($fullname).((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
  6452. }
  6453. } elseif (in_array($object->element, array('contact', 'user', 'usergroup')))
  6454. {
  6455. $ret .= dol_htmlentities($object->getFullName($langs));
  6456. } elseif (in_array($object->element, array('action', 'agenda')))
  6457. {
  6458. $ret .= $object->ref.'<br>'.$object->label;
  6459. } elseif (in_array($object->element, array('adherent_type')))
  6460. {
  6461. $ret .= $object->label;
  6462. } elseif ($object->element == 'ecm_directories')
  6463. {
  6464. $ret .= '';
  6465. } elseif ($fieldref != 'none')
  6466. {
  6467. $ret .= dol_htmlentities($object->$fieldref);
  6468. }
  6469. if ($morehtmlref)
  6470. {
  6471. // don't add a additional space, when "$morehtmlref" starts with a HTML div tag
  6472. if (substr($morehtmlref, 0, 4) != '<div')
  6473. {
  6474. $ret .= ' ';
  6475. }
  6476. $ret .= $morehtmlref;
  6477. }
  6478. $ret .= '</div>';
  6479. $ret .= '</div><!-- End banner content -->';
  6480. return $ret;
  6481. }
  6482. /**
  6483. * Return HTML code to output a barcode
  6484. *
  6485. * @param Object $object Object containing data to retrieve file name
  6486. * @param int $width Width of photo
  6487. * @return string HTML code to output barcode
  6488. */
  6489. public function showbarcode(&$object, $width = 100)
  6490. {
  6491. global $conf;
  6492. //Check if barcode is filled in the card
  6493. if (empty($object->barcode)) return '';
  6494. // Complete object if not complete
  6495. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
  6496. {
  6497. $result = $object->fetch_barcode();
  6498. //Check if fetch_barcode() failed
  6499. if ($result < 1) return '<!-- ErrorFetchBarcode -->';
  6500. }
  6501. // Barcode image
  6502. $url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  6503. $out = '<!-- url barcode = '.$url.' -->';
  6504. $out .= '<img src="'.$url.'">';
  6505. return $out;
  6506. }
  6507. /**
  6508. * Return HTML code to output a photo
  6509. *
  6510. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  6511. * @param object $object Object containing data to retrieve file name
  6512. * @param int $width Width of photo
  6513. * @param int $height Height of photo (auto if 0)
  6514. * @param int $caneditfield Add edit fields
  6515. * @param string $cssclass CSS name to use on img for photo
  6516. * @param string $imagesize 'mini', 'small' or '' (original)
  6517. * @param int $addlinktofullsize Add link to fullsize image
  6518. * @param int $cache 1=Accept to use image in cache
  6519. * @param string $forcecapture Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
  6520. * @return string HTML code to output photo
  6521. */
  6522. public static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '')
  6523. {
  6524. global $conf, $langs;
  6525. $entity = (!empty($object->entity) ? $object->entity : $conf->entity);
  6526. $id = (!empty($object->id) ? $object->id : $object->rowid);
  6527. $ret = ''; $dir = ''; $file = ''; $originalfile = ''; $altfile = ''; $email = ''; $capture = '';
  6528. if ($modulepart == 'societe')
  6529. {
  6530. $dir = $conf->societe->multidir_output[$entity];
  6531. if (!empty($object->logo))
  6532. {
  6533. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  6534. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
  6535. else $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6536. $originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  6537. }
  6538. $email = $object->email;
  6539. } elseif ($modulepart == 'contact')
  6540. {
  6541. $dir = $conf->societe->multidir_output[$entity].'/contact';
  6542. if (!empty($object->photo))
  6543. {
  6544. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
  6545. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
  6546. else $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6547. $originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  6548. }
  6549. $email = $object->email;
  6550. $capture = 'user';
  6551. } elseif ($modulepart == 'userphoto')
  6552. {
  6553. $dir = $conf->user->dir_output;
  6554. if (!empty($object->photo))
  6555. {
  6556. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
  6557. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
  6558. else $file = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6559. $originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
  6560. }
  6561. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6562. $email = $object->email;
  6563. $capture = 'user';
  6564. } elseif ($modulepart == 'memberphoto')
  6565. {
  6566. $dir = $conf->adherent->dir_output;
  6567. if (!empty($object->photo))
  6568. {
  6569. if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6570. elseif ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  6571. else $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6572. $originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  6573. }
  6574. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6575. $email = $object->email;
  6576. $capture = 'user';
  6577. } else {
  6578. // Generic case to show photos
  6579. $dir = $conf->$modulepart->dir_output;
  6580. if (!empty($object->photo))
  6581. {
  6582. if ((string) $imagesize == 'mini') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  6583. elseif ((string) $imagesize == 'small') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  6584. else $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6585. $originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  6586. }
  6587. if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
  6588. $email = $object->email;
  6589. }
  6590. if ($forcecapture) $capture = $forcecapture;
  6591. if ($dir)
  6592. {
  6593. if ($file && file_exists($dir."/".$file))
  6594. {
  6595. if ($addlinktofullsize)
  6596. {
  6597. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6598. if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
  6599. else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6600. }
  6601. $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.'">';
  6602. if ($addlinktofullsize) $ret .= '</a>';
  6603. } elseif ($altfile && file_exists($dir."/".$altfile))
  6604. {
  6605. if ($addlinktofullsize)
  6606. {
  6607. $urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  6608. if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
  6609. else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  6610. }
  6611. $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.'">';
  6612. if ($addlinktofullsize) $ret .= '</a>';
  6613. } else {
  6614. $nophoto = '/public/theme/common/nophoto.png';
  6615. if (in_array($modulepart, array('userphoto', 'contact', 'memberphoto'))) // For module that are "physical" users
  6616. {
  6617. if ($modulepart == 'memberphoto' && strpos($object->morphy, 'mor') !== false) {
  6618. $nophoto = '/public/theme/common/company.png';
  6619. } else {
  6620. $nophoto = '/public/theme/common/user_anonymous.png';
  6621. if ($object->gender == 'man') $nophoto = '/public/theme/common/user_man.png';
  6622. if ($object->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png';
  6623. }
  6624. }
  6625. if (!empty($conf->gravatar->enabled) && $email)
  6626. {
  6627. /**
  6628. * @see https://gravatar.com/site/implement/images/php/
  6629. */
  6630. global $dolibarr_main_url_root;
  6631. $ret .= '<!-- Put link to gravatar -->';
  6632. //$defaultimg=urlencode(dol_buildpath($nophoto,3));
  6633. $defaultimg = 'mm';
  6634. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Gravatar avatar" 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
  6635. } else {
  6636. $ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
  6637. }
  6638. }
  6639. if ($caneditfield)
  6640. {
  6641. if ($object->photo) $ret .= "<br>\n";
  6642. $ret .= '<table class="nobordernopadding centpercent">';
  6643. if ($object->photo) $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  6644. $ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput" accept="image/*"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
  6645. $ret .= '</table>';
  6646. }
  6647. } else dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
  6648. return $ret;
  6649. }
  6650. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  6651. /**
  6652. * Return select list of groups
  6653. *
  6654. * @param string $selected Id group preselected
  6655. * @param string $htmlname Field name in form
  6656. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  6657. * @param string $exclude Array list of groups id to exclude
  6658. * @param int $disabled If select list must be disabled
  6659. * @param string $include Array list of groups id to include
  6660. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  6661. * @param string $force_entity '0' or Ids of environment to force
  6662. * @param bool $multiple add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
  6663. * @param string $morecss More css to add to html component
  6664. * @return string
  6665. * @see select_dolusers()
  6666. */
  6667. public function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false, $morecss = '')
  6668. {
  6669. // phpcs:enable
  6670. global $conf, $user, $langs;
  6671. // Permettre l'exclusion de groupes
  6672. if (is_array($exclude)) $excludeGroups = implode("','", $exclude);
  6673. // Permettre l'inclusion de groupes
  6674. if (is_array($include)) $includeGroups = implode("','", $include);
  6675. if (!is_array($selected)) $selected = array($selected);
  6676. $out = '';
  6677. // On recherche les groupes
  6678. $sql = "SELECT ug.rowid, ug.nom as name";
  6679. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  6680. {
  6681. $sql .= ", e.label";
  6682. }
  6683. $sql .= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  6684. if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
  6685. {
  6686. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  6687. if ($force_entity) $sql .= " WHERE ug.entity IN (0,".$force_entity.")";
  6688. else $sql .= " WHERE ug.entity IS NOT NULL";
  6689. } else {
  6690. $sql .= " WHERE ug.entity IN (0,".$conf->entity.")";
  6691. }
  6692. if (is_array($exclude) && $excludeGroups) $sql .= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  6693. if (is_array($include) && $includeGroups) $sql .= " AND ug.rowid IN ('".$includeGroups."')";
  6694. $sql .= " ORDER BY ug.nom ASC";
  6695. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  6696. $resql = $this->db->query($sql);
  6697. if ($resql)
  6698. {
  6699. // Enhance with select2
  6700. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  6701. $out .= ajax_combobox($htmlname);
  6702. $out .= '<select class="flat minwidth200'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
  6703. $num = $this->db->num_rows($resql);
  6704. $i = 0;
  6705. if ($num)
  6706. {
  6707. if ($show_empty && !$multiple) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
  6708. while ($i < $num)
  6709. {
  6710. $obj = $this->db->fetch_object($resql);
  6711. $disableline = 0;
  6712. if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = 1;
  6713. $out .= '<option value="'.$obj->rowid.'"';
  6714. if ($disableline) $out .= ' disabled';
  6715. if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (!is_object($selected[0]) && in_array($obj->rowid, $selected)))
  6716. {
  6717. $out .= ' selected';
  6718. }
  6719. $out .= '>';
  6720. $out .= $obj->name;
  6721. if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
  6722. {
  6723. $out .= " (".$obj->label.")";
  6724. }
  6725. $out .= '</option>';
  6726. $i++;
  6727. }
  6728. } else {
  6729. if ($show_empty) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
  6730. $out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  6731. }
  6732. $out .= '</select>';
  6733. } else {
  6734. dol_print_error($this->db);
  6735. }
  6736. return $out;
  6737. }
  6738. /**
  6739. * Return HTML to show the search and clear seach button
  6740. *
  6741. * @return string
  6742. */
  6743. public function showFilterButtons()
  6744. {
  6745. $out = '<div class="nowrap">';
  6746. $out .= '<button type="submit" class="liste_titre button_search" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  6747. $out .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  6748. $out .= '</div>';
  6749. return $out;
  6750. }
  6751. /**
  6752. * Return HTML to show the search and clear seach button
  6753. *
  6754. * @param string $cssclass CSS class
  6755. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  6756. * @param string $massactionname Mass action button name that will launch an action on the selected items
  6757. * @return string
  6758. */
  6759. public function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  6760. {
  6761. global $conf, $langs;
  6762. $out = '';
  6763. $id = uniqid();
  6764. if (!empty($conf->use_javascript_ajax)) $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="' . $cssclass . 's" name="' . $cssclass . 's" class="checkallactions"></div>';
  6765. $out .= '<script>
  6766. $(document).ready(function() {
  6767. $("#' . $cssclass . 's").click(function() {
  6768. if($(this).is(\':checked\')){
  6769. console.log("We check all '.$cssclass.'");
  6770. $(".'.$cssclass.'").prop(\'checked\', true).trigger(\'change\');
  6771. }
  6772. else
  6773. {
  6774. console.log("We uncheck all");
  6775. $(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
  6776. }'."\n";
  6777. if ($calljsfunction) $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0, "' . $massactionname . '", "' . $cssclass . '"); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  6778. $out .= ' });
  6779. $(".' . $cssclass . '").change(function() {
  6780. $(this).closest("tr").toggleClass("highlight", this.checked);
  6781. });
  6782. });
  6783. </script>';
  6784. return $out;
  6785. }
  6786. /**
  6787. * Return HTML to show the search and clear seach button
  6788. *
  6789. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  6790. * @param string $cssclass CSS class
  6791. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  6792. * @param string $massactionname Mass action name
  6793. * @return string
  6794. */
  6795. public function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0, $massactionname = "massaction")
  6796. {
  6797. $out = $this->showFilterButtons();
  6798. if ($addcheckuncheckall)
  6799. {
  6800. $out .= $this->showCheckAddButtons($cssclass, $calljsfunction, $massactionname);
  6801. }
  6802. return $out;
  6803. }
  6804. /**
  6805. * Return HTML to show the select of expense categories
  6806. *
  6807. * @param string $selected preselected category
  6808. * @param string $htmlname name of HTML select list
  6809. * @param integer $useempty 1=Add empty line
  6810. * @param array $excludeid id to exclude
  6811. * @param string $target htmlname of target select to bind event
  6812. * @param int $default_selected default category to select if fk_c_type_fees change = EX_KME
  6813. * @param array $params param to give
  6814. * @return string
  6815. */
  6816. public function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array())
  6817. {
  6818. global $db, $conf, $langs, $user;
  6819. $out = '';
  6820. $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
  6821. $sql .= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
  6822. if (!empty($excludeid)) $sql .= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
  6823. $sql .= ' ORDER BY label';
  6824. $resql = $db->query($sql);
  6825. if ($resql)
  6826. {
  6827. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6828. if ($useempty) $out .= '<option value="0">&nbsp;</option>';
  6829. while ($obj = $db->fetch_object($resql))
  6830. {
  6831. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
  6832. }
  6833. $out .= '</select>';
  6834. if (!empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
  6835. if (!empty($target))
  6836. {
  6837. $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
  6838. $resql = $db->query($sql);
  6839. if ($resql)
  6840. {
  6841. if ($db->num_rows($resql) > 0)
  6842. {
  6843. $obj = $db->fetch_object($resql);
  6844. $out .= '<script>
  6845. $(function() {
  6846. $("select[name='.$target.']").on("change", function() {
  6847. var current_val = $(this).val();
  6848. if (current_val == '.$obj->id.') {';
  6849. if (!empty($default_selected) || !empty($selected)) $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
  6850. $out .= '
  6851. $("select[name='.$htmlname.']").change();
  6852. }
  6853. });
  6854. $("select[name='.$htmlname.']").change(function() {
  6855. if ($("select[name='.$target.']").val() == '.$obj->id.') {
  6856. // get price of kilometer to fill the unit price
  6857. var data = '.json_encode($params).';
  6858. data.fk_c_exp_tax_cat = $(this).val();
  6859. $.ajax({
  6860. method: "POST",
  6861. dataType: "json",
  6862. data: data,
  6863. url: "'.(DOL_URL_ROOT.'/expensereport/ajax/ajaxik.php').'",
  6864. }).done(function( data, textStatus, jqXHR ) {
  6865. console.log(data);
  6866. if (typeof data.up != "undefined") {
  6867. $("input[name=value_unit]").val(data.up);
  6868. $("select[name='.$htmlname.']").attr("title", data.title);
  6869. } else {
  6870. $("input[name=value_unit]").val("");
  6871. $("select[name='.$htmlname.']").attr("title", "");
  6872. }
  6873. });
  6874. }
  6875. });
  6876. });
  6877. </script>';
  6878. }
  6879. }
  6880. }
  6881. } else {
  6882. dol_print_error($db);
  6883. }
  6884. return $out;
  6885. }
  6886. /**
  6887. * Return HTML to show the select ranges of expense range
  6888. *
  6889. * @param string $selected preselected category
  6890. * @param string $htmlname name of HTML select list
  6891. * @param integer $useempty 1=Add empty line
  6892. * @return string
  6893. */
  6894. public function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
  6895. {
  6896. global $db, $conf, $langs;
  6897. $out = '';
  6898. $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
  6899. $sql .= ' WHERE entity = '.$conf->entity.' AND active = 1';
  6900. $resql = $db->query($sql);
  6901. if ($resql)
  6902. {
  6903. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6904. if ($useempty) $out .= '<option value="0"></option>';
  6905. while ($obj = $db->fetch_object($resql))
  6906. {
  6907. $out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
  6908. }
  6909. $out .= '</select>';
  6910. } else {
  6911. dol_print_error($db);
  6912. }
  6913. return $out;
  6914. }
  6915. /**
  6916. * Return HTML to show a select of expense
  6917. *
  6918. * @param string $selected preselected category
  6919. * @param string $htmlname name of HTML select list
  6920. * @param integer $useempty 1=Add empty choice
  6921. * @param integer $allchoice 1=Add all choice
  6922. * @param integer $useid 0=use 'code' as key, 1=use 'id' as key
  6923. * @return string
  6924. */
  6925. public function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
  6926. {
  6927. global $db, $langs;
  6928. $out = '';
  6929. $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
  6930. $sql .= ' WHERE active = 1';
  6931. $resql = $db->query($sql);
  6932. if ($resql)
  6933. {
  6934. $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
  6935. if ($useempty) $out .= '<option value="0"></option>';
  6936. if ($allchoice) $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
  6937. $field = 'code';
  6938. if ($useid) $field = 'id';
  6939. while ($obj = $db->fetch_object($resql))
  6940. {
  6941. $key = $langs->trans($obj->code);
  6942. $out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
  6943. }
  6944. $out .= '</select>';
  6945. } else {
  6946. dol_print_error($db);
  6947. }
  6948. return $out;
  6949. }
  6950. /**
  6951. * Output a combo list with invoices qualified for a third party
  6952. *
  6953. * @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)
  6954. * @param int $selected Id invoice preselected
  6955. * @param string $htmlname Name of HTML select
  6956. * @param int $maxlength Maximum length of label
  6957. * @param int $option_only Return only html options lines without the select tag
  6958. * @param string $show_empty Add an empty line ('1' or string to show for empty line)
  6959. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
  6960. * @param int $forcefocus Force focus on field (works with javascript only)
  6961. * @param int $disabled Disabled
  6962. * @param string $morecss More css added to the select component
  6963. * @param string $projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
  6964. * @param string $showproject 'all' = Show project info, ''=Hide project info
  6965. * @param User $usertofilter User object to use for filtering
  6966. * @return int Nbr of project if OK, <0 if KO
  6967. */
  6968. 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)
  6969. {
  6970. global $user, $conf, $langs;
  6971. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  6972. if (is_null($usertofilter))
  6973. {
  6974. $usertofilter = $user;
  6975. }
  6976. $out = '';
  6977. $hideunselectables = false;
  6978. if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
  6979. if (empty($projectsListId))
  6980. {
  6981. if (empty($usertofilter->rights->projet->all->lire))
  6982. {
  6983. $projectstatic = new Project($this->db);
  6984. $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
  6985. }
  6986. }
  6987. // Search all projects
  6988. $sql = 'SELECT f.rowid, f.ref as fref, "nolabel" as flabel, p.rowid as pid, f.ref,
  6989. p.title, p.fk_soc, p.fk_statut, p.public,';
  6990. $sql .= ' s.nom as name';
  6991. $sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p';
  6992. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
  6993. $sql .= ' '.MAIN_DB_PREFIX.'facture as f';
  6994. $sql .= " WHERE p.entity IN (".getEntity('project').")";
  6995. $sql .= " AND f.fk_projet = p.rowid AND f.fk_statut=0"; //Brouillons seulement
  6996. //if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
  6997. //if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
  6998. //if ($socid > 0) $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
  6999. $sql .= " GROUP BY f.ref ORDER BY p.ref, f.ref ASC";
  7000. $resql = $this->db->query($sql);
  7001. if ($resql)
  7002. {
  7003. // Use select2 selector
  7004. if (!empty($conf->use_javascript_ajax))
  7005. {
  7006. include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  7007. $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
  7008. $out .= $comboenhancement;
  7009. $morecss = 'minwidth200imp maxwidth500';
  7010. }
  7011. if (empty($option_only)) {
  7012. $out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
  7013. }
  7014. if (!empty($show_empty)) {
  7015. $out .= '<option value="0" class="optiongrey">';
  7016. if (!is_numeric($show_empty)) $out .= $show_empty;
  7017. else $out .= '&nbsp;';
  7018. $out .= '</option>';
  7019. }
  7020. $num = $this->db->num_rows($resql);
  7021. $i = 0;
  7022. if ($num)
  7023. {
  7024. while ($i < $num)
  7025. {
  7026. $obj = $this->db->fetch_object($resql);
  7027. // 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.
  7028. if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire))
  7029. {
  7030. // Do nothing
  7031. } else {
  7032. if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED)
  7033. {
  7034. $i++;
  7035. continue;
  7036. }
  7037. $labeltoshow = '';
  7038. if ($showproject == 'all')
  7039. {
  7040. $labeltoshow .= dol_trunc($obj->ref, 18); // Invoice ref
  7041. if ($obj->name) $labeltoshow .= ' - '.$obj->name; // Soc name
  7042. $disabled = 0;
  7043. if ($obj->fk_statut == Project::STATUS_DRAFT)
  7044. {
  7045. $disabled = 1;
  7046. $labeltoshow .= ' - '.$langs->trans("Draft");
  7047. } elseif ($obj->fk_statut == Project::STATUS_CLOSED)
  7048. {
  7049. if ($discard_closed == 2) $disabled = 1;
  7050. $labeltoshow .= ' - '.$langs->trans("Closed");
  7051. } elseif ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid))
  7052. {
  7053. $disabled = 1;
  7054. $labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
  7055. }
  7056. }
  7057. if (!empty($selected) && $selected == $obj->rowid)
  7058. {
  7059. $out .= '<option value="'.$obj->rowid.'" selected';
  7060. //if ($disabled) $out.=' disabled'; // with select2, field can't be preselected if disabled
  7061. $out .= '>'.$labeltoshow.'</option>';
  7062. } else {
  7063. if ($hideunselectables && $disabled && ($selected != $obj->rowid))
  7064. {
  7065. $resultat = '';
  7066. } else {
  7067. $resultat = '<option value="'.$obj->rowid.'"';
  7068. if ($disabled) $resultat .= ' disabled';
  7069. //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
  7070. //else $labeltoshow.=' ('.$langs->trans("Private").')';
  7071. $resultat .= '>';
  7072. $resultat .= $labeltoshow;
  7073. $resultat .= '</option>';
  7074. }
  7075. $out .= $resultat;
  7076. }
  7077. }
  7078. $i++;
  7079. }
  7080. }
  7081. if (empty($option_only)) {
  7082. $out .= '</select>';
  7083. }
  7084. print $out;
  7085. $this->db->free($resql);
  7086. return $num;
  7087. } else {
  7088. dol_print_error($this->db);
  7089. return -1;
  7090. }
  7091. }
  7092. /**
  7093. * Output the component to make advanced search criteries
  7094. *
  7095. * @param array $arrayofcriterias Array of available search criterias. Example: array($object->element => $object->fields, 'otherfamily' => otherarrayoffields, ...)
  7096. * @param array $search_component_params Array of selected search criterias
  7097. * @param array $arrayofinputfieldsalreadyoutput Array of input fields already inform. The component will not generate a hidden input field if it is in this list.
  7098. * @return string HTML component for advanced search
  7099. */
  7100. public function searchComponent($arrayofcriterias, $search_component_params, $arrayofinputfieldsalreadyoutput = array())
  7101. {
  7102. global $conf, $langs;
  7103. $ret = '';
  7104. $ret .= '<div class="nowrap centpercent">';
  7105. //$ret .= '<button type="submit" class="liste_titre button_removefilter" name="button_removefilter_x" value="x"><span class="fa fa-remove"></span></button>';
  7106. $ret .= '<a href="#" class="dropdownsearch-toggle unsetcolor paddingright">';
  7107. $ret .= '<span class="fas fa-filter linkobject boxfilter" title="Filter" id="idsubimgproductdistribution"></span>';
  7108. $ret .= $langs->trans("Filters");
  7109. $ret .= '</a>';
  7110. //$ret .= '<button type="submit" class="liste_titre button_search paddingleftonly" name="button_search_x" value="x"><span class="fa fa-search"></span></button>';
  7111. $ret .= '<div name="search_component_params" class="search_component_params inline-block minwidth500 maxwidth300onsmartphone valignmiddle">';
  7112. $texttoshow = '<div class="opacitymedium inline-block search_component_searchtext">'.$langs->trans("Search").'</div>';
  7113. $ret .= '<div class="search_component inline-block valignmiddle">'.$texttoshow.'</div>';
  7114. $ret .= '</div>';
  7115. $ret .= '<input type="hidden" name="search_component_params_hidden" class="search_component_params_hidden" value="'.GETPOST("search_component_params_hidden").'">';
  7116. // For compatibility with forms that show themself the search criteria in addition of this component, we output the fields
  7117. foreach ($arrayofcriterias as $criterias) {
  7118. foreach ($criterias as $criteriafamilykey => $criteriafamilyval) {
  7119. if (in_array('search_'.$criteriafamilykey, $arrayofinputfieldsalreadyoutput)) continue;
  7120. if (in_array($criteriafamilykey, array('rowid', 'ref_ext', 'entity', 'extraparams'))) continue;
  7121. if (in_array($criteriafamilyval['type'], array('date', 'datetime', 'timestamp'))) {
  7122. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_start">';
  7123. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startyear">';
  7124. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startmonth">';
  7125. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_startday">';
  7126. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_end">';
  7127. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endyear">';
  7128. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endmonth">';
  7129. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'_endday">';
  7130. } else {
  7131. $ret .= '<input type="hidden" name="search_'.$criteriafamilykey.'">';
  7132. }
  7133. }
  7134. }
  7135. $ret .= '</div>';
  7136. return $ret;
  7137. }
  7138. /**
  7139. * selectModelMail
  7140. *
  7141. * @param string $prefix Prefix
  7142. * @param string $modelType Model type
  7143. * @return string HTML select string
  7144. */
  7145. public function selectModelMail($prefix, $modelType = '')
  7146. {
  7147. global $langs, $db, $user;
  7148. $retstring = '';
  7149. $TModels = array();
  7150. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  7151. $formmail = new FormMail($db);
  7152. $result = $formmail->fetchAllEMailTemplate($modelType, $user, $langs);
  7153. if ($result > 0) {
  7154. foreach ($formmail->lines_model as $model){
  7155. $TModels[$model->id] = $model->label;
  7156. }
  7157. }
  7158. $retstring .= '<select class="flat" id="select_'.$prefix.'model_mail" name="'.$prefix.'model_mail">';
  7159. foreach ($TModels as $id_model=>$label_model){
  7160. $retstring .= '<option value="'.$id_model.'"';
  7161. $retstring .= ">".$label_model."</option>";
  7162. }
  7163. $retstring .= "</select>";
  7164. return $retstring;
  7165. }
  7166. }