html.form.class.php 277 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283
  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-2014 Regis Houssin <regis.houssin@capnetworks.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-2014 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.dolibarr@gmail.com>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  32. */
  33. /**
  34. * \file htdocs/core/class/html.form.class.php
  35. * \ingroup core
  36. * \brief File of class with all html predefined components
  37. */
  38. /**
  39. * Class to manage generation of HTML components
  40. * Only common components must be here.
  41. *
  42. * TODO Merge all function load_cache_* and loadCache* (except load_cache_vatrates) into one generic function loadCacheTable
  43. */
  44. class Form
  45. {
  46. var $db;
  47. var $error;
  48. var $num;
  49. // Cache arrays
  50. var $cache_types_paiements=array();
  51. var $cache_conditions_paiements=array();
  52. var $cache_availability=array();
  53. var $cache_demand_reason=array();
  54. var $cache_types_fees=array();
  55. var $cache_vatrates=array();
  56. /**
  57. * Constructor
  58. *
  59. * @param DoliDB $db Database handler
  60. */
  61. public function __construct($db)
  62. {
  63. $this->db = $db;
  64. }
  65. /**
  66. * Output key field for an editable field
  67. *
  68. * @param string $text Text of label or key to translate
  69. * @param string $htmlname Name of select field ('edit' prefix will be added)
  70. * @param string $preselected Value to show/edit (not used in this function)
  71. * @param object $object Object
  72. * @param boolean $perm Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
  73. * @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]'...)
  74. * @param string $moreparam More param to add on a href URL.
  75. * @param int $fieldrequired 1 if we want to show field as mandatory using the "fieldrequired" CSS.
  76. * @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 ' '
  77. * @return string HTML edit field
  78. */
  79. function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0)
  80. {
  81. global $conf,$langs;
  82. $ret='';
  83. // TODO change for compatibility
  84. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
  85. {
  86. if (! empty($perm))
  87. {
  88. $tmp=explode(':',$typeofdata);
  89. $ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
  90. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  91. $ret.= $langs->trans($text);
  92. if ($fieldrequired) $ret.='</span>';
  93. $ret.= '</div>'."\n";
  94. }
  95. else
  96. {
  97. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  98. $ret.= $langs->trans($text);
  99. if ($fieldrequired) $ret.='</span>';
  100. }
  101. }
  102. else
  103. {
  104. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
  105. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  106. $ret.=$langs->trans($text);
  107. if ($fieldrequired) $ret.='</span>';
  108. if (! empty($notabletag)) $ret.=' ';
  109. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
  110. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
  111. if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;id='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
  112. if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
  113. if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
  114. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
  115. if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
  116. }
  117. return $ret;
  118. }
  119. /**
  120. * Output val field for an editable field
  121. *
  122. * @param string $text Text of label (not used in this function)
  123. * @param string $htmlname Name of select field
  124. * @param string $value Value to show/edit
  125. * @param object $object Object
  126. * @param boolean $perm Permission to allow button to edit parameter
  127. * @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:xxx'...)
  128. * @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
  129. * @param object $extObject External object
  130. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  131. * @param string $moreparam More param to add on a href URL
  132. * @param int $notabletag Do no output table tags
  133. * @return string HTML edit field
  134. */
  135. function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0)
  136. {
  137. global $conf,$langs,$db;
  138. $ret='';
  139. // Check parameters
  140. if (empty($typeofdata)) return 'ErrorBadParameter';
  141. // When option to edit inline is activated
  142. if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
  143. {
  144. $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
  145. }
  146. else
  147. {
  148. if (GETPOST('action','aZ09') == 'edit'.$htmlname)
  149. {
  150. $ret.="\n";
  151. $ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
  152. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  153. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  154. $ret.='<input type="hidden" name="id" value="'.$object->id.'">';
  155. if (empty($notabletag)) $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  156. if (empty($notabletag)) $ret.='<tr><td>';
  157. if (preg_match('/^(string|email)/',$typeofdata))
  158. {
  159. $tmp=explode(':',$typeofdata);
  160. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  161. }
  162. else if (preg_match('/^(numeric|amount)/',$typeofdata))
  163. {
  164. $tmp=explode(':',$typeofdata);
  165. $valuetoshow=price2num($editvalue?$editvalue:$value);
  166. $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
  167. }
  168. else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
  169. {
  170. $tmp=explode(':',$typeofdata);
  171. $cols=$tmp[2];
  172. $morealt='';
  173. if (preg_match('/%/',$cols))
  174. {
  175. $morealt=' style="width: '.$cols.'"';
  176. $cols='';
  177. }
  178. $ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'').$morealt.'">'.($editvalue?$editvalue:$value).'</textarea>';
  179. }
  180. else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
  181. {
  182. $ret.=$this->select_date($value,$htmlname,0,0,1,'form'.$htmlname,1,0,1);
  183. }
  184. else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
  185. {
  186. $ret.=$this->select_date($value,$htmlname,1,1,1,'form'.$htmlname,1,0,1);
  187. }
  188. else if (preg_match('/^select;/',$typeofdata))
  189. {
  190. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  191. foreach($arraydata as $val)
  192. {
  193. $tmp=explode(':',$val);
  194. $arraylist[$tmp[0]]=$tmp[1];
  195. }
  196. $ret.=$this->selectarray($htmlname,$arraylist,$value);
  197. }
  198. else if (preg_match('/^ckeditor/',$typeofdata))
  199. {
  200. $tmp=explode(':',$typeofdata);
  201. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  202. $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), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
  203. $ret.=$doleditor->Create(1);
  204. }
  205. if (empty($notabletag)) $ret.='</td>';
  206. if (empty($notabletag)) $ret.='<td align="left">';
  207. //else $ret.='<div class="clearboth"></div>';
  208. $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
  209. if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
  210. $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
  211. if (empty($notabletag)) $ret.='</td>';
  212. if (empty($notabletag)) $ret.='</tr></table>'."\n";
  213. $ret.='</form>'."\n";
  214. }
  215. else
  216. {
  217. if (preg_match('/^(email)/',$typeofdata)) $ret.=dol_print_email($value,0,0,0,0,1);
  218. elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
  219. elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) $ret.=dol_htmlentitiesbr($value);
  220. elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
  221. elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
  222. else if (preg_match('/^select;/',$typeofdata))
  223. {
  224. $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
  225. foreach($arraydata as $val)
  226. {
  227. $tmp=explode(':',$val);
  228. $arraylist[$tmp[0]]=$tmp[1];
  229. }
  230. $ret.=$arraylist[$value];
  231. }
  232. else if (preg_match('/^ckeditor/',$typeofdata))
  233. {
  234. $tmpcontent=dol_htmlentitiesbr($value);
  235. if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
  236. {
  237. $firstline=preg_replace('/<br>.*/','',$tmpcontent);
  238. $firstline=preg_replace('/[\n\r].*/','',$firstline);
  239. $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
  240. }
  241. $ret.=$tmpcontent;
  242. }
  243. else $ret.=$value;
  244. }
  245. }
  246. return $ret;
  247. }
  248. /**
  249. * Output edit in place form
  250. *
  251. * @param object $object Object
  252. * @param string $value Value to show/edit
  253. * @param string $htmlname DIV ID (field name)
  254. * @param int $condition Condition to edit
  255. * @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:xxx')
  256. * @param string $editvalue When in edit mode, use this value as $value instead of value
  257. * @param object $extObject External object
  258. * @param mixed $custommsg String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
  259. * @return string HTML edit in place
  260. */
  261. private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
  262. {
  263. global $conf;
  264. $out='';
  265. // Check parameters
  266. if ($inputType == 'textarea') $value = dol_nl2br($value);
  267. else if (preg_match('/^numeric/',$inputType)) $value = price($value);
  268. else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
  269. if ($condition)
  270. {
  271. $element = false;
  272. $table_element = false;
  273. $fk_element = false;
  274. $loadmethod = false;
  275. $savemethod = false;
  276. $ext_element = false;
  277. $button_only = false;
  278. $inputOption = '';
  279. if (is_object($object))
  280. {
  281. $element = $object->element;
  282. $table_element = $object->table_element;
  283. $fk_element = $object->id;
  284. }
  285. if (is_object($extObject))
  286. {
  287. $ext_element = $extObject->element;
  288. }
  289. if (preg_match('/^(string|email|numeric)/',$inputType))
  290. {
  291. $tmp=explode(':',$inputType);
  292. $inputType=$tmp[0];
  293. if (! empty($tmp[1])) $inputOption=$tmp[1];
  294. if (! empty($tmp[2])) $savemethod=$tmp[2];
  295. $out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
  296. }
  297. else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
  298. {
  299. $tmp=explode(':',$inputType);
  300. $inputType=$tmp[0];
  301. if (! empty($tmp[1])) $inputOption=$tmp[1];
  302. if (! empty($tmp[2])) $savemethod=$tmp[2];
  303. $out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
  304. }
  305. else if (preg_match('/^(select|autocomplete)/',$inputType))
  306. {
  307. $tmp=explode(':',$inputType);
  308. $inputType=$tmp[0]; $loadmethod=$tmp[1];
  309. if (! empty($tmp[2])) $savemethod=$tmp[2];
  310. if (! empty($tmp[3])) $button_only=true;
  311. }
  312. else if (preg_match('/^textarea/',$inputType))
  313. {
  314. $tmp=explode(':',$inputType);
  315. $inputType=$tmp[0];
  316. $rows=(empty($tmp[1])?'8':$tmp[1]);
  317. $cols=(empty($tmp[2])?'80':$tmp[2]);
  318. }
  319. else if (preg_match('/^ckeditor/',$inputType))
  320. {
  321. $tmp=explode(':',$inputType);
  322. $inputType=$tmp[0]; $toolbar=$tmp[1];
  323. if (! empty($tmp[2])) $width=$tmp[2];
  324. if (! empty($tmp[3])) $heigth=$tmp[3];
  325. if (! empty($tmp[4])) $savemethod=$tmp[4];
  326. if (! empty($conf->fckeditor->enabled))
  327. {
  328. $out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
  329. }
  330. else
  331. {
  332. $inputType = 'textarea';
  333. }
  334. }
  335. $out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
  336. $out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
  337. $out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
  338. $out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
  339. if (! empty($savemethod)) $out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
  340. if (! empty($ext_element)) $out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
  341. if (! empty($custommsg))
  342. {
  343. if (is_array($custommsg))
  344. {
  345. if (!empty($custommsg['success']))
  346. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
  347. if (!empty($custommsg['error']))
  348. $out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
  349. }
  350. else
  351. $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
  352. }
  353. if ($inputType == 'textarea') {
  354. $out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
  355. $out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
  356. }
  357. $out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
  358. $out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
  359. }
  360. else
  361. {
  362. $out = $value;
  363. }
  364. return $out;
  365. }
  366. /**
  367. * Show a text and picto with tooltip on text or picto.
  368. * Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
  369. *
  370. * @param string $text Text to show
  371. * @param string $htmltext HTML content of tooltip. Must be HTML/UTF8 encoded.
  372. * @param int $tooltipon 1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
  373. * @param int $direction -1=image is before, 0=no image, 1=image is after
  374. * @param string $img Html code for image (use img_xxx() function to get it)
  375. * @param string $extracss Add a CSS style to td tags
  376. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  377. * @param string $incbefore Include code before the text
  378. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  379. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  380. * @return string Code html du tooltip (texte+picto)
  381. * @see Use function textwithpicto if you can.
  382. * TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
  383. */
  384. function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='')
  385. {
  386. global $conf;
  387. if ($incbefore) $text = $incbefore.$text;
  388. if (! $htmltext) return $text;
  389. $tag='td';
  390. if ($notabs == 2) $tag='div';
  391. if ($notabs == 3) $tag='span';
  392. // Sanitize tooltip
  393. $htmltext=str_replace("\\","\\\\",$htmltext);
  394. $htmltext=str_replace("\r","",$htmltext);
  395. $htmltext=str_replace("\n","",$htmltext);
  396. $extrastyle='';
  397. if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
  398. if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
  399. $classfortooltip='classfortooltip';
  400. $s='';$textfordialog='';
  401. $htmltext=str_replace('"',"&quot;",$htmltext);
  402. if ($tooltiptrigger != '')
  403. {
  404. $classfortooltip='classfortooltiponclick';
  405. $textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
  406. }
  407. if ($tooltipon == 2 || $tooltipon == 3)
  408. {
  409. $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
  410. if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
  411. else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
  412. }
  413. else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  414. if ($tooltipon == 1 || $tooltipon == 3)
  415. {
  416. $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
  417. if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
  418. else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
  419. }
  420. else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
  421. if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
  422. elseif ($notabs == 2) $s.='<div class="inline-block">';
  423. // Define value if value is before
  424. if ($direction < 0) {
  425. $s.='<'.$tag.$paramfortooltipimg;
  426. if ($tag == 'td') {
  427. $s .= ' valign="top" width="14"';
  428. }
  429. $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
  430. }
  431. // Use another method to help avoid having a space in value in order to use this value with jquery
  432. // Define label
  433. if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
  434. // Define value if value is after
  435. if ($direction > 0) {
  436. $s.='<'.$tag.$paramfortooltipimg;
  437. if ($tag == 'td') $s .= ' valign="middle" width="14"';
  438. $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
  439. }
  440. if (empty($notabs)) $s.='</tr></table>';
  441. elseif ($notabs == 2) $s.='</div>';
  442. return $s;
  443. }
  444. /**
  445. * Show a text with a picto and a tooltip on picto
  446. *
  447. * @param string $text Text to show
  448. * @param string $htmltext Content of tooltip
  449. * @param int $direction 1=Icon is after text, -1=Icon is before text, 0=no icon
  450. * @param string $type Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath
  451. * @param string $extracss Add a CSS style to td, div or span tag
  452. * @param int $noencodehtmltext Do not encode into html entity the htmltext
  453. * @param int $notabs 0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
  454. * @param string $tooltiptrigger ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
  455. * @return string HTML code of text, picto, tooltip
  456. */
  457. function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='')
  458. {
  459. global $conf, $langs;
  460. $alt = '';
  461. if ($tooltiptrigger) $alt=$langs->trans("ClickToShowHelp");
  462. //For backwards compatibility
  463. if ($type == '0') $type = 'info';
  464. elseif ($type == '1') $type = 'help';
  465. // If info or help with no javascript, show only text
  466. if (empty($conf->use_javascript_ajax))
  467. {
  468. if ($type == 'info' || $type == 'help') return $text;
  469. else
  470. {
  471. $alt = $htmltext;
  472. $htmltext = '';
  473. }
  474. }
  475. // If info or help with smartphone, show only text (tooltip can't works)
  476. if (! empty($conf->dol_no_mouse_hover))
  477. {
  478. if ($type == 'info' || $type == 'help') return $text;
  479. }
  480. if ($type == 'info') $img = img_help(0, $alt);
  481. elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
  482. elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
  483. elseif ($type == 'admin') $img = img_picto($alt, 'star');
  484. elseif ($type == 'warning') $img = img_warning($alt);
  485. else $img = img_picto($alt, $type);
  486. return $this->textwithtooltip($text, $htmltext, ($tooltiptrigger?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger);
  487. }
  488. /**
  489. * Generate select HTML to choose massaction
  490. *
  491. * @param string $selected Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
  492. * @param int $arrayofaction array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
  493. * @param int $alwaysvisible 1=select button always visible
  494. * @return string Select list
  495. */
  496. function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
  497. {
  498. global $conf,$langs,$hookmanager;
  499. if (count($arrayofaction) == 0) return;
  500. $disabled=0;
  501. $ret='<div class="centpercent center">';
  502. $ret.='<select data-role="none" class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
  503. $ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
  504. foreach($arrayofaction as $code => $label)
  505. {
  506. $ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
  507. }
  508. $ret.='</select>';
  509. // Warning: if you set submit button to disabled, post using 'Enter' will no more work.
  510. $ret.='<input type="submit" data-role="none" name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
  511. $ret.='</div>';
  512. if (! empty($conf->use_javascript_ajax))
  513. {
  514. $ret.='<!-- JS CODE TO ENABLE mass action select -->
  515. <script type="text/javascript">
  516. function initCheckForSelect()
  517. {
  518. atleastoneselected=0;
  519. jQuery(".checkforselect").each(function( index ) {
  520. /* console.log( index + ": " + $( this ).text() ); */
  521. if ($(this).is(\':checked\')) atleastoneselected++;
  522. });
  523. if (atleastoneselected || '.$alwaysvisible.')
  524. {
  525. jQuery(".massaction").show();
  526. '.($selected ? 'if (atleastoneselected) jQuery(".massactionselect").val("'.$selected.'");' : '').'
  527. '.($selected ? 'if (! atleastoneselected) jQuery(".massactionselect").val("0");' : '').'
  528. }
  529. else
  530. {
  531. jQuery(".massaction").hide();
  532. }
  533. }
  534. jQuery(document).ready(function () {
  535. initCheckForSelect();
  536. jQuery(".checkforselect").click(function() {
  537. initCheckForSelect();
  538. });
  539. jQuery(".massactionselect").change(function() {
  540. var massaction = $( this ).val();
  541. var urlform = $( this ).closest("form").attr("action").replace("#show_files","");
  542. if (massaction == "builddoc")
  543. {
  544. urlform = urlform + "#show_files";
  545. }
  546. $( this ).closest("form").attr("action", urlform);
  547. console.log("we select a mass action "+massaction+" - "+urlform);
  548. /* Warning: if you set submit button to disabled, post using Enter will no more work
  549. if ($(this).val() != \'0\')
  550. {
  551. jQuery(".massactionconfirmed").prop(\'disabled\', false);
  552. }
  553. else
  554. {
  555. jQuery(".massactionconfirmed").prop(\'disabled\', true);
  556. }
  557. */
  558. });
  559. });
  560. </script>
  561. ';
  562. }
  563. return $ret;
  564. }
  565. /**
  566. * Return combo list of activated countries, into language of user
  567. *
  568. * @param string $selected Id or Code or Label of preselected country
  569. * @param string $htmlname Name of html select object
  570. * @param string $htmloption Options html on select object
  571. * @param integer $maxlength Max length for labels (0=no limit)
  572. * @param string $morecss More css class
  573. * @return string HTML string with select
  574. */
  575. function select_country($selected='',$htmlname='country_id',$htmloption='',$maxlength=0,$morecss='minwidth300')
  576. {
  577. global $conf,$langs;
  578. $langs->load("dict");
  579. $out='';
  580. $countryArray=array();
  581. $favorite=array();
  582. $label=array();
  583. $atleastonefavorite=0;
  584. $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
  585. $sql.= " FROM ".MAIN_DB_PREFIX."c_country";
  586. $sql.= " WHERE active > 0";
  587. //$sql.= " ORDER BY code ASC";
  588. dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
  589. $resql=$this->db->query($sql);
  590. if ($resql)
  591. {
  592. $out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
  593. $num = $this->db->num_rows($resql);
  594. $i = 0;
  595. if ($num)
  596. {
  597. $foundselected=false;
  598. while ($i < $num)
  599. {
  600. $obj = $this->db->fetch_object($resql);
  601. $countryArray[$i]['rowid'] = $obj->rowid;
  602. $countryArray[$i]['code_iso'] = $obj->code_iso;
  603. $countryArray[$i]['code_iso3'] = $obj->code_iso3;
  604. $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:''));
  605. $countryArray[$i]['favorite'] = $obj->favorite;
  606. $favorite[$i] = $obj->favorite;
  607. $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
  608. $i++;
  609. }
  610. array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
  611. foreach ($countryArray as $row)
  612. {
  613. if ($row['favorite'] && $row['code_iso']) $atleastonefavorite++;
  614. if (empty($row['favorite']) && $atleastonefavorite)
  615. {
  616. $atleastonefavorite=0;
  617. $out.= '<option value="" disabled class="selectoptiondisabledwhite">----------------------</option>';
  618. }
  619. if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
  620. {
  621. $foundselected=true;
  622. $out.= '<option value="'.$row['rowid'].'" selected>';
  623. }
  624. else
  625. {
  626. $out.= '<option value="'.$row['rowid'].'">';
  627. }
  628. $out.= dol_trunc($row['label'],$maxlength,'middle');
  629. if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
  630. $out.= '</option>';
  631. }
  632. }
  633. $out.= '</select>';
  634. }
  635. else
  636. {
  637. dol_print_error($this->db);
  638. }
  639. // Make select dynamic
  640. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  641. $out .= ajax_combobox('select'.$htmlname);
  642. return $out;
  643. }
  644. /**
  645. * Return select list of incoterms
  646. *
  647. * @param string $selected Id or Code of preselected incoterm
  648. * @param string $location_incoterms Value of input location
  649. * @param string $page Defined the form action
  650. * @param string $htmlname Name of html select object
  651. * @param string $htmloption Options html on select object
  652. * @param int $forcecombo Force to use standard combo box (no ajax use)
  653. * @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')))
  654. * @return string HTML string with select and input
  655. */
  656. function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
  657. {
  658. global $conf,$langs;
  659. $langs->load("dict");
  660. $out='';
  661. $incotermArray=array();
  662. $sql = "SELECT rowid, code";
  663. $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
  664. $sql.= " WHERE active > 0";
  665. $sql.= " ORDER BY code ASC";
  666. dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
  667. $resql=$this->db->query($sql);
  668. if ($resql)
  669. {
  670. if ($conf->use_javascript_ajax && ! $forcecombo)
  671. {
  672. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  673. $out .= ajax_combobox($htmlname, $events);
  674. }
  675. if (!empty($page))
  676. {
  677. $out .= '<form method="post" action="'.$page.'">';
  678. $out .= '<input type="hidden" name="action" value="set_incoterms">';
  679. $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  680. }
  681. $out.= '<select id="'.$htmlname.'" class="flat selectincoterm noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
  682. $out.= '<option value="0">&nbsp;</option>';
  683. $num = $this->db->num_rows($resql);
  684. $i = 0;
  685. if ($num)
  686. {
  687. $foundselected=false;
  688. while ($i < $num)
  689. {
  690. $obj = $this->db->fetch_object($resql);
  691. $incotermArray[$i]['rowid'] = $obj->rowid;
  692. $incotermArray[$i]['code'] = $obj->code;
  693. $i++;
  694. }
  695. foreach ($incotermArray as $row)
  696. {
  697. if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
  698. {
  699. $out.= '<option value="'.$row['rowid'].'" selected>';
  700. }
  701. else
  702. {
  703. $out.= '<option value="'.$row['rowid'].'">';
  704. }
  705. if ($row['code']) $out.= $row['code'];
  706. $out.= '</option>';
  707. }
  708. }
  709. $out.= '</select>';
  710. $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
  711. if (!empty($page))
  712. {
  713. $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
  714. }
  715. }
  716. else
  717. {
  718. dol_print_error($this->db);
  719. }
  720. return $out;
  721. }
  722. /**
  723. * Return list of types of lines (product or service)
  724. * Example: 0=product, 1=service, 9=other (for external module)
  725. *
  726. * @param string $selected Preselected type
  727. * @param string $htmlname Name of field in html form
  728. * @param int $showempty Add an empty field
  729. * @param int $hidetext Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
  730. * @param integer $forceall 1=Force to show products and services in combo list, whatever are activated modules, 0=No force, -1=Force none (and set hidden field to 'service')
  731. * @return void
  732. */
  733. function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
  734. {
  735. global $db,$langs,$user,$conf;
  736. // If product & services are enabled or both disabled.
  737. if ($forceall > 0 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
  738. || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
  739. {
  740. if (empty($hidetext)) print $langs->trans("Type").': ';
  741. print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
  742. if ($showempty)
  743. {
  744. print '<option value="-1"';
  745. if ($selected == -1) print ' selected';
  746. print '>&nbsp;</option>';
  747. }
  748. print '<option value="0"';
  749. if (0 == $selected) print ' selected';
  750. print '>'.$langs->trans("Product");
  751. print '<option value="1"';
  752. if (1 == $selected) print ' selected';
  753. print '>'.$langs->trans("Service");
  754. print '</select>';
  755. //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  756. }
  757. if (empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled))
  758. {
  759. print $langs->trans("Service");
  760. print '<input type="hidden" name="'.$htmlname.'" value="1">';
  761. }
  762. if (empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled))
  763. {
  764. print $langs->trans("Product");
  765. print '<input type="hidden" name="'.$htmlname.'" value="0">';
  766. }
  767. if ($forceall < 0) // This should happened only for contracts when both predefined product and service are disabled.
  768. {
  769. 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
  770. }
  771. }
  772. /**
  773. * Load into cache cache_types_fees, array of types of fees
  774. *
  775. * @return int Nb of lines loaded, <0 if KO
  776. */
  777. function load_cache_types_fees()
  778. {
  779. global $langs;
  780. $num = count($this->cache_types_fees);
  781. if ($num > 0) return 0; // Cache already loaded
  782. dol_syslog(__METHOD__, LOG_DEBUG);
  783. $langs->load("trips");
  784. $sql = "SELECT c.code, c.label";
  785. $sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
  786. $sql.= " WHERE active > 0";
  787. $resql=$this->db->query($sql);
  788. if ($resql)
  789. {
  790. $num = $this->db->num_rows($resql);
  791. $i = 0;
  792. while ($i < $num)
  793. {
  794. $obj = $this->db->fetch_object($resql);
  795. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  796. $label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
  797. $this->cache_types_fees[$obj->code] = $label;
  798. $i++;
  799. }
  800. asort($this->cache_types_fees);
  801. return $num;
  802. }
  803. else
  804. {
  805. dol_print_error($this->db);
  806. return -1;
  807. }
  808. }
  809. /**
  810. * Return list of types of notes
  811. *
  812. * @param string $selected Preselected type
  813. * @param string $htmlname Name of field in form
  814. * @param int $showempty Add an empty field
  815. * @return void
  816. */
  817. function select_type_fees($selected='',$htmlname='type',$showempty=0)
  818. {
  819. global $user, $langs;
  820. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  821. $this->load_cache_types_fees();
  822. print '<select class="flat" name="'.$htmlname.'">';
  823. if ($showempty)
  824. {
  825. print '<option value="-1"';
  826. if ($selected == -1) print ' selected';
  827. print '>&nbsp;</option>';
  828. }
  829. foreach($this->cache_types_fees as $key => $value)
  830. {
  831. print '<option value="'.$key.'"';
  832. if ($key == $selected) print ' selected';
  833. print '>';
  834. print $value;
  835. print '</option>';
  836. }
  837. print '</select>';
  838. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  839. }
  840. /**
  841. * Return HTML code to select a company.
  842. *
  843. * @param int $selected Preselected products
  844. * @param string $htmlname Name of HTML select field (must be unique in page)
  845. * @param int $filter Filter on thirdparty
  846. * @param int $limit Limit on number of returned lines
  847. * @param array $ajaxoptions Options for ajax_autocompleter
  848. * @param int $forcecombo Force to use combo box
  849. * @return string Return select box for thirdparty.
  850. * @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)
  851. */
  852. function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
  853. {
  854. return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0,$limit);
  855. }
  856. /**
  857. * Output html form to select a third party
  858. *
  859. * @param string $selected Preselected type
  860. * @param string $htmlname Name of field in form
  861. * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
  862. * @param string $showempty Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
  863. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  864. * @param int $forcecombo Force to use combo box
  865. * @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')))
  866. * @param int $limit Maximum number of elements
  867. * @param string $morecss Add more css styles to the SELECT component
  868. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  869. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  870. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  871. * @param array $ajaxoptions Options for ajax_autocompleter
  872. * @return string HTML string with select box for thirdparty.
  873. */
  874. 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())
  875. {
  876. global $conf,$user,$langs;
  877. $out='';
  878. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
  879. {
  880. $placeholder='';
  881. if ($selected && empty($selected_input_value))
  882. {
  883. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  884. $societetmp = new Societe($this->db);
  885. $societetmp->fetch($selected);
  886. $selected_input_value=$societetmp->name;
  887. unset($societetmp);
  888. }
  889. // mode 1
  890. $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter;
  891. $out.= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  892. $out.='<style type="text/css">
  893. .ui-autocomplete {
  894. z-index: 250;
  895. }
  896. </style>';
  897. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  898. else if ($hidelabel > 1) {
  899. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  900. else $placeholder=' title="'.$langs->trans("RefOrLabel").'"';
  901. if ($hidelabel == 2) {
  902. $out.= img_picto($langs->trans("Search"), 'search');
  903. }
  904. }
  905. $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  906. if ($hidelabel == 3) {
  907. $out.= img_picto($langs->trans("Search"), 'search');
  908. }
  909. }
  910. else
  911. {
  912. $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam);
  913. }
  914. return $out;
  915. }
  916. /**
  917. * Output html form to select a third party
  918. *
  919. * @param string $selected Preselected type
  920. * @param string $htmlname Name of field in form
  921. * @param string $filter optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
  922. * @param string $showempty Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
  923. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  924. * @param int $forcecombo Force to use combo box
  925. * @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')))
  926. * @param string $filterkey Filter on key value
  927. * @param int $outputmode 0=HTML select string, 1=Array
  928. * @param int $limit Limit number of answers
  929. * @param string $morecss Add more css styles to the SELECT component
  930. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  931. * @return string HTML string with
  932. */
  933. function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='')
  934. {
  935. global $conf,$user,$langs;
  936. $out='';
  937. $num=0;
  938. $outarray=array();
  939. // On recherche les societes
  940. $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
  941. $sql.= " FROM ".MAIN_DB_PREFIX ."societe as s";
  942. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  943. $sql.= " WHERE s.entity IN (".getEntity('societe', 1).")";
  944. if (! empty($user->societe_id)) $sql.= " AND s.rowid = ".$user->societe_id;
  945. if ($filter) $sql.= " AND (".$filter.")";
  946. if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
  947. if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
  948. // Add criteria
  949. if ($filterkey && $filterkey != '')
  950. {
  951. $sql.=" AND (";
  952. $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
  953. // For natural search
  954. $scrit = explode(' ', $filterkey);
  955. $i=0;
  956. if (count($scrit) > 1) $sql.="(";
  957. foreach ($scrit as $crit) {
  958. if ($i > 0) $sql.=" AND ";
  959. $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
  960. $i++;
  961. }
  962. if (count($scrit) > 1) $sql.=")";
  963. if (! empty($conf->barcode->enabled))
  964. {
  965. $sql .= " OR s.barcode LIKE '".$this->db->escape($filterkey)."%'";
  966. }
  967. $sql.=")";
  968. }
  969. $sql.=$this->db->order("nom","ASC");
  970. if ($limit > 0) $sql.=$this->db->plimit($limit);
  971. // Build output string
  972. dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
  973. $resql=$this->db->query($sql);
  974. if ($resql)
  975. {
  976. $events = null;
  977. if ($conf->use_javascript_ajax && ! $forcecombo)
  978. {
  979. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  980. $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
  981. $out.= $comboenhancement;
  982. }
  983. // Construct $out and $outarray
  984. $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.'">'."\n";
  985. $textifempty='';
  986. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  987. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  988. if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
  989. {
  990. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  991. else $textifempty.=$langs->trans("All");
  992. }
  993. if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
  994. $num = $this->db->num_rows($resql);
  995. $i = 0;
  996. if ($num)
  997. {
  998. while ($i < $num)
  999. {
  1000. $obj = $this->db->fetch_object($resql);
  1001. $label='';
  1002. if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
  1003. if (($obj->client) && (!empty($obj->code_client))) {
  1004. $label = $obj->code_client. ' - ';
  1005. }
  1006. if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
  1007. $label .= $obj->code_fournisseur. ' - ';
  1008. }
  1009. $label.=' '.$obj->name;
  1010. }
  1011. else
  1012. {
  1013. $label=$obj->name;
  1014. }
  1015. if(!empty($obj->name_alias)) {
  1016. $label.=' ('.$obj->name_alias.')';
  1017. }
  1018. if ($showtype)
  1019. {
  1020. if ($obj->client || $obj->fournisseur) $label.=' (';
  1021. if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
  1022. if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
  1023. if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
  1024. if ($obj->client || $obj->fournisseur) $label.=')';
  1025. }
  1026. if ($selected > 0 && $selected == $obj->rowid)
  1027. {
  1028. $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
  1029. }
  1030. else
  1031. {
  1032. $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
  1033. }
  1034. array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
  1035. $i++;
  1036. if (($i % 10) == 0) $out.="\n";
  1037. }
  1038. }
  1039. $out.= '</select>'."\n";
  1040. }
  1041. else
  1042. {
  1043. dol_print_error($this->db);
  1044. }
  1045. $this->result=array('nbofthirdparties'=>$num);
  1046. if ($outputmode) return $outarray;
  1047. return $out;
  1048. }
  1049. /**
  1050. * Return HTML combo list of absolute discounts
  1051. *
  1052. * @param string $selected Id remise fixe pre-selectionnee
  1053. * @param string $htmlname Nom champ formulaire
  1054. * @param string $filter Criteres optionnels de filtre
  1055. * @param int $socid Id of thirdparty
  1056. * @param int $maxvalue Max value for lines that can be selected
  1057. * @return int Return number of qualifed lines in list
  1058. */
  1059. function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
  1060. {
  1061. global $langs,$conf;
  1062. // On recherche les remises
  1063. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  1064. $sql.= " re.description, re.fk_facture_source";
  1065. $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
  1066. $sql.= " WHERE re.fk_soc = ".(int) $socid;
  1067. $sql.= " AND re.entity = " . $conf->entity;
  1068. if ($filter) $sql.= " AND ".$filter;
  1069. $sql.= " ORDER BY re.description ASC";
  1070. dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
  1071. $resql=$this->db->query($sql);
  1072. if ($resql)
  1073. {
  1074. print '<select class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
  1075. $num = $this->db->num_rows($resql);
  1076. $qualifiedlines=$num;
  1077. $i = 0;
  1078. if ($num)
  1079. {
  1080. print '<option value="0">&nbsp;</option>';
  1081. while ($i < $num)
  1082. {
  1083. $obj = $this->db->fetch_object($resql);
  1084. $desc=dol_trunc($obj->description,40);
  1085. if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
  1086. if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
  1087. if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
  1088. $selectstring='';
  1089. if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
  1090. $disabled='';
  1091. if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
  1092. {
  1093. $qualifiedlines--;
  1094. $disabled=' disabled';
  1095. }
  1096. print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
  1097. $i++;
  1098. }
  1099. }
  1100. print '</select>';
  1101. return $qualifiedlines;
  1102. }
  1103. else
  1104. {
  1105. dol_print_error($this->db);
  1106. return -1;
  1107. }
  1108. }
  1109. /**
  1110. * Return list of all contacts (for a third party or all)
  1111. *
  1112. * @param int $socid Id ot third party or 0 for all
  1113. * @param string $selected Id contact pre-selectionne
  1114. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1115. * @param int $showempty 0=no empty value, 1=add an empty value
  1116. * @param string $exclude List of contacts id to exclude
  1117. * @param string $limitto Disable answers that are not id in this array list
  1118. * @param integer $showfunction Add function into label
  1119. * @param string $moreclass Add more class to class style
  1120. * @param integer $showsoc Add company into label
  1121. * @param int $forcecombo Force to use combo box
  1122. * @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')))
  1123. * @param bool $options_only Return options only (for ajax treatment)
  1124. * @return int <0 if KO, Nb of contact in list if OK
  1125. */
  1126. function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false)
  1127. {
  1128. print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events);
  1129. return $this->num;
  1130. }
  1131. /**
  1132. * Return list of all contacts (for a third party or all)
  1133. *
  1134. * @param int $socid Id ot third party or 0 for all
  1135. * @param string $selected Id contact pre-selectionne
  1136. * @param string $htmlname Name of HTML field ('none' for a not editable field)
  1137. * @param int $showempty 0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit)
  1138. * @param string $exclude List of contacts id to exclude
  1139. * @param string $limitto Disable answers that are not id in this array list
  1140. * @param integer $showfunction Add function into label
  1141. * @param string $moreclass Add more class to class style
  1142. * @param bool $options_only Return options only (for ajax treatment)
  1143. * @param integer $showsoc Add company into label
  1144. * @param int $forcecombo Force to use combo box
  1145. * @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')))
  1146. * @return int <0 if KO, Nb of contact in list if OK
  1147. */
  1148. function selectcontacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array())
  1149. {
  1150. global $conf,$langs;
  1151. $langs->load('companies');
  1152. $out='';
  1153. // On recherche les societes
  1154. $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
  1155. if ($showsoc > 0) $sql.= " , s.nom as company";
  1156. $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
  1157. if ($showsoc > 0) $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
  1158. $sql.= " WHERE sp.entity IN (".getEntity('societe', 1).")";
  1159. if ($socid > 0) $sql.= " AND sp.fk_soc=".$socid;
  1160. if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
  1161. $sql.= " ORDER BY sp.lastname ASC";
  1162. dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
  1163. $resql=$this->db->query($sql);
  1164. if ($resql)
  1165. {
  1166. $num=$this->db->num_rows($resql);
  1167. if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
  1168. {
  1169. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1170. $comboenhancement = ajax_combobox($htmlname, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
  1171. $out.= $comboenhancement;
  1172. }
  1173. if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
  1174. if ($showempty == 1) $out.= '<option value="0"'.($selected=='0'?' selected':'').'></option>';
  1175. if ($showempty == 2) $out.= '<option value="0"'.($selected=='0'?' selected':'').'>'.$langs->trans("Internal").'</option>';
  1176. $num = $this->db->num_rows($resql);
  1177. $i = 0;
  1178. if ($num)
  1179. {
  1180. include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  1181. $contactstatic=new Contact($this->db);
  1182. while ($i < $num)
  1183. {
  1184. $obj = $this->db->fetch_object($resql);
  1185. $contactstatic->id=$obj->rowid;
  1186. $contactstatic->lastname=$obj->lastname;
  1187. $contactstatic->firstname=$obj->firstname;
  1188. if ($obj->statut == 1){
  1189. if ($htmlname != 'none')
  1190. {
  1191. $disabled=0;
  1192. if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
  1193. if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
  1194. if ($selected && $selected == $obj->rowid)
  1195. {
  1196. $out.= '<option value="'.$obj->rowid.'"';
  1197. if ($disabled) $out.= ' disabled';
  1198. $out.= ' selected>';
  1199. $out.= $contactstatic->getFullName($langs);
  1200. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1201. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1202. $out.= '</option>';
  1203. }
  1204. else
  1205. {
  1206. $out.= '<option value="'.$obj->rowid.'"';
  1207. if ($disabled) $out.= ' disabled';
  1208. $out.= '>';
  1209. $out.= $contactstatic->getFullName($langs);
  1210. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1211. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1212. $out.= '</option>';
  1213. }
  1214. }
  1215. else
  1216. {
  1217. if ($selected == $obj->rowid)
  1218. {
  1219. $out.= $contactstatic->getFullName($langs);
  1220. if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
  1221. if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
  1222. }
  1223. }
  1224. }
  1225. $i++;
  1226. }
  1227. }
  1228. else
  1229. {
  1230. $out.= '<option value="-1"'.($showempty==2?'':' selected').' disabled>'.$langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined").'</option>';
  1231. }
  1232. if ($htmlname != 'none' || $options_only)
  1233. {
  1234. $out.= '</select>';
  1235. }
  1236. $this->num = $num;
  1237. return $out;
  1238. }
  1239. else
  1240. {
  1241. dol_print_error($this->db);
  1242. return -1;
  1243. }
  1244. }
  1245. /**
  1246. * Return select list of users
  1247. *
  1248. * @param string $selected Id user preselected
  1249. * @param string $htmlname Field name in form
  1250. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1251. * @param array $exclude Array list of users id to exclude
  1252. * @param int $disabled If select list must be disabled
  1253. * @param array $include Array list of users id to include
  1254. * @param int $enableonly Array list of users id to be enabled. All other must be disabled
  1255. * @param int $force_entity 0 or Id of environment to force
  1256. * @return void
  1257. * @deprecated
  1258. * @see select_dolusers()
  1259. */
  1260. function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude='',$disabled=0,$include='',$enableonly='',$force_entity=0)
  1261. {
  1262. print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
  1263. }
  1264. /**
  1265. * Return select list of users
  1266. *
  1267. * @param string $selected User id or user object of user preselected. If -1, we use id of current user.
  1268. * @param string $htmlname Field name in form
  1269. * @param int $show_empty 0=list with no empty value, 1=add also an empty value into list
  1270. * @param array $exclude Array list of users id to exclude
  1271. * @param int $disabled If select list must be disabled
  1272. * @param array|string $include Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
  1273. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1274. * @param int $force_entity 0 or Id of environment to force
  1275. * @param int $maxlength Maximum length of string into list (0=no limit)
  1276. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1277. * @param string $morefilter Add more filters into sql request
  1278. * @param integer $show_every 0=default list, 1=add also a value "Everybody" at beginning of list
  1279. * @param string $enableonlytext If option $enableonly is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
  1280. * @param string $morecss More css
  1281. * @param int $noactive Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
  1282. * @return string HTML select string
  1283. * @see select_dolgroups
  1284. */
  1285. function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0)
  1286. {
  1287. global $conf,$user,$langs;
  1288. // If no preselected user defined, we take current user
  1289. if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
  1290. $excludeUsers=null;
  1291. $includeUsers=null;
  1292. // Permettre l'exclusion d'utilisateurs
  1293. if (is_array($exclude)) $excludeUsers = implode(",",$exclude);
  1294. // Permettre l'inclusion d'utilisateurs
  1295. if (is_array($include)) $includeUsers = implode(",",$include);
  1296. else if ($include == 'hierarchy')
  1297. {
  1298. // Build list includeUsers to have only hierarchy
  1299. $includeUsers = implode(",",$user->getAllChildIds(0));
  1300. }
  1301. else if ($include == 'hierarchyme')
  1302. {
  1303. // Build list includeUsers to have only hierarchy and current user
  1304. $includeUsers = implode(",",$user->getAllChildIds(1));
  1305. }
  1306. $out='';
  1307. // On recherche les utilisateurs
  1308. $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
  1309. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1310. {
  1311. $sql.= ", e.label";
  1312. }
  1313. $sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
  1314. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1315. {
  1316. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
  1317. if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
  1318. else $sql.= " WHERE u.entity IS NOT NULL";
  1319. }
  1320. else
  1321. {
  1322. if (! empty($conf->multicompany->transverse_mode))
  1323. {
  1324. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
  1325. $sql.= " ON ug.fk_user = u.rowid";
  1326. $sql.= " WHERE ug.entity = ".$conf->entity;
  1327. }
  1328. else
  1329. {
  1330. $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
  1331. }
  1332. }
  1333. if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
  1334. if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
  1335. if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
  1336. if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
  1337. if (! empty($morefilter)) $sql.=" ".$morefilter;
  1338. if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){
  1339. $sql.= " ORDER BY u.firstname ASC";
  1340. }else{
  1341. $sql.= " ORDER BY u.lastname ASC";
  1342. }
  1343. dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
  1344. $resql=$this->db->query($sql);
  1345. if ($resql)
  1346. {
  1347. $num = $this->db->num_rows($resql);
  1348. $i = 0;
  1349. if ($num)
  1350. {
  1351. // Enhance with select2
  1352. if ($conf->use_javascript_ajax)
  1353. {
  1354. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1355. $comboenhancement = ajax_combobox($htmlname);
  1356. $out.=$comboenhancement;
  1357. }
  1358. // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
  1359. $out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').'>';
  1360. if ($show_empty) $out.= '<option value="-1"'.((empty($selected) || $selected==-1)?' selected':'').'>&nbsp;</option>'."\n";
  1361. if ($show_every) $out.= '<option value="-2"'.(($selected==-2)?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
  1362. $userstatic=new User($this->db);
  1363. while ($i < $num)
  1364. {
  1365. $obj = $this->db->fetch_object($resql);
  1366. $userstatic->id=$obj->rowid;
  1367. $userstatic->lastname=$obj->lastname;
  1368. $userstatic->firstname=$obj->firstname;
  1369. $disableline='';
  1370. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
  1371. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  1372. {
  1373. $out.= '<option value="'.$obj->rowid.'"';
  1374. if ($disableline) $out.= ' disabled';
  1375. $out.= ' selected>';
  1376. }
  1377. else
  1378. {
  1379. $out.= '<option value="'.$obj->rowid.'"';
  1380. if ($disableline) $out.= ' disabled';
  1381. $out.= '>';
  1382. }
  1383. $fullNameMode = 0; //Lastname + firstname
  1384. if(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)){
  1385. $fullNameMode = 1; //firstname + lastname
  1386. }
  1387. $out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
  1388. // Complete name with more info
  1389. $moreinfo=0;
  1390. if (! empty($conf->global->MAIN_SHOW_LOGIN))
  1391. {
  1392. $out.= ($moreinfo?' - ':' (').$obj->login;
  1393. $moreinfo++;
  1394. }
  1395. if ($showstatus >= 0)
  1396. {
  1397. if ($obj->statut == 1 && $showstatus == 1)
  1398. {
  1399. $out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
  1400. $moreinfo++;
  1401. }
  1402. if ($obj->statut == 0)
  1403. {
  1404. $out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
  1405. $moreinfo++;
  1406. }
  1407. }
  1408. if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode) && $conf->entity == 1 && $user->admin && ! $user->entity)
  1409. {
  1410. if ($obj->admin && ! $obj->entity)
  1411. {
  1412. $out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
  1413. $moreinfo++;
  1414. }
  1415. else
  1416. {
  1417. $out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
  1418. $moreinfo++;
  1419. }
  1420. }
  1421. $out.=($moreinfo?')':'');
  1422. if ($disableline && $disableline != '1')
  1423. {
  1424. $out.=' - '.$disableline; // This is text from $enableonlytext parameter
  1425. }
  1426. $out.= '</option>';
  1427. $i++;
  1428. }
  1429. }
  1430. else
  1431. {
  1432. $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
  1433. $out.= '<option value="">'.$langs->trans("None").'</option>';
  1434. }
  1435. $out.= '</select>';
  1436. }
  1437. else
  1438. {
  1439. dol_print_error($this->db);
  1440. }
  1441. return $out;
  1442. }
  1443. /**
  1444. * Return select list of users. Selected users are stored into session.
  1445. * List of users are provided into $_SESSION['assignedtouser'].
  1446. *
  1447. * @param string $action Value for $action
  1448. * @param string $htmlname Field name in form
  1449. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  1450. * @param array $exclude Array list of users id to exclude
  1451. * @param int $disabled If select list must be disabled
  1452. * @param array $include Array list of users id to include or 'hierarchy' to have only supervised users
  1453. * @param array $enableonly Array list of users id to be enabled. All other must be disabled
  1454. * @param int $force_entity 0 or Id of environment to force
  1455. * @param int $maxlength Maximum length of string into list (0=no limit)
  1456. * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
  1457. * @param string $morefilter Add more filters into sql request
  1458. * @return string HTML select string
  1459. * @see select_dolgroups
  1460. */
  1461. function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0, $maxlength=0, $showstatus=0, $morefilter='')
  1462. {
  1463. global $conf,$user,$langs;
  1464. $userstatic=new User($this->db);
  1465. $out='';
  1466. // Method with no ajax
  1467. //$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
  1468. if ($action == 'view')
  1469. {
  1470. $out.='';
  1471. }
  1472. else
  1473. {
  1474. $out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
  1475. $out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () { jQuery(".removedassigned").click(function() { jQuery(".removedassignedhidden").val(jQuery(this).val()); });})</script>';
  1476. $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
  1477. $out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
  1478. }
  1479. $assignedtouser=array();
  1480. if (!empty($_SESSION['assignedtouser']))
  1481. {
  1482. $assignedtouser=json_decode($_SESSION['assignedtouser'], true);
  1483. }
  1484. $nbassignetouser=count($assignedtouser);
  1485. if ($nbassignetouser && $action != 'view') $out.='<br>';
  1486. if ($nbassignetouser) $out.='<div class="myavailability">';
  1487. $i=0; $ownerid=0;
  1488. foreach($assignedtouser as $key => $value)
  1489. {
  1490. if ($value['id'] == $ownerid) continue;
  1491. $userstatic->fetch($value['id']);
  1492. $out.=$userstatic->getNomUrl(-1);
  1493. if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
  1494. if ($nbassignetouser > 1 && $action != 'view') $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.'">';
  1495. //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
  1496. //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
  1497. $out.='<br>';
  1498. $i++;
  1499. }
  1500. if ($nbassignetouser) $out.='</div>';
  1501. //$out.='</form>';
  1502. return $out;
  1503. }
  1504. /**
  1505. * Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
  1506. *
  1507. * @param int $selected Preselected products
  1508. * @param string $htmlname Name of HTML select field (must be unique in page)
  1509. * @param int $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1510. * @param int $limit Limit on number of returned lines
  1511. * @param int $price_level Level of price to show
  1512. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1513. * @param int $finished 2=all, 1=finished, 0=raw material
  1514. * @param string $selected_input_value Value of preselected input text (for use with ajax)
  1515. * @param int $hidelabel Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
  1516. * @param array $ajaxoptions Options for ajax_autocompleter
  1517. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1518. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1519. * @param int $forcecombo Force to use combo box
  1520. * @param string $morecss Add more css on select
  1521. * @param int $hidepriceinlabel 1=Hide prices in label
  1522. * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used
  1523. * 'warehouseopen' = select products from open warehouses,
  1524. * 'warehouseclosed' = select products from closed warehouses,
  1525. * 'warehouseinternal' = select products from warehouses for internal correct/transfer only
  1526. * @param array $selected_combinations Selected combinations. Format: array([attrid] => attrval, [...])
  1527. * @return void
  1528. */
  1529. 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())
  1530. {
  1531. global $langs,$conf;
  1532. $price_level = (! empty($price_level) ? $price_level : 0);
  1533. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1534. {
  1535. $placeholder='';
  1536. if ($selected && empty($selected_input_value))
  1537. {
  1538. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1539. $producttmpselect = new Product($this->db);
  1540. $producttmpselect->fetch($selected);
  1541. $selected_input_value=$producttmpselect->ref;
  1542. unset($producttmpselect);
  1543. }
  1544. // mode=1 means customers products
  1545. $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&warehousestatus='.$warehouseStatus;
  1546. //Price by customer
  1547. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1548. $urloption.='&socid='.$socid;
  1549. }
  1550. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  1551. if (!empty($conf->variants->enabled)) {
  1552. ?>
  1553. <script>
  1554. selected = <?php echo json_encode($selected_combinations) ?>;
  1555. combvalues = {};
  1556. jQuery(document).ready(function () {
  1557. jQuery("input[name='prod_entry_mode']").change(function () {
  1558. if (jQuery(this).val() == 'free') {
  1559. jQuery('div#attributes_box').empty();
  1560. }
  1561. });
  1562. jQuery("input#<?php echo $htmlname ?>").change(function () {
  1563. if (!jQuery(this).val()) {
  1564. jQuery('div#attributes_box').empty();
  1565. return;
  1566. }
  1567. jQuery.getJSON("<?php echo dol_buildpath('/variants/ajax/getCombinations.php', 2) ?>", {
  1568. id: jQuery(this).val()
  1569. }, function (data) {
  1570. jQuery('div#attributes_box').empty();
  1571. jQuery.each(data, function (key, val) {
  1572. combvalues[val.id] = val.values;
  1573. var span = jQuery(document.createElement('div')).css({
  1574. 'display': 'table-row'
  1575. });
  1576. span.append(
  1577. jQuery(document.createElement('div')).text(val.label).css({
  1578. 'font-weight': 'bold',
  1579. 'display': 'table-cell',
  1580. 'text-align': 'right'
  1581. })
  1582. );
  1583. var html = jQuery(document.createElement('select')).attr('name', 'combinations[' + val.id + ']').css({
  1584. 'margin-left': '15px',
  1585. 'white-space': 'pre'
  1586. }).append(
  1587. jQuery(document.createElement('option')).val('')
  1588. );
  1589. jQuery.each(combvalues[val.id], function (key, val) {
  1590. var tag = jQuery(document.createElement('option')).val(val.id).html(val.value);
  1591. if (selected[val.fk_product_attribute] == val.id) {
  1592. tag.attr('selected', 'selected');
  1593. }
  1594. html.append(tag);
  1595. });
  1596. span.append(html);
  1597. jQuery('div#attributes_box').append(span);
  1598. });
  1599. })
  1600. });
  1601. <?php if ($selected): ?>
  1602. jQuery("input#<?php echo $htmlname ?>").change();
  1603. <?php endif ?>
  1604. });
  1605. </script>
  1606. <?php
  1607. }
  1608. if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
  1609. else if ($hidelabel > 1) {
  1610. if (! empty($conf->global->MAIN_HTML5_PLACEHOLDER)) $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
  1611. else $placeholder=' title="'.$langs->trans("RefOrLabel").'"';
  1612. if ($hidelabel == 2) {
  1613. print img_picto($langs->trans("Search"), 'search');
  1614. }
  1615. }
  1616. print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
  1617. if ($hidelabel == 3) {
  1618. print img_picto($langs->trans("Search"), 'search');
  1619. }
  1620. }
  1621. else
  1622. {
  1623. print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
  1624. }
  1625. }
  1626. /**
  1627. * Return list of products for a customer
  1628. *
  1629. * @param int $selected Preselected product
  1630. * @param string $htmlname Name of select html
  1631. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  1632. * @param int $limit Limit on number of returned lines
  1633. * @param int $price_level Level of price to show
  1634. * @param string $filterkey Filter on product
  1635. * @param int $status -1=Return all products, 0=Products not on sell, 1=Products on sell
  1636. * @param int $finished Filter on finished field: 2=No filter
  1637. * @param int $outputmode 0=HTML select string, 1=Array
  1638. * @param int $socid Thirdparty Id (to get also price dedicated to this customer)
  1639. * @param string $showempty '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
  1640. * @param int $forcecombo Force to use combo box
  1641. * @param string $morecss Add more css on select
  1642. * @param int $hidepriceinlabel 1=Hide prices in label
  1643. * @param string $warehouseStatus warehouse status filter, following comma separated filter options can be used
  1644. * 'warehouseopen' = select products from open warehouses,
  1645. * 'warehouseclosed' = select products from closed warehouses,
  1646. * 'warehouseinternal' = select products from warehouses for internal correct/transfer only
  1647. * @return array Array of keys for json
  1648. */
  1649. 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='')
  1650. {
  1651. global $langs,$conf,$user,$db;
  1652. $out='';
  1653. $outarray=array();
  1654. $warehouseStatusArray = array();
  1655. if (! empty($warehouseStatus))
  1656. {
  1657. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  1658. if (preg_match('/warehouseclosed/', $warehouseStatus))
  1659. {
  1660. $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
  1661. }
  1662. if (preg_match('/warehouseopen/', $warehouseStatus))
  1663. {
  1664. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
  1665. }
  1666. if (preg_match('/warehouseinternal/', $warehouseStatus))
  1667. {
  1668. $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
  1669. }
  1670. }
  1671. $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression";
  1672. (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
  1673. $sql = "SELECT ";
  1674. $sql.= $selectFields . $selectFieldsGrouped;
  1675. //Price by customer
  1676. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1677. $sql.=' ,pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
  1678. $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
  1679. $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
  1680. }
  1681. // Multilang : we add translation
  1682. if (! empty($conf->global->MAIN_MULTILANGS))
  1683. {
  1684. $sql.= ", pl.label as label_translated";
  1685. $selectFields.= ", label_translated";
  1686. }
  1687. // Price by quantity
  1688. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
  1689. {
  1690. $sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1691. if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1692. $sql.= " ORDER BY date_price";
  1693. $sql.= " DESC LIMIT 1) as price_rowid";
  1694. $sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
  1695. if ($price_level >= 1 && !empty($conf->global->PRODUIT_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
  1696. $sql.= " ORDER BY date_price";
  1697. $sql.= " DESC LIMIT 1) as price_by_qty";
  1698. $selectFields.= ", price_rowid, price_by_qty";
  1699. }
  1700. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  1701. if (count($warehouseStatusArray))
  1702. {
  1703. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
  1704. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
  1705. }
  1706. //Price by customer
  1707. if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
  1708. $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
  1709. }
  1710. // Multilang : we add translation
  1711. if (! empty($conf->global->MAIN_MULTILANGS))
  1712. {
  1713. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
  1714. }
  1715. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1716. $sql .= " LEFT JOIN llx_product_attribute_combination pac ON pac.fk_product_child = p.rowid";
  1717. }
  1718. $sql.= ' WHERE p.entity IN ('.getEntity('product', 1).')';
  1719. if (count($warehouseStatusArray))
  1720. {
  1721. $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.implode(',',$warehouseStatusArray).'))';
  1722. }
  1723. if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
  1724. $sql .= " AND pac.rowid IS NULL";
  1725. }
  1726. if ($finished == 0)
  1727. {
  1728. $sql.= " AND p.finished = ".$finished;
  1729. }
  1730. elseif ($finished == 1)
  1731. {
  1732. $sql.= " AND p.finished = ".$finished;
  1733. if ($status >= 0) $sql.= " AND p.tosell = ".$status;
  1734. }
  1735. elseif ($status >= 0)
  1736. {
  1737. $sql.= " AND p.tosell = ".$status;
  1738. }
  1739. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
  1740. // Add criteria on ref/label
  1741. if ($filterkey != '')
  1742. {
  1743. $sql.=' AND (';
  1744. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  1745. // For natural search
  1746. $scrit = explode(' ', $filterkey);
  1747. $i=0;
  1748. if (count($scrit) > 1) $sql.="(";
  1749. foreach ($scrit as $crit)
  1750. {
  1751. if ($i > 0) $sql.=" AND ";
  1752. $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
  1753. if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
  1754. $sql.=")";
  1755. $i++;
  1756. }
  1757. if (count($scrit) > 1) $sql.=")";
  1758. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
  1759. $sql.=')';
  1760. }
  1761. if (count($warehouseStatusArray))
  1762. {
  1763. $sql.= ' GROUP BY'.$selectFields;
  1764. }
  1765. $sql.= $db->order("p.ref");
  1766. $sql.= $db->plimit($limit);
  1767. // Build output string
  1768. dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
  1769. $result=$this->db->query($sql);
  1770. if ($result)
  1771. {
  1772. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1773. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1774. $num = $this->db->num_rows($result);
  1775. $events=null;
  1776. if ($conf->use_javascript_ajax && ! $forcecombo)
  1777. {
  1778. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  1779. $comboenhancement =ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
  1780. $out.= $comboenhancement;
  1781. }
  1782. $out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
  1783. $textifempty='';
  1784. // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
  1785. //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
  1786. if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  1787. {
  1788. if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
  1789. else $textifempty.=$langs->trans("All");
  1790. }
  1791. if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
  1792. $i = 0;
  1793. while ($num && $i < $num)
  1794. {
  1795. $opt = '';
  1796. $optJson = array();
  1797. $objp = $this->db->fetch_object($result);
  1798. if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
  1799. { // Price by quantity will return many prices for the same product
  1800. $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise";
  1801. $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
  1802. $sql.= " WHERE fk_product_price=".$objp->price_rowid;
  1803. $sql.= " ORDER BY quantity ASC";
  1804. dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
  1805. $result2 = $this->db->query($sql);
  1806. if ($result2)
  1807. {
  1808. $nb_prices = $this->db->num_rows($result2);
  1809. $j = 0;
  1810. while ($nb_prices && $j < $nb_prices) {
  1811. $objp2 = $this->db->fetch_object($result2);
  1812. $objp->quantity = $objp2->quantity;
  1813. $objp->price = $objp2->price;
  1814. $objp->unitprice = $objp2->unitprice;
  1815. $objp->remise_percent = $objp2->remise_percent;
  1816. $objp->remise = $objp2->remise;
  1817. $objp->price_by_qty_rowid = $objp2->rowid;
  1818. $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);
  1819. $j++;
  1820. // Add new entry
  1821. // "key" value of json key array is used by jQuery automatically as selected value
  1822. // "label" value of json key array is used by jQuery automatically as text for combo box
  1823. $out.=$opt;
  1824. array_push($outarray, $optJson);
  1825. }
  1826. }
  1827. }
  1828. else
  1829. {
  1830. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
  1831. $price_product = new Product($this->db);
  1832. $price_product->fetch($objp->rowid, '', '', 1);
  1833. $priceparser = new PriceParser($this->db);
  1834. $price_result = $priceparser->parseProduct($price_product);
  1835. if ($price_result >= 0) {
  1836. $objp->price = $price_result;
  1837. $objp->unitprice = $price_result;
  1838. //Calculate the VAT
  1839. $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
  1840. $objp->price_ttc = price2num($objp->price_ttc,'MU');
  1841. }
  1842. }
  1843. $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
  1844. // Add new entry
  1845. // "key" value of json key array is used by jQuery automatically as selected value
  1846. // "label" value of json key array is used by jQuery automatically as text for combo box
  1847. $out.=$opt;
  1848. array_push($outarray, $optJson);
  1849. }
  1850. $i++;
  1851. }
  1852. $out.='</select>';
  1853. $this->db->free($result);
  1854. if (empty($outputmode)) return $out;
  1855. return $outarray;
  1856. }
  1857. else
  1858. {
  1859. dol_print_error($db);
  1860. }
  1861. }
  1862. /**
  1863. * constructProductListOption
  1864. *
  1865. * @param resultset $objp Resultset of fetch
  1866. * @param string $opt Option (var used for returned value in string option format)
  1867. * @param string $optJson Option (var used for returned value in json format)
  1868. * @param int $price_level Price level
  1869. * @param string $selected Preselected value
  1870. * @param int $hidepriceinlabel Hide price in label
  1871. * @return void
  1872. */
  1873. private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
  1874. {
  1875. global $langs,$conf,$user,$db;
  1876. $outkey='';
  1877. $outval='';
  1878. $outref='';
  1879. $outlabel='';
  1880. $outdesc='';
  1881. $outbarcode='';
  1882. $outtype='';
  1883. $outprice_ht='';
  1884. $outprice_ttc='';
  1885. $outpricebasetype='';
  1886. $outtva_tx='';
  1887. $outqty=1;
  1888. $outdiscount=0;
  1889. $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
  1890. $label=$objp->label;
  1891. if (! empty($objp->label_translated)) $label=$objp->label_translated;
  1892. if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  1893. $outkey=$objp->rowid;
  1894. $outref=$objp->ref;
  1895. $outlabel=$objp->label;
  1896. $outdesc=$objp->description;
  1897. $outbarcode=$objp->barcode;
  1898. $outtype=$objp->fk_product_type;
  1899. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  1900. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  1901. $opt = '<option value="'.$objp->rowid.'"';
  1902. $opt.= ($objp->rowid == $selected)?' selected':'';
  1903. $opt.= (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)?' pbq="'.$objp->price_by_qty_rowid.'"':'';
  1904. if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
  1905. {
  1906. if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
  1907. else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
  1908. }
  1909. $opt.= '>';
  1910. $opt.= $objp->ref;
  1911. if ($outbarcode) $opt.=' ('.$outbarcode.')';
  1912. $opt.=' - '.dol_trunc($label,$maxlengtharticle);
  1913. $objRef = $objp->ref;
  1914. if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  1915. $outval.=$objRef;
  1916. if ($outbarcode) $outval.=' ('.$outbarcode.')';
  1917. $outval.=' - '.dol_trunc($label,$maxlengtharticle);
  1918. $found=0;
  1919. // Multiprice
  1920. if (empty($hidepriceinlabel) && $price_level >= 1 && $conf->global->PRODUIT_MULTIPRICES) // If we need a particular price level (from 1 to 6)
  1921. {
  1922. $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
  1923. $sql.= " FROM ".MAIN_DB_PREFIX."product_price";
  1924. $sql.= " WHERE fk_product='".$objp->rowid."'";
  1925. $sql.= " AND entity IN (".getEntity('productprice', 1).")";
  1926. $sql.= " AND price_level=".$price_level;
  1927. $sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
  1928. $sql.= " LIMIT 1";
  1929. dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
  1930. $result2 = $this->db->query($sql);
  1931. if ($result2)
  1932. {
  1933. $objp2 = $this->db->fetch_object($result2);
  1934. if ($objp2)
  1935. {
  1936. $found=1;
  1937. if ($objp2->price_base_type == 'HT')
  1938. {
  1939. $opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  1940. $outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  1941. }
  1942. else
  1943. {
  1944. $opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  1945. $outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  1946. }
  1947. $outprice_ht=price($objp2->price);
  1948. $outprice_ttc=price($objp2->price_ttc);
  1949. $outpricebasetype=$objp2->price_base_type;
  1950. $outtva_tx=$objp2->tva_tx;
  1951. }
  1952. }
  1953. else
  1954. {
  1955. dol_print_error($this->db);
  1956. }
  1957. }
  1958. // Price by quantity
  1959. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
  1960. {
  1961. $found = 1;
  1962. $outqty=$objp->quantity;
  1963. $outdiscount=$objp->remise_percent;
  1964. if ($objp->quantity == 1)
  1965. {
  1966. $opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
  1967. $outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
  1968. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  1969. $outval.=$langs->transnoentities("Unit");
  1970. }
  1971. else
  1972. {
  1973. $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  1974. $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  1975. $opt.= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  1976. $outval.=$langs->transnoentities("Units");
  1977. }
  1978. $outprice_ht=price($objp->unitprice);
  1979. $outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
  1980. $outpricebasetype=$objp->price_base_type;
  1981. $outtva_tx=$objp->tva_tx;
  1982. }
  1983. if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
  1984. {
  1985. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  1986. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  1987. }
  1988. if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
  1989. {
  1990. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  1991. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  1992. }
  1993. // Price by customer
  1994. if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
  1995. {
  1996. if (!empty($objp->idprodcustprice))
  1997. {
  1998. $found = 1;
  1999. if ($objp->custprice_base_type == 'HT')
  2000. {
  2001. $opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  2002. $outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  2003. }
  2004. else
  2005. {
  2006. $opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  2007. $outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  2008. }
  2009. $outprice_ht=price($objp->custprice);
  2010. $outprice_ttc=price($objp->custprice_ttc);
  2011. $outpricebasetype=$objp->custprice_base_type;
  2012. $outtva_tx=$objp->custtva_tx;
  2013. }
  2014. }
  2015. // If level no defined or multiprice not found, we used the default price
  2016. if (empty($hidepriceinlabel) && ! $found)
  2017. {
  2018. if ($objp->price_base_type == 'HT')
  2019. {
  2020. $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
  2021. $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
  2022. }
  2023. else
  2024. {
  2025. $opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
  2026. $outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
  2027. }
  2028. $outprice_ht=price($objp->price);
  2029. $outprice_ttc=price($objp->price_ttc);
  2030. $outpricebasetype=$objp->price_base_type;
  2031. $outtva_tx=$objp->tva_tx;
  2032. }
  2033. if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
  2034. {
  2035. $opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
  2036. if ($objp->stock > 0) {
  2037. $outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
  2038. }elseif ($objp->stock <= 0) {
  2039. $outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
  2040. }
  2041. }
  2042. if ($outdurationvalue && $outdurationunit)
  2043. {
  2044. $da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
  2045. if (isset($da[$outdurationunit]))
  2046. {
  2047. $key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
  2048. $opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
  2049. $outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
  2050. }
  2051. }
  2052. $opt.= "</option>\n";
  2053. $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
  2054. }
  2055. /**
  2056. * Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
  2057. *
  2058. * @param int $socid Id third party
  2059. * @param string $selected Preselected product
  2060. * @param string $htmlname Name of HTML Select
  2061. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2062. * @param string $filtre For a SQL filter
  2063. * @param array $ajaxoptions Options for ajax_autocompleter
  2064. * @param int $hidelabel Hide label (0=no, 1=yes)
  2065. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2066. * @return void
  2067. */
  2068. function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)
  2069. {
  2070. global $langs,$conf;
  2071. global $price_level, $status, $finished;
  2072. $selected_input_value='';
  2073. if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
  2074. {
  2075. if ($selected > 0)
  2076. {
  2077. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2078. $producttmpselect = new Product($this->db);
  2079. $producttmpselect->fetch($selected);
  2080. $selected_input_value=$producttmpselect->ref;
  2081. unset($producttmpselect);
  2082. }
  2083. if (!empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
  2084. {
  2085. print '<input type="hidden" id="idprod" name="idprod" value="0" />';
  2086. }
  2087. // mode=2 means suppliers products
  2088. $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
  2089. print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
  2090. print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
  2091. }
  2092. else
  2093. {
  2094. if (!empty($conf->global->SUPPLIER_ORDER_WITH_NOPRICEDEFINED))
  2095. {
  2096. print '<input type="hidden" id="idprod" name="idprod" value="0" />';
  2097. print '<script type="text/javascript">$("#'.$htmlname.'").change(function() { $("#idprod").val($(this).val());});</script>';
  2098. }
  2099. print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
  2100. }
  2101. }
  2102. /**
  2103. * Return list of suppliers products
  2104. *
  2105. * @param int $socid Id societe fournisseur (0 pour aucun filtre)
  2106. * @param int $selected Produit pre-selectionne
  2107. * @param string $htmlname Nom de la zone select
  2108. * @param string $filtertype Filter on product type (''=nofilter, 0=product, 1=service)
  2109. * @param string $filtre Pour filtre sql
  2110. * @param string $filterkey Filtre des produits
  2111. * @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)
  2112. * @param int $outputmode 0=HTML select string, 1=Array
  2113. * @param int $limit Limit of line number
  2114. * @param int $alsoproductwithnosupplierprice 1=Add also product without supplier prices
  2115. * @return array Array of keys for json
  2116. */
  2117. function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)
  2118. {
  2119. global $langs,$conf,$db;
  2120. $out='';
  2121. $outarray=array();
  2122. $langs->load('stocks');
  2123. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
  2124. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
  2125. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
  2126. $sql.= " pfp.supplier_reputation";
  2127. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  2128. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2129. if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
  2130. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2131. $sql.= " WHERE p.entity IN (".getEntity('product', 1).")";
  2132. $sql.= " AND p.tobuy = 1";
  2133. if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
  2134. if (! empty($filtre)) $sql.=" ".$filtre;
  2135. // Add criteria on ref/label
  2136. if ($filterkey != '')
  2137. {
  2138. $sql.=' AND (';
  2139. $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
  2140. // For natural search
  2141. $scrit = explode(' ', $filterkey);
  2142. $i=0;
  2143. if (count($scrit) > 1) $sql.="(";
  2144. foreach ($scrit as $crit)
  2145. {
  2146. if ($i > 0) $sql.=" AND ";
  2147. $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)."%')";
  2148. $i++;
  2149. }
  2150. if (count($scrit) > 1) $sql.=")";
  2151. if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
  2152. $sql.=')';
  2153. }
  2154. $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
  2155. $sql.= $db->plimit($limit);
  2156. // Build output string
  2157. dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
  2158. $result=$this->db->query($sql);
  2159. if ($result)
  2160. {
  2161. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2162. $num = $this->db->num_rows($result);
  2163. //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">'; // remove select to have id same with combo and ajax
  2164. $out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
  2165. if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
  2166. else $out.='<option value="0">&nbsp;</option>';
  2167. $i = 0;
  2168. while ($i < $num)
  2169. {
  2170. $objp = $this->db->fetch_object($result);
  2171. $outkey=$objp->idprodfournprice; // id in table of price
  2172. if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid; // id of product
  2173. $outref=$objp->ref;
  2174. $outval='';
  2175. $outqty=1;
  2176. $outdiscount=0;
  2177. $outtype=$objp->fk_product_type;
  2178. $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
  2179. $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
  2180. $opt = '<option value="'.$outkey.'"';
  2181. if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
  2182. if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
  2183. $opt.= '>';
  2184. $objRef = $objp->ref;
  2185. if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
  2186. $objRefFourn = $objp->ref_fourn;
  2187. if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
  2188. $label = $objp->label;
  2189. if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
  2190. $opt.=$objp->ref;
  2191. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  2192. $opt.=' ('.$objp->ref_fourn.')';
  2193. $opt.=' - ';
  2194. $outval.=$objRef;
  2195. if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
  2196. $outval.=' ('.$objRefFourn.')';
  2197. $outval.=' - ';
  2198. $opt.=dol_trunc($label, 72).' - ';
  2199. $outval.=dol_trunc($label, 72).' - ';
  2200. if (! empty($objp->idprodfournprice))
  2201. {
  2202. $outqty=$objp->quantity;
  2203. $outdiscount=$objp->remise_percent;
  2204. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2205. $prod_supplier = new ProductFournisseur($this->db);
  2206. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2207. $prod_supplier->id = $objp->fk_product;
  2208. $prod_supplier->fourn_qty = $objp->quantity;
  2209. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2210. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2211. $priceparser = new PriceParser($this->db);
  2212. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2213. if ($price_result >= 0) {
  2214. $objp->fprice = $price_result;
  2215. if ($objp->quantity >= 1)
  2216. {
  2217. $objp->unitprice = $objp->fprice / $objp->quantity;
  2218. }
  2219. }
  2220. }
  2221. if ($objp->quantity == 1)
  2222. {
  2223. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2224. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
  2225. $opt.= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
  2226. $outval.=$langs->transnoentities("Unit");
  2227. }
  2228. else
  2229. {
  2230. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2231. $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
  2232. $opt.= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
  2233. $outval.= ' '.$langs->transnoentities("Units");
  2234. }
  2235. if ($objp->quantity >= 1)
  2236. {
  2237. $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2238. $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
  2239. }
  2240. if ($objp->remise_percent >= 1)
  2241. {
  2242. $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
  2243. $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
  2244. }
  2245. if ($objp->duration)
  2246. {
  2247. $opt .= " - ".$objp->duration;
  2248. $outval.=" - ".$objp->duration;
  2249. }
  2250. if (! $socid)
  2251. {
  2252. $opt .= " - ".dol_trunc($objp->name,8);
  2253. $outval.=" - ".dol_trunc($objp->name,8);
  2254. }
  2255. if ($objp->supplier_reputation)
  2256. {
  2257. //TODO dictionary
  2258. $reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  2259. $opt .= " - ".$reputations[$objp->supplier_reputation];
  2260. $outval.=" - ".$reputations[$objp->supplier_reputation];
  2261. }
  2262. }
  2263. else
  2264. {
  2265. if (empty($alsoproductwithnosupplierprice)) // No supplier price defined for couple product/supplier
  2266. {
  2267. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  2268. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2269. }
  2270. else // No supplier price defined for product, even on other suppliers
  2271. {
  2272. $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
  2273. $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
  2274. }
  2275. }
  2276. $opt .= "</option>\n";
  2277. // Add new entry
  2278. // "key" value of json key array is used by jQuery automatically as selected value
  2279. // "label" value of json key array is used by jQuery automatically as text for combo box
  2280. $out.=$opt;
  2281. array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
  2282. // Exemple of var_dump $outarray
  2283. // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
  2284. // ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
  2285. // ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
  2286. //}
  2287. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2288. //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
  2289. //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
  2290. $i++;
  2291. }
  2292. $out.='</select>';
  2293. $this->db->free($result);
  2294. if (empty($outputmode)) return $out;
  2295. return $outarray;
  2296. }
  2297. else
  2298. {
  2299. dol_print_error($this->db);
  2300. }
  2301. }
  2302. /**
  2303. * Return list of suppliers prices for a product
  2304. *
  2305. * @param int $productid Id of product
  2306. * @param string $htmlname Name of HTML field
  2307. * @param int $selected_supplier Pre-selected supplier if more than 1 result
  2308. * @return void
  2309. */
  2310. function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
  2311. {
  2312. global $langs,$conf;
  2313. $langs->load('stocks');
  2314. $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
  2315. $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
  2316. $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
  2317. $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
  2318. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
  2319. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
  2320. $sql.= " WHERE p.entity IN (".getEntity('productprice', 1).")";
  2321. $sql.= " AND p.tobuy = 1";
  2322. $sql.= " AND s.fournisseur = 1";
  2323. $sql.= " AND p.rowid = ".$productid;
  2324. $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
  2325. dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
  2326. $result=$this->db->query($sql);
  2327. if ($result)
  2328. {
  2329. $num = $this->db->num_rows($result);
  2330. $form = '<select class="flat" name="'.$htmlname.'">';
  2331. if (! $num)
  2332. {
  2333. $form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
  2334. }
  2335. else
  2336. {
  2337. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2338. $form.= '<option value="0">&nbsp;</option>';
  2339. $i = 0;
  2340. while ($i < $num)
  2341. {
  2342. $objp = $this->db->fetch_object($result);
  2343. $opt = '<option value="'.$objp->idprodfournprice.'"';
  2344. //if there is only one supplier, preselect it
  2345. if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
  2346. $opt .= ' selected';
  2347. }
  2348. $opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
  2349. if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
  2350. $prod_supplier = new ProductFournisseur($this->db);
  2351. $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
  2352. $prod_supplier->id = $productid;
  2353. $prod_supplier->fourn_qty = $objp->quantity;
  2354. $prod_supplier->fourn_tva_tx = $objp->tva_tx;
  2355. $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
  2356. $priceparser = new PriceParser($this->db);
  2357. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  2358. if ($price_result >= 0) {
  2359. $objp->fprice = $price_result;
  2360. if ($objp->quantity >= 1)
  2361. {
  2362. $objp->unitprice = $objp->fprice / $objp->quantity;
  2363. }
  2364. }
  2365. }
  2366. if ($objp->quantity == 1)
  2367. {
  2368. $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
  2369. }
  2370. $opt.= $objp->quantity.' ';
  2371. if ($objp->quantity == 1)
  2372. {
  2373. $opt.= $langs->trans("Unit");
  2374. }
  2375. else
  2376. {
  2377. $opt.= $langs->trans("Units");
  2378. }
  2379. if ($objp->quantity > 1)
  2380. {
  2381. $opt.=" - ";
  2382. $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
  2383. }
  2384. if ($objp->duration) $opt .= " - ".$objp->duration;
  2385. $opt .= "</option>\n";
  2386. $form.= $opt;
  2387. $i++;
  2388. }
  2389. }
  2390. $form.= '</select>';
  2391. $this->db->free($result);
  2392. return $form;
  2393. }
  2394. else
  2395. {
  2396. dol_print_error($this->db);
  2397. }
  2398. }
  2399. /**
  2400. * Return list of delivery address
  2401. *
  2402. * @param string $selected Id contact pre-selectionn
  2403. * @param int $socid Id of company
  2404. * @param string $htmlname Name of HTML field
  2405. * @param int $showempty Add an empty field
  2406. * @return integer|null
  2407. */
  2408. function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
  2409. {
  2410. // On recherche les utilisateurs
  2411. $sql = "SELECT a.rowid, a.label";
  2412. $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
  2413. $sql .= " WHERE a.fk_soc = ".$socid;
  2414. $sql .= " ORDER BY a.label ASC";
  2415. dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
  2416. $resql=$this->db->query($sql);
  2417. if ($resql)
  2418. {
  2419. print '<select class="flat" name="'.$htmlname.'">';
  2420. if ($showempty) print '<option value="0">&nbsp;</option>';
  2421. $num = $this->db->num_rows($resql);
  2422. $i = 0;
  2423. if ($num)
  2424. {
  2425. while ($i < $num)
  2426. {
  2427. $obj = $this->db->fetch_object($resql);
  2428. if ($selected && $selected == $obj->rowid)
  2429. {
  2430. print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
  2431. }
  2432. else
  2433. {
  2434. print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
  2435. }
  2436. $i++;
  2437. }
  2438. }
  2439. print '</select>';
  2440. return $num;
  2441. }
  2442. else
  2443. {
  2444. dol_print_error($this->db);
  2445. }
  2446. }
  2447. /**
  2448. * Load into cache list of payment terms
  2449. *
  2450. * @return int Nb of lines loaded, <0 if KO
  2451. */
  2452. function load_cache_conditions_paiements()
  2453. {
  2454. global $langs;
  2455. $num = count($this->cache_conditions_paiements);
  2456. if ($num > 0) return 0; // Cache already loaded
  2457. dol_syslog(__METHOD__, LOG_DEBUG);
  2458. $sql = "SELECT rowid, code, libelle as label";
  2459. $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
  2460. $sql.= " WHERE active > 0";
  2461. $sql.= " ORDER BY sortorder";
  2462. $resql = $this->db->query($sql);
  2463. if ($resql)
  2464. {
  2465. $num = $this->db->num_rows($resql);
  2466. $i = 0;
  2467. while ($i < $num)
  2468. {
  2469. $obj = $this->db->fetch_object($resql);
  2470. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2471. $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2472. $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
  2473. $this->cache_conditions_paiements[$obj->rowid]['label']=$label;
  2474. $i++;
  2475. }
  2476. //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1); // We use the field sortorder of table
  2477. return $num;
  2478. }
  2479. else
  2480. {
  2481. dol_print_error($this->db);
  2482. return -1;
  2483. }
  2484. }
  2485. /**
  2486. * Charge dans cache la liste des délais de livraison possibles
  2487. *
  2488. * @return int Nb of lines loaded, <0 if KO
  2489. */
  2490. function load_cache_availability()
  2491. {
  2492. global $langs;
  2493. $num = count($this->cache_availability);
  2494. if ($num > 0) return 0; // Cache already loaded
  2495. dol_syslog(__METHOD__, LOG_DEBUG);
  2496. $langs->load('propal');
  2497. $sql = "SELECT rowid, code, label";
  2498. $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
  2499. $sql.= " WHERE active > 0";
  2500. $resql = $this->db->query($sql);
  2501. if ($resql)
  2502. {
  2503. $num = $this->db->num_rows($resql);
  2504. $i = 0;
  2505. while ($i < $num)
  2506. {
  2507. $obj = $this->db->fetch_object($resql);
  2508. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2509. $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
  2510. $this->cache_availability[$obj->rowid]['code'] =$obj->code;
  2511. $this->cache_availability[$obj->rowid]['label']=$label;
  2512. $i++;
  2513. }
  2514. $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
  2515. return $num;
  2516. }
  2517. else
  2518. {
  2519. dol_print_error($this->db);
  2520. return -1;
  2521. }
  2522. }
  2523. /**
  2524. * Retourne la liste des types de delais de livraison possibles
  2525. *
  2526. * @param int $selected Id du type de delais pre-selectionne
  2527. * @param string $htmlname Nom de la zone select
  2528. * @param string $filtertype To add a filter
  2529. * @param int $addempty Add empty entry
  2530. * @return void
  2531. */
  2532. function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
  2533. {
  2534. global $langs,$user;
  2535. $this->load_cache_availability();
  2536. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2537. print '<select class="flat" name="'.$htmlname.'">';
  2538. if ($addempty) print '<option value="0">&nbsp;</option>';
  2539. foreach($this->cache_availability as $id => $arrayavailability)
  2540. {
  2541. if ($selected == $id)
  2542. {
  2543. print '<option value="'.$id.'" selected>';
  2544. }
  2545. else
  2546. {
  2547. print '<option value="'.$id.'">';
  2548. }
  2549. print $arrayavailability['label'];
  2550. print '</option>';
  2551. }
  2552. print '</select>';
  2553. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2554. }
  2555. /**
  2556. * Load into cache cache_demand_reason, array of input reasons
  2557. *
  2558. * @return int Nb of lines loaded, <0 if KO
  2559. */
  2560. function loadCacheInputReason()
  2561. {
  2562. global $langs;
  2563. $num = count($this->cache_demand_reason);
  2564. if ($num > 0) return 0; // Cache already loaded
  2565. $sql = "SELECT rowid, code, label";
  2566. $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
  2567. $sql.= " WHERE active > 0";
  2568. $resql = $this->db->query($sql);
  2569. if ($resql)
  2570. {
  2571. $num = $this->db->num_rows($resql);
  2572. $i = 0;
  2573. $tmparray=array();
  2574. while ($i < $num)
  2575. {
  2576. $obj = $this->db->fetch_object($resql);
  2577. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2578. $label=($langs->trans("DemandReasonType".$obj->code)!=("DemandReasonType".$obj->code)?$langs->trans("DemandReasonType".$obj->code):($obj->label!='-'?$obj->label:''));
  2579. $tmparray[$obj->rowid]['id'] =$obj->rowid;
  2580. $tmparray[$obj->rowid]['code'] =$obj->code;
  2581. $tmparray[$obj->rowid]['label']=$label;
  2582. $i++;
  2583. }
  2584. $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
  2585. unset($tmparray);
  2586. return $num;
  2587. }
  2588. else
  2589. {
  2590. dol_print_error($this->db);
  2591. return -1;
  2592. }
  2593. }
  2594. /**
  2595. * Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  2596. * List found into table c_input_reason loaded by loadCacheInputReason
  2597. *
  2598. * @param int $selected Id or code of type origin to select by default
  2599. * @param string $htmlname Nom de la zone select
  2600. * @param string $exclude To exclude a code value (Example: SRC_PROP)
  2601. * @param int $addempty Add an empty entry
  2602. * @return void
  2603. */
  2604. function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
  2605. {
  2606. global $langs,$user;
  2607. $this->loadCacheInputReason();
  2608. print '<select class="flat" name="'.$htmlname.'">';
  2609. if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
  2610. foreach($this->cache_demand_reason as $id => $arraydemandreason)
  2611. {
  2612. if ($arraydemandreason['code']==$exclude) continue;
  2613. if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
  2614. {
  2615. print '<option value="'.$arraydemandreason['id'].'" selected>';
  2616. }
  2617. else
  2618. {
  2619. print '<option value="'.$arraydemandreason['id'].'">';
  2620. }
  2621. print $arraydemandreason['label'];
  2622. print '</option>';
  2623. }
  2624. print '</select>';
  2625. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2626. }
  2627. /**
  2628. * Charge dans cache la liste des types de paiements possibles
  2629. *
  2630. * @return int Nb of lines loaded, <0 if KO
  2631. */
  2632. function load_cache_types_paiements()
  2633. {
  2634. global $langs;
  2635. $num=count($this->cache_types_paiements);
  2636. if ($num > 0) return $num; // Cache already loaded
  2637. dol_syslog(__METHOD__, LOG_DEBUG);
  2638. $this->cache_types_paiements = array();
  2639. $sql = "SELECT id, code, libelle as label, type, active";
  2640. $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
  2641. //if ($active >= 0) $sql.= " WHERE active = ".$active;
  2642. $resql = $this->db->query($sql);
  2643. if ($resql)
  2644. {
  2645. $num = $this->db->num_rows($resql);
  2646. $i = 0;
  2647. while ($i < $num)
  2648. {
  2649. $obj = $this->db->fetch_object($resql);
  2650. // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
  2651. $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
  2652. $this->cache_types_paiements[$obj->id]['id'] =$obj->id;
  2653. $this->cache_types_paiements[$obj->id]['code'] =$obj->code;
  2654. $this->cache_types_paiements[$obj->id]['label']=$label;
  2655. $this->cache_types_paiements[$obj->id]['type'] =$obj->type;
  2656. $this->cache_types_paiements[$obj->id]['active'] =$obj->active;
  2657. $i++;
  2658. }
  2659. $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
  2660. return $num;
  2661. }
  2662. else
  2663. {
  2664. dol_print_error($this->db);
  2665. return -1;
  2666. }
  2667. }
  2668. /**
  2669. * Return list of payment modes.
  2670. * Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
  2671. * See instead to force the default value by the caller.
  2672. *
  2673. * @param int $selected Id of payment term to preselect by default
  2674. * @param string $htmlname Nom de la zone select
  2675. * @param int $filtertype Not used
  2676. * @param int $addempty Add an empty entry
  2677. * @return void
  2678. */
  2679. function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0)
  2680. {
  2681. global $langs, $user, $conf;
  2682. dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
  2683. $this->load_cache_conditions_paiements();
  2684. // Set default value if not already set by caller
  2685. if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
  2686. print '<select class="flat" name="'.$htmlname.'">';
  2687. if ($addempty) print '<option value="0">&nbsp;</option>';
  2688. foreach($this->cache_conditions_paiements as $id => $arrayconditions)
  2689. {
  2690. if ($selected == $id)
  2691. {
  2692. print '<option value="'.$id.'" selected>';
  2693. }
  2694. else
  2695. {
  2696. print '<option value="'.$id.'">';
  2697. }
  2698. print $arrayconditions['label'];
  2699. print '</option>';
  2700. }
  2701. print '</select>';
  2702. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2703. }
  2704. /**
  2705. * Return list of payment methods
  2706. *
  2707. * @param string $selected Id du mode de paiement pre-selectionne
  2708. * @param string $htmlname Nom de la zone select
  2709. * @param string $filtertype To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
  2710. * @param int $format 0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
  2711. * @param int $empty 1=peut etre vide, 0 sinon
  2712. * @param int $noadmininfo 0=Add admin info, 1=Disable admin info
  2713. * @param int $maxlength Max length of label
  2714. * @param int $active Active or not, -1 = all
  2715. * @param string $morecss Add more css
  2716. * @return void
  2717. */
  2718. function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=0, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
  2719. {
  2720. global $langs,$user;
  2721. dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
  2722. $filterarray=array();
  2723. if ($filtertype == 'CRDT') $filterarray=array(0,2,3);
  2724. elseif ($filtertype == 'DBIT') $filterarray=array(1,2,3);
  2725. elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
  2726. $this->load_cache_types_paiements();
  2727. print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
  2728. if ($empty) print '<option value="">&nbsp;</option>';
  2729. foreach($this->cache_types_paiements as $id => $arraytypes)
  2730. {
  2731. // If not good status
  2732. if ($active >= 0 && $arraytypes['active'] != $active) continue;
  2733. // On passe si on a demande de filtrer sur des modes de paiments particuliers
  2734. if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
  2735. // We discard empty line if showempty is on because an empty line has already been output.
  2736. if ($empty && empty($arraytypes['code'])) continue;
  2737. if ($format == 0) print '<option value="'.$id.'"';
  2738. if ($format == 1) print '<option value="'.$arraytypes['code'].'"';
  2739. if ($format == 2) print '<option value="'.$arraytypes['code'].'"';
  2740. if ($format == 3) print '<option value="'.$id.'"';
  2741. // Si selected est text, on compare avec code, sinon avec id
  2742. if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
  2743. elseif ($selected == $id) print ' selected';
  2744. print '>';
  2745. if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2746. if ($format == 1) $value=$arraytypes['code'];
  2747. if ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
  2748. if ($format == 3) $value=$arraytypes['code'];
  2749. print $value?$value:'&nbsp;';
  2750. print '</option>';
  2751. }
  2752. print '</select>';
  2753. if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2754. }
  2755. /**
  2756. * Selection HT or TTC
  2757. *
  2758. * @param string $selected Id pre-selectionne
  2759. * @param string $htmlname Nom de la zone select
  2760. * @return string Code of HTML select to chose tax or not
  2761. */
  2762. function selectPriceBaseType($selected='',$htmlname='price_base_type')
  2763. {
  2764. global $langs;
  2765. $return='';
  2766. $return.= '<select class="flat" name="'.$htmlname.'">';
  2767. $options = array(
  2768. 'HT'=>$langs->trans("HT"),
  2769. 'TTC'=>$langs->trans("TTC")
  2770. );
  2771. foreach($options as $id => $value)
  2772. {
  2773. if ($selected == $id)
  2774. {
  2775. $return.= '<option value="'.$id.'" selected>'.$value;
  2776. }
  2777. else
  2778. {
  2779. $return.= '<option value="'.$id.'">'.$value;
  2780. }
  2781. $return.= '</option>';
  2782. }
  2783. $return.= '</select>';
  2784. return $return;
  2785. }
  2786. /**
  2787. * Return a HTML select list of shipping mode
  2788. *
  2789. * @param string $selected Id shipping mode pre-selected
  2790. * @param string $htmlname Name of select zone
  2791. * @param string $filtre To filter list
  2792. * @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.
  2793. * @param string $moreattrib To add more attribute on select
  2794. * @return void
  2795. */
  2796. function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
  2797. {
  2798. global $langs, $conf, $user;
  2799. $langs->load("admin");
  2800. $langs->load("deliveries");
  2801. $sql = "SELECT rowid, code, libelle as label";
  2802. $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
  2803. $sql.= " WHERE active > 0";
  2804. if ($filtre) $sql.=" AND ".$filtre;
  2805. $sql.= " ORDER BY libelle ASC";
  2806. dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
  2807. $result = $this->db->query($sql);
  2808. if ($result) {
  2809. $num = $this->db->num_rows($result);
  2810. $i = 0;
  2811. if ($num) {
  2812. print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  2813. if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
  2814. print '<option value="-1">&nbsp;</option>';
  2815. }
  2816. while ($i < $num) {
  2817. $obj = $this->db->fetch_object($result);
  2818. if ($selected == $obj->rowid) {
  2819. print '<option value="'.$obj->rowid.'" selected>';
  2820. } else {
  2821. print '<option value="'.$obj->rowid.'">';
  2822. }
  2823. print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
  2824. print '</option>';
  2825. $i++;
  2826. }
  2827. print "</select>";
  2828. if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  2829. } else {
  2830. print $langs->trans("NoShippingMethodDefined");
  2831. }
  2832. } else {
  2833. dol_print_error($this->db);
  2834. }
  2835. }
  2836. /**
  2837. * Display form to select shipping mode
  2838. *
  2839. * @param string $page Page
  2840. * @param int $selected Id of shipping mode
  2841. * @param string $htmlname Name of select html field
  2842. * @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.
  2843. * @return void
  2844. */
  2845. function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
  2846. {
  2847. global $langs, $db;
  2848. $langs->load("deliveries");
  2849. if ($htmlname != "none") {
  2850. print '<form method="POST" action="'.$page.'">';
  2851. print '<input type="hidden" name="action" value="setshippingmethod">';
  2852. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  2853. $this->selectShippingMethod($selected, $htmlname, '', $addempty);
  2854. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  2855. print '</form>';
  2856. } else {
  2857. if ($selected) {
  2858. $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
  2859. print $langs->trans("SendingMethod".strtoupper($code));
  2860. } else {
  2861. print "&nbsp;";
  2862. }
  2863. }
  2864. }
  2865. /**
  2866. * Creates HTML last in cycle situation invoices selector
  2867. *
  2868. * @param string $selected Preselected ID
  2869. * @param int $socid Company ID
  2870. *
  2871. * @return string HTML select
  2872. */
  2873. function selectSituationInvoices($selected = '', $socid = 0)
  2874. {
  2875. global $langs;
  2876. $langs->load('bills');
  2877. $opt = '<option value ="" selected></option>';
  2878. $sql = 'SELECT rowid, facnumber, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
  2879. $sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
  2880. $resql = $this->db->query($sql);
  2881. if ($resql && $this->db->num_rows($resql) > 0) {
  2882. // Last seen cycle
  2883. $ref = 0;
  2884. while ($res = $this->db->fetch_array($resql, MYSQL_NUM)) {
  2885. //Same company ?
  2886. if ($socid == $res[5]) {
  2887. //Same cycle ?
  2888. if ($res[2] != $ref) {
  2889. // Just seen this cycle
  2890. $ref = $res[2];
  2891. //not final ?
  2892. if ($res[4] != 1) {
  2893. //Not prov?
  2894. if (substr($res[1], 1, 4) != 'PROV') {
  2895. if ($selected == $res[0]) {
  2896. $opt .= '<option value="' . $res[0] . '" selected>' . $res[1] . '</option>';
  2897. } else {
  2898. $opt .= '<option value="' . $res[0] . '">' . $res[1] . '</option>';
  2899. }
  2900. }
  2901. }
  2902. }
  2903. }
  2904. }
  2905. }
  2906. else
  2907. {
  2908. dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
  2909. }
  2910. if ($opt == '<option value ="" selected></option>')
  2911. {
  2912. $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
  2913. }
  2914. return $opt;
  2915. }
  2916. /**
  2917. * Creates HTML units selector (code => label)
  2918. *
  2919. * @param string $selected Preselected Unit ID
  2920. * @param string $htmlname Select name
  2921. * @param int $showempty Add a nempty line
  2922. * @return string HTML select
  2923. */
  2924. function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
  2925. {
  2926. global $langs;
  2927. $langs->load('products');
  2928. $return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
  2929. $sql = 'SELECT rowid, label from '.MAIN_DB_PREFIX.'c_units';
  2930. $sql.= ' WHERE active > 0';
  2931. $resql = $this->db->query($sql);
  2932. if($resql && $this->db->num_rows($resql) > 0)
  2933. {
  2934. if ($showempty) $return .= '<option value="none"></option>';
  2935. while($res = $this->db->fetch_object($resql))
  2936. {
  2937. if ($selected == $res->rowid)
  2938. {
  2939. $return.='<option value="'.$res->rowid.'" selected>'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';
  2940. }
  2941. else
  2942. {
  2943. $return.='<option value="'.$res->rowid.'">'.($langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label).'</option>';
  2944. }
  2945. }
  2946. $return.='</select>';
  2947. }
  2948. return $return;
  2949. }
  2950. /**
  2951. * Return a HTML select list of bank accounts
  2952. *
  2953. * @param string $selected Id account pre-selected
  2954. * @param string $htmlname Name of select zone
  2955. * @param int $statut Status of searched accounts (0=open, 1=closed, 2=both)
  2956. * @param string $filtre To filter list
  2957. * @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.
  2958. * @param string $moreattrib To add more attribute on select
  2959. * @return void
  2960. */
  2961. function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='')
  2962. {
  2963. global $langs, $conf;
  2964. $langs->load("admin");
  2965. $sql = "SELECT rowid, label, bank, clos as status";
  2966. $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
  2967. $sql.= " WHERE entity IN (".getEntity('bank_account', 1).")";
  2968. if ($statut != 2) $sql.= " AND clos = '".$statut."'";
  2969. if ($filtre) $sql.=" AND ".$filtre;
  2970. $sql.= " ORDER BY label";
  2971. dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
  2972. $result = $this->db->query($sql);
  2973. if ($result)
  2974. {
  2975. $num = $this->db->num_rows($result);
  2976. $i = 0;
  2977. if ($num)
  2978. {
  2979. print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
  2980. if ($useempty == 1 || ($useempty == 2 && $num > 1))
  2981. {
  2982. print '<option value="-1">&nbsp;</option>';
  2983. }
  2984. while ($i < $num)
  2985. {
  2986. $obj = $this->db->fetch_object($result);
  2987. if ($selected == $obj->rowid)
  2988. {
  2989. print '<option value="'.$obj->rowid.'" selected>';
  2990. }
  2991. else
  2992. {
  2993. print '<option value="'.$obj->rowid.'">';
  2994. }
  2995. print trim($obj->label);
  2996. if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
  2997. print '</option>';
  2998. $i++;
  2999. }
  3000. print "</select>";
  3001. }
  3002. else
  3003. {
  3004. print $langs->trans("NoActiveBankAccountDefined");
  3005. }
  3006. }
  3007. else {
  3008. dol_print_error($this->db);
  3009. }
  3010. }
  3011. /**
  3012. * Display form to select bank account
  3013. *
  3014. * @param string $page Page
  3015. * @param int $selected Id of bank account
  3016. * @param string $htmlname Name of select html field
  3017. * @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.
  3018. * @return void
  3019. */
  3020. function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
  3021. {
  3022. global $langs;
  3023. if ($htmlname != "none") {
  3024. print '<form method="POST" action="'.$page.'">';
  3025. print '<input type="hidden" name="action" value="setbankaccount">';
  3026. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3027. $this->select_comptes($selected, $htmlname, 0, '', $addempty);
  3028. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3029. print '</form>';
  3030. } else {
  3031. $langs->load('banks');
  3032. if ($selected) {
  3033. require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
  3034. $bankstatic=new Account($this->db);
  3035. $bankstatic->fetch($selected);
  3036. print $this->textwithpicto($bankstatic->getNomUrl(1),$langs->trans("AccountCurrency").'&nbsp;'.$bankstatic->currency_code);
  3037. } else {
  3038. print "&nbsp;";
  3039. }
  3040. }
  3041. }
  3042. /**
  3043. * Return list of categories having choosed type
  3044. *
  3045. * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
  3046. * @param string $selected Id of category preselected or 'auto' (autoselect category if there is only one element)
  3047. * @param string $htmlname HTML field name
  3048. * @param int $maxlength Maximum length for labels
  3049. * @param int $excludeafterid Exclude all categories after this leaf in category tree.
  3050. * @param int $outputmode 0=HTML select string, 1=Array
  3051. * @return string
  3052. * @see select_categories
  3053. */
  3054. function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
  3055. {
  3056. global $conf, $langs;
  3057. $langs->load("categories");
  3058. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  3059. // For backward compatibility
  3060. if (is_numeric($type))
  3061. {
  3062. dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
  3063. }
  3064. if ($type === Categorie::TYPE_BANK_LINE)
  3065. {
  3066. // TODO Move this into common category feature
  3067. $categids=array();
  3068. $sql = "SELECT c.label, c.rowid";
  3069. $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
  3070. $sql.= " WHERE entity = ".$conf->entity;
  3071. $sql.= " ORDER BY c.label";
  3072. $result = $this->db->query($sql);
  3073. if ($result)
  3074. {
  3075. $num = $this->db->num_rows($result);
  3076. $i = 0;
  3077. while ($i < $num)
  3078. {
  3079. $objp = $this->db->fetch_object($result);
  3080. if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
  3081. $i++;
  3082. }
  3083. $this->db->free($result);
  3084. }
  3085. else dol_print_error($this->db);
  3086. }
  3087. else
  3088. {
  3089. $cat = new Categorie($this->db);
  3090. $cate_arbo = $cat->get_full_arbo($type,$excludeafterid);
  3091. }
  3092. $output = '<select class="flat" name="'.$htmlname.'">';
  3093. $outarray=array();
  3094. if (is_array($cate_arbo))
  3095. {
  3096. if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
  3097. else
  3098. {
  3099. $output.= '<option value="-1">&nbsp;</option>';
  3100. foreach($cate_arbo as $key => $value)
  3101. {
  3102. if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
  3103. {
  3104. $add = 'selected ';
  3105. }
  3106. else
  3107. {
  3108. $add = '';
  3109. }
  3110. $output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
  3111. $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
  3112. }
  3113. }
  3114. }
  3115. $output.= '</select>';
  3116. $output.= "\n";
  3117. if ($outputmode) return $outarray;
  3118. return $output;
  3119. }
  3120. /**
  3121. * Show a confirmation HTML form or AJAX popup
  3122. *
  3123. * @param string $page Url of page to call if confirmation is OK
  3124. * @param string $title Title
  3125. * @param string $question Question
  3126. * @param string $action Action
  3127. * @param array $formquestion An array with forms complementary inputs
  3128. * @param string $selectedchoice "" or "no" or "yes"
  3129. * @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
  3130. * @param int $height Force height of box
  3131. * @param int $width Force width of box
  3132. * @return void
  3133. * @deprecated
  3134. * @see formconfirm()
  3135. */
  3136. function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
  3137. {
  3138. print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
  3139. }
  3140. /**
  3141. * Show a confirmation HTML form or AJAX popup.
  3142. * Easiest way to use this is with useajax=1.
  3143. * If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
  3144. * just after calling this method. For example:
  3145. * print '<script type="text/javascript">'."\n";
  3146. * print 'jQuery(document).ready(function() {'."\n";
  3147. * print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
  3148. * print '});'."\n";
  3149. * print '</script>'."\n";
  3150. *
  3151. * @param string $page Url of page to call if confirmation is OK
  3152. * @param string $title Title
  3153. * @param string $question Question
  3154. * @param string $action Action
  3155. * @param array $formquestion An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
  3156. * @param string $selectedchoice "" or "no" or "yes"
  3157. * @param int $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
  3158. * @param int $height Force height of box
  3159. * @param int $width Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
  3160. * @return string HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
  3161. */
  3162. function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=200, $width=500)
  3163. {
  3164. global $langs,$conf;
  3165. global $useglobalvars;
  3166. $more='';
  3167. $formconfirm='';
  3168. $inputok=array();
  3169. $inputko=array();
  3170. // Clean parameters
  3171. $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
  3172. if ($conf->browser->layout == 'phone') $width='95%';
  3173. if (is_array($formquestion) && ! empty($formquestion))
  3174. {
  3175. // First add hidden fields and value
  3176. foreach ($formquestion as $key => $input)
  3177. {
  3178. if (is_array($input) && ! empty($input))
  3179. {
  3180. if ($input['type'] == 'hidden')
  3181. {
  3182. $more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
  3183. }
  3184. }
  3185. }
  3186. // Now add questions
  3187. $more.='<table class="paddingtopbottomonly" width="100%">'."\n";
  3188. $more.='<tr><td colspan="3">'.(! empty($formquestion['text'])?$formquestion['text']:'').'</td></tr>'."\n";
  3189. foreach ($formquestion as $key => $input)
  3190. {
  3191. if (is_array($input) && ! empty($input))
  3192. {
  3193. $size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
  3194. if ($input['type'] == 'text')
  3195. {
  3196. $more.='<tr><td>'.$input['label'].'</td><td colspan="2" align="left"><input type="text" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'" /></td></tr>'."\n";
  3197. }
  3198. else if ($input['type'] == 'password')
  3199. {
  3200. $more.='<tr><td>'.$input['label'].'</td><td colspan="2" align="left"><input type="password" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'" /></td></tr>'."\n";
  3201. }
  3202. else if ($input['type'] == 'select')
  3203. {
  3204. $more.='<tr><td>';
  3205. if (! empty($input['label'])) $more.=$input['label'].'</td><td valign="top" colspan="2" align="left">';
  3206. $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1);
  3207. $more.='</td></tr>'."\n";
  3208. }
  3209. else if ($input['type'] == 'checkbox')
  3210. {
  3211. $more.='<tr>';
  3212. $more.='<td>'.$input['label'].' </td><td align="left">';
  3213. $more.='<input type="checkbox" class="flat" id="'.$input['name'].'" name="'.$input['name'].'"';
  3214. if (! is_bool($input['value']) && $input['value'] != 'false') $more.=' checked';
  3215. if (is_bool($input['value']) && $input['value']) $more.=' checked';
  3216. if (isset($input['disabled'])) $more.=' disabled';
  3217. $more.=' /></td>';
  3218. $more.='<td align="left">&nbsp;</td>';
  3219. $more.='</tr>'."\n";
  3220. }
  3221. else if ($input['type'] == 'radio')
  3222. {
  3223. $i=0;
  3224. foreach($input['values'] as $selkey => $selval)
  3225. {
  3226. $more.='<tr>';
  3227. if ($i==0) $more.='<td class="tdtop">'.$input['label'].'</td>';
  3228. else $more.='<td>&nbsp;</td>';
  3229. $more.='<td width="20"><input type="radio" class="flat" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"';
  3230. if ($input['disabled']) $more.=' disabled';
  3231. $more.=' /></td>';
  3232. $more.='<td align="left">';
  3233. $more.=$selval;
  3234. $more.='</td></tr>'."\n";
  3235. $i++;
  3236. }
  3237. }
  3238. else if ($input['type'] == 'date')
  3239. {
  3240. $more.='<tr><td>'.$input['label'].'</td>';
  3241. $more.='<td colspan="2" align="left">';
  3242. $more.=$this->select_date($input['value'],$input['name'],0,0,0,'',1,0,1);
  3243. $more.='</td></tr>'."\n";
  3244. $formquestion[] = array('name'=>$input['name'].'day');
  3245. $formquestion[] = array('name'=>$input['name'].'month');
  3246. $formquestion[] = array('name'=>$input['name'].'year');
  3247. $formquestion[] = array('name'=>$input['name'].'hour');
  3248. $formquestion[] = array('name'=>$input['name'].'min');
  3249. }
  3250. else if ($input['type'] == 'other')
  3251. {
  3252. $more.='<tr><td>';
  3253. if (! empty($input['label'])) $more.=$input['label'].'</td><td colspan="2" align="left">';
  3254. $more.=$input['value'];
  3255. $more.='</td></tr>'."\n";
  3256. }
  3257. }
  3258. }
  3259. $more.='</table>'."\n";
  3260. }
  3261. // JQUI method dialog is broken with jmobile, we use standard HTML.
  3262. // 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
  3263. // See page product/card.php for example
  3264. if (! empty($conf->dol_use_jmobile)) $useajax=0;
  3265. if (empty($conf->use_javascript_ajax)) $useajax=0;
  3266. if ($useajax)
  3267. {
  3268. $autoOpen=true;
  3269. $dialogconfirm='dialog-confirm';
  3270. $button='';
  3271. if (! is_numeric($useajax))
  3272. {
  3273. $button=$useajax;
  3274. $useajax=1;
  3275. $autoOpen=false;
  3276. $dialogconfirm.='-'.$button;
  3277. }
  3278. $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
  3279. $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
  3280. // Add input fields into list of fields to read during submit (inputok and inputko)
  3281. if (is_array($formquestion))
  3282. {
  3283. foreach ($formquestion as $key => $input)
  3284. {
  3285. //print "xx ".$key." rr ".is_array($input)."<br>\n";
  3286. if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
  3287. if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
  3288. }
  3289. }
  3290. // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
  3291. $formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
  3292. if (! empty($more)) {
  3293. $formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
  3294. }
  3295. $formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
  3296. $formconfirm.= '</div>'."\n";
  3297. $formconfirm.= "\n<!-- begin ajax form_confirm page=".$page." -->\n";
  3298. $formconfirm.= '<script type="text/javascript">'."\n";
  3299. $formconfirm.= 'jQuery(document).ready(function() {
  3300. $(function() {
  3301. $( "#'.$dialogconfirm.'" ).dialog(
  3302. {
  3303. autoOpen: '.($autoOpen ? "true" : "false").',';
  3304. if ($newselectedchoice == 'no')
  3305. {
  3306. $formconfirm.='
  3307. open: function() {
  3308. $(this).parent().find("button.ui-button:eq(2)").focus();
  3309. },';
  3310. }
  3311. $formconfirm.='
  3312. resizable: false,
  3313. height: "'.$height.'",
  3314. width: "'.$width.'",
  3315. modal: true,
  3316. closeOnEscape: false,
  3317. buttons: {
  3318. "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
  3319. var options="";
  3320. var inputok = '.json_encode($inputok).';
  3321. var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
  3322. if (inputok.length>0) {
  3323. $.each(inputok, function(i, inputname) {
  3324. var more = "";
  3325. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3326. if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
  3327. var inputvalue = $("#" + inputname + more).val();
  3328. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3329. options += "&" + inputname + "=" + inputvalue;
  3330. });
  3331. }
  3332. var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
  3333. //alert(urljump);
  3334. if (pageyes.length > 0) { location.href = urljump; }
  3335. $(this).dialog("close");
  3336. },
  3337. "'.dol_escape_js($langs->transnoentities("No")).'": function() {
  3338. var options = "";
  3339. var inputko = '.json_encode($inputko).';
  3340. var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
  3341. if (inputko.length>0) {
  3342. $.each(inputko, function(i, inputname) {
  3343. var more = "";
  3344. if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
  3345. var inputvalue = $("#" + inputname + more).val();
  3346. if (typeof inputvalue == "undefined") { inputvalue=""; }
  3347. options += "&" + inputname + "=" + inputvalue;
  3348. });
  3349. }
  3350. var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
  3351. //alert(urljump);
  3352. if (pageno.length > 0) { location.href = urljump; }
  3353. $(this).dialog("close");
  3354. }
  3355. }
  3356. }
  3357. );
  3358. var button = "'.$button.'";
  3359. if (button.length > 0) {
  3360. $( "#" + button ).click(function() {
  3361. $("#'.$dialogconfirm.'").dialog("open");
  3362. });
  3363. }
  3364. });
  3365. });
  3366. </script>';
  3367. $formconfirm.= "<!-- end ajax form_confirm -->\n";
  3368. }
  3369. else
  3370. {
  3371. $formconfirm.= "\n<!-- begin form_confirm page=".$page." -->\n";
  3372. $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
  3373. $formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
  3374. $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
  3375. $formconfirm.= '<table width="100%" class="valid">'."\n";
  3376. // Line title
  3377. $formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
  3378. // Line form fields
  3379. if ($more)
  3380. {
  3381. $formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
  3382. $formconfirm.=$more;
  3383. $formconfirm.='</td></tr>'."\n";
  3384. }
  3385. // Line with question
  3386. $formconfirm.= '<tr class="valid">';
  3387. $formconfirm.= '<td class="valid">'.$question.'</td>';
  3388. $formconfirm.= '<td class="valid">';
  3389. $formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
  3390. $formconfirm.= '</td>';
  3391. $formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
  3392. $formconfirm.= '</tr>'."\n";
  3393. $formconfirm.= '</table>'."\n";
  3394. $formconfirm.= "</form>\n";
  3395. $formconfirm.= '<br>';
  3396. $formconfirm.= "<!-- end form_confirm -->\n";
  3397. }
  3398. return $formconfirm;
  3399. }
  3400. /**
  3401. * Show a form to select a project
  3402. *
  3403. * @param int $page Page
  3404. * @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)
  3405. * @param int $selected Id pre-selected project
  3406. * @param string $htmlname Name of select field
  3407. * @param int $discard_closed Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
  3408. * @param int $maxlength Max length
  3409. * @param int $forcefocus Force focus on field (works with javascript only)
  3410. * @param int $nooutput No print is done. String is returned.
  3411. * @return string Return html content
  3412. */
  3413. function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
  3414. {
  3415. global $langs;
  3416. require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
  3417. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  3418. $out='';
  3419. $formproject=new FormProjets($this->db);
  3420. $langs->load("project");
  3421. if ($htmlname != "none")
  3422. {
  3423. $out.="\n";
  3424. $out.='<form method="post" action="'.$page.'">';
  3425. $out.='<input type="hidden" name="action" value="classin">';
  3426. $out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3427. $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
  3428. $out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3429. $out.='</form>';
  3430. }
  3431. else
  3432. {
  3433. if ($selected)
  3434. {
  3435. $projet = new Project($this->db);
  3436. $projet->fetch($selected);
  3437. //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
  3438. $out.=$projet->getNomUrl(0,'',1);
  3439. }
  3440. else
  3441. {
  3442. $out.="&nbsp;";
  3443. }
  3444. }
  3445. if (empty($nooutput))
  3446. {
  3447. print $out;
  3448. return '';
  3449. }
  3450. return $out;
  3451. }
  3452. /**
  3453. * Show a form to select payment conditions
  3454. *
  3455. * @param int $page Page
  3456. * @param string $selected Id condition pre-selectionne
  3457. * @param string $htmlname Name of select html field
  3458. * @param int $addempty Add empty entry
  3459. * @return void
  3460. */
  3461. function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
  3462. {
  3463. global $langs;
  3464. if ($htmlname != "none")
  3465. {
  3466. print '<form method="post" action="'.$page.'">';
  3467. print '<input type="hidden" name="action" value="setconditions">';
  3468. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3469. $this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
  3470. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3471. print '</form>';
  3472. }
  3473. else
  3474. {
  3475. if ($selected)
  3476. {
  3477. $this->load_cache_conditions_paiements();
  3478. print $this->cache_conditions_paiements[$selected]['label'];
  3479. } else {
  3480. print "&nbsp;";
  3481. }
  3482. }
  3483. }
  3484. /**
  3485. * Show a form to select a delivery delay
  3486. *
  3487. * @param int $page Page
  3488. * @param string $selected Id condition pre-selectionne
  3489. * @param string $htmlname Name of select html field
  3490. * @param int $addempty Ajoute entree vide
  3491. * @return void
  3492. */
  3493. function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
  3494. {
  3495. global $langs;
  3496. if ($htmlname != "none")
  3497. {
  3498. print '<form method="post" action="'.$page.'">';
  3499. print '<input type="hidden" name="action" value="setavailability">';
  3500. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3501. $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
  3502. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3503. print '</form>';
  3504. }
  3505. else
  3506. {
  3507. if ($selected)
  3508. {
  3509. $this->load_cache_availability();
  3510. print $this->cache_availability[$selected]['label'];
  3511. } else {
  3512. print "&nbsp;";
  3513. }
  3514. }
  3515. }
  3516. /**
  3517. * Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
  3518. * List found into table c_input_reason loaded by loadCacheInputReason
  3519. *
  3520. * @param string $page Page
  3521. * @param string $selected Id condition pre-selectionne
  3522. * @param string $htmlname Name of select html field
  3523. * @param int $addempty Add empty entry
  3524. * @return void
  3525. */
  3526. function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
  3527. {
  3528. global $langs;
  3529. if ($htmlname != "none")
  3530. {
  3531. print '<form method="post" action="'.$page.'">';
  3532. print '<input type="hidden" name="action" value="setdemandreason">';
  3533. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3534. $this->selectInputReason($selected,$htmlname,-1,$addempty);
  3535. print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
  3536. print '</form>';
  3537. }
  3538. else
  3539. {
  3540. if ($selected)
  3541. {
  3542. $this->loadCacheInputReason();
  3543. foreach ($this->cache_demand_reason as $key => $val)
  3544. {
  3545. if ($val['id'] == $selected)
  3546. {
  3547. print $val['label'];
  3548. break;
  3549. }
  3550. }
  3551. } else {
  3552. print "&nbsp;";
  3553. }
  3554. }
  3555. }
  3556. /**
  3557. * Show a form + html select a date
  3558. *
  3559. * @param string $page Page
  3560. * @param string $selected Date preselected
  3561. * @param string $htmlname Html name of date input fields or 'none'
  3562. * @param int $displayhour Display hour selector
  3563. * @param int $displaymin Display minutes selector
  3564. * @param int $nooutput 1=No print output, return string
  3565. * @return string
  3566. * @see select_date
  3567. */
  3568. function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
  3569. {
  3570. global $langs;
  3571. $ret='';
  3572. if ($htmlname != "none")
  3573. {
  3574. $ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
  3575. $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
  3576. $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3577. $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3578. $ret.='<tr><td>';
  3579. $ret.=$this->select_date($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0,1);
  3580. $ret.='</td>';
  3581. $ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3582. $ret.='</tr></table></form>';
  3583. }
  3584. else
  3585. {
  3586. if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
  3587. else $ret.=dol_print_date($selected,'day');
  3588. }
  3589. if (empty($nooutput)) print $ret;
  3590. return $ret;
  3591. }
  3592. /**
  3593. * Show a select form to choose a user
  3594. *
  3595. * @param string $page Page
  3596. * @param string $selected Id of user preselected
  3597. * @param string $htmlname Name of input html field. If 'none', we just output the user link.
  3598. * @param array $exclude List of users id to exclude
  3599. * @param array $include List of users id to include
  3600. * @return void
  3601. */
  3602. function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
  3603. {
  3604. global $langs;
  3605. if ($htmlname != "none")
  3606. {
  3607. print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
  3608. print '<input type="hidden" name="action" value="set'.$htmlname.'">';
  3609. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3610. print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
  3611. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3612. print '</form>';
  3613. }
  3614. else
  3615. {
  3616. if ($selected)
  3617. {
  3618. require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
  3619. $theuser=new User($this->db);
  3620. $theuser->fetch($selected);
  3621. print $theuser->getNomUrl(1);
  3622. } else {
  3623. print "&nbsp;";
  3624. }
  3625. }
  3626. }
  3627. /**
  3628. * Show form with payment mode
  3629. *
  3630. * @param string $page Page
  3631. * @param int $selected Id mode pre-selectionne
  3632. * @param string $htmlname Name of select html field
  3633. * @param string $filtertype To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
  3634. * @param int $active Active or not, -1 = all
  3635. * @return void
  3636. */
  3637. function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
  3638. {
  3639. global $langs;
  3640. if ($htmlname != "none")
  3641. {
  3642. print '<form method="POST" action="'.$page.'">';
  3643. print '<input type="hidden" name="action" value="setmode">';
  3644. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3645. $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
  3646. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3647. print '</form>';
  3648. }
  3649. else
  3650. {
  3651. if ($selected)
  3652. {
  3653. $this->load_cache_types_paiements();
  3654. print $this->cache_types_paiements[$selected]['label'];
  3655. } else {
  3656. print "&nbsp;";
  3657. }
  3658. }
  3659. }
  3660. /**
  3661. * Show form with multicurrency code
  3662. *
  3663. * @param string $page Page
  3664. * @param string $selected code pre-selectionne
  3665. * @param string $htmlname Name of select html field
  3666. * @return void
  3667. */
  3668. function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
  3669. {
  3670. global $langs;
  3671. if ($htmlname != "none")
  3672. {
  3673. print '<form method="POST" action="'.$page.'">';
  3674. print '<input type="hidden" name="action" value="setmulticurrencycode">';
  3675. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3676. print $this->selectMultiCurrency($selected, $htmlname, 0);
  3677. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3678. print '</form>';
  3679. }
  3680. else
  3681. {
  3682. dol_include_once('/core/lib/company.lib.php');
  3683. print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
  3684. }
  3685. }
  3686. /**
  3687. * Show form with multicurrency rate
  3688. *
  3689. * @param string $page Page
  3690. * @param double $rate Current rate
  3691. * @param string $htmlname Name of select html field
  3692. * @param string $currency Currency code to explain the rate
  3693. * @return void
  3694. */
  3695. function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
  3696. {
  3697. global $langs, $mysoc, $conf;
  3698. if ($htmlname != "none")
  3699. {
  3700. print '<form method="POST" action="'.$page.'">';
  3701. print '<input type="hidden" name="action" value="setmulticurrencyrate">';
  3702. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3703. print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" /> ';
  3704. print '<select name="calculation_mode">';
  3705. print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
  3706. print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
  3707. print '</select> ';
  3708. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3709. print '</form>';
  3710. }
  3711. else
  3712. {
  3713. if (! empty($rate))
  3714. {
  3715. print price($rate, 1, $langs, 1, 0);
  3716. if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
  3717. }
  3718. else
  3719. {
  3720. print 1;
  3721. }
  3722. }
  3723. }
  3724. /**
  3725. * Show a select box with available absolute discounts
  3726. *
  3727. * @param string $page Page URL where form is shown
  3728. * @param int $selected Value pre-selected
  3729. * @param string $htmlname Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
  3730. * @param int $socid Third party id
  3731. * @param float $amount Total amount available
  3732. * @param string $filter SQL filter on discounts
  3733. * @param int $maxvalue Max value for lines that can be selected
  3734. * @param string $more More string to add
  3735. * @param int $hidelist 1=Hide list
  3736. * @return void
  3737. */
  3738. function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0)
  3739. {
  3740. global $conf,$langs;
  3741. if ($htmlname != "none")
  3742. {
  3743. print '<form method="post" action="'.$page.'">';
  3744. print '<input type="hidden" name="action" value="setabsolutediscount">';
  3745. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3746. print '<div class="inline-block">';
  3747. if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
  3748. {
  3749. if (! $filter || $filter=="fk_facture_source IS NULL") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency)); // If we want deposit to be substracted to payments only and not to total of final invoice
  3750. else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency));
  3751. }
  3752. else
  3753. {
  3754. if (! $filter || $filter=="fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND (description LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%'))") print $langs->trans("CompanyHasAbsoluteDiscount",price($amount,0,$langs,0,0,-1,$conf->currency));
  3755. else print $langs->trans("CompanyHasCreditNote",price($amount,0,$langs,0,0,-1,$conf->currency));
  3756. }
  3757. if (empty($hidelist)) print ': ';
  3758. print '</div>';
  3759. if (empty($hidelist))
  3760. {
  3761. print '<div class="inline-block" style="padding-right: 10px">';
  3762. $newfilter='fk_facture IS NULL AND fk_facture_line IS NULL'; // Remises disponibles
  3763. if ($filter) $newfilter.=' AND ('.$filter.')';
  3764. $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
  3765. if ($nbqualifiedlines > 0)
  3766. {
  3767. print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
  3768. if ($filter && $filter != "fk_facture_source IS NULL OR (fk_facture_source IS NOT NULL AND description LIKE '(DEPOSIT)%')") print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
  3769. print '>';
  3770. }
  3771. print '</div>';
  3772. }
  3773. if ($more)
  3774. {
  3775. print '<div class="inline-block">';
  3776. print $more;
  3777. print '</div>';
  3778. }
  3779. print '</form>';
  3780. }
  3781. else
  3782. {
  3783. if ($selected)
  3784. {
  3785. print $selected;
  3786. }
  3787. else
  3788. {
  3789. print "0";
  3790. }
  3791. }
  3792. }
  3793. /**
  3794. * Show forms to select a contact
  3795. *
  3796. * @param string $page Page
  3797. * @param Societe $societe Filter on third party
  3798. * @param int $selected Id contact pre-selectionne
  3799. * @param string $htmlname Name of HTML select. If 'none', we just show contact link.
  3800. * @return void
  3801. */
  3802. function form_contacts($page, $societe, $selected='', $htmlname='contactid')
  3803. {
  3804. global $langs, $conf;
  3805. if ($htmlname != "none")
  3806. {
  3807. print '<form method="post" action="'.$page.'">';
  3808. print '<input type="hidden" name="action" value="set_contact">';
  3809. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3810. print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
  3811. print '<tr><td>';
  3812. $num=$this->select_contacts($societe->id, $selected, $htmlname);
  3813. if ($num==0)
  3814. {
  3815. $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
  3816. print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
  3817. }
  3818. print '</td>';
  3819. print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
  3820. print '</tr></table></form>';
  3821. }
  3822. else
  3823. {
  3824. if ($selected)
  3825. {
  3826. require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
  3827. $contact=new Contact($this->db);
  3828. $contact->fetch($selected);
  3829. print $contact->getFullName($langs);
  3830. } else {
  3831. print "&nbsp;";
  3832. }
  3833. }
  3834. }
  3835. /**
  3836. * Output html select to select thirdparty
  3837. *
  3838. * @param string $page Page
  3839. * @param string $selected Id preselected
  3840. * @param string $htmlname Name of HTML select
  3841. * @param string $filter optional filters criteras
  3842. * @param int $showempty Add an empty field
  3843. * @param int $showtype Show third party type in combolist (customer, prospect or supplier)
  3844. * @param int $forcecombo Force to use combo box
  3845. * @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')))
  3846. * @return void
  3847. */
  3848. function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array())
  3849. {
  3850. global $langs;
  3851. if ($htmlname != "none")
  3852. {
  3853. print '<form method="post" action="'.$page.'">';
  3854. print '<input type="hidden" name="action" value="set_thirdparty">';
  3855. print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
  3856. print $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
  3857. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3858. print '</form>';
  3859. }
  3860. else
  3861. {
  3862. if ($selected)
  3863. {
  3864. require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
  3865. $soc = new Societe($this->db);
  3866. $soc->fetch($selected);
  3867. print $soc->getNomUrl($langs);
  3868. }
  3869. else
  3870. {
  3871. print "&nbsp;";
  3872. }
  3873. }
  3874. }
  3875. /**
  3876. * Retourne la liste des devises, dans la langue de l'utilisateur
  3877. *
  3878. * @param string $selected preselected currency code
  3879. * @param string $htmlname name of HTML select list
  3880. * @return void
  3881. */
  3882. function select_currency($selected='',$htmlname='currency_id')
  3883. {
  3884. print $this->selectcurrency($selected,$htmlname);
  3885. }
  3886. /**
  3887. * Retourne la liste des devises, dans la langue de l'utilisateur
  3888. *
  3889. * @param string $selected preselected currency code
  3890. * @param string $htmlname name of HTML select list
  3891. * @return string
  3892. */
  3893. function selectCurrency($selected='',$htmlname='currency_id')
  3894. {
  3895. global $conf,$langs,$user;
  3896. $langs->loadCacheCurrencies('');
  3897. $out='';
  3898. if ($selected=='euro' || $selected=='euros') $selected='EUR'; // Pour compatibilite
  3899. $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3900. foreach ($langs->cache_currencies as $code_iso => $currency)
  3901. {
  3902. if ($selected && $selected == $code_iso)
  3903. {
  3904. $out.= '<option value="'.$code_iso.'" selected>';
  3905. }
  3906. else
  3907. {
  3908. $out.= '<option value="'.$code_iso.'">';
  3909. }
  3910. $out.= $currency['label'];
  3911. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  3912. $out.= '</option>';
  3913. }
  3914. $out.= '</select>';
  3915. if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
  3916. return $out;
  3917. }
  3918. /**
  3919. * Return array of currencies in user language
  3920. *
  3921. * @param string $selected preselected currency code
  3922. * @param string $htmlname name of HTML select list
  3923. * @param integer $useempty 1=Add empty line
  3924. * @return string
  3925. */
  3926. function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
  3927. {
  3928. global $db,$conf,$langs,$user;
  3929. $langs->loadCacheCurrencies(''); // Load ->cache_currencies
  3930. $TCurrency = array();
  3931. $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
  3932. $sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
  3933. $resql = $db->query($sql);
  3934. if ($resql)
  3935. {
  3936. while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
  3937. }
  3938. $out='';
  3939. $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
  3940. if ($useempty) $out .= '<option value=""></option>';
  3941. // If company current currency not in table, we add it into list. Should always be available.
  3942. if (! in_array($conf->currency, $TCurrency))
  3943. {
  3944. $TCurrency[$conf->currency] = $conf->currency;
  3945. }
  3946. if (count($TCurrency) > 0)
  3947. {
  3948. foreach ($langs->cache_currencies as $code_iso => $currency)
  3949. {
  3950. if (isset($TCurrency[$code_iso]))
  3951. {
  3952. if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
  3953. else $out.= '<option value="'.$code_iso.'">';
  3954. $out.= $currency['label'];
  3955. $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
  3956. $out.= '</option>';
  3957. }
  3958. }
  3959. }
  3960. $out.= '</select>';
  3961. // Make select dynamic
  3962. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  3963. $out.= ajax_combobox($htmlname);
  3964. return $out;
  3965. }
  3966. /**
  3967. * Load into the cache vat rates of a country
  3968. *
  3969. * @param string $country_code Country code with quotes ("'CA'", or "'CA,IN,...'")
  3970. * @return int Nb of loaded lines, 0 if already loaded, <0 if KO
  3971. */
  3972. function load_cache_vatrates($country_code)
  3973. {
  3974. global $langs;
  3975. $num = count($this->cache_vatrates);
  3976. if ($num > 0) return $num; // Cache already loaded
  3977. dol_syslog(__METHOD__, LOG_DEBUG);
  3978. $sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.recuperableonly";
  3979. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3980. $sql.= " WHERE t.fk_pays = c.rowid";
  3981. $sql.= " AND t.active > 0";
  3982. $sql.= " AND c.code IN (".$country_code.")";
  3983. $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
  3984. $resql=$this->db->query($sql);
  3985. if ($resql)
  3986. {
  3987. $num = $this->db->num_rows($resql);
  3988. if ($num)
  3989. {
  3990. for ($i = 0; $i < $num; $i++)
  3991. {
  3992. $obj = $this->db->fetch_object($resql);
  3993. $this->cache_vatrates[$i]['rowid'] = $obj->rowid;
  3994. $this->cache_vatrates[$i]['code'] = $obj->code;
  3995. $this->cache_vatrates[$i]['txtva'] = $obj->taux;
  3996. $this->cache_vatrates[$i]['libtva'] = $obj->taux.'%'.($obj->code?' ('.$obj->code.')':''); // Label must contains only 0-9 , . % or *
  3997. $this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
  3998. }
  3999. return $num;
  4000. }
  4001. else
  4002. {
  4003. $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
  4004. return -1;
  4005. }
  4006. }
  4007. else
  4008. {
  4009. $this->error = '<font class="error">'.$this->db->error().'</font>';
  4010. return -2;
  4011. }
  4012. }
  4013. /**
  4014. * Output an HTML select vat rate.
  4015. * The name of this function should be selectVat. We keep bad name for compatibility purpose.
  4016. *
  4017. * @param string $htmlname Name of HTML select field
  4018. * @param float|string $selectedrate Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
  4019. * @param Societe $societe_vendeuse Thirdparty seller
  4020. * @param Societe $societe_acheteuse Thirdparty buyer
  4021. * @param int $idprod Id product. O if unknown of NA.
  4022. * @param int $info_bits Miscellaneous information on line (1 for NPR)
  4023. * @param int|string $type ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
  4024. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4025. * Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4026. * 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.
  4027. * Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
  4028. * Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
  4029. * Sinon la TVA proposee par defaut=0. Fin de regle.
  4030. * @param bool $options_only Return HTML options lines only (for ajax treatment)
  4031. * @param int $mode 1=Add code into key in select list
  4032. * @return string
  4033. */
  4034. function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
  4035. {
  4036. global $langs,$conf,$mysoc;
  4037. $return='';
  4038. // Define defaultnpr, defaultttx and defaultcode
  4039. $defaultnpr=($info_bits & 0x01);
  4040. $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
  4041. $defaulttx=str_replace('*','',$selectedrate);
  4042. $defaultcode='';
  4043. if (preg_match('/\((.*)\)/', $defaulttx, $reg))
  4044. {
  4045. $defaultcode=$reg[1];
  4046. $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
  4047. }
  4048. //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
  4049. // Check parameters
  4050. if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
  4051. {
  4052. if ($societe_vendeuse->id == $mysoc->id)
  4053. {
  4054. $return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
  4055. }
  4056. else
  4057. {
  4058. $return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
  4059. }
  4060. return $return;
  4061. }
  4062. //var_dump($societe_acheteuse);
  4063. //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";
  4064. //exit;
  4065. // Define list of countries to use to search VAT rates to show
  4066. // First we defined code_country to use to find list
  4067. if (is_object($societe_vendeuse))
  4068. {
  4069. $code_country="'".$societe_vendeuse->country_code."'";
  4070. }
  4071. else
  4072. {
  4073. $code_country="'".$mysoc->country_code."'"; // Pour compatibilite ascendente
  4074. }
  4075. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) // If option to have vat for end customer for services is on
  4076. {
  4077. if (! $societe_vendeuse->isInEEC() && (! is_object($societe_acheteuse) || ($societe_acheteuse->isInEEC() && ! $societe_acheteuse->isACompany())))
  4078. {
  4079. // We also add the buyer
  4080. if (is_numeric($type))
  4081. {
  4082. if ($type == 1) // We know product is a service
  4083. {
  4084. $code_country.=",'".$societe_acheteuse->country_code."'";
  4085. }
  4086. }
  4087. else if (! $idprod) // We don't know type of product
  4088. {
  4089. $code_country.=",'".$societe_acheteuse->country_code."'";
  4090. }
  4091. else
  4092. {
  4093. $prodstatic=new Product($this->db);
  4094. $prodstatic->fetch($idprod);
  4095. if ($prodstatic->type == Product::TYPE_SERVICE) // We know product is a service
  4096. {
  4097. $code_country.=",'".$societe_acheteuse->country_code."'";
  4098. }
  4099. }
  4100. }
  4101. }
  4102. // Now we get list
  4103. $num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
  4104. if ($num > 0)
  4105. {
  4106. // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
  4107. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4108. {
  4109. $tmpthirdparty=new Societe($this->db);
  4110. $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  4111. $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
  4112. if (empty($defaulttx)) $defaultnpr=0;
  4113. }
  4114. // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
  4115. // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
  4116. if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
  4117. {
  4118. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
  4119. else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
  4120. }
  4121. // Disabled if seller is not subject to VAT
  4122. $disabled=false; $title='';
  4123. if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
  4124. {
  4125. $title=' title="'.$langs->trans('VATIsNotUsed').'"';
  4126. $disabled=true;
  4127. }
  4128. if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
  4129. $selectedfound=false;
  4130. foreach ($this->cache_vatrates as $rate)
  4131. {
  4132. // Keep only 0 if seller is not subject to VAT
  4133. if ($disabled && $rate['txtva'] != 0) continue;
  4134. // Define key to use into select list
  4135. $key = $rate['txtva'];
  4136. $key.= $rate['nprtva'] ? '*': '';
  4137. if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
  4138. if ($mode < 0) $key = $rate['rowid'];
  4139. $return.= '<option value="'.$key.'"';
  4140. if (! $selectedfound)
  4141. {
  4142. if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
  4143. {
  4144. if ($defaultcode == $rate['code'])
  4145. {
  4146. $return.= ' selected';
  4147. $selectedfound=true;
  4148. }
  4149. }
  4150. elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
  4151. {
  4152. $return.= ' selected';
  4153. $selectedfound=true;
  4154. }
  4155. }
  4156. $return.= '>'.vatrate($rate['libtva']);
  4157. //$return.=($rate['code']?' '.$rate['code']:'');
  4158. $return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': ''; // We show the * (old behaviour only if new vat code is not used)
  4159. $return.= '</option>';
  4160. }
  4161. if (! $options_only) $return.= '</select>';
  4162. }
  4163. else
  4164. {
  4165. $return.= $this->error;
  4166. }
  4167. $this->num = $num;
  4168. return $return;
  4169. }
  4170. /**
  4171. * Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
  4172. * Fields are preselected with :
  4173. * - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
  4174. * - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
  4175. * - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
  4176. *
  4177. * @param timestamp $set_time Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date (emptydate must be 0).
  4178. * @param string $prefix Prefix for fields name
  4179. * @param int $h 1=Show also hours
  4180. * @param int $m 1=Show also minutes
  4181. * @param int $empty 0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
  4182. * @param string $form_name Not used
  4183. * @param int $d 1=Show days, month, years
  4184. * @param int $addnowlink Add a link "Now"
  4185. * @param int $nooutput Do not output html string but return it
  4186. * @param int $disabled Disable input fields
  4187. * @param int $fullday When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
  4188. * @param string $addplusone Add a link "+1 hour". Value must be name of another select_date field.
  4189. * @param datetime $adddateof Add a link "Date of invoice" using the following date.
  4190. * @return string|null Nothing or string if nooutput is 1
  4191. * @see form_date
  4192. */
  4193. 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='')
  4194. {
  4195. global $conf,$langs;
  4196. $retstring='';
  4197. if($prefix=='') $prefix='re';
  4198. if($h == '') $h=0;
  4199. if($m == '') $m=0;
  4200. $emptydate=0;
  4201. $emptyhours=0;
  4202. if ($empty == 1) { $emptydate=1; $emptyhours=1; }
  4203. if ($empty == 2) { $emptydate=0; $emptyhours=1; }
  4204. $orig_set_time=$set_time;
  4205. if ($set_time === '' && $emptydate == 0)
  4206. {
  4207. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4208. $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
  4209. }
  4210. // Analysis of the pre-selection date
  4211. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))
  4212. {
  4213. // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  4214. $syear = (! empty($reg[1])?$reg[1]:'');
  4215. $smonth = (! empty($reg[2])?$reg[2]:'');
  4216. $sday = (! empty($reg[3])?$reg[3]:'');
  4217. $shour = (! empty($reg[4])?$reg[4]:'');
  4218. $smin = (! empty($reg[5])?$reg[5]:'');
  4219. }
  4220. elseif (strval($set_time) != '' && $set_time != -1)
  4221. {
  4222. // set_time est un timestamps (0 possible)
  4223. $syear = dol_print_date($set_time, "%Y");
  4224. $smonth = dol_print_date($set_time, "%m");
  4225. $sday = dol_print_date($set_time, "%d");
  4226. if ($orig_set_time != '')
  4227. {
  4228. $shour = dol_print_date($set_time, "%H");
  4229. $smin = dol_print_date($set_time, "%M");
  4230. }
  4231. }
  4232. else
  4233. {
  4234. // Date est '' ou vaut -1
  4235. $syear = '';
  4236. $smonth = '';
  4237. $sday = '';
  4238. $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? '' : $conf->global->MAIN_DEFAULT_DATE_HOUR;
  4239. $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? '' : $conf->global->MAIN_DEFAULT_DATE_MIN;
  4240. }
  4241. $usecalendar='combo';
  4242. if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) $usecalendar=empty($conf->global->MAIN_POPUP_CALENDAR)?'eldy':$conf->global->MAIN_POPUP_CALENDAR;
  4243. if ($conf->browser->phone) $usecalendar='combo';
  4244. if ($d)
  4245. {
  4246. // Show date with popup
  4247. if ($usecalendar != 'combo')
  4248. {
  4249. $formated_date='';
  4250. //print "e".$set_time." t ".$conf->format_date_short;
  4251. if (strval($set_time) != '' && $set_time != -1)
  4252. {
  4253. //$formated_date=dol_print_date($set_time,$conf->format_date_short);
  4254. $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4255. }
  4256. // Calendrier popup version eldy
  4257. if ($usecalendar == "eldy")
  4258. {
  4259. // Zone de saisie manuelle de la date
  4260. $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
  4261. $retstring.=($disabled?' disabled':'');
  4262. $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
  4263. $retstring.='>';
  4264. // Icone calendrier
  4265. if (! $disabled)
  4266. {
  4267. $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
  4268. $base=DOL_URL_ROOT.'/core/';
  4269. $retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');">'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
  4270. }
  4271. else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
  4272. $retstring.='<input type="hidden" id="'.$prefix.'day" name="'.$prefix.'day" value="'.$sday.'">'."\n";
  4273. $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
  4274. $retstring.='<input type="hidden" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">'."\n";
  4275. }
  4276. else
  4277. {
  4278. print "Bad value of MAIN_POPUP_CALENDAR";
  4279. }
  4280. }
  4281. // Show date with combo selects
  4282. else
  4283. {
  4284. //$retstring.='<div class="inline-block">';
  4285. // Day
  4286. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
  4287. if ($emptydate || $set_time == -1)
  4288. {
  4289. $retstring.='<option value="0" selected>&nbsp;</option>';
  4290. }
  4291. for ($day = 1 ; $day <= 31; $day++)
  4292. {
  4293. $retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
  4294. }
  4295. $retstring.="</select>";
  4296. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
  4297. if ($emptydate || $set_time == -1)
  4298. {
  4299. $retstring.='<option value="0" selected>&nbsp;</option>';
  4300. }
  4301. // Month
  4302. for ($month = 1 ; $month <= 12 ; $month++)
  4303. {
  4304. $retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
  4305. $retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
  4306. $retstring.="</option>";
  4307. }
  4308. $retstring.="</select>";
  4309. // Year
  4310. if ($emptydate || $set_time == -1)
  4311. {
  4312. $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.'">';
  4313. }
  4314. else
  4315. {
  4316. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
  4317. for ($year = $syear - 10; $year < $syear + 10 ; $year++)
  4318. {
  4319. $retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
  4320. }
  4321. $retstring.="</select>\n";
  4322. }
  4323. //$retstring.='</div>';
  4324. }
  4325. }
  4326. if ($d && $h) $retstring.=($h==2?'<br>':' ');
  4327. if ($h)
  4328. {
  4329. // Show hour
  4330. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
  4331. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4332. for ($hour = 0; $hour < 24; $hour++)
  4333. {
  4334. if (strlen($hour) < 2) $hour = "0" . $hour;
  4335. $retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
  4336. }
  4337. $retstring.='</select>';
  4338. if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
  4339. }
  4340. if ($m)
  4341. {
  4342. // Show minutes
  4343. $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
  4344. if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
  4345. for ($min = 0; $min < 60 ; $min++)
  4346. {
  4347. if (strlen($min) < 2) $min = "0" . $min;
  4348. $retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
  4349. }
  4350. $retstring.='</select>';
  4351. }
  4352. // Add a "Now" link
  4353. if ($conf->use_javascript_ajax && $addnowlink)
  4354. {
  4355. // Script which will be inserted in the onClick of the "Now" link
  4356. $reset_scripts = "";
  4357. // Generate the date part, depending on the use or not of the javascript calendar
  4358. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4359. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4360. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4361. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4362. /*if ($usecalendar == "eldy")
  4363. {
  4364. $base=DOL_URL_ROOT.'/core/';
  4365. $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
  4366. }
  4367. else
  4368. {
  4369. $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
  4370. $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
  4371. $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
  4372. }*/
  4373. // Update the hour part
  4374. if ($h)
  4375. {
  4376. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4377. //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
  4378. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4379. if ($fullday) $reset_scripts .= ' } ';
  4380. }
  4381. // Update the minute part
  4382. if ($m)
  4383. {
  4384. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4385. //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
  4386. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4387. if ($fullday) $reset_scripts .= ' } ';
  4388. }
  4389. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4390. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4391. {
  4392. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
  4393. $retstring.=$langs->trans("Now");
  4394. $retstring.='</button> ';
  4395. }
  4396. }
  4397. // Add a "Plus one hour" link
  4398. if ($conf->use_javascript_ajax && $addplusone)
  4399. {
  4400. // Script which will be inserted in the onClick of the "Add plusone" link
  4401. $reset_scripts = "";
  4402. // Generate the date part, depending on the use or not of the javascript calendar
  4403. $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
  4404. $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
  4405. $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
  4406. $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
  4407. // Update the hour part
  4408. if ($h)
  4409. {
  4410. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4411. $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
  4412. if ($fullday) $reset_scripts .= ' } ';
  4413. }
  4414. // Update the minute part
  4415. if ($m)
  4416. {
  4417. if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
  4418. $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
  4419. if ($fullday) $reset_scripts .= ' } ';
  4420. }
  4421. // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
  4422. if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
  4423. {
  4424. $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
  4425. $retstring.=$langs->trans("DateStartPlusOne");
  4426. $retstring.='</button> ';
  4427. }
  4428. }
  4429. // Add a "Plus one hour" link
  4430. if ($conf->use_javascript_ajax && $adddateof)
  4431. {
  4432. $tmparray=dol_getdate($adddateof);
  4433. $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'].'\');">'.$langs->trans("DateInvoice").'</a>';
  4434. }
  4435. if (! empty($nooutput)) return $retstring;
  4436. print $retstring;
  4437. return;
  4438. }
  4439. /**
  4440. * Function to show a form to select a duration on a page
  4441. *
  4442. * @param string $prefix Prefix for input fields
  4443. * @param int $iSecond Default preselected duration (number of seconds or '')
  4444. * @param int $disabled Disable the combo box
  4445. * @param string $typehour If 'select' then input hour and input min is a combo,
  4446. * if 'text' input hour is in text and input min is a text,
  4447. * if 'textselect' input hour is in text and input min is a combo
  4448. * @param integer $minunderhours If 1, show minutes selection under the hours
  4449. * @param int $nooutput Do not output html string but return it
  4450. * @return string|null
  4451. */
  4452. function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
  4453. {
  4454. global $langs;
  4455. $retstring='';
  4456. $hourSelected=0; $minSelected=0;
  4457. // Hours
  4458. if ($iSecond != '')
  4459. {
  4460. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4461. $hourSelected = convertSecondToTime($iSecond,'allhour');
  4462. $minSelected = convertSecondToTime($iSecond,'min');
  4463. }
  4464. if ($typehour=='select' )
  4465. {
  4466. $retstring.='<select class="flat" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
  4467. for ($hour = 0; $hour < 25; $hour++) // For a duration, we allow 24 hours
  4468. {
  4469. $retstring.='<option value="'.$hour.'"';
  4470. if ($hourSelected == $hour)
  4471. {
  4472. $retstring.=" selected";
  4473. }
  4474. $retstring.=">".$hour."</option>";
  4475. }
  4476. $retstring.="</select>";
  4477. }
  4478. elseif ($typehour=='text' || $typehour=='textselect')
  4479. {
  4480. $retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
  4481. }
  4482. else return 'BadValueForParameterTypeHour';
  4483. if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
  4484. else $retstring.=':';
  4485. // Minutes
  4486. if ($minunderhours) $retstring.='<br>';
  4487. else $retstring.="&nbsp;";
  4488. if ($typehour=='select' || $typehour=='textselect')
  4489. {
  4490. $retstring.='<select class="flat" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
  4491. for ($min = 0; $min <= 55; $min=$min+5)
  4492. {
  4493. $retstring.='<option value="'.$min.'"';
  4494. if ($minSelected == $min) $retstring.=' selected';
  4495. $retstring.='>'.$min.'</option>';
  4496. }
  4497. $retstring.="</select>";
  4498. }
  4499. elseif ($typehour=='text' )
  4500. {
  4501. $retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
  4502. }
  4503. if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
  4504. //$retstring.="&nbsp;";
  4505. if (! empty($nooutput)) return $retstring;
  4506. print $retstring;
  4507. return;
  4508. }
  4509. /**
  4510. * Return a HTML select string, built from an array of key+value.
  4511. * Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
  4512. *
  4513. * @param string $htmlname Name of html select area. Must start with "multi" if this is a multiselect
  4514. * @param array $array Array (key => value)
  4515. * @param string|string[] $id Preselected key or preselected keys for multiselect
  4516. * @param int $show_empty 0 no empty value allowed, 1 or string to add an empty value into list (value is '' or '&nbsp;' if 1), <0 to add an empty value with key that is this value.
  4517. * @param int $key_in_label 1 to show key into label with format "[key] value"
  4518. * @param int $value_as_key 1 to use value as key
  4519. * @param string $moreparam Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
  4520. * @param int $translate 1=Translate and encode value
  4521. * @param int $maxlen Length maximum for labels
  4522. * @param int $disabled Html select box is disabled
  4523. * @param string $sort 'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
  4524. * @param string $morecss Add more class to css styles
  4525. * @param int $addjscombo Add js combo
  4526. * @param string $moreparamonempty Add more param on the empty option line. Not used if show_empty not set
  4527. * @param int $disablebademail Check if an email is found into value and if not disable and colorize entry
  4528. * @param int $nohtmlescape No html escaping.
  4529. * @return string HTML select string.
  4530. * @see multiselectarray
  4531. */
  4532. 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)
  4533. {
  4534. global $conf, $langs;
  4535. // Do we want a multiselect ?
  4536. //$jsbeautify = 0;
  4537. //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
  4538. $jsbeautify = 1;
  4539. if ($value_as_key) $array=array_combine($array, $array);
  4540. $out='';
  4541. // Add code for jquery to use multiselect
  4542. if ($addjscombo && empty($conf->dol_use_jmobile) && $jsbeautify)
  4543. {
  4544. $minLengthToAutocomplete=0;
  4545. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  4546. // Enhance with select2
  4547. if ($conf->use_javascript_ajax)
  4548. {
  4549. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  4550. $comboenhancement = ajax_combobox($htmlname);
  4551. $out.=$comboenhancement;
  4552. }
  4553. }
  4554. $out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'" name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'').'>';
  4555. if ($show_empty)
  4556. {
  4557. $textforempty=' ';
  4558. 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.
  4559. if (! is_numeric($show_empty)) $textforempty=$show_empty;
  4560. $out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
  4561. }
  4562. if (is_array($array))
  4563. {
  4564. // Translate
  4565. if ($translate)
  4566. {
  4567. foreach($array as $key => $value)
  4568. {
  4569. $array[$key]=$langs->trans($value);
  4570. }
  4571. }
  4572. // Sort
  4573. if ($sort == 'ASC') asort($array);
  4574. elseif ($sort == 'DESC') arsort($array);
  4575. foreach($array as $key => $value)
  4576. {
  4577. $disabled=''; $style='';
  4578. if (! empty($disablebademail))
  4579. {
  4580. if (! preg_match('/&lt;.+@.+&gt;/', $value))
  4581. {
  4582. //$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
  4583. $disabled=' disabled';
  4584. $style=' class="warning"';
  4585. }
  4586. }
  4587. $out.='<option value="'.$key.'"';
  4588. $out.=$style.$disabled;
  4589. if ($id != '' && $id == $key && ! $disabled) $out.=' selected'; // To preselect a value
  4590. $out.='>';
  4591. if ($key_in_label)
  4592. {
  4593. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
  4594. else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
  4595. }
  4596. else
  4597. {
  4598. if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
  4599. else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
  4600. if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
  4601. }
  4602. //var_dump($selectOptionValue);
  4603. $out.=$selectOptionValue;
  4604. $out.="</option>\n";
  4605. }
  4606. }
  4607. $out.="</select>";
  4608. return $out;
  4609. }
  4610. /**
  4611. * 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.
  4612. * Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
  4613. *
  4614. * @param string $htmlname Name of html select area
  4615. * @param string $url Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
  4616. * @param string $id Preselected key
  4617. * @param string $moreparam Add more parameters onto the select tag
  4618. * @param string $moreparamtourl Add more parameters onto the Ajax called URL
  4619. * @param int $disabled Html select box is disabled
  4620. * @param int $minimumInputLength Minimum Input Length
  4621. * @param string $morecss Add more class to css styles
  4622. * @param int $callurlonselect If set to 1, some code is added so an url return by the ajax is called when value is selected.
  4623. * @param string $placeholder String to use as placeholder
  4624. * @param integer $acceptdelayedhtml 1 if caller request 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)
  4625. * @return string HTML select string
  4626. */
  4627. static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
  4628. {
  4629. global $langs;
  4630. global $delayedhtmlcontent;
  4631. $tmpplugin='select2';
  4632. $out='<input type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'">';
  4633. // TODO Use an internal dolibarr component instead of select2
  4634. $outdelayed='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  4635. <script type="text/javascript">
  4636. $(document).ready(function () {
  4637. '.($callurlonselect ? 'var saveRemoteData = [];':'').'
  4638. $(".'.$htmlname.'").select2({
  4639. ajax: {
  4640. dir: "ltr",
  4641. url: "'.$url.'",
  4642. dataType: \'json\',
  4643. delay: 250,
  4644. data: function (searchTerm, pageNumber, context) {
  4645. return {
  4646. q: searchTerm, // search term
  4647. page: pageNumber
  4648. };
  4649. },
  4650. results: function (remoteData, pageNumber, query) {
  4651. console.log(remoteData);
  4652. saveRemoteData = remoteData;
  4653. /* format json result for select2 */
  4654. result = []
  4655. $.each( remoteData, function( key, value ) {
  4656. result.push({id: key, text: value.text});
  4657. });
  4658. //return {results:[{id:\'none\', text:\'aa\'}, {id:\'rrr\', text:\'Red\'},{id:\'bbb\', text:\'Search a into projects\'}], more:false}
  4659. return {results: result, more:false}
  4660. },
  4661. /*processResults: function (data, page) {
  4662. // parse the results into the format expected by Select2.
  4663. // since we are using custom formatting functions we do not need to
  4664. // alter the remote JSON data
  4665. console.log(data);
  4666. return {
  4667. results: data.items
  4668. };
  4669. },*/
  4670. cache: true
  4671. },
  4672. dropdownCssClass: "css-'.$htmlname.'",
  4673. placeholder: "'.dol_escape_js($placeholder).'",
  4674. escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
  4675. minimumInputLength: '.$minimumInputLength.',
  4676. formatResult: function(result, container, query, escapeMarkup) {
  4677. return escapeMarkup(result.text);
  4678. }
  4679. });
  4680. '.($callurlonselect ? '
  4681. $(".'.$htmlname.'").change(function() {
  4682. var selected = $(".'.$htmlname.'").select2("val");
  4683. $(".'.$htmlname.'").select2("val",""); /* reset visible combo value */
  4684. $.each( saveRemoteData, function( key, value ) {
  4685. if (key == selected)
  4686. {
  4687. console.log("Do a redirect into selectArrayAjax to "+value.url)
  4688. location.assign(value.url);
  4689. }
  4690. });
  4691. });' : '' ) . '
  4692. });
  4693. </script>';
  4694. if ($acceptdelayedhtml)
  4695. {
  4696. $delayedhtmlcontent.=$outdelayed;
  4697. }
  4698. else
  4699. {
  4700. $out.=$outdelayed;
  4701. }
  4702. return $out;
  4703. }
  4704. /**
  4705. * Show a multiselect form from an array.
  4706. *
  4707. * @param string $htmlname Name of select
  4708. * @param array $array Array with key+value
  4709. * @param array $selected Array with key+value preselected
  4710. * @param int $key_in_label 1 pour afficher la key dans la valeur "[key] value"
  4711. * @param int $value_as_key 1 to use value as key
  4712. * @param string $morecss Add more css style
  4713. * @param int $translate Translate and encode value
  4714. * @param int $width Force width of select box. May be used only when using jquery couch. Example: 250, 95%
  4715. * @param string $moreattrib Add more options on select component. Example: 'disabled'
  4716. * @param string $elemtype Type of element we show ('category', ...)
  4717. * @return string HTML multiselect string
  4718. * @see selectarray
  4719. */
  4720. static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='',$elemtype='')
  4721. {
  4722. global $conf, $langs;
  4723. $out = '';
  4724. // Add code for jquery to use multiselect
  4725. if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
  4726. {
  4727. $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
  4728. $out.='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
  4729. <script type="text/javascript">
  4730. function formatResult(record) {'."\n";
  4731. if ($elemtype == 'category')
  4732. {
  4733. $out.=' //return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
  4734. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  4735. }
  4736. else
  4737. {
  4738. $out.='return record.text;';
  4739. }
  4740. $out.= ' };
  4741. function formatSelection(record) {'."\n";
  4742. if ($elemtype == 'category')
  4743. {
  4744. $out.=' //return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
  4745. return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
  4746. }
  4747. else
  4748. {
  4749. $out.='return record.text;';
  4750. }
  4751. $out.= ' };
  4752. $(document).ready(function () {
  4753. $(\'#'.$htmlname.'\').'.$tmpplugin.'({
  4754. dir: \'ltr\',
  4755. // Specify format function for dropdown item
  4756. formatResult: formatResult,
  4757. templateResult: formatResult, /* For 4.0 */
  4758. // Specify format function for selected item
  4759. formatSelection: formatSelection,
  4760. templateResult: formatSelection /* For 4.0 */
  4761. });
  4762. });
  4763. </script>';
  4764. }
  4765. // Try also magic suggest
  4766. $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
  4767. if (is_array($array) && ! empty($array))
  4768. {
  4769. if ($value_as_key) $array=array_combine($array, $array);
  4770. if (! empty($array))
  4771. {
  4772. foreach ($array as $key => $value)
  4773. {
  4774. $out.= '<option value="'.$key.'"';
  4775. if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
  4776. {
  4777. $out.= ' selected';
  4778. }
  4779. $out.= '>';
  4780. $newval = ($translate ? $langs->trans($value) : $value);
  4781. $newval = ($key_in_label ? $key.' - '.$newval : $newval);
  4782. $out.= dol_htmlentitiesbr($newval);
  4783. $out.= '</option>'."\n";
  4784. }
  4785. }
  4786. }
  4787. $out.= '</select>'."\n";
  4788. return $out;
  4789. }
  4790. /**
  4791. * Show a multiselect form from an array.
  4792. *
  4793. * @param string $htmlname Name of select
  4794. * @param array $array Array with array of fields we could show. This array may be modified according to setup of user.
  4795. * @param string $varpage Id of context for page. Can be set with $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
  4796. * @return string HTML multiselect string
  4797. * @see selectarray
  4798. */
  4799. static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
  4800. {
  4801. global $conf,$langs,$user;
  4802. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
  4803. $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
  4804. if (! empty($user->conf->$tmpvar))
  4805. {
  4806. $tmparray=explode(',', $user->conf->$tmpvar);
  4807. foreach($array as $key => $val)
  4808. {
  4809. //var_dump($key);
  4810. //var_dump($tmparray);
  4811. if (in_array($key, $tmparray)) $array[$key]['checked']=1;
  4812. else $array[$key]['checked']=0;
  4813. }
  4814. }
  4815. //var_dump($array);
  4816. $lis='';
  4817. $listcheckedstring='';
  4818. foreach($array as $key => $val)
  4819. {
  4820. /* var_dump($val);
  4821. var_dump(array_key_exists('enabled', $val));
  4822. var_dump(!$val['enabled']);*/
  4823. if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
  4824. {
  4825. unset($array[$key]); // We don't want this field
  4826. continue;
  4827. }
  4828. if ($val['label'])
  4829. {
  4830. $lis.='<li><input type="checkbox" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/>'.dol_escape_htmltag($langs->trans($val['label'])).'</li>';
  4831. $listcheckedstring.=(empty($val['checked'])?'':$key.',');
  4832. }
  4833. }
  4834. $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
  4835. <dl class="dropdown">
  4836. <dt>
  4837. <a href="#">
  4838. '.img_picto('','list').'
  4839. </a>
  4840. <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
  4841. </dt>
  4842. <dd class="dropowndd">
  4843. <div class="multiselectcheckbox'.$htmlname.'">
  4844. <ul class="ul'.$htmlname.'">
  4845. '.$lis.'
  4846. </ul>
  4847. </div>
  4848. </dd>
  4849. </dl>
  4850. <script type="text/javascript">
  4851. jQuery(document).ready(function () {
  4852. $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
  4853. console.log("A new field was added/removed")
  4854. $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
  4855. var title = $(this).val() + ",";
  4856. if ($(this).is(\':checked\')) {
  4857. $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
  4858. }
  4859. else {
  4860. $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
  4861. }
  4862. // Now, we submit page
  4863. $(this).parents(\'form:first\').submit();
  4864. });
  4865. });
  4866. </script>
  4867. ';
  4868. return $out;
  4869. }
  4870. /**
  4871. * Render list of categories linked to object with id $id and type $type
  4872. *
  4873. * @param int $id Id of object
  4874. * @param string $type Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
  4875. * @param int $rendermode 0=Default, use multiselect. 1=Emulate multiselect (recommended)
  4876. * @return string String with categories
  4877. */
  4878. function showCategories($id, $type, $rendermode=0)
  4879. {
  4880. global $db;
  4881. include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4882. $cat = new Categorie($db);
  4883. $categories = $cat->containing($id, $type);
  4884. if ($rendermode == 1)
  4885. {
  4886. $toprint = array();
  4887. foreach($categories as $c)
  4888. {
  4889. $ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
  4890. foreach($ways as $way)
  4891. {
  4892. $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
  4893. }
  4894. }
  4895. return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
  4896. }
  4897. if ($rendermode == 0)
  4898. {
  4899. $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
  4900. foreach($categories as $c) {
  4901. $arrayselected[] = $c->id;
  4902. }
  4903. return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
  4904. }
  4905. return 'ErrorBadValueForParameterRenderMode'; // Should not happened
  4906. }
  4907. /**
  4908. * Show linked object block.
  4909. *
  4910. * @param CommonObject $object Object we want to show links to
  4911. * @param string $morehtmlright More html to show on right of title
  4912. * @return int <0 if KO, >=0 if OK
  4913. */
  4914. function showLinkedObjectBlock($object, $morehtmlright='')
  4915. {
  4916. global $conf,$langs,$hookmanager;
  4917. global $bc;
  4918. $object->fetchObjectLinked();
  4919. // Bypass the default method
  4920. $hookmanager->initHooks(array('commonobject'));
  4921. $parameters=array();
  4922. $reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
  4923. if (empty($reshook))
  4924. {
  4925. $nbofdifferenttypes = count($object->linkedObjects);
  4926. print '<br><!-- showLinkedObjectBlock -->';
  4927. print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '');
  4928. print '<table class="noborder allwidth">';
  4929. print '<tr class="liste_titre">';
  4930. print '<td>'.$langs->trans("Type").'</td>';
  4931. print '<td>'.$langs->trans("Ref").'</td>';
  4932. print '<td align="center"></td>';
  4933. print '<td align="center">'.$langs->trans("Date").'</td>';
  4934. print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
  4935. print '<td align="right">'.$langs->trans("Status").'</td>';
  4936. print '<td></td>';
  4937. print '</tr>';
  4938. $nboftypesoutput=0;
  4939. foreach($object->linkedObjects as $objecttype => $objects)
  4940. {
  4941. $tplpath = $element = $subelement = $objecttype;
  4942. if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
  4943. {
  4944. $element = $regs[1];
  4945. $subelement = $regs[2];
  4946. $tplpath = $element.'/'.$subelement;
  4947. }
  4948. $tplname='linkedobjectblock';
  4949. // To work with non standard path
  4950. if ($objecttype == 'facture') {
  4951. $tplpath = 'compta/'.$element;
  4952. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  4953. }
  4954. else if ($objecttype == 'facturerec') {
  4955. $tplpath = 'compta/facture';
  4956. $tplname = 'linkedobjectblockForRec';
  4957. if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
  4958. }
  4959. else if ($objecttype == 'propal') {
  4960. $tplpath = 'comm/'.$element;
  4961. if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
  4962. }
  4963. else if ($objecttype == 'supplier_proposal') {
  4964. if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
  4965. }
  4966. else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
  4967. $tplpath = 'expedition';
  4968. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  4969. }
  4970. else if ($objecttype == 'delivery') {
  4971. $tplpath = 'livraison';
  4972. if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
  4973. }
  4974. else if ($objecttype == 'invoice_supplier') {
  4975. $tplpath = 'fourn/facture';
  4976. }
  4977. else if ($objecttype == 'order_supplier') {
  4978. $tplpath = 'fourn/commande';
  4979. }
  4980. else if ($objecttype == 'expensereport') {
  4981. $tplpath = 'expensereport';
  4982. }
  4983. else if ($objecttype == 'subscription') {
  4984. $tplpath = 'adherents';
  4985. }
  4986. global $linkedObjectBlock;
  4987. $linkedObjectBlock = $objects;
  4988. // Output template part (modules that overwrite templates must declare this into descriptor)
  4989. $dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
  4990. foreach($dirtpls as $reldir)
  4991. {
  4992. if ($nboftypesoutput == ($nbofdifferenttypes - 1)) // No more type to show after
  4993. {
  4994. global $noMoreLinkedObjectBlockAfter;
  4995. $noMoreLinkedObjectBlockAfter=1;
  4996. }
  4997. $res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
  4998. if ($res)
  4999. {
  5000. $nboftypesoutput++;
  5001. break;
  5002. }
  5003. }
  5004. }
  5005. if (! $nboftypesoutput)
  5006. {
  5007. print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
  5008. }
  5009. print '</table>';
  5010. return $nbofdifferenttypes;
  5011. }
  5012. }
  5013. /**
  5014. * Show block with links to link to other objects.
  5015. *
  5016. * @param CommonObject $object Object we want to show links to
  5017. * @param array $restrictlinksto Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
  5018. * @param array $excludelinksto Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
  5019. * @return string <0 if KO, >0 if OK
  5020. */
  5021. function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
  5022. {
  5023. global $conf, $langs, $hookmanager;
  5024. global $bc;
  5025. $linktoelem='';
  5026. $linktoelemlist='';
  5027. if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
  5028. $possiblelinks=array();
  5029. if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
  5030. {
  5031. $listofidcompanytoscan=$object->thirdparty->id;
  5032. if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
  5033. $possiblelinks=array(
  5034. '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',1).')'),
  5035. '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',1).')'),
  5036. '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.facnumber as 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('facture',1).')'),
  5037. 'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, 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',1).')'),
  5038. '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',1).')'),
  5039. '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',1).')'),
  5040. 'order_supplier'=>array('enabled'=>$conf->fournisseur->commande->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',1).')'),
  5041. 'invoice_supplier'=>array('enabled'=>$conf->fournisseur->facture->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',1).')')
  5042. );
  5043. }
  5044. global $action;
  5045. // Can complete the possiblelink array
  5046. $hookmanager->initHooks(array('commonobject'));
  5047. $parameters=array();
  5048. $reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
  5049. if (empty($reshook))
  5050. {
  5051. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  5052. {
  5053. $possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
  5054. }
  5055. }
  5056. else if ($reshook > 0)
  5057. {
  5058. if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
  5059. {
  5060. $possiblelinks=$hookmanager->resArray;
  5061. }
  5062. }
  5063. foreach($possiblelinks as $key => $possiblelink)
  5064. {
  5065. $num = 0;
  5066. if (empty($possiblelink['enabled'])) continue;
  5067. if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
  5068. {
  5069. print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
  5070. $sql = $possiblelink['sql'];
  5071. $resqllist = $this->db->query($sql);
  5072. if ($resqllist)
  5073. {
  5074. $num = $this->db->num_rows($resqllist);
  5075. $i = 0;
  5076. print '<br><form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
  5077. print '<input type="hidden" name="id" value="'.$object->id.'">';
  5078. print '<input type="hidden" name="action" value="addlink">';
  5079. print '<input type="hidden" name="addlink" value="'.$key.'">';
  5080. print '<table class="noborder">';
  5081. print '<tr class="liste_titre">';
  5082. print '<td class="nowrap"></td>';
  5083. print '<td align="center">' . $langs->trans("Ref") . '</td>';
  5084. print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
  5085. print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
  5086. print '<td align="left">' . $langs->trans("Company") . '</td>';
  5087. print '</tr>';
  5088. while ($i < $num)
  5089. {
  5090. $objp = $this->db->fetch_object($resqlorderlist);
  5091. $var = ! $var;
  5092. print '<tr ' . $bc [$var] . '>';
  5093. print '<td aling="left">';
  5094. print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
  5095. print '</td>';
  5096. print '<td align="center">' . $objp->ref . '</td>';
  5097. print '<td>' . $objp->ref_client . '</td>';
  5098. print '<td align="right">' . price($objp->total_ht) . '</td>';
  5099. print '<td>' . $objp->name . '</td>';
  5100. print '</tr>';
  5101. $i++;
  5102. }
  5103. print '</table>';
  5104. 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>';
  5105. print '</form>';
  5106. $this->db->free($resqllist);
  5107. } else {
  5108. dol_print_error($this->db);
  5109. }
  5110. print '</div>';
  5111. if ($num > 0)
  5112. {
  5113. }
  5114. //$linktoelem.=($linktoelem?' &nbsp; ':'');
  5115. if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
  5116. //else $linktoelem.=$langs->trans($possiblelink['label']);
  5117. else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
  5118. }
  5119. }
  5120. if ($linktoelemlist)
  5121. {
  5122. $linktoelem='
  5123. <dl class="dropdown" id="linktoobjectname">
  5124. <dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>
  5125. <dd>
  5126. <div class="multiselectlinkto">
  5127. <ul class="ulselectedfields">'.$linktoelemlist.'
  5128. </ul>
  5129. </div>
  5130. </dd>
  5131. </dl>';
  5132. }
  5133. else
  5134. {
  5135. $linktoelem='';
  5136. }
  5137. print '<!-- Add js to show linkto box -->
  5138. <script type="text/javascript" language="javascript">
  5139. jQuery(document).ready(function() {
  5140. jQuery(".linkto").click(function() {
  5141. console.log("We choose to show/hide link for rel="+jQuery(this).attr(\'rel\'));
  5142. jQuery("#"+jQuery(this).attr(\'rel\')+"list").toggle();
  5143. jQuery(this).toggle();
  5144. });
  5145. });
  5146. </script>
  5147. ';
  5148. return $linktoelem;
  5149. }
  5150. /**
  5151. * Return an html string with a select combo box to choose yes or no
  5152. *
  5153. * @param string $htmlname Name of html select field
  5154. * @param string $value Pre-selected value
  5155. * @param int $option 0 return yes/no, 1 return 1/0
  5156. * @param bool $disabled true or false
  5157. * @param int $useempty 1=Add empty line
  5158. * @return string See option
  5159. */
  5160. function selectyesno($htmlname,$value='',$option=0,$disabled=false,$useempty='')
  5161. {
  5162. global $langs;
  5163. $yes="yes"; $no="no";
  5164. if ($option)
  5165. {
  5166. $yes="1";
  5167. $no="0";
  5168. }
  5169. $disabled = ($disabled ? ' disabled' : '');
  5170. $resultyesno = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
  5171. if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'></option>'."\n";
  5172. if (("$value" == 'yes') || ($value == 1))
  5173. {
  5174. $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
  5175. $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
  5176. }
  5177. else
  5178. {
  5179. $selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
  5180. $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
  5181. $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
  5182. }
  5183. $resultyesno .= '</select>'."\n";
  5184. return $resultyesno;
  5185. }
  5186. /**
  5187. * Return list of export templates
  5188. *
  5189. * @param string $selected Id modele pre-selectionne
  5190. * @param string $htmlname Name of HTML select
  5191. * @param string $type Type of searched templates
  5192. * @param int $useempty Affiche valeur vide dans liste
  5193. * @return void
  5194. */
  5195. function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
  5196. {
  5197. $sql = "SELECT rowid, label";
  5198. $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
  5199. $sql.= " WHERE type = '".$type."'";
  5200. $sql.= " ORDER BY rowid";
  5201. $result = $this->db->query($sql);
  5202. if ($result)
  5203. {
  5204. print '<select class="flat" name="'.$htmlname.'">';
  5205. if ($useempty)
  5206. {
  5207. print '<option value="-1">&nbsp;</option>';
  5208. }
  5209. $num = $this->db->num_rows($result);
  5210. $i = 0;
  5211. while ($i < $num)
  5212. {
  5213. $obj = $this->db->fetch_object($result);
  5214. if ($selected == $obj->rowid)
  5215. {
  5216. print '<option value="'.$obj->rowid.'" selected>';
  5217. }
  5218. else
  5219. {
  5220. print '<option value="'.$obj->rowid.'">';
  5221. }
  5222. print $obj->label;
  5223. print '</option>';
  5224. $i++;
  5225. }
  5226. print "</select>";
  5227. }
  5228. else {
  5229. dol_print_error($this->db);
  5230. }
  5231. }
  5232. /**
  5233. * Return a HTML area with the reference of object and a navigation bar for a business object
  5234. * To add a particular filter on select, you must set $object->next_prev_filter to SQL criteria.
  5235. *
  5236. * @param object $object Object to show.
  5237. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link.
  5238. * @param string $morehtml More html content to output just before the nav bar.
  5239. * @param int $shownav Show Condition (navigation is shown if value is 1).
  5240. * @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).
  5241. * @param string $fieldref Name of field ref of object (object->ref) to show or 'none' to not show ref.
  5242. * @param string $morehtmlref More html to show after ref.
  5243. * @param string $moreparam More param to add in nav link url. Must start with '&...'.
  5244. * @param int $nodbprefix Do not include DB prefix to forge table name.
  5245. * @param string $morehtmlleft More html code to show before ref.
  5246. * @param string $morehtmlstatus More html code to show under navigation arrows (status place).
  5247. * @param string $morehtmlright More html code to show after ref.
  5248. * @return string Portion HTML with ref + navigation buttons
  5249. */
  5250. function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
  5251. {
  5252. global $langs,$conf;
  5253. $ret='';
  5254. if (empty($fieldid)) $fieldid='rowid';
  5255. if (empty($fieldref)) $fieldref='ref';
  5256. //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
  5257. $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''),$fieldid,$nodbprefix);
  5258. $navurl = $_SERVER["PHP_SELF"];
  5259. // Special case for project/task page
  5260. if ($paramid == 'project_ref')
  5261. {
  5262. $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document).php/','/tasks.php',$navurl);
  5263. $paramid='ref';
  5264. }
  5265. $previous_ref = $object->ref_previous?'<a 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>';
  5266. $next_ref = $object->ref_next?'<a 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>';
  5267. //print "xx".$previous_ref."x".$next_ref;
  5268. $ret.='<!-- Start banner content --><div style="vertical-align: middle">';
  5269. // Right part of banner
  5270. if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
  5271. if ($previous_ref || $next_ref || $morehtml)
  5272. {
  5273. $ret.='<div class="pagination"><ul>';
  5274. }
  5275. if ($morehtml)
  5276. {
  5277. $ret.='<li class="noborder litext">'.$morehtml.'</li>';
  5278. }
  5279. if ($shownav && ($previous_ref || $next_ref))
  5280. {
  5281. $ret.='<li class="pagination">'.$previous_ref.'</li>';
  5282. $ret.='<li class="pagination">'.$next_ref.'</li>';
  5283. }
  5284. if ($previous_ref || $next_ref || $morehtml)
  5285. {
  5286. $ret.='</ul></div>';
  5287. }
  5288. if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
  5289. // Left part of banner
  5290. if ($morehtmlleft)
  5291. {
  5292. if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
  5293. else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
  5294. }
  5295. //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
  5296. $ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
  5297. // For thirdparty, contact, user, member, the ref is the id, so we show something else
  5298. if ($object->element == 'societe')
  5299. {
  5300. $ret.=dol_htmlentities($object->name);
  5301. }
  5302. else if (in_array($object->element, array('contact', 'user', 'member')))
  5303. {
  5304. $ret.=dol_htmlentities($object->getFullName($langs));
  5305. }
  5306. else if (in_array($object->element, array('action', 'agenda')))
  5307. {
  5308. $ret.=$object->ref.'<br>'.$object->label;
  5309. }
  5310. else if (in_array($object->element, array('adherent_type')))
  5311. {
  5312. $ret.=$object->label;
  5313. }
  5314. else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
  5315. if ($morehtmlref)
  5316. {
  5317. $ret.=' '.$morehtmlref;
  5318. }
  5319. $ret.='</div>';
  5320. $ret.='</div><!-- End banner content -->';
  5321. return $ret;
  5322. }
  5323. /**
  5324. * Return HTML code to output a barcode
  5325. *
  5326. * @param Object $object Object containing data to retrieve file name
  5327. * @param int $width Width of photo
  5328. * @return string HTML code to output barcode
  5329. */
  5330. function showbarcode(&$object,$width=100)
  5331. {
  5332. global $conf;
  5333. //Check if barcode is filled in the card
  5334. if (empty($object->barcode)) return '';
  5335. // Complete object if not complete
  5336. if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
  5337. {
  5338. $result = $object->fetch_barcode();
  5339. //Check if fetch_barcode() failed
  5340. if ($result < 1) return '<!-- ErrorFetchBarcode -->';
  5341. }
  5342. // Barcode image
  5343. $url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
  5344. $out ='<!-- url barcode = '.$url.' -->';
  5345. $out.='<img src="'.$url.'">';
  5346. return $out;
  5347. }
  5348. /**
  5349. * Return HTML code to output a photo
  5350. *
  5351. * @param string $modulepart Key to define module concerned ('societe', 'userphoto', 'memberphoto')
  5352. * @param object $object Object containing data to retrieve file name
  5353. * @param int $width Width of photo
  5354. * @param int $height Height of photo (auto if 0)
  5355. * @param int $caneditfield Add edit fields
  5356. * @param string $cssclass CSS name to use on img for photo
  5357. * @param string $imagesize 'mini', 'small' or '' (original)
  5358. * @param int $addlinktofullsize Add link to fullsize image
  5359. * @param int $cache 1=Accept to use image in cache
  5360. * @return string HTML code to output photo
  5361. */
  5362. static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0)
  5363. {
  5364. global $conf,$langs;
  5365. $entity = (! empty($object->entity) ? $object->entity : $conf->entity);
  5366. $id = (! empty($object->id) ? $object->id : $object->rowid);
  5367. $ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';
  5368. if ($modulepart=='societe')
  5369. {
  5370. $dir=$conf->societe->multidir_output[$entity];
  5371. if (! empty($object->logo))
  5372. {
  5373. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
  5374. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
  5375. else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  5376. $originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
  5377. }
  5378. $email=$object->email;
  5379. }
  5380. else if ($modulepart=='contact')
  5381. {
  5382. $dir=$conf->societe->multidir_output[$entity].'/contact';
  5383. if (! empty($object->photo))
  5384. {
  5385. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
  5386. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
  5387. else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  5388. $originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
  5389. }
  5390. $email=$object->email;
  5391. }
  5392. else if ($modulepart=='userphoto')
  5393. {
  5394. $dir=$conf->user->dir_output;
  5395. if (! empty($object->photo))
  5396. {
  5397. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_mini');
  5398. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, 'user').getImageFileNameForSize($object->photo, '_small');
  5399. else $file=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;
  5400. $originalfile=get_exdir($id, 2, 0, 0, $object, 'user').$object->photo;
  5401. }
  5402. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5403. $email=$object->email;
  5404. }
  5405. else if ($modulepart=='memberphoto')
  5406. {
  5407. $dir=$conf->adherent->dir_output;
  5408. if (! empty($object->photo))
  5409. {
  5410. if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
  5411. else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
  5412. else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  5413. $originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
  5414. }
  5415. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5416. $email=$object->email;
  5417. }
  5418. else
  5419. {
  5420. // Generic case to show photos
  5421. $dir=$conf->$modulepart->dir_output;
  5422. if (! empty($object->photo))
  5423. {
  5424. if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
  5425. else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
  5426. else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  5427. $originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
  5428. }
  5429. if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg"; // For backward compatibility
  5430. $email=$object->email;
  5431. }
  5432. if ($dir)
  5433. {
  5434. if ($file && file_exists($dir."/".$file))
  5435. {
  5436. if ($addlinktofullsize)
  5437. {
  5438. $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  5439. if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
  5440. else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  5441. }
  5442. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="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.'">';
  5443. if ($addlinktofullsize) $ret.='</a>';
  5444. }
  5445. else if ($altfile && file_exists($dir."/".$altfile))
  5446. {
  5447. if ($addlinktofullsize)
  5448. {
  5449. $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
  5450. if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
  5451. else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
  5452. }
  5453. $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.'">';
  5454. if ($addlinktofullsize) $ret.='</a>';
  5455. }
  5456. else
  5457. {
  5458. $nophoto='/public/theme/common/nophoto.png';
  5459. if (in_array($modulepart,array('userphoto','contact'))) // For module that are "physical" users
  5460. {
  5461. $nophoto='/public/theme/common/user_anonymous.png';
  5462. if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
  5463. if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
  5464. }
  5465. if (! empty($conf->gravatar->enabled) && $email)
  5466. {
  5467. /**
  5468. * @see https://gravatar.com/site/implement/images/php/
  5469. */
  5470. global $dolibarr_main_url_root;
  5471. $ret.='<!-- Put link to gravatar -->';
  5472. $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/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.urlencode(dol_buildpath($nophoto,3)).'">'; // gravatar need md5 hash
  5473. }
  5474. else
  5475. {
  5476. if ($conf->browser->layout != 'phone')
  5477. {
  5478. $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
  5479. }
  5480. }
  5481. }
  5482. if ($caneditfield)
  5483. {
  5484. if ($object->photo) $ret.="<br>\n";
  5485. $ret.='<table class="nobordernopadding centpercent">';
  5486. if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
  5487. $ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"></td></tr>';
  5488. $ret.='</table>';
  5489. }
  5490. }
  5491. else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
  5492. return $ret;
  5493. }
  5494. /**
  5495. * Return select list of groups
  5496. *
  5497. * @param string $selected Id group preselected
  5498. * @param string $htmlname Field name in form
  5499. * @param int $show_empty 0=liste sans valeur nulle, 1=ajoute valeur inconnue
  5500. * @param string $exclude Array list of groups id to exclude
  5501. * @param int $disabled If select list must be disabled
  5502. * @param string $include Array list of groups id to include
  5503. * @param int $enableonly Array list of groups id to be enabled. All other must be disabled
  5504. * @param int $force_entity 0 or Id of environment to force
  5505. * @return string
  5506. * @see select_dolusers
  5507. */
  5508. function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity=0)
  5509. {
  5510. global $conf,$user,$langs;
  5511. // Permettre l'exclusion de groupes
  5512. if (is_array($exclude)) $excludeGroups = implode("','",$exclude);
  5513. // Permettre l'inclusion de groupes
  5514. if (is_array($include)) $includeGroups = implode("','",$include);
  5515. $out='';
  5516. // On recherche les groupes
  5517. $sql = "SELECT ug.rowid, ug.nom as name";
  5518. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  5519. {
  5520. $sql.= ", e.label";
  5521. }
  5522. $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
  5523. if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
  5524. {
  5525. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
  5526. if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
  5527. else $sql.= " WHERE ug.entity IS NOT NULL";
  5528. }
  5529. else
  5530. {
  5531. $sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
  5532. }
  5533. if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
  5534. if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
  5535. $sql.= " ORDER BY ug.nom ASC";
  5536. dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
  5537. $resql=$this->db->query($sql);
  5538. if ($resql)
  5539. {
  5540. // Enhance with select2
  5541. if ($conf->use_javascript_ajax)
  5542. {
  5543. include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
  5544. $comboenhancement = ajax_combobox($htmlname);
  5545. $out.= $comboenhancement;
  5546. }
  5547. $out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').'>';
  5548. $num = $this->db->num_rows($resql);
  5549. $i = 0;
  5550. if ($num)
  5551. {
  5552. if ($show_empty) $out.= '<option value="-1"'.($selected==-1?' selected':'').'>&nbsp;</option>'."\n";
  5553. while ($i < $num)
  5554. {
  5555. $obj = $this->db->fetch_object($resql);
  5556. $disableline=0;
  5557. if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
  5558. $out.= '<option value="'.$obj->rowid.'"';
  5559. if ($disableline) $out.= ' disabled';
  5560. if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && $selected == $obj->rowid))
  5561. {
  5562. $out.= ' selected';
  5563. }
  5564. $out.= '>';
  5565. $out.= $obj->name;
  5566. if (! empty($conf->multicompany->enabled) && empty($conf->multicompany->transverse_mode) && $conf->entity == 1)
  5567. {
  5568. $out.= " (".$obj->label.")";
  5569. }
  5570. $out.= '</option>';
  5571. $i++;
  5572. }
  5573. }
  5574. else
  5575. {
  5576. if ($show_empty) $out.= '<option value="-1"'.($selected==-1?' selected':'').'></option>'."\n";
  5577. $out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
  5578. }
  5579. $out.= '</select>';
  5580. }
  5581. else
  5582. {
  5583. dol_print_error($this->db);
  5584. }
  5585. return $out;
  5586. }
  5587. /**
  5588. * Return HTML to show the search and clear seach button
  5589. *
  5590. * @return string
  5591. */
  5592. function showFilterButtons()
  5593. {
  5594. global $conf, $langs;
  5595. $out='<div class="nowrap">';
  5596. $out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
  5597. $out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
  5598. $out.='</div>';
  5599. return $out;
  5600. }
  5601. /**
  5602. * Return HTML to show the search and clear seach button
  5603. *
  5604. * @param string $cssclass CSS class
  5605. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  5606. * @return string
  5607. */
  5608. function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
  5609. {
  5610. global $conf, $langs;
  5611. $out='';
  5612. if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
  5613. $out.='<script type="text/javascript">
  5614. $(document).ready(function() {
  5615. $("#checkallactions").click(function() {
  5616. if($(this).is(\':checked\')){
  5617. console.log("We check all");
  5618. $(".'.$cssclass.'").prop(\'checked\', true);
  5619. }
  5620. else
  5621. {
  5622. console.log("We uncheck all");
  5623. $(".'.$cssclass.'").prop(\'checked\', false);
  5624. }'."\n";
  5625. if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
  5626. $out.=' });
  5627. });
  5628. </script>';
  5629. return $out;
  5630. }
  5631. /**
  5632. * Return HTML to show the search and clear seach button
  5633. *
  5634. * @param int $addcheckuncheckall Add the check all/uncheck all checkbox (use javascript) and code to manage this
  5635. * @param string $cssclass CSS class
  5636. * @param int $calljsfunction 0=default. 1=call function initCheckForSelect() after changing status of checkboxes
  5637. * @return string
  5638. */
  5639. function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
  5640. {
  5641. $out.=$this->showFilterButtons();
  5642. if ($addcheckuncheckall)
  5643. {
  5644. $out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
  5645. }
  5646. return $out;
  5647. }
  5648. }