html.form.class.php 278 KB

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