functions.lib.php 244 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@capnetworks.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2016 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2017 Alexandre Spangaro <aspangaro@zendsi.com>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. *
  17. * This program is free software; you can redistribute it and/or modify
  18. * it under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation; either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. * or see http://www.gnu.org/
  30. */
  31. /**
  32. * \file htdocs/core/lib/functions.lib.php
  33. * \brief A set of functions for Dolibarr
  34. * This file contains all frequently used functions.
  35. */
  36. include_once DOL_DOCUMENT_ROOT .'/core/lib/json.lib.php';
  37. /**
  38. * Function to return value of a static property when class
  39. * name is dynamically defined (not hard coded).
  40. * This is because $myclass::$myvar works from PHP 5.3.0+ only
  41. *
  42. * @param string $class Class name
  43. * @param string $member Name of property
  44. * @return mixed Return value of static property
  45. * @deprecated Dolibarr now requires 5.3.0+, use $class::$property syntax
  46. * @see https://php.net/manual/language.oop5.static.php
  47. */
  48. function getStaticMember($class, $member)
  49. {
  50. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  51. // This part is deprecated. Uncomment if for php 5.2.*, and comment next isset class::member
  52. /*if (version_compare(phpversion(), '5.3.0', '<'))
  53. {
  54. if (is_object($class)) $class = get_class($class);
  55. $classObj = new ReflectionClass($class);
  56. $result = null;
  57. $found=0;
  58. foreach($classObj->getStaticProperties() as $prop => $value)
  59. {
  60. if ($prop == $member)
  61. {
  62. $result = $value;
  63. $found++;
  64. break;
  65. }
  66. }
  67. if ($found) return $result;
  68. }*/
  69. if (isset($class::$member)) return $class::$member;
  70. dol_print_error('','Try to get a static member "'.$member.'" in class "'.$class.'" that does not exists or is not static.');
  71. return null;
  72. }
  73. /**
  74. * Return a DoliDB instance (database handler).
  75. *
  76. * @param string $type Type of database (mysql, pgsql...)
  77. * @param string $host Address of database server
  78. * @param string $user Nom de l'utilisateur autorise
  79. * @param string $pass Mot de passe
  80. * @param string $name Nom de la database
  81. * @param int $port Port of database server
  82. * @return DoliDB A DoliDB instance
  83. */
  84. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  85. {
  86. require_once DOL_DOCUMENT_ROOT ."/core/db/".$type.'.class.php';
  87. $class='DoliDB'.ucfirst($type);
  88. $dolidb=new $class($type, $host, $user, $pass, $name, $port);
  89. return $dolidb;
  90. }
  91. /**
  92. * Get list of entity id to use
  93. *
  94. * @param string $element Current element
  95. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  96. * 'product', 'productprice', 'stock',
  97. * 'propal', 'facture', 'facture_fourn',
  98. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  99. * 'commande', 'commande_fournisseur', 'expedition', 'intervention', 'survey',
  100. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  101. * 'email_template', 'event',
  102. * @param int $shared 0=Return id of entity, 1=Return id entity + shared entities
  103. * @return mixed Entity id(s) to use
  104. */
  105. function getEntity($element=false, $shared=0)
  106. {
  107. global $conf, $mc;
  108. // For backward compatibilty
  109. if ($element == 'actioncomm') $element='agenda';
  110. if ($element == 'fichinter') $element='intervention';
  111. if ($element == 'categorie') $element='category';
  112. if (is_object($mc))
  113. {
  114. return $mc->getEntity($element, $shared);
  115. }
  116. else
  117. {
  118. $out='';
  119. $addzero = array('user', 'usergroup', 'email_template', 'default_values');
  120. if (in_array($element, $addzero)) $out.= '0,';
  121. $out.= $conf->entity;
  122. return $out;
  123. }
  124. }
  125. /**
  126. * Return information about user browser
  127. *
  128. * Returns array with the following format:
  129. * array(
  130. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  131. * 'browserversion' => Browser version. Empty if unknown
  132. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  133. * 'layout' => (tablet|phone|classic)
  134. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  135. * 'tablet' => true/false
  136. * )
  137. *
  138. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  139. * @return array Check function documentation
  140. */
  141. function getBrowserInfo($user_agent)
  142. {
  143. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  144. $name='unknown';
  145. $version='';
  146. $os='unknown';
  147. $phone = '';
  148. $detectmobile = new Mobile_Detect(null, $user_agent);
  149. $tablet = $detectmobile->isTablet();
  150. if ($detectmobile->isMobile()) {
  151. $phone = 'unknown';
  152. // If phone/smartphone, we set phone os name.
  153. if ($detectmobile->is('AndroidOS')) {
  154. $os = $phone = 'android';
  155. } elseif ($detectmobile->is('BlackBerryOS')) {
  156. $os = $phone = 'blackberry';
  157. } elseif ($detectmobile->is('iOS')) {
  158. $os = 'ios';
  159. $phone = 'iphone';
  160. } elseif ($detectmobile->is('PalmOS')) {
  161. $os = $phone = 'palm';
  162. } elseif ($detectmobile->is('SymbianOS')) {
  163. $os = 'symbian';
  164. } elseif ($detectmobile->is('webOS')) {
  165. $os = 'webos';
  166. } elseif ($detectmobile->is('MaemoOS')) {
  167. $os = 'maemo';
  168. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  169. $os = 'windows';
  170. }
  171. }
  172. // OS
  173. if (preg_match('/linux/i', $user_agent)) { $os='linux'; }
  174. elseif (preg_match('/macintosh/i', $user_agent)) { $os='macintosh'; }
  175. // Name
  176. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='firefox'; $version=$reg[2]; }
  177. elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name='chrome'; $version=$reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string
  178. elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name='chrome'; }
  179. elseif (preg_match('/iceweasel/i', $user_agent)) { $name='iceweasel'; }
  180. elseif (preg_match('/epiphany/i', $user_agent)) { $name='epiphany'; }
  181. elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='safari'; $version=$reg[2]; } // Safari is often present in string for mobile but its not.
  182. elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='opera'; $version=$reg[2]; }
  183. elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];\srv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name='ie'; $version=end($reg); } // MS products at end
  184. elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name='lynxlinks'; $version=$reg[4]; }
  185. if ($tablet) {
  186. $layout = 'tablet';
  187. } elseif ($phone) {
  188. $layout = 'phone';
  189. } else {
  190. $layout = 'classic';
  191. }
  192. return array(
  193. 'browsername' => $name,
  194. 'browserversion' => $version,
  195. 'browseros' => $os,
  196. 'layout' => $layout,
  197. 'phone' => $phone,
  198. 'tablet' => $tablet
  199. );
  200. }
  201. /**
  202. * Function called at end of web php process
  203. *
  204. * @return void
  205. */
  206. function dol_shutdown()
  207. {
  208. global $conf,$user,$langs,$db;
  209. $disconnectdone=false; $depth=0;
  210. if (is_object($db) && ! empty($db->connected)) { $depth=$db->transaction_opened; $disconnectdone=$db->close(); }
  211. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth)?' (Warn: db disconnection forced, transaction depth was '.$depth.')':''), (($disconnectdone && $depth)?LOG_WARNING:LOG_INFO));
  212. }
  213. /**
  214. * Return value of a param into GET or POST supervariable.
  215. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  216. * Note: The property $user->default_values is loaded by the main when loading the user.
  217. *
  218. * @param string $paramname Name of parameter to found
  219. * @param string $check Type of check
  220. * ''=no check (deprecated)
  221. * 'none'=no check (only for param that should have very rich content)
  222. * 'int'=check it's numeric
  223. * 'alpha'=check it's text and sign
  224. * 'aZ'=check it's a-z only
  225. * 'aZ09'=check it's simple alpha string (recommended for keys)
  226. * 'array'=check it's array
  227. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  228. * 'nohtml', 'alphanohtml'=check there is no html content
  229. * 'custom'= custom filter specify $filter and $options)
  230. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get, 4 = post then get then cookie)
  231. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  232. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'.
  233. * @return string|string[] Value found (string or array), or '' if check fails
  234. *
  235. * @TODO Set default value for check to alpha. Check all WYSIWYG edition (email and description...) is still ok with rich text.
  236. */
  237. function GETPOST($paramname, $check='', $method=0, $filter=NULL, $options=NULL)
  238. {
  239. global $mysoc,$user,$conf;
  240. if (empty($paramname)) return 'BadFirstParameterForGETPOST';
  241. if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
  242. elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
  243. elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
  244. elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
  245. elseif ($method==4) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:(isset($_COOKIE[$paramname])?$_COOKIE[$paramname]:''));
  246. else return 'BadThirdParameterForGETPOST';
  247. if (empty($method) || $method == 3 || $method == 4)
  248. {
  249. $relativepathstring = $_SERVER["PHP_SELF"];
  250. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
  251. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  252. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  253. // Retrieve values if restore_lastsearch_values is set and there is saved values
  254. if ($_GET['restore_lastsearch_values'] && ! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // Keep $_GET here
  255. {
  256. $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  257. if (is_array($tmp))
  258. {
  259. foreach($tmp as $key => $val)
  260. {
  261. if ($key == $paramname)
  262. {
  263. $out=$val;
  264. break;
  265. }
  266. }
  267. }
  268. }
  269. // Else, retreive default values if we are not doing a sort
  270. elseif (! isset($_GET['sortfield']) && ! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
  271. {
  272. if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  273. {
  274. if (! empty($user->default_values)) // $user->default_values defined from menu default values
  275. {
  276. //var_dump($user->default_values[$relativepathstring]['createform']);
  277. if (isset($user->default_values[$relativepathstring]['createform'][$paramname])) $out = $user->default_values[$relativepathstring]['createform'][$paramname];
  278. }
  279. }
  280. // Management of default search_filters and sort order
  281. //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  282. elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  283. {
  284. if (! empty($user->default_values)) // $user->default_values defined from menu default values
  285. {
  286. //var_dump($user->default_values[$relativepathstring]);
  287. if ($paramname == 'sortfield')
  288. {
  289. if (isset($user->default_values[$relativepathstring]['sortorder'])) // We will use the key of $user->default_values[path][sortorder]
  290. {
  291. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  292. foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val)
  293. {
  294. if ($out) $out.=', ';
  295. $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  296. }
  297. }
  298. }
  299. elseif ($paramname == 'sortorder')
  300. {
  301. if (isset($user->default_values[$relativepathstring]['sortorder'])) // We will use the val of $user->default_values[path][sortorder]
  302. {
  303. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  304. foreach($user->default_values[$relativepathstring]['sortorder'] as $key => $val)
  305. {
  306. if ($out) $out.=', ';
  307. $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  308. }
  309. }
  310. }
  311. elseif (isset($user->default_values[$relativepathstring]['filters'][$paramname]))
  312. {
  313. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  314. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$paramname], '', $forbidden_chars_to_replace);
  315. }
  316. }
  317. }
  318. }
  319. }
  320. if (empty($check) && ! empty($conf->global->MAIN_FEATURES_LEVEL) && $conf->global->MAIN_FEATURES_LEVEL >= 2)
  321. {
  322. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param not defined, when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  323. // Enable this line to know who call the GETPOST with empty $check parameter.
  324. //var_dump(debug_backtrace()[0]);
  325. }
  326. if (! empty($check))
  327. {
  328. // Replace vars like __DAY__, __MONTH__, __YEAR__, __MYCOUNTRYID__, __USERID__, __ENTITYID__, ...
  329. if (! is_array($out))
  330. {
  331. $maxloop=20; $loopnb=0; // Protection against infinite loop
  332. while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
  333. {
  334. $loopnb++; $newout = '';
  335. if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; }
  336. elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; }
  337. elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; }
  338. elseif ($reg[1] == 'PREVIOUS_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; }
  339. elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; }
  340. elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); }
  341. elseif ($reg[1] == 'NEXT_DAY') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['day']; }
  342. elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mday'], $tmp['mon'], $tmp['year']); $newout = $tmp2['month']; }
  343. elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); }
  344. elseif ($reg[1] == 'MYCOUNTRYID')
  345. {
  346. $newout = $mysoc->country_id;
  347. }
  348. elseif ($reg[1] == 'USERID')
  349. {
  350. $newout = $user->id;
  351. }
  352. elseif ($reg[1] == 'SUPERVISORID')
  353. {
  354. $newout = $user->fk_user;
  355. }
  356. elseif ($reg[1] == 'ENTITYID')
  357. {
  358. $newout = $conf->entity;
  359. }
  360. else $newout = ''; // Key not found, we replace with empty string
  361. //var_dump('__'.$reg[1].'__ -> '.$newout);
  362. $out = preg_replace('/__'.preg_quote($reg[1],'/').'__/', $newout, $out);
  363. }
  364. }
  365. // Check is done after replacement
  366. switch ($check)
  367. {
  368. case 'none':
  369. break;
  370. case 'int':
  371. if (! is_numeric($out)) { $out=''; }
  372. break;
  373. case 'alpha':
  374. $out=trim($out);
  375. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  376. // '../' is dangerous because it allows dir transversals
  377. if (preg_match('/"/',$out)) $out='';
  378. else if (preg_match('/\.\.\//',$out)) $out='';
  379. break;
  380. case 'san_alpha':
  381. $out=filter_var($out,FILTER_SANITIZE_STRING);
  382. break;
  383. case 'aZ':
  384. $out=trim($out);
  385. if (preg_match('/[^a-z]+/i',$out)) $out='';
  386. break;
  387. case 'aZ09':
  388. $out=trim($out);
  389. if (preg_match('/[^a-z0-9_\-]+/i',$out)) $out='';
  390. break;
  391. case 'array':
  392. if (! is_array($out) || empty($out)) $out=array();
  393. break;
  394. case 'nohtml':
  395. $out=dol_string_nohtmltag($out);
  396. break;
  397. case 'alphanohtml': // Recommended for search params
  398. $out=trim($out);
  399. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  400. // '../' is dangerous because it allows dir transversals
  401. if (preg_match('/"/',$out)) $out='';
  402. else if (preg_match('/\.\.\//',$out)) $out='';
  403. $out=dol_string_nohtmltag($out);
  404. break;
  405. case 'custom':
  406. if (empty($filter)) return 'BadFourthParameterForGETPOST';
  407. $out=filter_var($out, $filter, $options);
  408. break;
  409. }
  410. }
  411. // Code for search criteria persistence.
  412. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  413. if (empty($method) || $method == 3 || $method == 4)
  414. {
  415. //if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield", 'smonth', 'syear', 'month', 'year')))
  416. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield')))
  417. {
  418. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  419. // We save search key only if:
  420. // - not empty, or
  421. // - if value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not).
  422. //if (! empty($out) || ! empty($user->default_values[$relativepathstring]['filters'][$paramname]))
  423. if (! empty($out))
  424. {
  425. $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out;
  426. }
  427. }
  428. }
  429. return $out;
  430. }
  431. /**
  432. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  433. * This prefix is unique for instance and avoid conflict between multi-instances,
  434. * even when having two instances with one root dir or two instances in virtual servers.
  435. *
  436. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  437. * @return string A calculated prefix
  438. */
  439. function dol_getprefix($mode='')
  440. {
  441. global $conf;
  442. // If MAIL_PREFIX_FOR_EMAIL_ID is set and prefix is for email
  443. if ($mode == 'email' && ! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID))
  444. {
  445. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  446. else if (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"];
  447. }
  448. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"]))
  449. {
  450. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  451. // Use this for a "clear" cookie name
  452. //return dol_sanitizeFileName($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  453. }
  454. else return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  455. }
  456. /**
  457. * Make an include_once using default root and alternate root if it fails.
  458. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  459. * To link to a module file from a module file, use include './mymodulefile';
  460. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  461. *
  462. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  463. * @param string $classname Class name (deprecated)
  464. * @return bool True if load is a success, False if it fails
  465. */
  466. function dol_include_once($relpath, $classname='')
  467. {
  468. global $conf,$langs,$user,$mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var']
  469. $fullpath = dol_buildpath($relpath);
  470. if (!file_exists($fullpath)) {
  471. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_ERR);
  472. return false;
  473. }
  474. if (! empty($classname) && ! class_exists($classname)) {
  475. return include $fullpath;
  476. } else {
  477. return include_once $fullpath;
  478. }
  479. }
  480. /**
  481. * Return path of url or filesystem. Return alternate root if exists.
  482. *
  483. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  484. * @param int $type 0=Used for a Filesystem path, 1=Used for an URL path (output relative), 2=Used for an URL path (output full path using same host that current url), 3=Used for an URL path (output full path using host defined into $dolibarr_main_url_root of conf file)
  485. * @return string Full filesystem path (if mode=0), Full url path (if mode=1)
  486. */
  487. function dol_buildpath($path, $type=0)
  488. {
  489. global $conf;
  490. $path=preg_replace('/^\//','',$path);
  491. if (empty($type)) // For a filesystem path
  492. {
  493. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard value
  494. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  495. {
  496. if ($key == 'main') continue;
  497. if (file_exists($dirroot.'/'.$path))
  498. {
  499. $res=$dirroot.'/'.$path;
  500. break;
  501. }
  502. }
  503. }
  504. else // For an url path
  505. {
  506. // We try to get local path of file on filesystem from url
  507. // Note that trying to know if a file on disk exist by forging path on disk from url
  508. // works only for some web server and some setup. This is bugged when
  509. // using proxy, rewriting, virtual path, etc...
  510. $res='';
  511. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  512. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  513. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  514. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  515. {
  516. if ($key == 'main')
  517. {
  518. if ($type == 3)
  519. {
  520. global $dolibarr_main_url_root;
  521. // Define $urlwithroot
  522. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  523. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  524. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  525. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  526. }
  527. continue;
  528. }
  529. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  530. if (! empty($regs[1]))
  531. {
  532. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  533. if (file_exists($dirroot.'/'.$regs[1]))
  534. {
  535. if ($type == 1)
  536. {
  537. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  538. }
  539. if ($type == 2)
  540. {
  541. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  542. }
  543. if ($type == 3)
  544. {
  545. global $dolibarr_main_url_root;
  546. // Define $urlwithroot
  547. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  548. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  549. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  550. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax
  551. }
  552. break;
  553. }
  554. }
  555. }
  556. }
  557. return $res;
  558. }
  559. /**
  560. * Create a clone of instance of object (new instance with same properties)
  561. * This function works for both PHP4 and PHP5
  562. *
  563. * @param object $object Object to clone
  564. * @return object Object clone
  565. * @deprecated Dolibarr no longer supports PHP4, use PHP5 native clone construct
  566. * @see https://php.net/manual/language.oop5.cloning.php
  567. */
  568. function dol_clone($object)
  569. {
  570. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  571. $myclone = clone $object;
  572. return $myclone;
  573. }
  574. /**
  575. * Optimize a size for some browsers (phone, smarphone, ...)
  576. *
  577. * @param int $size Size we want
  578. * @param string $type Type of optimizing:
  579. * '' = function used to define a size for truncation
  580. * 'width' = function is used to define a width
  581. * @return int New size after optimizing
  582. */
  583. function dol_size($size,$type='')
  584. {
  585. global $conf;
  586. if (empty($conf->dol_optimize_smallscreen)) return $size;
  587. if ($type == 'width' && $size > 250) return 250;
  588. else return 10;
  589. }
  590. /**
  591. * Clean a string to use it as a file name
  592. *
  593. * @param string $str String to clean
  594. * @param string $newstr String to replace bad chars with
  595. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  596. * @return string String cleaned (a-zA-Z_)
  597. *
  598. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizePathName
  599. */
  600. function dol_sanitizeFileName($str,$newstr='_',$unaccent=1)
  601. {
  602. $filesystem_forbidden_chars = array('<','>',':','/','\\','?','*','|','"','°');
  603. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  604. }
  605. /**
  606. * Clean a string to use it as a path name
  607. *
  608. * @param string $str String to clean
  609. * @param string $newstr String to replace bad chars with
  610. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  611. * @return string String cleaned (a-zA-Z_)
  612. *
  613. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizeFileName
  614. */
  615. function dol_sanitizePathName($str,$newstr='_',$unaccent=1)
  616. {
  617. $filesystem_forbidden_chars = array('<','>','?','*','|','"','°');
  618. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  619. }
  620. /**
  621. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  622. *
  623. * @param string $str String to clean
  624. * @return string Cleaned string
  625. *
  626. * @see dol_sanitizeFilename, dol_string_nospecial
  627. */
  628. function dol_string_unaccent($str)
  629. {
  630. if (utf8_check($str))
  631. {
  632. // See http://www.utf8-chartable.de/
  633. $string = rawurlencode($str);
  634. $replacements = array(
  635. '%C3%80' => 'A','%C3%81' => 'A','%C3%82' => 'A','%C3%83' => 'A','%C3%84' => 'A','%C3%85' => 'A',
  636. '%C3%88' => 'E','%C3%89' => 'E','%C3%8A' => 'E','%C3%8B' => 'E',
  637. '%C3%8C' => 'I','%C3%8D' => 'I','%C3%8E' => 'I','%C3%8F' => 'I',
  638. '%C3%92' => 'O','%C3%93' => 'O','%C3%94' => 'O','%C3%95' => 'O','%C3%96' => 'O',
  639. '%C3%99' => 'U','%C3%9A' => 'U','%C3%9B' => 'U','%C3%9C' => 'U',
  640. '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a','%C3%A3' => 'a','%C3%A4' => 'a','%C3%A5' => 'a',
  641. '%C3%A7' => 'c',
  642. '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
  643. '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i','%C3%AF' => 'i',
  644. '%C3%B1' => 'n',
  645. '%C3%B2' => 'o','%C3%B3' => 'o','%C3%B4' => 'o','%C3%B5' => 'o','%C3%B6' => 'o',
  646. '%C3%B9' => 'u','%C3%BA' => 'u','%C3%BB' => 'u','%C3%BC' => 'u',
  647. '%C3%BF' => 'y'
  648. );
  649. $string=strtr($string, $replacements);
  650. return rawurldecode($string);
  651. }
  652. else
  653. {
  654. // See http://www.ascii-code.com/
  655. $string = strtr(
  656. $str,
  657. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  658. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  659. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  660. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  661. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  662. \xF9\xFA\xFB\xFC\xFD\xFF",
  663. "AAAAAAC
  664. EEEEIIIIDN
  665. OOOOOUUUY
  666. aaaaaaceeee
  667. iiiidnooooo
  668. uuuuyy"
  669. );
  670. $string = strtr($string, array("\xC4"=>"Ae", "\xC6"=>"AE", "\xD6"=>"Oe", "\xDC"=>"Ue", "\xDE"=>"TH", "\xDF"=>"ss", "\xE4"=>"ae", "\xE6"=>"ae", "\xF6"=>"oe", "\xFC"=>"ue", "\xFE"=>"th"));
  671. return $string;
  672. }
  673. }
  674. /**
  675. * Clean a string from all punctuation characters to use it as a ref or login
  676. *
  677. * @param string $str String to clean
  678. * @param string $newstr String to replace forbidden chars with
  679. * @param array $badcharstoreplace List of forbidden characters
  680. * @return string Cleaned string
  681. *
  682. * @see dol_sanitizeFilename, dol_string_unaccent
  683. */
  684. function dol_string_nospecial($str,$newstr='_',$badcharstoreplace='')
  685. {
  686. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",",",";","=");
  687. $forbidden_chars_to_remove=array();
  688. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace=$badcharstoreplace;
  689. //$forbidden_chars_to_remove=array("(",")");
  690. return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
  691. }
  692. /**
  693. * Encode string for xml usage
  694. *
  695. * @param string $string String to encode
  696. * @return string String encoded
  697. */
  698. function dolEscapeXML($string)
  699. {
  700. return strtr($string, array('\''=>'&apos;','"'=>'&quot;','&'=>'&amp;','<'=>'&lt;','>'=>'&gt;'));
  701. }
  702. /**
  703. * Returns text escaped for inclusion into javascript code
  704. *
  705. * @param string $stringtoescape String to escape
  706. * @param int $mode 0=Escape also ' and " into ', 1=Escape ' but not " for usage into 'string', 2=Escape " but not ' for usage into "string", 3=Escape ' and " with \
  707. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  708. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  709. */
  710. function dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
  711. {
  712. // escape quotes and backslashes, newlines, etc.
  713. $substitjs=array("&#039;"=>"\\'","\r"=>'\\r');
  714. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  715. if (empty($noescapebackslashn)) { $substitjs["\n"]='\\n'; $substitjs['\\']='\\\\'; }
  716. if (empty($mode)) { $substitjs["'"]="\\'"; $substitjs['"']="\\'"; }
  717. else if ($mode == 1) $substitjs["'"]="\\'";
  718. else if ($mode == 2) { $substitjs['"']='\\"'; }
  719. else if ($mode == 3) { $substitjs["'"]="\\'"; $substitjs['"']="\\\""; }
  720. return strtr($stringtoescape, $substitjs);
  721. }
  722. /**
  723. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  724. *
  725. * @param string $stringtoescape String to escape
  726. * @param int $keepb 1=Preserve b tags (otherwise, remove them)
  727. * @param int $keepn 1=Preserve \r\n strings (otherwise, remove them)
  728. * @return string Escaped string
  729. *
  730. * @see dol_string_nohtmltag
  731. */
  732. function dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0)
  733. {
  734. // escape quotes and backslashes, newlines, etc.
  735. $tmp=dol_html_entity_decode($stringtoescape,ENT_COMPAT,'UTF-8');
  736. if (! $keepb) $tmp=strtr($tmp, array("<b>"=>'','</b>'=>''));
  737. if (! $keepn) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n'));
  738. return dol_htmlentities($tmp,ENT_COMPAT,'UTF-8');
  739. }
  740. /**
  741. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  742. *
  743. * @param string $utf8_string String to encode
  744. * @return string String converted
  745. */
  746. function dol_strtolower($utf8_string)
  747. {
  748. return mb_strtolower($utf8_string, "UTF-8");
  749. }
  750. /**
  751. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  752. *
  753. * @param string $utf8_string String to encode
  754. * @return string String converted
  755. */
  756. function dol_strtoupper($utf8_string)
  757. {
  758. return mb_strtoupper($utf8_string, "UTF-8");
  759. }
  760. /**
  761. * Write log message into outputs. Possible outputs can be:
  762. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  763. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  764. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  765. * this, use logging to files instead of syslog (see setup of module).
  766. * Note: If SYSLOG_FILE_NO_ERROR defined, we never output any error message when writing to log fails.
  767. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  768. * This function works only if syslog module is enabled.
  769. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  770. *
  771. * @param string $message Line to log. ''=Show nothing
  772. * @param int $level Log level
  773. * On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 si define_syslog_variables ou PHP 5.3+, 7 si dolibarr
  774. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  775. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  776. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  777. * @param string $restricttologhandler Output log only for this log handler
  778. * @return void
  779. */
  780. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename='', $restricttologhandler='')
  781. {
  782. global $conf, $user;
  783. // If syslog module enabled
  784. if (empty($conf->syslog->enabled)) return;
  785. if (! empty($message))
  786. {
  787. // Test log level
  788. $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG);
  789. if (!in_array($level, $logLevels, true))
  790. {
  791. throw new Exception('Incorrect log level');
  792. }
  793. if ($level > $conf->global->SYSLOG_LEVEL) return;
  794. // If adding log inside HTML page is required
  795. if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility
  796. {
  797. $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
  798. }
  799. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  800. // If enable html log tag enabled and url parameter log defined, we show output log on HTML comments
  801. if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"]))
  802. {
  803. print "\n\n<!-- Log start\n";
  804. print $message."\n";
  805. print "Log end -->\n";
  806. }
  807. $data = array(
  808. 'message' => $message,
  809. 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false),
  810. 'level' => $level,
  811. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  812. 'ip' => false
  813. );
  814. // This is when server run behind a reverse proxy
  815. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']);
  816. // This is when server run normally on a server
  817. else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR'];
  818. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  819. else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  820. // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it).
  821. else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']);
  822. // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
  823. else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  824. // Loop on each log handler and send output
  825. foreach ($conf->loghandlers as $loghandlerinstance)
  826. {
  827. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  828. $loghandlerinstance->export($data,$suffixinfilename);
  829. }
  830. unset($data);
  831. }
  832. if (! empty($ident))
  833. {
  834. foreach ($conf->loghandlers as $loghandlerinstance)
  835. {
  836. $loghandlerinstance->setIdent($ident);
  837. }
  838. }
  839. }
  840. /**
  841. * Show tab header of a card
  842. *
  843. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  844. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  845. * @param string $title Title
  846. * @param int $notab -1 or 0=Add tab header, 1=no tab header. If you set this to 1, using dol_fiche_end() to close tab is not required.
  847. * @param string $picto Add a picto on tab title
  848. * @param int $pictoisfullpath If 1, image path is a full path. If you set this to 1, you can use url returned by dol_buildpath('/mymodyle/img/myimg.png',1) for $picto.
  849. * @return void
  850. */
  851. function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0)
  852. {
  853. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath);
  854. }
  855. /**
  856. * Show tab header of a card
  857. *
  858. * @param array $links Array of tabs
  859. * @param string $active Active tab name
  860. * @param string $title Title
  861. * @param int $notab -1 or 0=Add tab header, 1=no tab header. If you set this to 1, using dol_fiche_end() to close tab is not required.
  862. * @param string $picto Add a picto on tab title
  863. * @param int $pictoisfullpath If 1, image path is a full path. If you set this to 1, you can use url returned by dol_buildpath('/mymodyle/img/myimg.png',1) for $picto.
  864. * @return string
  865. */
  866. function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0)
  867. {
  868. global $conf, $langs, $hookmanager;
  869. $out="\n".'<div class="tabs" data-role="controlgroup" data-type="horizontal">'."\n";
  870. // Show title
  871. $showtitle=1;
  872. if (! empty($conf->dol_optimize_smallscreen)) $showtitle=0;
  873. if (! empty($title) && $showtitle)
  874. {
  875. $limittitle=30;
  876. $out.='<a class="tabTitle">';
  877. if ($picto) $out.=img_picto($title,($pictoisfullpath?'':'object_').$picto,'',$pictoisfullpath).' ';
  878. $out.='<span class="tabTitleText">'.dol_trunc($title,$limittitle).'</span>';
  879. $out.='</a>';
  880. }
  881. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  882. $maxkey=-1;
  883. if (is_array($links) && ! empty($links))
  884. {
  885. $keys=array_keys($links);
  886. if (count($keys)) $maxkey=max($keys);
  887. }
  888. // Show tabs
  889. $bactive=false;
  890. // if =0 we don't use the feature
  891. $limittoshow=(empty($conf->global->MAIN_MAXTABS_IN_CARD)?99:$conf->global->MAIN_MAXTABS_IN_CARD);
  892. $displaytab=0;
  893. $nbintab=0;
  894. $popuptab=0; $outmore='';
  895. for ($i = 0 ; $i <= $maxkey ; $i++)
  896. {
  897. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  898. {
  899. // si l'active est présent dans la box
  900. if ($i >= $limittoshow)
  901. $limittoshow--;
  902. }
  903. }
  904. for ($i = 0 ; $i <= $maxkey ; $i++)
  905. {
  906. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  907. {
  908. $isactive=true;
  909. $bactive=true;
  910. }
  911. else
  912. $isactive=false;
  913. if ($i < $limittoshow || $isactive)
  914. {
  915. $out.='<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((! $isactive && ! empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT))?' hideonprint':'').'"><!-- id tab = '.(empty($links[$i][2])?'':$links[$i][2]).' -->';
  916. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  917. {
  918. if (!empty($links[$i][0]))
  919. {
  920. $out.='<a data-role="button" class="tabimage" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  921. }
  922. else
  923. {
  924. $out.='<span data-role="button" class="tabspan">'.$links[$i][1].'</span>'."\n";
  925. }
  926. }
  927. else if (! empty($links[$i][1]))
  928. {
  929. //print "x $i $active ".$links[$i][2]." z";
  930. if ($isactive)
  931. {
  932. $out.='<a data-role="button"'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabactive tab inline-block" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  933. }
  934. else
  935. {
  936. $out.='<a data-role="button"'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabunactive tab inline-block" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  937. }
  938. }
  939. $out.='</div>';
  940. }
  941. else
  942. {
  943. // The popup with the other tabs
  944. if (! $popuptab)
  945. {
  946. $popuptab=1;
  947. $outmore.='<div class="popuptabset">';
  948. }
  949. $outmore.='<div class="popuptab" style="display:inherit;">';
  950. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  951. {
  952. if (!empty($links[$i][0]))
  953. $outmore.='<a class="tabimage" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  954. else
  955. $outmore.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  956. }
  957. else if (! empty($links[$i][1]))
  958. $outmore.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="inline-block" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  959. $outmore.='</div>';
  960. $nbintab++;
  961. }
  962. $displaytab=$i;
  963. }
  964. if ($popuptab) $outmore.='</div>';
  965. if ($displaytab > $limittoshow)
  966. {
  967. $tabsname=str_replace("@", "", $picto);
  968. $out.='<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  969. $out.='<a href="#" data-role="button" class="tab moretab inline-block">'.$langs->trans("More").'... ('.$nbintab.')</a>';
  970. $out.='<div id="moretabsList'.$tabsname.'" style="position: absolute; left: -999em;text-align: left;margin:0px;padding:2px">'.$outmore.'</div>';
  971. $out.="</div>\n";
  972. $out.="<script>";
  973. $out.="$('#moretabs".$tabsname."').mouseenter( function() { $('#moretabsList".$tabsname."').css('left','auto');});";
  974. $out.="$('#moretabs".$tabsname."').mouseleave( function() { $('#moretabsList".$tabsname."').css('left','-999em');});";
  975. $out.="</script>";
  976. }
  977. $out.="</div>\n";
  978. if (! $notab || $notab == -1) $out.="\n".'<div class="tabBar'.($notab == -1 ? '' : ' tabBarWithBottom').'">'."\n";
  979. $parameters=array('tabname' => $active, 'out' => $out);
  980. $reshook=$hookmanager->executeHooks('printTabsHead',$parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  981. if ($reshook > 0)
  982. {
  983. $out = $hookmanager->resPrint;
  984. }
  985. return $out;
  986. }
  987. /**
  988. * Show tab footer of a card
  989. *
  990. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  991. * @return void
  992. */
  993. function dol_fiche_end($notab=0)
  994. {
  995. print dol_get_fiche_end($notab);
  996. }
  997. /**
  998. * Return tab footer of a card
  999. *
  1000. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1001. * @return string
  1002. */
  1003. function dol_get_fiche_end($notab=0)
  1004. {
  1005. if (! $notab || $notab == -1) return "\n</div>\n";
  1006. else return '';
  1007. }
  1008. /**
  1009. * Show tab footer of a card
  1010. *
  1011. * @param object $object Object to show
  1012. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1013. * @param string $morehtml More html content to output just before the nav bar
  1014. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1015. * @param string $fieldid Nom du champ en base a utiliser pour select next et previous (we make the select max and min on this field)
  1016. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1017. * @param string $morehtmlref More html to show after ref
  1018. * @param string $moreparam More param to add in nav link url.
  1019. * @param int $nodbprefix Do not include DB prefix to forge table name
  1020. * @param string $morehtmlleft More html code to show before ref
  1021. * @param string $morehtmlstatus More html code to show under navigation arrows
  1022. * @param int $onlybanner Put this to 1, if the card will contains only a banner (add css 'arearefnobottom' on div)
  1023. * @param string $morehtmlright More html code to show before navigation arrows
  1024. * @return void
  1025. */
  1026. function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
  1027. {
  1028. global $conf, $form, $user, $langs;
  1029. $error = 0;
  1030. $maxvisiblephotos=1;
  1031. $showimage=1;
  1032. $showbarcode=empty($conf->barcode->enabled)?0:($object->barcode?1:0);
  1033. if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;
  1034. $modulepart='unknown';
  1035. if ($object->element == 'societe') $modulepart='societe';
  1036. if ($object->element == 'contact') $modulepart='contact';
  1037. if ($object->element == 'member') $modulepart='memberphoto';
  1038. if ($object->element == 'user') $modulepart='userphoto';
  1039. if ($object->element == 'product') $modulepart='product';
  1040. if (class_exists("Imagick"))
  1041. {
  1042. if ($object->element == 'propal') $modulepart='propal';
  1043. if ($object->element == 'commande') $modulepart='commande';
  1044. if ($object->element == 'facture') $modulepart='facture';
  1045. if ($object->element == 'fichinter') $modulepart='ficheinter';
  1046. if ($object->element == 'contrat') $modulepart='contract';
  1047. if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal';
  1048. if ($object->element == 'order_supplier') $modulepart='supplier_order';
  1049. if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice';
  1050. }
  1051. if ($object->element == 'product')
  1052. {
  1053. $width=80; $cssclass='photoref';
  1054. $showimage=$object->is_photo_available($conf->product->multidir_output[$object->entity]);
  1055. $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5);
  1056. if ($conf->browser->phone) $maxvisiblephotos=1;
  1057. if ($showimage) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos($conf->product->multidir_output[$object->entity],'small',$maxvisiblephotos,0,0,0,$width,0).'</div>';
  1058. else
  1059. {
  1060. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1061. $nophoto='';
  1062. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1063. }
  1064. elseif ($conf->browser->layout != 'phone') { // Show no photo link
  1065. $nophoto='/public/theme/common/nophoto.png';
  1066. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1067. }
  1068. }
  1069. }
  1070. else
  1071. {
  1072. if ($showimage)
  1073. {
  1074. if ($modulepart != 'unknown')
  1075. {
  1076. $phototoshow='';
  1077. // Check if a preview file is available
  1078. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice')) && class_exists("Imagick"))
  1079. {
  1080. $objectref = dol_sanitizeFileName($object->ref);
  1081. $dir_output = $conf->$modulepart->dir_output . "/";
  1082. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1083. {
  1084. $subdir = get_exdir($object->id, 2, 0, 0, $object, $modulepart).$objectref;
  1085. }
  1086. else
  1087. {
  1088. $subdir = get_exdir($object->id, 0, 0, 0, $object, $modulepart).$objectref;
  1089. }
  1090. $filepath = $dir_output . $subdir . "/";
  1091. $file = $filepath . $objectref . ".pdf";
  1092. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1093. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1094. $fileimage = $file.'_preview.png'; // If PDF has 1 page
  1095. $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page
  1096. $relativepathimage = $relativepath.'_preview.png';
  1097. // Si fichier PDF existe
  1098. if (file_exists($file))
  1099. {
  1100. $encfile = urlencode($file);
  1101. // Conversion du PDF en image png si fichier png non existant
  1102. if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file)))
  1103. && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file)))
  1104. )
  1105. {
  1106. $ret = dol_convert_file($file, 'png', $fileimage);
  1107. if ($ret < 0) $error++;
  1108. }
  1109. // Si fichier png PDF d'1 page trouve
  1110. if (file_exists($fileimage))
  1111. {
  1112. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1113. $phototoshow.= '<img height="70" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1114. $phototoshow.= '</div></div>';
  1115. }
  1116. // Si fichier png PDF de plus d'1 page trouve
  1117. elseif (file_exists($fileimagebis))
  1118. {
  1119. $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png";
  1120. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1121. $phototoshow.= '<img height="70" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
  1122. $phototoshow.= '</div></div>';
  1123. }
  1124. }
  1125. }
  1126. else if (! $phototoshow)
  1127. {
  1128. $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos);
  1129. }
  1130. if ($phototoshow)
  1131. {
  1132. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1133. $morehtmlleft.=$phototoshow;
  1134. $morehtmlleft.='</div>';
  1135. }
  1136. }
  1137. if (! $phototoshow && $conf->browser->layout != 'phone') // Show No photo link (picto of pbject)
  1138. {
  1139. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1140. if ($object->element == 'action')
  1141. {
  1142. $width=80;
  1143. $cssclass='photorefcenter';
  1144. $nophoto=img_picto('', 'title_agenda', '', false, 1);
  1145. }
  1146. else
  1147. {
  1148. $width=14; $cssclass='photorefcenter';
  1149. $picto = $object->picto;
  1150. if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub
  1151. $nophoto=img_picto('', 'object_'.$picto, '', false, 1);
  1152. }
  1153. $morehtmlleft.='<!-- No photo to show --><div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" border="0"'.($width?' width="'.$width.'"':'').' src="'.$nophoto.'"></div></div>';
  1154. $morehtmlleft.='</div>';
  1155. }
  1156. }
  1157. }
  1158. if ($showbarcode) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1159. if ($object->element == 'societe')
  1160. {
  1161. if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1162. {
  1163. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1164. }
  1165. }
  1166. elseif ($object->element == 'product')
  1167. {
  1168. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1169. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1170. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1171. } else {
  1172. $morehtmlstatus.=$object->getLibStatut(5,0);
  1173. }
  1174. $morehtmlstatus.=' &nbsp; ';
  1175. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1176. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1177. $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1178. } else {
  1179. $morehtmlstatus.=$object->getLibStatut(5,1);
  1180. }
  1181. }
  1182. elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan')))
  1183. {
  1184. $tmptxt=$object->getLibStatut(6, $object->totalpaye);
  1185. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye);
  1186. $morehtmlstatus.=$tmptxt;
  1187. }
  1188. elseif ($object->element == 'contrat' || $object->element == 'contract')
  1189. {
  1190. if ($object->statut==0) $morehtmlstatus.=$object->getLibStatut(2);
  1191. else $morehtmlstatus.=$object->getLibStatut(4);
  1192. }
  1193. else { // Generic case
  1194. $tmptxt=$object->getLibStatut(6);
  1195. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5);
  1196. $morehtmlstatus.=$tmptxt;
  1197. }
  1198. if (! empty($object->name_alias)) $morehtmlref.='<div class="refidno">'.$object->name_alias.'</div>'; // For thirdparty
  1199. // Add label
  1200. if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task')
  1201. {
  1202. if (! empty($object->label)) $morehtmlref.='<div class="refidno">'.$object->label.'</div>';
  1203. }
  1204. if ($object->element != 'product' && $object->element != 'bookmark')
  1205. {
  1206. $morehtmlref.='<div class="refidno">';
  1207. $morehtmlref.=$object->getBannerAddress('refaddress',$object);
  1208. $morehtmlref.='</div>';
  1209. }
  1210. if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product')))
  1211. {
  1212. $morehtmlref.='<div style="clear: both;"></div><div class="refidno">';
  1213. $morehtmlref.=$langs->trans("TechnicalID").': '.$object->id;
  1214. $morehtmlref.='</div>';
  1215. }
  1216. print '<div class="'.($onlybanner?'arearefnobottom ':'arearef ').'heightref valignmiddle" width="100%">';
  1217. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1218. print '</div>';
  1219. print '<div class="underrefbanner clearboth"></div>';
  1220. }
  1221. /**
  1222. * Show a string with the label tag dedicated to the HTML edit field.
  1223. *
  1224. * @param string $langkey Translation key
  1225. * @param string $fieldkey Key of the html select field the text refers to
  1226. * @param int $fieldrequired 1=Field is mandatory
  1227. * @deprecated Form::editfieldkey
  1228. */
  1229. function fieldLabel($langkey, $fieldkey, $fieldrequired=0)
  1230. {
  1231. global $conf, $langs;
  1232. $ret='';
  1233. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  1234. if (($conf->dol_use_jmobile != 4)) $ret.='<label for="'.$fieldkey.'">';
  1235. $ret.=$langs->trans($langkey);
  1236. if (($conf->dol_use_jmobile != 4)) $ret.='</label>';
  1237. if ($fieldrequired) $ret.='</span>';
  1238. return $ret;
  1239. }
  1240. /**
  1241. * Return string to add class property on html element with pair/impair.
  1242. *
  1243. * @param string $var 0 or 1
  1244. * @param string $moreclass More class to add
  1245. * @return string String to add class onto HTML element
  1246. */
  1247. function dol_bc($var,$moreclass='')
  1248. {
  1249. global $bc;
  1250. $ret=' '.$bc[$var];
  1251. if ($moreclass) $ret=preg_replace('/class=\"/','class="'.$moreclass.' ',$ret);
  1252. return $ret;
  1253. }
  1254. /**
  1255. * Return a formated address (part address/zip/town/state) according to country rules
  1256. *
  1257. * @param Object $object A company or contact object
  1258. * @param int $withcountry 1=Add country into address string
  1259. * @param string $sep Separator to use to build string
  1260. * @param Translate $outputlangs Object lang that contains language for text translation.
  1261. * @return string Formated string
  1262. * @see dol_print_address
  1263. */
  1264. function dol_format_address($object,$withcountry=0,$sep="\n",$outputlangs='')
  1265. {
  1266. global $conf,$langs;
  1267. $ret='';
  1268. $countriesusingstate=array('AU','CA','US','IN','GB','ES','UK','TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1269. // Address
  1270. $ret .= $object->address;
  1271. // Zip/Town/State
  1272. if (in_array($object->country_code,array('AU', 'CA', 'US')) || ! empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) // US: title firstname name \n address lines \n town, state, zip \n country
  1273. {
  1274. $ret .= ($ret ? $sep : '' ).$object->town;
  1275. if ($object->state)
  1276. {
  1277. $ret.=($ret?", ":'').$object->state;
  1278. }
  1279. if ($object->zip) $ret .= ($ret?", ":'').$object->zip;
  1280. }
  1281. else if (in_array($object->country_code,array('GB','UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country
  1282. {
  1283. $ret .= ($ret ? $sep : '' ).$object->town;
  1284. if ($object->state)
  1285. {
  1286. $ret.=($ret?", ":'').$object->state;
  1287. }
  1288. if ($object->zip) $ret .= ($ret ? $sep : '' ).$object->zip;
  1289. }
  1290. else if (in_array($object->country_code,array('ES','TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country
  1291. {
  1292. $ret .= ($ret ? $sep : '' ).$object->zip;
  1293. $ret .= ($object->town?(($object->zip?' ':'').$object->town):'');
  1294. if ($object->state)
  1295. {
  1296. $ret.="\n".$object->state;
  1297. }
  1298. }
  1299. else // Other: title firstname name \n address lines \n zip town \n country
  1300. {
  1301. $ret .= $object->zip ? (($ret ? $sep : '' ).$object->zip) : '';
  1302. $ret .= ($object->town?(($object->zip?' ':($ret ? $sep : '' )).$object->town):'');
  1303. if ($object->state && in_array($object->country_code,$countriesusingstate))
  1304. {
  1305. $ret.=($ret?", ":'').$object->state;
  1306. }
  1307. }
  1308. if (! is_object($outputlangs)) $outputlangs=$langs;
  1309. if ($withcountry) $ret.=($object->country_code?($ret?$sep:'').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)):'');
  1310. return $ret;
  1311. }
  1312. /**
  1313. * Format a string.
  1314. *
  1315. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1316. * @param int $ts Timesamp (If is_gmt is true, timestamp is already includes timezone and daylight saving offset, if is_gmt is false, timestamp is a GMT timestamp and we must compensate with server PHP TZ)
  1317. * @param int $is_gmt See comment of timestamp parameter
  1318. * @return string A formatted string
  1319. */
  1320. function dol_strftime($fmt, $ts=false, $is_gmt=false)
  1321. {
  1322. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1323. return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
  1324. }
  1325. else return 'Error date into a not supported range';
  1326. }
  1327. /**
  1328. * Output date in a string format according to outputlangs (or langs if not defined).
  1329. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1330. *
  1331. * @param int $time GM Timestamps date
  1332. * @param string $format Output date format (tag of strftime function)
  1333. * "%d %b %Y",
  1334. * "%d/%m/%Y %H:%M",
  1335. * "%d/%m/%Y %H:%M:%S",
  1336. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1337. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1338. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1339. * false or 'tzserver' => output string is for local PHP server TZ usage
  1340. * 'tzuser' => output string is for user TZ (current browser TZ with current dst)
  1341. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  1342. * @param Translate $outputlangs Object lang that contains language for text translation.
  1343. * @param boolean $encodetooutput false=no convert into output pagecode
  1344. * @return string Formated date or '' if time is null
  1345. *
  1346. * @see dol_mktime, dol_stringtotime, dol_getdate
  1347. */
  1348. function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
  1349. {
  1350. global $conf,$langs;
  1351. // Clean parameters
  1352. $to_gmt=false;
  1353. $offsettz=$offsetdst=0;
  1354. if ($tzoutput)
  1355. {
  1356. $to_gmt=true; // For backward compatibility
  1357. if (is_string($tzoutput))
  1358. {
  1359. if ($tzoutput == 'tzserver')
  1360. {
  1361. $to_gmt=false;
  1362. $offsettzstring=@date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1363. $offsettz=0;
  1364. $offsetdst=0;
  1365. }
  1366. elseif ($tzoutput == 'tzuser')
  1367. {
  1368. $to_gmt=true;
  1369. $offsettzstring=(empty($_SESSION['dol_tz_string'])?'UTC':$_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1370. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
  1371. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
  1372. }
  1373. }
  1374. }
  1375. if (! is_object($outputlangs)) $outputlangs=$langs;
  1376. if (! $format) $format='daytextshort';
  1377. $reduceformat=(! empty($conf->dol_optimize_smallscreen) && in_array($format,array('day','dayhour')))?1:0;
  1378. $formatwithoutreduce = preg_replace('/reduceformat/','',$format);
  1379. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat=1; } // so format 'dayreduceformat' is processed like day
  1380. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1381. // TODO Add format daysmallyear and dayhoursmallyear
  1382. if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
  1383. else if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
  1384. else if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
  1385. else if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
  1386. else if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
  1387. else if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
  1388. else if ($format == 'dayhoursec') $format=($outputlangs->trans("FormatDateHourSecShort")!="FormatDateHourSecShort"?$outputlangs->trans("FormatDateHourSecShort"):$conf->format_date_hour_sec_short);
  1389. else if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
  1390. else if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
  1391. // Format not sensitive to language
  1392. else if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
  1393. else if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
  1394. else if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
  1395. else if ($format == 'dayxcard') $format='%Y%m%d';
  1396. else if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
  1397. else if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1398. else if ($format == 'standard') $format='%Y-%m-%d %H:%M:%S';
  1399. if ($reduceformat)
  1400. {
  1401. $format=str_replace('%Y','%y',$format);
  1402. $format=str_replace('yyyy','yy',$format);
  1403. }
  1404. // If date undefined or "", we return ""
  1405. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1406. // Clean format
  1407. if (preg_match('/%b/i',$format)) // There is some text to translate
  1408. {
  1409. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1410. $format=str_replace('%b','__b__',$format);
  1411. $format=str_replace('%B','__B__',$format);
  1412. }
  1413. if (preg_match('/%a/i',$format)) // There is some text to translate
  1414. {
  1415. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1416. $format=str_replace('%a','__a__',$format);
  1417. $format=str_replace('%A','__A__',$format);
  1418. }
  1419. // Analyze date
  1420. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
  1421. || preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i',$time,$reg)) // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
  1422. {
  1423. // This part of code should not be used. TODO Remove this.
  1424. dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  1425. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
  1426. $syear = (! empty($reg[1]) ? $reg[1] : '');
  1427. $smonth = (! empty($reg[2]) ? $reg[2] : '');
  1428. $sday = (! empty($reg[3]) ? $reg[3] : '');
  1429. $shour = (! empty($reg[4]) ? $reg[4] : '');
  1430. $smin = (! empty($reg[5]) ? $reg[5] : '');
  1431. $ssec = (! empty($reg[6]) ? $reg[6] : '');
  1432. $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
  1433. $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt);
  1434. }
  1435. else
  1436. {
  1437. // Date is a timestamps
  1438. if ($time < 100000000000) // Protection against bad date values
  1439. {
  1440. $ret=adodb_strftime($format,$time+$offsettz+$offsetdst,$to_gmt); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1441. }
  1442. else $ret='Bad value '.$time.' for date';
  1443. }
  1444. if (preg_match('/__b__/i',$format))
  1445. {
  1446. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1447. $month=adodb_strftime('%m',$time+$offsettz+$offsetdst); // TODO Remove this
  1448. if ($encodetooutput)
  1449. {
  1450. $monthtext=$outputlangs->transnoentities('Month'.$month);
  1451. $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
  1452. }
  1453. else
  1454. {
  1455. $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
  1456. $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1457. }
  1458. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1459. $ret=str_replace('__b__',$monthtextshort,$ret);
  1460. $ret=str_replace('__B__',$monthtext,$ret);
  1461. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1462. //return $ret;
  1463. }
  1464. if (preg_match('/__a__/i',$format))
  1465. {
  1466. $w=adodb_strftime('%w',$time+$offsettz+$offsetdst); // TODO Remove this
  1467. $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
  1468. $ret=str_replace('__A__',$dayweek,$ret);
  1469. $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
  1470. }
  1471. return $ret;
  1472. }
  1473. /**
  1474. * Return an array with locale date info.
  1475. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1476. * WARNING: This function always use PHP server timezone to return locale informations !!!
  1477. * Usage must be avoid.
  1478. * FIXME: Replace this with PHP date function and a parameter $gm
  1479. *
  1480. * @param int $timestamp Timestamp
  1481. * @param boolean $fast Fast mode
  1482. * @return array Array of informations
  1483. * If no fast mode:
  1484. * 'seconds' => $secs,
  1485. * 'minutes' => $min,
  1486. * 'hours' => $hour,
  1487. * 'mday' => $day,
  1488. * 'wday' => $dow, 0=sunday, 6=saturday
  1489. * 'mon' => $month,
  1490. * 'year' => $year,
  1491. * 'yday' => floor($secsInYear/$_day_power),
  1492. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  1493. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  1494. * If fast mode:
  1495. * 'seconds' => $secs,
  1496. * 'minutes' => $min,
  1497. * 'hours' => $hour,
  1498. * 'mday' => $day,
  1499. * 'mon' => $month,
  1500. * 'year' => $year,
  1501. * 'yday' => floor($secsInYear/$_day_power),
  1502. * 'leap' => $leaf,
  1503. * 'ndays' => $ndays
  1504. * @see dol_print_date, dol_stringtotime, dol_mktime
  1505. */
  1506. function dol_getdate($timestamp,$fast=false)
  1507. {
  1508. global $conf;
  1509. $usealternatemethod=false;
  1510. if ($timestamp <= 0) $usealternatemethod=true; // <= 1970
  1511. if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038
  1512. if ($usealternatemethod)
  1513. {
  1514. $arrayinfo=adodb_getdate($timestamp,$fast);
  1515. }
  1516. else
  1517. {
  1518. $arrayinfo=getdate($timestamp);
  1519. }
  1520. return $arrayinfo;
  1521. }
  1522. /**
  1523. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  1524. * Replace function mktime not available under Windows if year < 1970
  1525. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1526. *
  1527. * @param int $hour Hour (can be -1 for undefined)
  1528. * @param int $minute Minute (can be -1 for undefined)
  1529. * @param int $second Second (can be -1 for undefined)
  1530. * @param int $month Month (1 to 12)
  1531. * @param int $day Day (1 to 31)
  1532. * @param int $year Year
  1533. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  1534. * False or 0 or 'server' = local to server TZ
  1535. * 'user' = local to user TZ
  1536. * 'tz,TimeZone' = use specified timezone
  1537. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  1538. * @return int|string Date as a timestamp, '' or false if error
  1539. * @see dol_print_date, dol_stringtotime, dol_getdate
  1540. */
  1541. function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
  1542. {
  1543. global $conf;
  1544. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  1545. // Clean parameters
  1546. if ($hour == -1 || empty($hour)) $hour=0;
  1547. if ($minute == -1 || empty($minute)) $minute=0;
  1548. if ($second == -1 || empty($second)) $second=0;
  1549. // Check parameters
  1550. if ($check)
  1551. {
  1552. if (! $month || ! $day) return '';
  1553. if ($day > 31) return '';
  1554. if ($month > 12) return '';
  1555. if ($hour < 0 || $hour > 24) return '';
  1556. if ($minute< 0 || $minute > 60) return '';
  1557. if ($second< 0 || $second > 60) return '';
  1558. }
  1559. if (method_exists('DateTime','getTimestamp'))
  1560. {
  1561. if (empty($gm) || $gm === 'server')
  1562. {
  1563. $default_timezone=@date_default_timezone_get(); // Example 'Europe/Berlin'
  1564. $localtz = new DateTimeZone($default_timezone);
  1565. }
  1566. else if ($gm === 'user')
  1567. {
  1568. // We use dol_tz_string first because it is more reliable.
  1569. $default_timezone=(empty($_SESSION["dol_tz_string"])?@date_default_timezone_get():$_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  1570. try {
  1571. $localtz = new DateTimeZone($default_timezone);
  1572. }
  1573. catch(Exception $e)
  1574. {
  1575. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  1576. $default_timezone=@date_default_timezone_get();
  1577. }
  1578. }
  1579. else if (strrpos($gm, "tz,") !== false)
  1580. {
  1581. $timezone=str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  1582. try
  1583. {
  1584. $localtz = new DateTimeZone($timezone);
  1585. }
  1586. catch(Exception $e)
  1587. {
  1588. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  1589. }
  1590. }
  1591. if (empty($localtz)) {
  1592. $localtz = new DateTimeZone('UTC');
  1593. }
  1594. $dt = new DateTime(null,$localtz);
  1595. $dt->setDate($year,$month,$day);
  1596. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  1597. $date=$dt->getTimestamp(); // should include daylight saving time
  1598. return $date;
  1599. }
  1600. else
  1601. {
  1602. dol_print_error('','PHP version must be 5.3+');
  1603. return '';
  1604. }
  1605. }
  1606. /**
  1607. * Return date for now. In mot cases, we use this function without parameters (that means GMT time).
  1608. *
  1609. * @param string $mode 'gmt' => we return GMT timestamp,
  1610. * 'tzserver' => we add the PHP server timezone
  1611. * 'tzref' => we add the company timezone
  1612. * 'tzuser' => we add the user timezone
  1613. * @return int $date Timestamp
  1614. */
  1615. function dol_now($mode='gmt')
  1616. {
  1617. $ret='';
  1618. // Note that gmmktime and mktime return same value (GMT) when used without parameters
  1619. //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead
  1620. if ($mode == 'gmt') $ret=time(); // Time for now at greenwich.
  1621. else if ($mode == 'tzserver') // Time for now with PHP server timezone added
  1622. {
  1623. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1624. $tzsecond=getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  1625. $ret=dol_now('gmt')+($tzsecond*3600);
  1626. }
  1627. /*else if ($mode == 'tzref') // Time for now with parent company timezone is added
  1628. {
  1629. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1630. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  1631. $ret=dol_now('gmt')+($tzsecond*3600);
  1632. }*/
  1633. else if ($mode == 'tzuser') // Time for now with user timezone added
  1634. {
  1635. //print 'eeee'.time().'-'.mktime().'-'.gmmktime();
  1636. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
  1637. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
  1638. $ret=dol_now('gmt')+($offsettz+$offsetdst);
  1639. }
  1640. return $ret;
  1641. }
  1642. /**
  1643. * Return string with formated size
  1644. *
  1645. * @param int $size Size to print
  1646. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1647. * @param int $shortunit Use short value of size unit
  1648. * @return string Link
  1649. */
  1650. function dol_print_size($size,$shortvalue=0,$shortunit=0)
  1651. {
  1652. global $conf,$langs;
  1653. $level=1024;
  1654. if (! empty($conf->dol_optimize_smallscreen)) $shortunit=1;
  1655. // Set value text
  1656. if (empty($shortvalue) || $size < ($level*10))
  1657. {
  1658. $ret=$size;
  1659. $textunitshort=$langs->trans("b");
  1660. $textunitlong=$langs->trans("Bytes");
  1661. }
  1662. else
  1663. {
  1664. $ret=round($size/$level,0);
  1665. $textunitshort=$langs->trans("Kb");
  1666. $textunitlong=$langs->trans("KiloBytes");
  1667. }
  1668. // Use long or short text unit
  1669. if (empty($shortunit)) { $ret.=' '.$textunitlong; }
  1670. else { $ret.=' '.$textunitshort; }
  1671. return $ret;
  1672. }
  1673. /**
  1674. * Show Url link
  1675. *
  1676. * @param string $url Url to show
  1677. * @param string $target Target for link
  1678. * @param int $max Max number of characters to show
  1679. * @param int $withpicto With picto
  1680. * @return string HTML Link
  1681. */
  1682. function dol_print_url($url,$target='_blank',$max=32,$withpicto=0)
  1683. {
  1684. global $langs;
  1685. if (empty($url)) return '';
  1686. $link='<a href="';
  1687. if (! preg_match('/^http/i',$url)) $link.='http://';
  1688. $link.=$url;
  1689. $link.='"';
  1690. if ($target) $link.=' target="'.$target.'"';
  1691. $link.='>';
  1692. if (! preg_match('/^http/i',$url)) $link.='http://';
  1693. $link.=dol_trunc($url,$max);
  1694. $link.='</a>';
  1695. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("Url"), 'object_globe.png').' ':'').$link.'</div>';
  1696. }
  1697. /**
  1698. * Show EMail link
  1699. *
  1700. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  1701. * @param int $cid Id of contact if known
  1702. * @param int $socid Id of third party if known
  1703. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  1704. * @param int $max Max number of characters to show
  1705. * @param int $showinvalid Show warning if syntax email is wrong
  1706. * @param int $withpicto Show picto
  1707. * @return string HTML Link
  1708. */
  1709. function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1,$withpicto=0)
  1710. {
  1711. global $conf,$user,$langs;
  1712. $newemail=$email;
  1713. if (empty($email)) return '&nbsp;';
  1714. if (! empty($addlink))
  1715. {
  1716. $newemail='<a style="text-overflow: ellipsis;" href="';
  1717. if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
  1718. $newemail.=$email;
  1719. $newemail.='">';
  1720. $newemail.=dol_trunc($email,$max);
  1721. $newemail.='</a>';
  1722. if ($showinvalid && ! isValidEmail($email))
  1723. {
  1724. $langs->load("errors");
  1725. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  1726. }
  1727. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  1728. {
  1729. $type='AC_EMAIL'; $link='';
  1730. if (! empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  1731. if ($link) $newemail='<div>'.$newemail.' '.$link.'</div>';
  1732. }
  1733. }
  1734. else
  1735. {
  1736. if ($showinvalid && ! isValidEmail($email))
  1737. {
  1738. $langs->load("errors");
  1739. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  1740. }
  1741. }
  1742. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("EMail"), 'object_email.png').' ':'').$newemail.'</div>';
  1743. }
  1744. /**
  1745. * Show Skype link
  1746. *
  1747. * @param string $skype Skype to show (only skype, without 'Name of recipient' before)
  1748. * @param int $cid Id of contact if known
  1749. * @param int $socid Id of third party if known
  1750. * @param int $addlink 0=no link to create action
  1751. * @param int $max Max number of characters to show
  1752. * @return string HTML Link
  1753. */
  1754. function dol_print_skype($skype,$cid=0,$socid=0,$addlink=0,$max=64)
  1755. {
  1756. global $conf,$user,$langs;
  1757. $newskype=$skype;
  1758. if (empty($skype)) return '&nbsp;';
  1759. if (! empty($addlink))
  1760. {
  1761. $newskype =img_picto($langs->trans("Skype"), 'object_skype.png');
  1762. $newskype.= '&nbsp;';
  1763. $newskype.=dol_trunc($skype,$max);
  1764. $newskype.= '&nbsp;';
  1765. $newskype.='<a href="skype:';
  1766. $newskype.=dol_trunc($skype,$max);
  1767. $newskype.='?call" alt="'.$langs->trans("Call").'&nbsp;'.$skype.'" title="'.$langs->trans("Call").'&nbsp;'.$skype.'">';
  1768. $newskype.='<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  1769. $newskype.='</a>&nbsp;&nbsp;&nbsp;<a href="skype:';
  1770. $newskype.=dol_trunc($skype,$max);
  1771. $newskype.='?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$skype.'" title="'.$langs->trans("Chat").'&nbsp;'.$skype.'">';
  1772. $newskype.='<img src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  1773. $newskype.='</a>';
  1774. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  1775. {
  1776. $type='AC_SKYPE'; $link='';
  1777. if (! empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  1778. $newskype='<div class="divskype nowrap">'.$newskype.($link?' '.$link:'').'</div>';
  1779. }
  1780. }
  1781. else
  1782. {
  1783. $langs->load("errors");
  1784. $newskype.=img_warning($langs->trans("ErrorBadSkype",$skype));
  1785. }
  1786. return $newskype;
  1787. }
  1788. /**
  1789. * Format phone numbers according to country
  1790. *
  1791. * @param string $phone Phone number to format
  1792. * @param string $countrycode Country code to use for formatting
  1793. * @param int $cid Id of contact if known
  1794. * @param int $socid Id of third party if known
  1795. * @param string $addlink ''=no link to create action, 'AC_TEL'=add link to clicktodial (if module enabled) and add link to create event (if conf->global->AGENDA_ADDACTIONFORPHONE set)
  1796. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  1797. * @param string $withpicto Show picto
  1798. * @param string $titlealt Text to show on alt
  1799. * @param int $adddivfloat Add div float around phone.
  1800. * @return string Formated phone number
  1801. */
  1802. function dol_print_phone($phone,$countrycode='',$cid=0,$socid=0,$addlink='',$separ="&nbsp;",$withpicto='',$titlealt='',$adddivfloat=0)
  1803. {
  1804. global $conf,$user,$langs,$mysoc;
  1805. // Clean phone parameter
  1806. $phone = preg_replace("/[\s.-]/","",trim($phone));
  1807. if (empty($phone)) { return ''; }
  1808. if (empty($countrycode)) $countrycode=$mysoc->country_code;
  1809. // Short format for small screens
  1810. if ($conf->dol_optimize_smallscreen) $separ='';
  1811. $newphone=$phone;
  1812. if (strtoupper($countrycode) == "FR")
  1813. {
  1814. // France
  1815. if (dol_strlen($phone) == 10) {
  1816. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,2).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2);
  1817. }
  1818. elseif (dol_strlen($newphone) == 7)
  1819. {
  1820. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
  1821. }
  1822. elseif (dol_strlen($newphone) == 9)
  1823. {
  1824. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
  1825. }
  1826. elseif (dol_strlen($newphone) == 11)
  1827. {
  1828. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
  1829. }
  1830. elseif (dol_strlen($newphone) == 12)
  1831. {
  1832. $newphone=substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  1833. }
  1834. }
  1835. if (strtoupper($countrycode) == "CA")
  1836. {
  1837. if (dol_strlen($phone) == 10) {
  1838. $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4);
  1839. }
  1840. }
  1841. if (! empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  1842. {
  1843. if (! empty($conf->browser->phone) || (! empty($conf->clicktodial->enabled) && ! empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) // If phone or option for, we use link of phone
  1844. {
  1845. $newphone ='<a href="tel:'.$phone.'"';
  1846. $newphone.='>'.$phone.'</a>';
  1847. }
  1848. else if (! empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  1849. {
  1850. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  1851. // Define urlmask
  1852. $urlmask='ErrorClickToDialModuleNotConfigured';
  1853. if (! empty($conf->global->CLICKTODIAL_URL)) $urlmask=$conf->global->CLICKTODIAL_URL;
  1854. if (! empty($user->clicktodial_url)) $urlmask=$user->clicktodial_url;
  1855. $clicktodial_poste=(! empty($user->clicktodial_poste)?urlencode($user->clicktodial_poste):'');
  1856. $clicktodial_login=(! empty($user->clicktodial_login)?urlencode($user->clicktodial_login):'');
  1857. $clicktodial_password=(! empty($user->clicktodial_password)?urlencode($user->clicktodial_password):'');
  1858. // This line is for backward compatibility
  1859. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  1860. // Thoose lines are for substitution
  1861. $substitarray=array('__PHONEFROM__'=>$clicktodial_poste,
  1862. '__PHONETO__'=>urlencode($phone),
  1863. '__LOGIN__'=>$clicktodial_login,
  1864. '__PASS__'=>$clicktodial_password);
  1865. $url = make_substitutions($url, $substitarray);
  1866. $newphonesav=$newphone;
  1867. $newphone ='<a href="'.$url.'"';
  1868. if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
  1869. $newphone.='>'.$newphonesav.'</a>';
  1870. }
  1871. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  1872. if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  1873. {
  1874. $type='AC_TEL'; $link='';
  1875. if ($addlink == 'AC_FAX') $type='AC_FAX';
  1876. if (! empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid?'&amp;contactid='.$cid:'').($socid?'&amp;socid='.$socid:'').'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  1877. if ($link) $newphone='<div>'.$newphone.' '.$link.'</div>';
  1878. }
  1879. }
  1880. if (empty($titlealt))
  1881. {
  1882. $titlealt=($withpicto=='fax'?$langs->trans("Fax"):$langs->trans("Phone"));
  1883. }
  1884. $rep='';
  1885. if ($adddivfloat) $rep.='<div class="nospan float" style="margin-right: 10px">';
  1886. else $rep.='<span style="margin-right: 10px;">';
  1887. $rep.=($withpicto?img_picto($titlealt, 'object_'.($withpicto=='fax'?'phoning_fax':'phoning').'.png').' ':'').$newphone;
  1888. if ($adddivfloat) $rep.='</div>';
  1889. else $rep.='</span>';
  1890. return $rep;
  1891. }
  1892. /**
  1893. * Return an IP formated to be shown on screen
  1894. *
  1895. * @param string $ip IP
  1896. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  1897. * @return string Formated IP, with country if GeoIP module is enabled
  1898. */
  1899. function dol_print_ip($ip,$mode=0)
  1900. {
  1901. global $conf,$langs;
  1902. $ret='';
  1903. if (empty($mode)) $ret.=$ip;
  1904. if (! empty($conf->geoipmaxmind->enabled) && $mode != 2)
  1905. {
  1906. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  1907. //$ip='24.24.24.24';
  1908. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  1909. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  1910. $geoip=new DolGeoIP('country',$datafile);
  1911. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  1912. //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
  1913. $countrycode=$geoip->getCountryCodeFromIP($ip);
  1914. if ($countrycode) // If success, countrycode is us, fr, ...
  1915. {
  1916. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  1917. {
  1918. $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
  1919. }
  1920. else $ret.=' ('.$countrycode.')';
  1921. }
  1922. }
  1923. return $ret;
  1924. }
  1925. /**
  1926. * Return country code for current user.
  1927. * If software is used inside a local network, detection may fails (we need a public ip)
  1928. *
  1929. * @return string Country code (fr, es, it, us, ...)
  1930. */
  1931. function dol_user_country()
  1932. {
  1933. global $conf,$langs,$user;
  1934. //$ret=$user->xxx;
  1935. $ret='';
  1936. if (! empty($conf->geoipmaxmind->enabled))
  1937. {
  1938. $ip=$_SERVER["REMOTE_ADDR"];
  1939. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  1940. //$ip='24.24.24.24';
  1941. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  1942. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  1943. $geoip=new DolGeoIP('country',$datafile);
  1944. $countrycode=$geoip->getCountryCodeFromIP($ip);
  1945. $ret=$countrycode;
  1946. }
  1947. return $ret;
  1948. }
  1949. /**
  1950. * Format address string
  1951. *
  1952. * @param string $address Address
  1953. * @param int $htmlid Html ID (for example 'gmap')
  1954. * @param int $mode thirdparty|contact|member|other
  1955. * @param int $id Id of object
  1956. * @param int $noprint No output. Result is the function return
  1957. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  1958. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  1959. * @see dol_format_address
  1960. */
  1961. function dol_print_address($address, $htmlid, $mode, $id, $noprint=0, $charfornl='')
  1962. {
  1963. global $conf, $user, $langs, $hookmanager;
  1964. $out = '';
  1965. if ($address)
  1966. {
  1967. if ($hookmanager) {
  1968. $parameters = array('element' => $mode, 'id' => $id);
  1969. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  1970. $out.=$hookmanager->resPrint;
  1971. }
  1972. if (empty($reshook))
  1973. {
  1974. if (empty($charfornl)) $out.=nl2br($address);
  1975. else $out.=preg_replace('/[\r\n]+/', $charfornl, $address);
  1976. $showgmap=$showomap=0;
  1977. // TODO Add a hook here
  1978. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1;
  1979. if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1;
  1980. if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1;
  1981. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1;
  1982. if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1;
  1983. if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1;
  1984. if ($showgmap)
  1985. {
  1986. $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1);
  1987. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  1988. }
  1989. if ($showomap)
  1990. {
  1991. $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1);
  1992. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  1993. }
  1994. }
  1995. }
  1996. if ($noprint) return $out;
  1997. else print $out;
  1998. }
  1999. /**
  2000. * Return true if email syntax is ok
  2001. *
  2002. * @param string $address email (Ex: "toto@examle.com", "John Do <johndo@example.com>")
  2003. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2004. * @return boolean true if email syntax is OK, false if KO or empty string
  2005. */
  2006. function isValidEmail($address, $acceptsupervisorkey=0)
  2007. {
  2008. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2009. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2010. return false;
  2011. }
  2012. /**
  2013. * Return true if phone number syntax is ok
  2014. * TODO Decide what to do with this
  2015. *
  2016. * @param string $phone phone (Ex: "0601010101")
  2017. * @return boolean true if phone syntax is OK, false if KO or empty string
  2018. */
  2019. function isValidPhone($phone)
  2020. {
  2021. return true;
  2022. }
  2023. /**
  2024. * Make a strlen call. Works even if mbstring module not enabled
  2025. *
  2026. * @param string $string String to calculate length
  2027. * @param string $stringencoding Encoding of string
  2028. * @return int Length of string
  2029. */
  2030. function dol_strlen($string,$stringencoding='UTF-8')
  2031. {
  2032. if (function_exists('mb_strlen')) return mb_strlen($string,$stringencoding);
  2033. else return strlen($string);
  2034. }
  2035. /**
  2036. * Make a substring. Works even in mbstring module is not enabled.
  2037. *
  2038. * @param string $string String to scan
  2039. * @param string $start Start position
  2040. * @param int $length Length
  2041. * @param string $stringencoding Page code used for input string encoding
  2042. * @return string substring
  2043. */
  2044. function dol_substr($string,$start,$length,$stringencoding='')
  2045. {
  2046. global $langs;
  2047. if (empty($stringencoding)) $stringencoding=$langs->charset_output;
  2048. $ret='';
  2049. if (function_exists('mb_substr'))
  2050. {
  2051. $ret=mb_substr($string,$start,$length,$stringencoding);
  2052. }
  2053. else
  2054. {
  2055. $ret=substr($string,$start,$length);
  2056. }
  2057. return $ret;
  2058. }
  2059. /**
  2060. * Show a javascript graph.
  2061. * Do not use this function anymore. Use DolGraph class instead.
  2062. *
  2063. * @param string $htmlid Html id name
  2064. * @param int $width Width in pixel
  2065. * @param int $height Height in pixel
  2066. * @param array $data Data array
  2067. * @param int $showlegend 1 to show legend, 0 otherwise
  2068. * @param string $type Type of graph ('pie', 'barline')
  2069. * @param int $showpercent Show percent (with type='pie' only)
  2070. * @param string $url Param to add an url to click values
  2071. * @param int $combineother 0=No combine, 0.05=Combine if lower than 5%
  2072. * @param int $shownographyet Show graph to say there is not enough data
  2073. * @return void
  2074. * @deprecated
  2075. * @see DolGraph
  2076. */
  2077. function dol_print_graph($htmlid,$width,$height,$data,$showlegend=0,$type='pie',$showpercent=0,$url='',$combineother=0.05,$shownographyet=0)
  2078. {
  2079. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  2080. global $conf,$langs;
  2081. global $theme_datacolor; // To have var kept when function is called several times
  2082. if ($shownographyet)
  2083. {
  2084. print '<div class="nographyet" style="width:'.$width.'px;height:'.$height.'px;"></div>';
  2085. print '<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
  2086. return;
  2087. }
  2088. if (empty($conf->use_javascript_ajax)) return;
  2089. $jsgraphlib='flot';
  2090. $datacolor=array();
  2091. // Load colors of theme into $datacolor array
  2092. $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/graph-color.php";
  2093. if (is_readable($color_file))
  2094. {
  2095. include_once $color_file;
  2096. if (isset($theme_datacolor))
  2097. {
  2098. $datacolor=array();
  2099. foreach($theme_datacolor as $val)
  2100. {
  2101. $datacolor[]="#".sprintf("%02x",$val[0]).sprintf("%02x",$val[1]).sprintf("%02x",$val[2]);
  2102. }
  2103. }
  2104. }
  2105. print '<div id="'.$htmlid.'" style="width:'.$width.'px;height:'.$height.'px;"></div>';
  2106. // We use Flot js lib
  2107. if ($jsgraphlib == 'flot')
  2108. {
  2109. if ($type == 'pie')
  2110. {
  2111. // data is array('series'=>array(serie1,serie2,...),
  2112. // 'seriestype'=>array('bar','line',...),
  2113. // 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
  2114. // 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
  2115. // serieX is array('label'=>'label', data=>val)
  2116. print '
  2117. <script type="text/javascript">
  2118. $(function () {
  2119. var data = '.json_encode($data['series']).';
  2120. function plotWithOptions() {
  2121. $.plot($("#'.$htmlid.'"), data,
  2122. {
  2123. series: {
  2124. pie: {
  2125. show: true,
  2126. radius: 0.8,';
  2127. if ($combineother)
  2128. {
  2129. print '
  2130. combine: {
  2131. threshold: '.$combineother.'
  2132. },';
  2133. }
  2134. print '
  2135. label: {
  2136. show: true,
  2137. radius: 0.9,
  2138. formatter: function(label, series) {
  2139. var percent=Math.round(series.percent);
  2140. var number=series.data[0][1];
  2141. return \'';
  2142. print '<div style="font-size:8pt;text-align:center;padding:2px;color:black;">';
  2143. if ($url) print '<a style="color: #FFFFFF;" border="0" href="'.$url.'=">';
  2144. print '\'+'.($showlegend?'number':'label+\' \'+number');
  2145. if (! empty($showpercent)) print '+\'<br/>\'+percent+\'%\'';
  2146. print '+\'';
  2147. if ($url) print '</a>';
  2148. print '</div>\';
  2149. },
  2150. background: {
  2151. opacity: 0.0,
  2152. color: \'#000000\'
  2153. },
  2154. }
  2155. }
  2156. },
  2157. zoom: {
  2158. interactive: true
  2159. },
  2160. pan: {
  2161. interactive: true
  2162. },';
  2163. if (count($datacolor))
  2164. {
  2165. print 'colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
  2166. }
  2167. print 'legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
  2168. });
  2169. }
  2170. plotWithOptions();
  2171. });
  2172. </script>';
  2173. }
  2174. else if ($type == 'barline')
  2175. {
  2176. // data is array('series'=>array(serie1,serie2,...),
  2177. // 'seriestype'=>array('bar','line',...),
  2178. // 'seriescolor'=>array(0=>'#999999',1=>'#999999',...)
  2179. // 'xlabel'=>array(0=>labelx1,1=>labelx2,...));
  2180. // serieX is array('label'=>'label', data=>array(0=>y1,1=>y2,...)) with same nb of value than into xlabel
  2181. print '
  2182. <script type="text/javascript">
  2183. $(function () {
  2184. var data = [';
  2185. $i=0; $outputserie=0;
  2186. foreach($data['series'] as $serie)
  2187. {
  2188. if ($data['seriestype'][$i]=='line') { $i++; continue; };
  2189. if ($outputserie > 0) print ',';
  2190. print '{ bars: { stack: 0, show: true, barWidth: 0.9, align: \'center\' }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
  2191. $outputserie++; $i++;
  2192. }
  2193. if ($outputserie) print ', ';
  2194. //print '];
  2195. //var datalines = [';
  2196. $i=0; $outputserie=0;
  2197. foreach($data['series'] as $serie)
  2198. {
  2199. if (empty($data['seriestype'][$i]) || $data['seriestype'][$i]=='bar') { $i++; continue; };
  2200. if ($outputserie > 0) print ',';
  2201. print '{ lines: { show: true }, label: \''.dol_escape_js($serie['label']).'\', data: '.json_encode($serie['data']).'}'."\n";
  2202. $outputserie++; $i++;
  2203. }
  2204. print '];
  2205. var dataticks = '.json_encode($data['xlabel']).'
  2206. function plotWithOptions() {
  2207. $.plot(jQuery("#'.$htmlid.'"), data,
  2208. {
  2209. series: {
  2210. stack: 0
  2211. },
  2212. zoom: {
  2213. interactive: true
  2214. },
  2215. pan: {
  2216. interactive: true
  2217. },';
  2218. if (count($datacolor))
  2219. {
  2220. print 'colors: '.json_encode($datacolor).',';
  2221. }
  2222. print 'legend: {show: '.($showlegend?'true':'false').'},
  2223. xaxis: {ticks: dataticks}
  2224. });
  2225. }
  2226. plotWithOptions();
  2227. });
  2228. </script>';
  2229. }
  2230. else print 'BadValueForParameterType';
  2231. }
  2232. }
  2233. /**
  2234. * Truncate a string to a particular length adding '...' if string larger than length.
  2235. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2236. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2237. *
  2238. * @param string $string String to truncate
  2239. * @param int $size Max string size visible. 0 for no limit. Final string size can be 1 more (if size was max+1) or 3 more (if we added ...)
  2240. * @param string $trunc Where to trunc: right, left, middle (size must be a 2 power), wrap
  2241. * @param string $stringencoding Tell what is source string encoding
  2242. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2243. * @param int $display Trunc is use to display and can be changed for small screen. TODO Remove this param (must be dealt with CSS)
  2244. * @return string Truncated string
  2245. */
  2246. function dol_trunc($string,$size=40,$trunc='right',$stringencoding='UTF-8',$nodot=0, $display=0)
  2247. {
  2248. global $conf;
  2249. if ($size==0 || ! empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2250. if (empty($stringencoding)) $stringencoding='UTF-8';
  2251. // reduce for small screen
  2252. if ($conf->dol_optimize_smallscreen==1 && $display==1) $size = round($size/3);
  2253. // We go always here
  2254. if ($trunc == 'right')
  2255. {
  2256. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2257. if (dol_strlen($newstring,$stringencoding) > ($size+($nodot?0:1)))
  2258. return dol_substr($newstring,0,$size,$stringencoding).($nodot?'':'...');
  2259. else
  2260. return $string;
  2261. }
  2262. elseif ($trunc == 'middle')
  2263. {
  2264. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2265. if (dol_strlen($newstring,$stringencoding) > 2 && dol_strlen($newstring,$stringencoding) > ($size+1))
  2266. {
  2267. $size1=round($size/2);
  2268. $size2=round($size/2);
  2269. return dol_substr($newstring,0,$size1,$stringencoding).'...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size2,$size2,$stringencoding);
  2270. }
  2271. else
  2272. return $string;
  2273. }
  2274. elseif ($trunc == 'left')
  2275. {
  2276. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2277. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  2278. return '...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size,$size,$stringencoding);
  2279. else
  2280. return $string;
  2281. }
  2282. elseif ($trunc == 'wrap')
  2283. {
  2284. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2285. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  2286. return dol_substr($newstring,0,$size,$stringencoding)."\n".dol_trunc(dol_substr($newstring,$size,dol_strlen($newstring,$stringencoding)-$size,$stringencoding),$size,$trunc);
  2287. else
  2288. return $string;
  2289. }
  2290. else return 'BadParam3CallingDolTrunc';
  2291. }
  2292. /**
  2293. * Show picto whatever it's its name (generic function)
  2294. *
  2295. * @param string $titlealt Text on title and alt. If text is "TextA:TextB", use Text A on alt and Text B on title. Alt only if param notitle is set to 1.
  2296. * @param string $picto Name of image file to show ('filenew', ...)
  2297. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2298. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2299. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2300. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2301. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2302. * @param int $pictoisfullpath If 1, image path is a full path
  2303. * @param int $srconly Return only content of the src attribute of img.
  2304. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2305. * @return string Return img tag
  2306. * @see #img_object, #img_picto_common
  2307. */
  2308. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0)
  2309. {
  2310. global $conf;
  2311. // Define fullpathpicto to use into src
  2312. if ($pictoisfullpath)
  2313. {
  2314. // Clean parameters
  2315. if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto .= '.png';
  2316. $fullpathpicto = $picto;
  2317. }
  2318. else
  2319. {
  2320. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2321. $url = DOL_URL_ROOT;
  2322. $theme = $conf->theme;
  2323. $path = 'theme/'.$theme;
  2324. if (! empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  2325. else if (! empty($conf->global->MAIN_OVERWRITE_THEME_RES)) $path = $conf->global->MAIN_OVERWRITE_THEME_RES.'/theme/'.$conf->global->MAIN_OVERWRITE_THEME_RES; // To allow an external module to overwrite image resources whatever is activated theme
  2326. else if (! empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  2327. // If we ask an image into $url/$mymodule/img (instead of default path)
  2328. if (preg_match('/^([^@]+)@([^@]+)$/i',$picto,$regs))
  2329. {
  2330. $picto = $regs[1];
  2331. $path = $regs[2]; // $path is $mymodule
  2332. }
  2333. // Clean parameters
  2334. if (! preg_match('/(\.png|\.gif)$/i',$picto)) $picto .= '.png';
  2335. // If alt path are defined, define url where img file is, according to physical path
  2336. foreach ($conf->file->dol_document_root as $type => $dirroot) // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  2337. {
  2338. if ($type == 'main') continue;
  2339. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  2340. {
  2341. $url=DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  2342. break;
  2343. }
  2344. }
  2345. // $url is '' or '/custom', $path is current theme or
  2346. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  2347. }
  2348. if ($srconly) return $fullpathpicto;
  2349. else
  2350. {
  2351. $tmparray=array(0=>$titlealt);
  2352. if (preg_match('/:[^\s0-9]/',$titlealt)) $tmparray=explode(':',$titlealt); // We explode if we have TextA:TextB. Not if we have TextA: TextB
  2353. $title=$tmparray[0];
  2354. $alt=empty($tmparray[1])?'':$tmparray[1];
  2355. return '<img src="'.$fullpathpicto.'" alt="'.dol_escape_htmltag($alt).'"'.($notitle?'':' title="'.dol_escape_htmltag($title).'"').($moreatt?' '.$moreatt:' class="inline-block valigntextbottom"').'>'; // Alt is used for accessibility, title for popup
  2356. }
  2357. }
  2358. /**
  2359. * Show a picto called object_picto (generic function)
  2360. *
  2361. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2362. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  2363. * For external modules use imagename@mymodule to search into directory "img" of module.
  2364. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  2365. * @param int $pictoisfullpath If 1, image path is a full path
  2366. * @param int $srconly Return only content of the src attribute of img.
  2367. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2368. * @return string Return img tag
  2369. * @see #img_picto, #img_picto_common
  2370. */
  2371. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0)
  2372. {
  2373. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  2374. }
  2375. /**
  2376. * Show weather picto
  2377. *
  2378. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2379. * @param string $picto Name of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory.
  2380. * @param string $moreatt Add more attribute on img tag
  2381. * @param int $pictoisfullpath If 1, image path is a full path
  2382. * @return string Return img tag
  2383. * @see #img_object, #img_picto
  2384. */
  2385. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  2386. {
  2387. global $conf;
  2388. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  2389. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  2390. return img_picto($titlealt, $path, $moreatt, 1);
  2391. }
  2392. /**
  2393. * Show picto (generic function)
  2394. *
  2395. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2396. * @param string $picto Name of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory.
  2397. * @param string $moreatt Add more attribute on img tag
  2398. * @param int $pictoisfullpath If 1, image path is a full path
  2399. * @return string Return img tag
  2400. * @see #img_object, #img_picto
  2401. */
  2402. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  2403. {
  2404. global $conf;
  2405. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  2406. if ($pictoisfullpath) $path = $picto;
  2407. else
  2408. {
  2409. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  2410. if (! empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  2411. {
  2412. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  2413. if (file_exists($themepath)) $path = $themepath;
  2414. }
  2415. }
  2416. return img_picto($titlealt, $path, $moreatt, 1);
  2417. }
  2418. /**
  2419. * Show logo action
  2420. *
  2421. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2422. * @param string $numaction Action id or code to show
  2423. * @return string Return an img tag
  2424. */
  2425. function img_action($titlealt, $numaction)
  2426. {
  2427. global $conf, $langs;
  2428. if (empty($titlealt) || $titlealt == 'default')
  2429. {
  2430. if ($numaction == '-1' || $numaction == 'ST_NO') { $numaction = -1; $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); }
  2431. elseif ($numaction == '0' || $numaction == 'ST_NEVER') { $numaction = 0; $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); }
  2432. elseif ($numaction == '1' || $numaction == 'ST_TODO') { $numaction = 1; $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); }
  2433. elseif ($numaction == '2' || $numaction == 'ST_PEND') { $numaction = 2; $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); }
  2434. elseif ($numaction == '3' || $numaction == 'ST_DONE') { $numaction = 3; $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); }
  2435. else { $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction); $numaction = 0; }
  2436. }
  2437. if (! is_numeric($numaction)) $numaction=0;
  2438. return img_picto($titlealt, 'stcomm'.$numaction.'.png');
  2439. }
  2440. /**
  2441. * Show pdf logo
  2442. *
  2443. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2444. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  2445. * @return string Retourne tag img
  2446. */
  2447. function img_pdf($titlealt = 'default', $size = 3)
  2448. {
  2449. global $conf, $langs;
  2450. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  2451. return img_picto($titlealt, 'pdf'.$size.'.png');
  2452. }
  2453. /**
  2454. * Show logo +
  2455. *
  2456. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2457. * @param string $other Add more attributes on img
  2458. * @return string Return tag img
  2459. */
  2460. function img_edit_add($titlealt = 'default', $other = '')
  2461. {
  2462. global $conf, $langs;
  2463. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  2464. return img_picto($titlealt, 'edit_add.png', $other);
  2465. }
  2466. /**
  2467. * Show logo -
  2468. *
  2469. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2470. * @param string $other Add more attributes on img
  2471. * @return string Return tag img
  2472. */
  2473. function img_edit_remove($titlealt = 'default', $other='')
  2474. {
  2475. global $conf, $langs;
  2476. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  2477. return img_picto($titlealt, 'edit_remove.png', $other);
  2478. }
  2479. /**
  2480. * Show logo editer/modifier fiche
  2481. *
  2482. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2483. * @param integer $float Si il faut y mettre le style "float: right"
  2484. * @param string $other Add more attributes on img
  2485. * @return string Return tag img
  2486. */
  2487. function img_edit($titlealt = 'default', $float = 0, $other = 'class="pictoedit"')
  2488. {
  2489. global $conf, $langs;
  2490. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  2491. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl'?'left':'right').'"' : $other));
  2492. }
  2493. /**
  2494. * Show logo view card
  2495. *
  2496. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2497. * @param integer $float Si il faut y mettre le style "float: right"
  2498. * @param string $other Add more attributes on img
  2499. * @return string Return tag img
  2500. */
  2501. function img_view($titlealt = 'default', $float = 0, $other = '')
  2502. {
  2503. global $conf, $langs;
  2504. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  2505. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  2506. return img_picto($titlealt, 'view.png', $moreatt);
  2507. }
  2508. /**
  2509. * Show delete logo
  2510. *
  2511. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2512. * @param string $other Add more attributes on img
  2513. * @return string Retourne tag img
  2514. */
  2515. function img_delete($titlealt = 'default', $other = 'class="pictodelete"')
  2516. {
  2517. global $conf, $langs;
  2518. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  2519. return img_picto($titlealt, 'delete.png', $other);
  2520. }
  2521. /**
  2522. * Show printer logo
  2523. *
  2524. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2525. * @param string $other Add more attributes on img
  2526. * @return string Retourne tag img
  2527. */
  2528. function img_printer($titlealt = "default", $other='')
  2529. {
  2530. global $conf,$langs;
  2531. if ($titlealt=="default") $titlealt=$langs->trans("Print");
  2532. return img_picto($titlealt,'printer.png',$other);
  2533. }
  2534. /**
  2535. * Show delete logo
  2536. *
  2537. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2538. * @param string $other Add more attributes on img
  2539. * @return string Retourne tag img
  2540. */
  2541. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  2542. {
  2543. global $conf, $langs;
  2544. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  2545. return img_picto($titlealt, 'split.png', $other);
  2546. }
  2547. /**
  2548. * Show help logo with cursor "?"
  2549. *
  2550. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  2551. * @param int|string $usealttitle Text to use as alt title
  2552. * @return string Return tag img
  2553. */
  2554. function img_help($usehelpcursor = 1, $usealttitle = 1)
  2555. {
  2556. global $conf, $langs;
  2557. if ($usealttitle)
  2558. {
  2559. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  2560. else $usealttitle = $langs->trans('Info');
  2561. }
  2562. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help': ($usehelpcursor == 2 ? ' cursor: pointer':'')).'"');
  2563. }
  2564. /**
  2565. * Show info logo
  2566. *
  2567. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2568. * @return string Return img tag
  2569. */
  2570. function img_info($titlealt = 'default')
  2571. {
  2572. global $conf, $langs;
  2573. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  2574. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  2575. }
  2576. /**
  2577. * Show warning logo
  2578. *
  2579. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2580. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1
  2581. * @return string Return img tag
  2582. */
  2583. function img_warning($titlealt = 'default', $moreatt = '')
  2584. {
  2585. global $conf, $langs;
  2586. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  2587. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  2588. return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): ''));
  2589. }
  2590. /**
  2591. * Show error logo
  2592. *
  2593. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2594. * @return string Return img tag
  2595. */
  2596. function img_error($titlealt = 'default')
  2597. {
  2598. global $conf, $langs;
  2599. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  2600. return img_picto($titlealt, 'error.png', 'class="valigntextbottom"');
  2601. }
  2602. /**
  2603. * Show next logo
  2604. *
  2605. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2606. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2607. * @return string Return img tag
  2608. */
  2609. function img_next($titlealt = 'default', $moreatt='')
  2610. {
  2611. global $conf, $langs;
  2612. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  2613. //return img_picto($titlealt, 'next.png', $moreatt);
  2614. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  2615. }
  2616. /**
  2617. * Show previous logo
  2618. *
  2619. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2620. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2621. * @return string Return img tag
  2622. */
  2623. function img_previous($titlealt = 'default', $moreatt='')
  2624. {
  2625. global $conf, $langs;
  2626. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  2627. //return img_picto($titlealt, 'previous.png', $moreatt);
  2628. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  2629. }
  2630. /**
  2631. * Show down arrow logo
  2632. *
  2633. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2634. * @param int $selected Selected
  2635. * @param string $moreclass Add more CSS classes
  2636. * @return string Return img tag
  2637. */
  2638. function img_down($titlealt = 'default', $selected = 0, $moreclass='')
  2639. {
  2640. global $conf, $langs;
  2641. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  2642. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass?" ".$moreclass:"").'"');
  2643. }
  2644. /**
  2645. * Show top arrow logo
  2646. *
  2647. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2648. * @param int $selected Selected
  2649. * @param string $moreclass Add more CSS classes
  2650. * @return string Return img tag
  2651. */
  2652. function img_up($titlealt = 'default', $selected = 0, $moreclass='')
  2653. {
  2654. global $conf, $langs;
  2655. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  2656. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass?" ".$moreclass:"").'"');
  2657. }
  2658. /**
  2659. * Show left arrow logo
  2660. *
  2661. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2662. * @param int $selected Selected
  2663. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2664. * @return string Return img tag
  2665. */
  2666. function img_left($titlealt = 'default', $selected = 0, $moreatt='')
  2667. {
  2668. global $conf, $langs;
  2669. if ($titlealt == 'default') $titlealt = $langs->trans('Left');
  2670. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  2671. }
  2672. /**
  2673. * Show right arrow logo
  2674. *
  2675. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2676. * @param int $selected Selected
  2677. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2678. * @return string Return img tag
  2679. */
  2680. function img_right($titlealt = 'default', $selected = 0, $moreatt='')
  2681. {
  2682. global $conf, $langs;
  2683. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  2684. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  2685. }
  2686. /**
  2687. * Show tick logo if allowed
  2688. *
  2689. * @param string $allow Allow
  2690. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2691. * @return string Return img tag
  2692. */
  2693. function img_allow($allow, $titlealt = 'default')
  2694. {
  2695. global $conf, $langs;
  2696. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  2697. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  2698. return '-';
  2699. }
  2700. /**
  2701. * Show MIME img of a file
  2702. *
  2703. * @param string $file Filename
  2704. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2705. * @return string Return img tag
  2706. */
  2707. function img_mime($file, $titlealt = '')
  2708. {
  2709. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2710. $mimetype = dol_mimetype($file, '', 1);
  2711. $mimeimg = dol_mimetype($file, '', 2);
  2712. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  2713. return img_picto_common($titlealt, 'mime/'.$mimeimg);
  2714. }
  2715. /**
  2716. * Show phone logo.
  2717. * Use img_picto instead.
  2718. *
  2719. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2720. * @param int $option Option
  2721. * @return string Return img tag
  2722. * @deprecated
  2723. * @see img_picto
  2724. */
  2725. function img_phone($titlealt = 'default', $option = 0)
  2726. {
  2727. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  2728. global $conf,$langs;
  2729. if ($titlealt == 'default') $titlealt = $langs->trans('Call');
  2730. if ($option == 1) $img = 'call';
  2731. else $img = 'call_out';
  2732. return img_picto($titlealt, $img);
  2733. }
  2734. /**
  2735. * Show search logo
  2736. *
  2737. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2738. * @param string $other Add more attributes on img
  2739. * @return string Retourne tag img
  2740. */
  2741. function img_search($titlealt = 'default', $other = '')
  2742. {
  2743. global $conf, $langs;
  2744. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  2745. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  2746. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  2747. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  2748. return $input;
  2749. }
  2750. /**
  2751. * Show search logo
  2752. *
  2753. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  2754. * @param string $other Add more attributes on img
  2755. * @return string Retourne tag img
  2756. */
  2757. function img_searchclear($titlealt = 'default', $other = '')
  2758. {
  2759. global $conf, $langs;
  2760. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  2761. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  2762. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  2763. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  2764. return $input;
  2765. }
  2766. /**
  2767. * Show information for admin users or standard users
  2768. *
  2769. * @param string $text Text info
  2770. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  2771. * @param int $nodiv No div
  2772. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'xxx'=Other
  2773. * @return string String with info text
  2774. */
  2775. function info_admin($text, $infoonimgalt = 0, $nodiv=0, $admin='1')
  2776. {
  2777. global $conf, $langs;
  2778. if ($infoonimgalt)
  2779. {
  2780. return img_picto($text, 'info', 'class="hideonsmartphone"');
  2781. }
  2782. return ($nodiv?'':'<div class="'.(empty($admin)?'':($admin=='1'?'info':$admin)).' hideonsmartphone">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin?$langs->trans('InfoAdmin'):$langs->trans('Note')).'"></span> '.$text.($nodiv?'':'</div>');
  2783. }
  2784. /**
  2785. * Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
  2786. * On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
  2787. * Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
  2788. * renvoyer leur erreur par l'intermediaire de leur propriete "error".
  2789. *
  2790. * @param DoliDB $db Database handler
  2791. * @param mixed $error String or array of errors strings to show
  2792. * @param array $errors Array of errors
  2793. * @return void
  2794. * @see dol_htmloutput_errors
  2795. */
  2796. function dol_print_error($db='',$error='',$errors=null)
  2797. {
  2798. global $conf,$langs,$argv;
  2799. global $dolibarr_main_prod;
  2800. $out = '';
  2801. $syslog = '';
  2802. // Si erreur intervenue avant chargement langue
  2803. if (! $langs)
  2804. {
  2805. require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
  2806. $langs = new Translate('', $conf);
  2807. $langs->load("main");
  2808. }
  2809. $langs->load("main");
  2810. $langs->load("errors");
  2811. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  2812. {
  2813. $out.=$langs->trans("DolibarrHasDetectedError").".<br>\n";
  2814. if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $out.="You use an experimental or develop level of features, so please do NOT report any bugs, except if problem is confirmed moving option MAIN_FEATURES_LEVEL back to 0.<br>\n";
  2815. $out.=$langs->trans("InformationToHelpDiagnose").":<br>\n";
  2816. $out.="<b>".$langs->trans("Date").":</b> ".dol_print_date(time(),'dayhourlog')."<br>\n";
  2817. $out.="<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";
  2818. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  2819. if (function_exists("phpversion"))
  2820. {
  2821. $out.="<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  2822. }
  2823. $out.="<b>".$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";
  2824. if (function_exists("php_uname"))
  2825. {
  2826. $out.="<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  2827. }
  2828. $out.="<b>".$langs->trans("UserAgent").":</b> ".$_SERVER["HTTP_USER_AGENT"]."<br>\n";
  2829. $out.="<br>\n";
  2830. $out.="<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"],ENT_COMPAT,'UTF-8')."<br>\n";
  2831. $out.="<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"])?dol_htmlentities($_SERVER["HTTP_REFERER"],ENT_COMPAT,'UTF-8'):'')."<br>\n";
  2832. $out.="<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu)?$conf->standard_menu:'')."<br>\n";
  2833. $out.="<br>\n";
  2834. $syslog.="url=".$_SERVER["REQUEST_URI"];
  2835. $syslog.=", query_string=".$_SERVER["QUERY_STRING"];
  2836. }
  2837. else // Mode CLI
  2838. {
  2839. $out.='> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  2840. $syslog.="pid=".dol_getmypid();
  2841. }
  2842. if (is_object($db))
  2843. {
  2844. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  2845. {
  2846. $out.="<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  2847. $out.="<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror()?dol_escape_htmltag($db->lastqueryerror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  2848. $out.="<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno()?dol_escape_htmltag($db->lasterrno()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  2849. $out.="<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror()?dol_escape_htmltag($db->lasterror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  2850. $out.="<br>\n";
  2851. }
  2852. else // Mode CLI
  2853. {
  2854. // No dol_escape_htmltag for output, we are in CLI mode
  2855. $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  2856. $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  2857. $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  2858. $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  2859. }
  2860. $syslog.=", sql=".$db->lastquery();
  2861. $syslog.=", db_error=".$db->lasterror();
  2862. }
  2863. if ($error || $errors)
  2864. {
  2865. $langs->load("errors");
  2866. // Merge all into $errors array
  2867. if (is_array($error) && is_array($errors)) $errors=array_merge($error,$errors);
  2868. elseif (is_array($error)) $errors=$error;
  2869. elseif (is_array($errors)) $errors=array_merge(array($error),$errors);
  2870. else $errors=array_merge(array($error));
  2871. foreach($errors as $msg)
  2872. {
  2873. if (empty($msg)) continue;
  2874. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  2875. {
  2876. $out.="<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n" ;
  2877. }
  2878. else // Mode CLI
  2879. {
  2880. $out.='> '.$langs->transnoentities("Message").":\n".$msg."\n" ;
  2881. }
  2882. $syslog.=", msg=".$msg;
  2883. }
  2884. }
  2885. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  2886. {
  2887. xdebug_print_function_stack();
  2888. $out.='<b>XDebug informations:</b>'."<br>\n";
  2889. $out.='File: '.xdebug_call_file()."<br>\n";
  2890. $out.='Line: '.xdebug_call_line()."<br>\n";
  2891. $out.='Function: '.xdebug_call_function()."<br>\n";
  2892. $out.="<br>\n";
  2893. }
  2894. if (empty($dolibarr_main_prod)) print $out;
  2895. else define("MAIN_CORE_ERROR", 1);
  2896. //else print 'Sorry, an error occured but the parameter $dolibarr_main_prod is defined in conf file so no message is reported to your browser. Please read the log file for error message.';
  2897. dol_syslog("Error ".$syslog, LOG_ERR);
  2898. }
  2899. /**
  2900. * Show a public email and error code to contact if technical error
  2901. *
  2902. * @param string $prefixcode Prefix of public error code
  2903. * @return void
  2904. */
  2905. function dol_print_error_email($prefixcode)
  2906. {
  2907. global $langs,$conf;
  2908. $langs->load("errors");
  2909. $now=dol_now();
  2910. print '<br><div class="error">'.$langs->trans("ErrorContactEMail", $conf->global->MAIN_INFO_SOCIETE_MAIL, $prefixcode.dol_print_date($now,'%Y%m%d')).'</div>';
  2911. }
  2912. /**
  2913. * Show title line of an array
  2914. *
  2915. * @param string $name Label of field
  2916. * @param string $file Url used when we click on sort picto
  2917. * @param string $field Field to use for new sorting
  2918. * @param string $begin ("" by defaut)
  2919. * @param string $moreparam Add more parameters on sort url links ("" by default)
  2920. * @param string $td Options of attribute td ("" by defaut, example: 'align="center"')
  2921. * @param string $sortfield Current field used to sort
  2922. * @param string $sortorder Current sort order
  2923. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  2924. * @return void
  2925. */
  2926. function print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $td="", $sortfield="", $sortorder="", $prefix="")
  2927. {
  2928. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $td, $sortfield, $sortorder, $prefix);
  2929. }
  2930. /**
  2931. * Get title line of an array
  2932. *
  2933. * @param string $name Translation key of field
  2934. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  2935. * @param string $file Url used when we click on sort picto
  2936. * @param string $field Field to use for new sorting. Empty if this field is not sortable.
  2937. * @param string $begin ("" by defaut)
  2938. * @param string $moreparam Add more parameters on sort url links ("" by default)
  2939. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  2940. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  2941. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  2942. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  2943. * @return string
  2944. */
  2945. function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="")
  2946. {
  2947. global $conf, $langs;
  2948. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  2949. $sortorder=strtoupper($sortorder);
  2950. $out='';
  2951. $sortimg='';
  2952. $tag='th';
  2953. if ($thead==2) $tag='div';
  2954. $tmpsortfield=explode(',',$sortfield);
  2955. $sortfield1=trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  2956. $tmpfield=explode(',',$field);
  2957. $field1=trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  2958. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  2959. // If field is used as sort criteria we use a specific css class liste_titre_sel
  2960. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  2961. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./","",$field1))) $out.= '<'.$tag.' class="'.$prefix.'liste_titre_sel" '. $moreattrib.'>';
  2962. else $out.= '<'.$tag.' class="'.$prefix.'liste_titre" '. $moreattrib.'>';
  2963. if (empty($thead) && $field) // If this is a sort field
  2964. {
  2965. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  2966. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  2967. $options=preg_replace('/&+/i','&',$options);
  2968. if (! preg_match('/^&/',$options)) $options='&'.$options;
  2969. if ($field1 != $sortfield1) // We are on another field
  2970. {
  2971. if (preg_match('/^DESC/', $sortorder)) $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">';
  2972. else $out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">';
  2973. }
  2974. else // We are of first sorting criteria
  2975. {
  2976. if (preg_match('/^ASC/', $sortorder)) $out.= '<a href="'.$file.'?sortfield='.$sortfield.'&sortorder=desc&begin='.$begin.$options.'">';
  2977. else $out.= '<a href="'.$file.'?sortfield='.$sortfield.'&sortorder=asc&begin='.$begin.$options.'">';
  2978. }
  2979. }
  2980. $out.=$langs->trans($name);
  2981. if (empty($thead) && $field) // If this is a sort field
  2982. {
  2983. $out.='</a>';
  2984. }
  2985. if (empty($thead) && $field) // If this is a sort field
  2986. {
  2987. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  2988. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  2989. $options=preg_replace('/&+/i','&',$options);
  2990. if (! preg_match('/^&/',$options)) $options='&'.$options;
  2991. //print "&nbsp;";
  2992. //$sortimg.= '<img width="2" src="'.DOL_URL_ROOT.'/theme/common/transparent.png" alt="">';
  2993. //$sortimg.= '<span class="nowrap">';
  2994. if (! $sortorder || $field1 != $sortfield1)
  2995. {
  2996. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  2997. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  2998. }
  2999. else
  3000. {
  3001. if (preg_match('/^DESC/', $sortorder)) {
  3002. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3003. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3004. $sortimg.= '<span class="nowrap">'.img_up("Z-A",0).'</span>';
  3005. }
  3006. if (preg_match('/^ASC/', $sortorder)) {
  3007. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3008. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3009. $sortimg.= '<span class="nowrap">'.img_down("A-Z",0).'</span>';
  3010. }
  3011. }
  3012. //$sortimg.= '</span>';
  3013. }
  3014. $out.=$sortimg;
  3015. $out.='</'.$tag.'>';
  3016. return $out;
  3017. }
  3018. /**
  3019. * Show a title.
  3020. *
  3021. * @param string $title Title to show
  3022. * @return string Title to show
  3023. * @deprecated Use load_fiche_titre instead
  3024. * @see load_fiche_titre
  3025. */
  3026. function print_titre($title)
  3027. {
  3028. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  3029. print '<div class="titre">'.$title.'</div>';
  3030. }
  3031. /**
  3032. * Show a title with picto
  3033. *
  3034. * @param string $title Title to show
  3035. * @param string $mesg Added message to show on right
  3036. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3037. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3038. * @param int $id To force an id on html objects
  3039. * @return void
  3040. * @deprecated Use print load_fiche_titre instead
  3041. */
  3042. function print_fiche_titre($title, $mesg='', $picto='title_generic.png', $pictoisfullpath=0, $id='')
  3043. {
  3044. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3045. }
  3046. /**
  3047. * Load a title with picto
  3048. *
  3049. * @param string $titre Title to show
  3050. * @param string $morehtmlright Added message to show on right
  3051. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3052. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3053. * @param int $id To force an id on html objects
  3054. * @param string $morecssontable More css on table
  3055. * @return string
  3056. * @see print_barre_liste
  3057. */
  3058. function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id=0, $morecssontable='')
  3059. {
  3060. global $conf;
  3061. $return='';
  3062. if ($picto == 'setup') $picto='title.png';
  3063. if (($conf->browser->name == 'ie') && $picto=='title.png') $picto='title.gif';
  3064. $return.= "\n";
  3065. $return.= '<table '.($id?'id="'.$id.'" ':'').'summary="" class="centpercent notopnoleftnoright'.($morecssontable?' '.$morecssontable:'').'" style="margin-bottom: 2px;"><tr>';
  3066. if ($picto) $return.= '<td class="nobordernopadding widthpictotitle" valign="middle">'.img_picto('',$picto, 'class="valignmiddle" id="pictotitle"', $pictoisfullpath).'</td>';
  3067. $return.= '<td class="nobordernopadding" valign="middle">';
  3068. $return.= '<div class="titre">'.$titre.'</div>';
  3069. $return.= '</td>';
  3070. if (dol_strlen($morehtmlright))
  3071. {
  3072. $return.= '<td class="nobordernopadding titre_right" align="right" valign="middle">'.$morehtmlright.'</td>';
  3073. }
  3074. $return.= '</tr></table>'."\n";
  3075. return $return;
  3076. }
  3077. /**
  3078. * Print a title with navigation controls for pagination
  3079. *
  3080. * @param string $titre Title to show (required)
  3081. * @param int $page Numero of page to show in navigation links (required)
  3082. * @param string $file Url of page (required)
  3083. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder)
  3084. * @param string $sortfield Field to sort on ('' by default)
  3085. * @param string $sortorder Order to sort ('' by default)
  3086. * @param string $center String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  3087. * @param int $num Number of records found by select with limit+1
  3088. * @param int|string $totalnboflines Total number of records/lines for all pages (if known). Use a negative value of number to not show number. Use '' if unknown.
  3089. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3090. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3091. * @param string $morehtml More html to show
  3092. * @param string $morecss More css to the table
  3093. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  3094. * @param int $hideselectlimit Force to hide select limit
  3095. * @return void
  3096. */
  3097. function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $center='', $num=-1, $totalnboflines='', $picto='title_generic.png', $pictoisfullpath=0, $morehtml='', $morecss='', $limit=-1, $hideselectlimit=0)
  3098. {
  3099. global $conf,$langs;
  3100. $savlimit = $limit;
  3101. $savtotalnboflines = $totalnboflines;
  3102. $totalnboflines=abs($totalnboflines);
  3103. if ($picto == 'setup') $picto='title_setup.png';
  3104. if (($conf->browser->name == 'ie') && $picto=='title_generic.png') $picto='title.gif';
  3105. if ($limit < 0) $limit = $conf->liste_limit;
  3106. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  3107. {
  3108. $nextpage = 1;
  3109. }
  3110. else
  3111. {
  3112. $nextpage = 0;
  3113. }
  3114. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  3115. print "\n";
  3116. print "<!-- Begin title '".$titre."' -->\n";
  3117. print '<table width="100%" border="0" class="notopnoleftnoright'.($morecss?' '.$morecss:'').'" style="margin-bottom: 6px;"><tr>';
  3118. // Left
  3119. //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
  3120. print '<td class="nobordernopadding valignmiddle">';
  3121. if ($picto && $titre) print img_picto('', $picto, 'class="hideonsmartphone valignmiddle" id="pictotitle"', $pictoisfullpath);
  3122. print '<div class="titre inline-block">'.$titre;
  3123. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print ' ('.$totalnboflines.')';
  3124. print '</div></td>';
  3125. // Center
  3126. if ($center)
  3127. {
  3128. print '<td class="nobordernopadding center valignmiddle">'.$center.'</td>';
  3129. }
  3130. // Right
  3131. print '<td class="nobordernopadding valignmiddle" align="right">';
  3132. if ($sortfield) $options .= "&amp;sortfield=".$sortfield;
  3133. if ($sortorder) $options .= "&amp;sortorder=".$sortorder;
  3134. // Show navigation bar
  3135. $pagelist = '';
  3136. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  3137. {
  3138. if ($totalnboflines) // If we know total nb of lines
  3139. {
  3140. $maxnbofpage=(empty($conf->dol_optimize_smallscreen) ? 4 : 1); // page nb before and after selected page + ... + first or last
  3141. if ($limit > 0) $nbpages=ceil($totalnboflines/$limit);
  3142. else $nbpages=1;
  3143. $cpt=($page-$maxnbofpage);
  3144. if ($cpt < 0) { $cpt=0; }
  3145. if ($cpt>=1)
  3146. {
  3147. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  3148. if ($cpt > 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3149. else if ($cpt == 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  3150. }
  3151. do
  3152. {
  3153. if ($cpt==$page)
  3154. {
  3155. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1).'</span></li>';
  3156. }
  3157. else
  3158. {
  3159. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt+1).'</a></li>';
  3160. }
  3161. $cpt++;
  3162. }
  3163. while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage);
  3164. if ($cpt<$nbpages)
  3165. {
  3166. if ($cpt<$nbpages-2) $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3167. else if ($cpt == $nbpages-2) $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.($nbpages-2).$options.'">'.($nbpages - 1).'</a></li>';
  3168. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.($nbpages-1).$options.'">'.$nbpages.'</a></li>';
  3169. }
  3170. }
  3171. else
  3172. {
  3173. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1)."</li>";
  3174. }
  3175. }
  3176. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtml, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist
  3177. print '</td>';
  3178. print '</tr></table>'."\n";
  3179. print "<!-- End title -->\n\n";
  3180. }
  3181. /**
  3182. * Function to show navigation arrows into lists
  3183. *
  3184. * @param int $page Number of page
  3185. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  3186. * @param string $options Other url paramaters to propagate ("" by default, may include sortfield and sortorder)
  3187. * @param integer $nextpage Do we show a next page button
  3188. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  3189. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  3190. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  3191. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  3192. * @param int $hideselectlimit Force to hide select limit
  3193. * @return void
  3194. */
  3195. function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0)
  3196. {
  3197. global $conf, $langs;
  3198. print '<div class="pagination"><ul>';
  3199. if ((int) $limit >= 0 && empty($hideselectlimit))
  3200. {
  3201. $pagesizechoices='10:10,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  3202. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  3203. //$pagesizechoices.=',2:2';
  3204. if (! empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices=$conf->global->MAIN_PAGESIZE_CHOICES;
  3205. print '<li class="pagination">';
  3206. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  3207. $tmpchoice=explode(',',$pagesizechoices);
  3208. $tmpkey=$limit.':'.$limit;
  3209. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3210. $tmpkey=$conf->liste_limit.':'.$conf->liste_limit;
  3211. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3212. asort($tmpchoice, SORT_NUMERIC);
  3213. $found=false;
  3214. foreach($tmpchoice as $val)
  3215. {
  3216. $selected='';
  3217. $tmp=explode(':',$val);
  3218. $key=$tmp[0];
  3219. $val=$tmp[1];
  3220. if ($key != '' && $val != '')
  3221. {
  3222. if ((int) $key == (int) $limit)
  3223. {
  3224. $selected = ' selected="selected"';
  3225. $found = true;
  3226. }
  3227. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  3228. }
  3229. }
  3230. print '</select>';
  3231. if ($conf->use_javascript_ajax)
  3232. {
  3233. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  3234. <script type="text/javascript">
  3235. jQuery(document).ready(function () {
  3236. jQuery(".selectlimit").change(function() {
  3237. console.log("Change limit. Send submit");
  3238. $(this).parents(\'form:first\').submit();
  3239. });
  3240. });
  3241. </script>
  3242. ';
  3243. }
  3244. print '</li>';
  3245. }
  3246. if ($page > 0)
  3247. {
  3248. print '<li class="pagination"><a class="paginationprevious" href="'.$file.'?page='.($page-1).$options.'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag($langs->trans("Previous")).'"></i></a></li>';
  3249. }
  3250. if ($betweenarrows)
  3251. {
  3252. print $betweenarrows;
  3253. }
  3254. if ($nextpage > 0)
  3255. {
  3256. print '<li class="pagination"><a class="paginationnext" href="'.$file.'?page='.($page+1).$options.'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag($langs->trans("Next")).'"></i></a></li>';
  3257. }
  3258. if ($afterarrows)
  3259. {
  3260. print '<li class="paginationafterarrows">';
  3261. print $afterarrows;
  3262. print '</li>';
  3263. }
  3264. print '</ul></div>'."\n";
  3265. }
  3266. /**
  3267. * Return a string with VAT rate label formated for view output
  3268. * Used into pdf and HTML pages
  3269. *
  3270. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  3271. * @param boolean $addpercent Add a percent % sign in output
  3272. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  3273. * @param int $usestarfornpr 1=Use '*' for NPR vat rate intead of MAIN_LABEL_MENTION_NPR
  3274. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  3275. */
  3276. function vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
  3277. {
  3278. $morelabel='';
  3279. if (preg_match('/%/',$rate))
  3280. {
  3281. $rate=str_replace('%','',$rate);
  3282. $addpercent=true;
  3283. }
  3284. if (preg_match('/\((.*)\)/',$rate,$reg))
  3285. {
  3286. $morelabel=' ('.$reg[1].')';
  3287. $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate);
  3288. }
  3289. if (preg_match('/\*/',$rate))
  3290. {
  3291. $rate=str_replace('*','',$rate);
  3292. $info_bits |= 1;
  3293. }
  3294. $ret=price($rate,0,'',0,0).($addpercent?'%':'');
  3295. if ($info_bits & 1) $ret.=' *';
  3296. $ret.=$morelabel;
  3297. return $ret;
  3298. }
  3299. /**
  3300. * Function to format a value into an amount for visual output
  3301. * Function used into PDF and HTML pages
  3302. *
  3303. * @param float $amount Amount to format
  3304. * @param integer $form Type of format, HTML or not (not by default)
  3305. * @param Translate $outlangs Object langs for output
  3306. * @param int $trunc 1=Truncate if there is too much decimals (default), 0=Does not truncate. Deprecated because amount are rounded (to unit or total amount accurancy) before inserted into database or after a computation, so this parameter should be useless.
  3307. * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOTAL)
  3308. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  3309. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  3310. * @return string Chaine avec montant formate
  3311. *
  3312. * @see price2num Revert function of price
  3313. */
  3314. function price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
  3315. {
  3316. global $langs,$conf;
  3317. // Clean parameters
  3318. if (empty($amount)) $amount=0; // To have a numeric value if amount not defined or = ''
  3319. $amount = (is_numeric($amount)?$amount:0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  3320. if ($rounding < 0) $rounding=min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
  3321. $nbdecimal=$rounding;
  3322. // Output separators by default (french)
  3323. $dec=','; $thousand=' ';
  3324. // If $outlangs not forced, we use use language
  3325. if (! is_object($outlangs)) $outlangs=$langs;
  3326. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$outlangs->transnoentitiesnoconv("SeparatorDecimal");
  3327. if ($outlangs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$outlangs->transnoentitiesnoconv("SeparatorThousand");
  3328. if ($thousand == 'None') $thousand='';
  3329. else if ($thousand == 'Space') $thousand=' ';
  3330. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  3331. //print "amount=".$amount."-";
  3332. $amount = str_replace(',','.',$amount); // should be useless
  3333. //print $amount."-";
  3334. $datas = explode('.',$amount);
  3335. $decpart = isset($datas[1])?$datas[1]:'';
  3336. $decpart = preg_replace('/0+$/i','',$decpart); // Supprime les 0 de fin de partie decimale
  3337. //print "decpart=".$decpart."<br>";
  3338. $end='';
  3339. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  3340. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal=dol_strlen($decpart);
  3341. // Si on depasse max
  3342. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  3343. {
  3344. $nbdecimal=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
  3345. if (preg_match('/\.\.\./i',$conf->global->MAIN_MAX_DECIMALS_SHOWN))
  3346. {
  3347. // Si un affichage est tronque, on montre des ...
  3348. $end='...';
  3349. }
  3350. }
  3351. // If force rounding
  3352. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  3353. // Format number
  3354. $output=number_format($amount, $nbdecimal, $dec, $thousand);
  3355. if ($form)
  3356. {
  3357. $output=preg_replace('/\s/','&nbsp;',$output);
  3358. $output=preg_replace('/\'/','&#039;',$output);
  3359. }
  3360. // Add symbol of currency if requested
  3361. $cursymbolbefore=$cursymbolafter='';
  3362. if ($currency_code)
  3363. {
  3364. if ($currency_code == 'auto') $currency_code=$conf->currency;
  3365. $listofcurrenciesbefore=array('USD','GBP','AUD','MXN');
  3366. if (in_array($currency_code,$listofcurrenciesbefore)) $cursymbolbefore.=$outlangs->getCurrencySymbol($currency_code);
  3367. else
  3368. {
  3369. $tmpcur=$outlangs->getCurrencySymbol($currency_code);
  3370. $cursymbolafter.=($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  3371. }
  3372. }
  3373. $output=$cursymbolbefore.$output.$end.($cursymbolafter?' ':'').$cursymbolafter;
  3374. return $output;
  3375. }
  3376. /**
  3377. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  3378. * Function to use on each input amount before any numeric test or database insert
  3379. *
  3380. * @param float $amount Amount to convert/clean
  3381. * @param string $rounding ''=No rounding
  3382. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  3383. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  3384. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  3385. * @param int $alreadysqlnb Put 1 if you know that content is already universal format number
  3386. * @return string Amount with universal numeric format (Example: '99.99999') or unchanged text if conversion fails.
  3387. *
  3388. * @see price Opposite function of price2num
  3389. */
  3390. function price2num($amount,$rounding='',$alreadysqlnb=0)
  3391. {
  3392. global $langs,$conf;
  3393. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  3394. // Numbers must be '1234.56'
  3395. // Decimal delimiter for PHP and database SQL requests must be '.'
  3396. $dec=','; $thousand=' ';
  3397. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$langs->transnoentitiesnoconv("SeparatorDecimal");
  3398. if ($langs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$langs->transnoentitiesnoconv("SeparatorThousand");
  3399. if ($thousand == 'None') $thousand='';
  3400. elseif ($thousand == 'Space') $thousand=' ';
  3401. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  3402. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  3403. if ($alreadysqlnb != 1) // If not a PHP number or unknown, we change format
  3404. {
  3405. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  3406. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  3407. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  3408. if (is_numeric($amount))
  3409. {
  3410. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  3411. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  3412. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  3413. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  3414. $amount=number_format($amount,$nbofdec,$dec,$thousand);
  3415. }
  3416. //print "QQ".$amount.'<br>';
  3417. // Now make replace (the main goal of function)
  3418. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  3419. $amount=str_replace(' ','',$amount); // To avoid spaces
  3420. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  3421. $amount=str_replace($dec,'.',$amount);
  3422. }
  3423. // Now, make a rounding if required
  3424. if ($rounding)
  3425. {
  3426. $nbofdectoround='';
  3427. if ($rounding == 'MU') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_UNIT;
  3428. elseif ($rounding == 'MT') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_TOT;
  3429. elseif ($rounding == 'MS') $nbofdectoround=empty($conf->global->MAIN_MAX_DECIMALS_STOCK)?5:$conf->global->MAIN_MAX_DECIMALS_STOCK;
  3430. elseif (is_numeric($rounding)) $nbofdectoround=$rounding; // For admin info page
  3431. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  3432. if (dol_strlen($nbofdectoround)) $amount = round($amount,$nbofdectoround); // $nbofdectoround can be 0.
  3433. else return 'ErrorBadParameterProvidedToFunction';
  3434. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  3435. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  3436. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  3437. if (is_numeric($amount))
  3438. {
  3439. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  3440. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  3441. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  3442. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  3443. $amount=number_format($amount,min($nbofdec,$nbofdectoround),$dec,$thousand); // Convert amount to format with dolibarr dec and thousand
  3444. }
  3445. //print "TT".$amount.'<br>';
  3446. // Always make replace because each math function (like round) replace
  3447. // with local values and we want a number that has a SQL string format x.y
  3448. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  3449. $amount=str_replace(' ','',$amount); // To avoid spaces
  3450. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  3451. $amount=str_replace($dec,'.',$amount);
  3452. }
  3453. return $amount;
  3454. }
  3455. /**
  3456. * Output a dimension with best unit
  3457. *
  3458. * @param float $dimension Dimension
  3459. * @param int $unit Unit of dimension (0, -3, ...)
  3460. * @param string $type 'weight', 'volume', ...
  3461. * @param Translate $outputlangs Translate language object
  3462. * @param int $round -1 = non rounding, x = number of decimal
  3463. * @param string $forceunitoutput 'no' or numeric (-3, -6, ...) compared to $unit
  3464. * @return string String to show dimensions
  3465. */
  3466. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no')
  3467. {
  3468. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  3469. if (($forceunitoutput == 'no' && $dimension < 1/10000) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  3470. {
  3471. $dimension = $dimension * 1000000;
  3472. $unit = $unit - 6;
  3473. }
  3474. elseif (($forceunitoutput == 'no' && $dimension < 1/10) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  3475. {
  3476. $dimension = $dimension * 1000;
  3477. $unit = $unit - 3;
  3478. }
  3479. elseif (($forceunitoutput == 'no' && $dimension > 100000000) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  3480. {
  3481. $dimension = $dimension / 1000000;
  3482. $unit = $unit + 6;
  3483. }
  3484. elseif (($forceunitoutput == 'no' && $dimension > 100000) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  3485. {
  3486. $dimension = $dimension / 1000;
  3487. $unit = $unit + 3;
  3488. }
  3489. $ret=price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type);
  3490. return $ret;
  3491. }
  3492. /**
  3493. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  3494. * Note: This function applies same rules than get_default_tva
  3495. *
  3496. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  3497. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  3498. * @param Societe $thirdparty_buyer Object of buying third party
  3499. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  3500. * @param int $vatnpr If vat rate is NPR or not
  3501. * @return mixed 0 if not found, localtax rate if found
  3502. * @see get_default_tva
  3503. */
  3504. function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
  3505. {
  3506. global $db, $conf, $mysoc;
  3507. if (empty($thirdparty_seller) || ! is_object($thirdparty_seller)) $thirdparty_seller=$mysoc;
  3508. dol_syslog("get_localtax tva=".$vatrate." local=".$local." thirdparty_buyer id=".(is_object($thirdparty_buyer)?$thirdparty_buyer->id:'')."/country_code=".(is_object($thirdparty_buyer)?$thirdparty_buyer->country_code:'')." thirdparty_seller id=".$thirdparty_seller->id."/country_code=".$thirdparty_seller->country_code." thirdparty_seller localtax1_assuj=".$thirdparty_seller->localtax1_assuj." thirdparty_seller localtax2_assuj=".$thirdparty_seller->localtax2_assuj);
  3509. $vatratecleaned = $vatrate;
  3510. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  3511. {
  3512. $vatratecleaned = trim($reg[1]);
  3513. $vatratecode = $reg[2];
  3514. }
  3515. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  3516. {
  3517. return 0;
  3518. }*/
  3519. // Some test to guess with no need to make database access
  3520. if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local taxe
  3521. {
  3522. if ($local == 1)
  3523. {
  3524. if (! $mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  3525. if ($thirdparty_seller->id == $mysoc->id)
  3526. {
  3527. if (! $thirdparty_buyer->localtax1_assuj) return 0;
  3528. }
  3529. else
  3530. {
  3531. if (! $thirdparty_seller->localtax1_assuj) return 0;
  3532. }
  3533. }
  3534. if ($local == 2)
  3535. {
  3536. if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  3537. if ($thirdparty_seller->id == $mysoc->id)
  3538. {
  3539. if (! $thirdparty_buyer->localtax2_assuj) return 0;
  3540. }
  3541. else
  3542. {
  3543. if (! $thirdparty_seller->localtax2_assuj) return 0;
  3544. }
  3545. }
  3546. }
  3547. else
  3548. {
  3549. if ($local == 1 && ! $thirdparty_seller->localtax1_assuj) return 0;
  3550. if ($local == 2 && ! $thirdparty_seller->localtax2_assuj) return 0;
  3551. }
  3552. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  3553. if (in_array($mysoc->country_code, array('ES')))
  3554. {
  3555. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  3556. }
  3557. // Search local taxes
  3558. if (! empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  3559. {
  3560. if ($local==1)
  3561. {
  3562. if ($thirdparty_seller != $mysoc)
  3563. {
  3564. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  3565. {
  3566. return $thirdparty_seller->localtax1_value;
  3567. }
  3568. }
  3569. else // i am the seller
  3570. {
  3571. if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  3572. {
  3573. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  3574. }
  3575. }
  3576. }
  3577. if ($local==2)
  3578. {
  3579. if ($thirdparty_seller != $mysoc)
  3580. {
  3581. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  3582. // TODO We should also return value defined on thirdparty only if defined
  3583. {
  3584. return $thirdparty_seller->localtax2_value;
  3585. }
  3586. }
  3587. else // i am the seller
  3588. {
  3589. if (!isOnlyOneLocalTax($local)) // This is for spain only, we don't return value found into datbase even if there is only one locatax vat.
  3590. {
  3591. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  3592. }
  3593. }
  3594. }
  3595. }
  3596. // By default, search value of local tax on line of common tax
  3597. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  3598. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3599. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$thirdparty_seller->country_code."'";
  3600. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  3601. if ($vatratecode) $sql.= " AND t.code ='".$vatratecode."'"; // If we have the code, we use it in priority
  3602. else $sql.= " AND t.recuperableonly ='".$vatnpr."'";
  3603. dol_syslog("get_localtax", LOG_DEBUG);
  3604. $resql=$db->query($sql);
  3605. if ($resql)
  3606. {
  3607. $obj = $db->fetch_object($resql);
  3608. if ($local==1) return $obj->localtax1;
  3609. elseif ($local==2) return $obj->localtax2;
  3610. }
  3611. return 0;
  3612. }
  3613. /**
  3614. * Return true if LocalTax (1 or 2) is unique.
  3615. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  3616. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  3617. *
  3618. * @param int $local Local tax to test (1 or 2)
  3619. * @return boolean True if LocalTax have multiple values, False if not
  3620. */
  3621. function isOnlyOneLocalTax($local)
  3622. {
  3623. $tax=get_localtax_by_third($local);
  3624. $valors=explode(":", $tax);
  3625. if (count($valors)>1)
  3626. {
  3627. return false;
  3628. }
  3629. else
  3630. {
  3631. return true;
  3632. }
  3633. }
  3634. /**
  3635. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  3636. *
  3637. * @param int $local LocalTax to get
  3638. * @return number Values of localtax
  3639. */
  3640. function get_localtax_by_third($local)
  3641. {
  3642. global $db, $mysoc;
  3643. $sql ="SELECT t.localtax1, t.localtax2 ";
  3644. $sql.=" FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  3645. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND t.active = 1 AND t.taux=(";
  3646. $sql.=" SELECT max(tt.taux) FROM ".MAIN_DB_PREFIX."c_tva as tt inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=tt.fk_pays";
  3647. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND tt.active = 1";
  3648. $sql.=" )";
  3649. $resql=$db->query($sql);
  3650. if ($resql)
  3651. {
  3652. $obj = $db->fetch_object($resql);
  3653. if ($local==1) return $obj->localtax1;
  3654. elseif ($local==2) return $obj->localtax2;
  3655. }
  3656. return 0;
  3657. }
  3658. /**
  3659. * Get vat rate and npr from id.
  3660. * You can call getLocalTaxesFromRate after to get other fields
  3661. *
  3662. * @param int $vatrowid Line ID into vat rate table.
  3663. * @return array array(localtax_type1(1-6 / 0 if not found), rate of localtax1, ...)
  3664. */
  3665. function getTaxesFromId($vatrowid)
  3666. {
  3667. global $db, $mysoc;
  3668. dol_syslog("getTaxesFromId vatrowid=".$vatrowid);
  3669. // Search local taxes
  3670. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr";
  3671. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  3672. $sql.= " WHERE t.rowid ='".$vatrowid."'";
  3673. $resql=$db->query($sql);
  3674. if ($resql)
  3675. {
  3676. $obj = $db->fetch_object($resql);
  3677. return array('rowid'=>$obj->rowid, 'code'=>$obj->code, 'rate'=>$obj->rate, 'npr'=>$obj->npr);
  3678. }
  3679. else dol_print_error($db);
  3680. return array();
  3681. }
  3682. /**
  3683. * Get type and rate of localtaxes for a particular vat rate/country fo thirdparty
  3684. * TODO
  3685. * This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  3686. * Instead this function must be called when adding a line to get the array of localtax and type, and then
  3687. * provide it to the function calcul_price_total.
  3688. *
  3689. * @param string $vatrate VAT Rate. Value can be value or the string with code into parenthesis or rowid if $firstparamisid is 1. Example: '8.5' or '8.5 (8.5NPR)' or 123.
  3690. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  3691. * @param Societe $buyer Company object
  3692. * @param Societe $seller Company object
  3693. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  3694. * @return array array(localtax_type1(1-6 / 0 if not found), rate of localtax1, ...)
  3695. */
  3696. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
  3697. {
  3698. global $db, $mysoc;
  3699. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  3700. $vatratecleaned = $vatrate;
  3701. $vatratecode = '';
  3702. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  3703. {
  3704. $vatratecleaned = $reg[1];
  3705. $vatratecode = $reg[2];
  3706. }
  3707. // Search local taxes
  3708. $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
  3709. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  3710. if ($firstparamisid) $sql.= " WHERE t.rowid ='".$vatrate."'";
  3711. else
  3712. {
  3713. $sql.=", ".MAIN_DB_PREFIX."c_country as c";
  3714. if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ??
  3715. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
  3716. $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  3717. if ($vatratecode) $sql.= " AND t.code ='".$vatratecode."'";
  3718. }
  3719. $resql=$db->query($sql);
  3720. if ($resql)
  3721. {
  3722. $obj = $db->fetch_object($resql);
  3723. if ($local == 1)
  3724. {
  3725. if (! isOnlyOneLocalTax(1))
  3726. {
  3727. return array($obj->localtax1_type, get_localtax($vatrate, $local, $buyer, $seller), $obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3728. }
  3729. else
  3730. {
  3731. return array($obj->localtax1_type, $obj->localtax1,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3732. }
  3733. }
  3734. elseif ($local == 2)
  3735. {
  3736. if (! isOnlyOneLocalTax(2))
  3737. {
  3738. return array($obj->localtax2_type, get_localtax($vatrate, $local, $buyer, $seller),$obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3739. }
  3740. else
  3741. {
  3742. return array($obj->localtax2_type, $obj->localtax2,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3743. }
  3744. }
  3745. else
  3746. {
  3747. if(! isOnlyOneLocalTax(1))
  3748. {
  3749. if(! isOnlyOneLocalTax(2))
  3750. {
  3751. return array($obj->localtax1_type, get_localtax($vatrate, 1, $buyer, $seller), $obj->localtax2_type, get_localtax($vatrate, 2, $buyer, $seller),$obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3752. }
  3753. else
  3754. {
  3755. return array($obj->localtax1_type, get_localtax($vatrate, 1, $buyer, $seller), $obj->localtax2_type, $obj->localtax2,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3756. }
  3757. }
  3758. else
  3759. {
  3760. if(! isOnlyOneLocalTax(2))
  3761. {
  3762. return array($obj->localtax1_type, $obj->localtax1, $obj->localtax2_type,get_localtax($vatrate, 2, $buyer, $seller) ,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3763. }
  3764. else
  3765. {
  3766. return array($obj->localtax1_type, $obj->localtax1, $obj->localtax2_type, $obj->localtax2,$obj->accountancy_code_sell,$obj->accountancy_code_buy);
  3767. }
  3768. }
  3769. }
  3770. }
  3771. return 0;
  3772. }
  3773. /**
  3774. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  3775. * Function called by get_default_tva
  3776. *
  3777. * @param int $idprod Id of product or 0 if not a predefined product
  3778. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  3779. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" order/invoice)
  3780. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  3781. * @see get_product_localtax_for_country
  3782. */
  3783. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice=0)
  3784. {
  3785. global $db,$conf,$mysoc;
  3786. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  3787. $ret=0;
  3788. $found=0;
  3789. if ($idprod > 0)
  3790. {
  3791. // Load product
  3792. $product=new Product($db);
  3793. $result=$product->fetch($idprod);
  3794. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  3795. {
  3796. if ($idprodfournprice > 0) // We want vat for product for a "supplier" order or invoice
  3797. {
  3798. $product->get_buyprice($idprodfournprice,0,0,0);
  3799. $ret=$product->vatrate_supplier;
  3800. }
  3801. else
  3802. {
  3803. $ret=$product->tva_tx; // Default vat of product we defined
  3804. if ($product->default_vat_code) $ret.=' ('.$product->default_vat_code.')';
  3805. }
  3806. $found=1;
  3807. }
  3808. else
  3809. {
  3810. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  3811. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  3812. }
  3813. }
  3814. if (! $found)
  3815. {
  3816. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  3817. {
  3818. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  3819. $sql = "SELECT taux as vat_rate";
  3820. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3821. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  3822. $sql.= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  3823. $sql.= $db->plimit(1);
  3824. $resql=$db->query($sql);
  3825. if ($resql)
  3826. {
  3827. $obj=$db->fetch_object($resql);
  3828. if ($obj)
  3829. {
  3830. $ret=$obj->vat_rate;
  3831. }
  3832. $db->free($sql);
  3833. }
  3834. else dol_print_error($db);
  3835. }
  3836. else $ret=$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  3837. }
  3838. dol_syslog("get_product_vat_for_country: ret=".$ret);
  3839. return $ret;
  3840. }
  3841. /**
  3842. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  3843. *
  3844. * @param int $idprod Id of product
  3845. * @param int $local 1 for localtax1, 2 for localtax 2
  3846. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  3847. * @return int <0 if KO, Vat rate if OK
  3848. * @see get_product_vat_for_country
  3849. */
  3850. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  3851. {
  3852. global $db,$mysoc;
  3853. if (! class_exists('Product')) {
  3854. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  3855. }
  3856. $ret=0;
  3857. $found=0;
  3858. if ($idprod > 0)
  3859. {
  3860. // Load product
  3861. $product=new Product($db);
  3862. $result=$product->fetch($idprod);
  3863. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  3864. {
  3865. /* Not defined yet, so we don't use this
  3866. if ($local==1) $ret=$product->localtax1_tx;
  3867. elseif ($local==2) $ret=$product->localtax2_tx;
  3868. $found=1;
  3869. */
  3870. }
  3871. else
  3872. {
  3873. // TODO Read default product vat according to countrycode and product
  3874. }
  3875. }
  3876. if (! $found)
  3877. {
  3878. // If vat of product for the country not found or not defined, we return higher vat of country.
  3879. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  3880. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3881. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  3882. $sql.= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  3883. $sql.= $db->plimit(1);
  3884. $resql=$db->query($sql);
  3885. if ($resql)
  3886. {
  3887. $obj=$db->fetch_object($resql);
  3888. if ($obj)
  3889. {
  3890. if ($local==1) $ret=$obj->localtax1;
  3891. elseif ($local==2) $ret=$obj->localtax2;
  3892. }
  3893. }
  3894. else dol_print_error($db);
  3895. }
  3896. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  3897. return $ret;
  3898. }
  3899. /**
  3900. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  3901. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  3902. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  3903. * Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  3904. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par defaut=TVA du produit vendu. Fin de regle
  3905. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  3906. * Sinon TVA proposee par defaut=0. Fin de regle.
  3907. *
  3908. * @param Societe $thirdparty_seller Objet societe vendeuse
  3909. * @param Societe $thirdparty_buyer Objet societe acheteuse
  3910. * @param int $idprod Id product
  3911. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  3912. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  3913. * @see get_default_npr, get_default_localtax
  3914. */
  3915. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  3916. {
  3917. global $conf;
  3918. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  3919. $seller_use_vat=((is_numeric($thirdparty_seller->tva_assuj) && ! $thirdparty_seller->tva_assuj) || (! is_numeric($thirdparty_seller->tva_assuj) && $thirdparty_seller->tva_assuj=='franchise'))?0:1;
  3920. $seller_country_code=$thirdparty_seller->country_code;
  3921. $seller_in_cee=$thirdparty_seller->isInEEC();
  3922. $buyer_country_code=$thirdparty_buyer->country_code;
  3923. $buyer_in_cee=$thirdparty_buyer->isInEEC();
  3924. dol_syslog("get_default_tva: seller use vat=".$seller_use_vat.", seller country=".$seller_country_code.", seller in cee=".$seller_in_cee.", buyer country=".$buyer_country_code.", buyer in cee=".$buyer_in_cee.", idprod=".$idprod.", idprodfournprice=".$idprodfournprice.", SERVICE_ARE_ECOMMERCE_200238EC=".(! empty($conf->global->SERVICES_ARE_ECOMMERCE_200238EC)?$conf->global->SERVICES_ARE_ECOMMERCE_200238EC:''));
  3925. // If services are eServices according to EU Council Directive 2002/38/EC (http://ec.europa.eu/taxation_customs/taxation/vat/traders/e-commerce/article_1610_en.htm)
  3926. // we use the buyer VAT.
  3927. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  3928. {
  3929. if ($seller_in_cee && $buyer_in_cee && ! $thirdparty_buyer->isACompany())
  3930. {
  3931. //print 'VATRULE 0';
  3932. return get_product_vat_for_country($idprod,$thirdparty_buyer,$idprodfournprice);
  3933. }
  3934. }
  3935. // If seller does not use VAT
  3936. if (! $seller_use_vat)
  3937. {
  3938. //print 'VATRULE 1';
  3939. return 0;
  3940. }
  3941. // Le test ci-dessus ne devrait pas etre necessaire. Me signaler l'exemple du cas juridique concerne si le test suivant n'est pas suffisant.
  3942. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  3943. if (($seller_country_code == $buyer_country_code)
  3944. || (in_array($seller_country_code,array('FR,MC')) && in_array($buyer_country_code,array('FR','MC')))) // Warning ->country_code not always defined
  3945. {
  3946. //print 'VATRULE 2';
  3947. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  3948. }
  3949. // Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors 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.
  3950. // Not supported
  3951. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  3952. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  3953. if (($seller_in_cee && $buyer_in_cee))
  3954. {
  3955. $isacompany=$thirdparty_buyer->isACompany();
  3956. if ($isacompany)
  3957. {
  3958. //print 'VATRULE 3';
  3959. return 0;
  3960. }
  3961. else
  3962. {
  3963. //print 'VATRULE 4';
  3964. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  3965. }
  3966. }
  3967. // Sinon la TVA proposee par defaut=0. Fin de regle.
  3968. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  3969. //print 'VATRULE 5';
  3970. return 0;
  3971. }
  3972. /**
  3973. * Fonction qui renvoie si tva doit etre tva percue recuperable
  3974. *
  3975. * @param Societe $thirdparty_seller Thirdparty seller
  3976. * @param Societe $thirdparty_buyer Thirdparty buyer
  3977. * @param int $idprod Id product
  3978. * @param int $idprodfournprice Id supplier price for product
  3979. * @return float 0 or 1
  3980. * @see get_default_tva, get_default_localtax
  3981. */
  3982. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  3983. {
  3984. global $db;
  3985. if ($idprodfournprice > 0)
  3986. {
  3987. if (! class_exists('ProductFournisseur'))
  3988. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  3989. $prodprice = new ProductFournisseur($db);
  3990. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  3991. return $prodprice->fourn_tva_npr;
  3992. }
  3993. elseif ($idprod > 0)
  3994. {
  3995. if (! class_exists('Product'))
  3996. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  3997. $prod = new Product($db);
  3998. $prod->fetch($idprod);
  3999. return $prod->tva_npr;
  4000. }
  4001. return 0;
  4002. }
  4003. /**
  4004. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4005. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4006. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4007. * Sinon TVA proposee par defaut=0. Fin de regle.
  4008. *
  4009. * @param Societe $thirdparty_seller Thirdparty seller
  4010. * @param Societe $thirdparty_buyer Thirdparty buyer
  4011. * @param int $local Localtax to process (1 or 2)
  4012. * @param int $idprod Id product
  4013. * @return integer localtax, -1 si ne peut etre determine
  4014. * @see get_default_tva, get_default_npr
  4015. */
  4016. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod=0)
  4017. {
  4018. global $mysoc;
  4019. if (!is_object($thirdparty_seller)) return -1;
  4020. if (!is_object($thirdparty_buyer)) return -1;
  4021. if ($local==1) // Localtax 1
  4022. {
  4023. if ($mysoc->country_code == 'ES')
  4024. {
  4025. if (is_numeric($thirdparty_buyer->localtax1_assuj) && ! $thirdparty_buyer->localtax1_assuj) return 0;
  4026. }
  4027. else
  4028. {
  4029. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  4030. if (is_numeric($thirdparty_seller->localtax1_assuj) && ! $thirdparty_seller->localtax1_assuj) return 0;
  4031. if (! is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj=='localtax1off') return 0;
  4032. }
  4033. }
  4034. elseif ($local==2) //I Localtax 2
  4035. {
  4036. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  4037. if (is_numeric($thirdparty_seller->localtax2_assuj) && ! $thirdparty_seller->localtax2_assuj) return 0;
  4038. if (! is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj=='localtax2off') return 0;
  4039. }
  4040. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  4041. {
  4042. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  4043. }
  4044. return 0;
  4045. }
  4046. /**
  4047. * Return yes or no in current language
  4048. *
  4049. * @param string $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  4050. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  4051. * @param int $color 0=texte only, 1=Text is formated with a color font style ('ok' or 'error'), 2=Text is formated with 'ok' color.
  4052. * @return string HTML string
  4053. */
  4054. function yn($yesno, $case=1, $color=0)
  4055. {
  4056. global $langs;
  4057. $result='unknown'; $classname='';
  4058. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  4059. {
  4060. $result=$langs->trans('yes');
  4061. if ($case == 1 || $case == 3) $result=$langs->trans("Yes");
  4062. if ($case == 2) $result='<input type="checkbox" value="1" checked disabled>';
  4063. if ($case == 3) $result='<input type="checkbox" value="1" checked disabled> '.$result;
  4064. $classname='ok';
  4065. }
  4066. elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  4067. {
  4068. $result=$langs->trans("no");
  4069. if ($case == 1 || $case == 3) $result=$langs->trans("No");
  4070. if ($case == 2) $result='<input type="checkbox" value="0" disabled>';
  4071. if ($case == 3) $result='<input type="checkbox" value="0" disabled> '.$result;
  4072. if ($color == 2) $classname='ok';
  4073. else $classname='error';
  4074. }
  4075. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  4076. return $result;
  4077. }
  4078. /**
  4079. * Return a path to have a directory according to object.
  4080. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'modulepart')
  4081. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, 'modulepart') if multidir_output not defined.
  4082. * Old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  4083. *
  4084. * @param string $num Id of object (deprecated, $object will be used in future)
  4085. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  4086. * @param int $alpha 0=Keep number only to forge path, 1=Use alpha part afer the - (By default, use 0). (deprecated, global option will be used in future)
  4087. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  4088. * @param Object $object Object
  4089. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...')
  4090. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  4091. */
  4092. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
  4093. {
  4094. global $conf;
  4095. $path = '';
  4096. $arrayforoldpath=array('cheque','user','category','holiday','shipment','supplier_invoice','invoice_supplier','mailing','supplier_payment');
  4097. if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[]='product';
  4098. if (! empty($level) && in_array($modulepart, $arrayforoldpath))
  4099. {
  4100. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  4101. if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
  4102. else $num = preg_replace('/^.*\-/i','',$num);
  4103. $num = substr("000".$num, -$level);
  4104. if ($level == 1) $path = substr($num,0,1);
  4105. if ($level == 2) $path = substr($num,1,1).'/'.substr($num,0,1);
  4106. if ($level == 3) $path = substr($num,2,1).'/'.substr($num,1,1).'/'.substr($num,0,1);
  4107. }
  4108. else
  4109. {
  4110. // TODO
  4111. // We will enhance here a common way of forging path for document storage
  4112. // Here, object->id, object->ref and object->modulepart are required.
  4113. if (in_array($modulepart, array('thirdparty','contact','member')))
  4114. {
  4115. $path=$object->ref?$object->ref:$object->id;
  4116. }
  4117. }
  4118. if (empty($withoutslash) && ! empty($path)) $path.='/';
  4119. return $path;
  4120. }
  4121. /**
  4122. * Creation of a directory (this can create recursive subdir)
  4123. *
  4124. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  4125. * @param string $dataroot Data root directory (To avoid having the data root in the loop. Using this will also lost the warning on first dir PHP has no permission when open_basedir is used)
  4126. * @param int $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  4127. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  4128. */
  4129. function dol_mkdir($dir, $dataroot='', $newmask=null)
  4130. {
  4131. global $conf;
  4132. dol_syslog("functions.lib::dol_mkdir: dir=".$dir,LOG_INFO);
  4133. $dir_osencoded=dol_osencode($dir);
  4134. if (@is_dir($dir_osencoded)) return 0;
  4135. $nberr=0;
  4136. $nbcreated=0;
  4137. $ccdir='';
  4138. if (! empty($dataroot)) {
  4139. // Remove data root from loop
  4140. $dir = str_replace($dataroot.'/', '', $dir);
  4141. $ccdir = $dataroot.'/';
  4142. }
  4143. $cdir = explode("/", $dir);
  4144. $num=count($cdir);
  4145. for ($i = 0; $i < $num; $i++)
  4146. {
  4147. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  4148. else $ccdir .= $cdir[$i];
  4149. if (preg_match("/^.:$/",$ccdir,$regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  4150. // Attention, le is_dir() peut echouer bien que le rep existe.
  4151. // (ex selon config de open_basedir)
  4152. if ($ccdir)
  4153. {
  4154. $ccdir_osencoded=dol_osencode($ccdir);
  4155. if (! @is_dir($ccdir_osencoded))
  4156. {
  4157. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.",LOG_DEBUG);
  4158. umask(0);
  4159. $dirmaskdec=octdec($newmask);
  4160. if (empty($newmask)) {
  4161. $dirmaskdec = empty( $conf->global->MAIN_UMASK ) ? octdec( '0755' ) : octdec( $conf->global->MAIN_UMASK );
  4162. }
  4163. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  4164. if (! @mkdir($ccdir_osencoded, $dirmaskdec))
  4165. {
  4166. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  4167. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING);
  4168. $nberr++;
  4169. }
  4170. else
  4171. {
  4172. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created",LOG_DEBUG);
  4173. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  4174. $nbcreated++;
  4175. }
  4176. }
  4177. else
  4178. {
  4179. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  4180. }
  4181. }
  4182. }
  4183. return ($nberr ? -$nberr : $nbcreated);
  4184. }
  4185. /**
  4186. * Return picto saying a field is required
  4187. *
  4188. * @return string Chaine avec picto obligatoire
  4189. */
  4190. function picto_required()
  4191. {
  4192. return '<span class="fieldrequired">*</span>';
  4193. }
  4194. /**
  4195. * Clean a string from all HTML tags and entities
  4196. *
  4197. * @param string $StringHtml String to clean
  4198. * @param integer $removelinefeed 1=Replace also new lines by a space, 0=Only last one are removed
  4199. * @param string $pagecodeto Encoding of input/output string
  4200. * @return string String cleaned
  4201. *
  4202. * @see dol_escape_htmltag
  4203. */
  4204. function dol_string_nohtmltag($StringHtml,$removelinefeed=1,$pagecodeto='UTF-8')
  4205. {
  4206. $pattern = "/<[^<>]+>/";
  4207. $StringHtml = preg_replace('/<br[^>]*>/', "\n", $StringHtml);
  4208. $temp = dol_html_entity_decode($StringHtml,ENT_COMPAT,$pagecodeto);
  4209. $temp = preg_replace($pattern,"",$temp);
  4210. // Supprime aussi les retours
  4211. if ($removelinefeed) $temp=str_replace(array("\r\n","\r","\n")," ",$temp);
  4212. // et les espaces doubles
  4213. while(strpos($temp," "))
  4214. {
  4215. $temp = str_replace(" "," ",$temp);
  4216. }
  4217. $CleanString = trim($temp);
  4218. return $CleanString;
  4219. }
  4220. /**
  4221. * Return first line of text. Cut will depends if content is HTML or not.
  4222. *
  4223. * @param string $text Input text
  4224. * @return string Output text
  4225. * @see dol_nboflines_bis, dol_string_nohtmltag, dol_escape_htmltag
  4226. */
  4227. function dolGetFirstLineOfText($text)
  4228. {
  4229. if (dol_textishtml($text))
  4230. {
  4231. $firstline=preg_replace('/<br[^>]*>.*$/s','',$text); // The s pattern modifier means the . can match newline characters
  4232. $firstline=preg_replace('/<div[^>]*>.*$/s','',$firstline); // The s pattern modifier means the . can match newline characters
  4233. }
  4234. else
  4235. {
  4236. $firstline=preg_replace('/[\n\r].*/','',$text);
  4237. }
  4238. return $firstline.((strlen($firstline) != strlen($text))?'...':'');
  4239. }
  4240. /**
  4241. * Replace CRLF in string with a HTML BR tag
  4242. *
  4243. * @param string $stringtoencode String to encode
  4244. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  4245. * @param bool $forxml false=Use <br>, true=Use <br />
  4246. * @return string String encoded
  4247. * @see dol_nboflines, dolGetFirstLineOfText
  4248. */
  4249. function dol_nl2br($stringtoencode,$nl2brmode=0,$forxml=false)
  4250. {
  4251. if (!$nl2brmode) {
  4252. return nl2br($stringtoencode, $forxml);
  4253. } else {
  4254. $ret=preg_replace('/(\r\n|\r|\n)/i', ($forxml?'<br />':'<br>'), $stringtoencode);
  4255. return $ret;
  4256. }
  4257. }
  4258. /**
  4259. * This function is called to encode a string into a HTML string but differs from htmlentities because
  4260. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,> are converted.
  4261. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  4262. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  4263. * For PDF usage, you can show text by 2 ways:
  4264. * - writeHTMLCell -> param must be encoded into HTML.
  4265. * - MultiCell -> param must not be encoded into HTML.
  4266. * Because writeHTMLCell convert also \n into <br>, if function
  4267. * is used to build PDF, nl2brmode must be 1.
  4268. *
  4269. * @param string $stringtoencode String to encode
  4270. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  4271. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  4272. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  4273. * @return string String encoded
  4274. */
  4275. function dol_htmlentitiesbr($stringtoencode,$nl2brmode=0,$pagecodefrom='UTF-8',$removelasteolbr=1)
  4276. {
  4277. $newstring=$stringtoencode;
  4278. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  4279. {
  4280. $newstring=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i','<br>',$newstring); // Replace "<br type="_moz" />" by "<br>". It's same and avoid pb with FPDF.
  4281. if ($removelasteolbr) $newstring=preg_replace('/<br>$/i','',$newstring); // Remove last <br> (remove only last one)
  4282. $newstring=strtr($newstring,array('&'=>'__and__','<'=>'__lt__','>'=>'__gt__','"'=>'__dquot__'));
  4283. $newstring=dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom); // Make entity encoding
  4284. $newstring=strtr($newstring,array('__and__'=>'&','__lt__'=>'<','__gt__'=>'>','__dquot__'=>'"'));
  4285. }
  4286. else
  4287. {
  4288. if ($removelasteolbr) $newstring=preg_replace('/(\r\n|\r|\n)$/i','',$newstring); // Remove last \n (may remove several)
  4289. $newstring=dol_nl2br(dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom),$nl2brmode);
  4290. }
  4291. // Other substitutions that htmlentities does not do
  4292. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  4293. return $newstring;
  4294. }
  4295. /**
  4296. * This function is called to decode a HTML string (it decodes entities and br tags)
  4297. *
  4298. * @param string $stringtodecode String to decode
  4299. * @param string $pagecodeto Page code for result
  4300. * @return string String decoded
  4301. */
  4302. function dol_htmlentitiesbr_decode($stringtodecode,$pagecodeto='UTF-8')
  4303. {
  4304. $ret=dol_html_entity_decode($stringtodecode,ENT_COMPAT,$pagecodeto);
  4305. $ret=preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i',"<br>",$ret);
  4306. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i',"\r\n",$ret);
  4307. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i',"\n",$ret);
  4308. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i',"\n",$ret);
  4309. return $ret;
  4310. }
  4311. /**
  4312. * This function remove all ending \n and br at end
  4313. *
  4314. * @param string $stringtodecode String to decode
  4315. * @return string String decoded
  4316. */
  4317. function dol_htmlcleanlastbr($stringtodecode)
  4318. {
  4319. $ret=preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i',"",$stringtodecode);
  4320. return $ret;
  4321. }
  4322. /**
  4323. * Replace html_entity_decode functions to manage errors
  4324. *
  4325. * @param string $a Operand a
  4326. * @param string $b Operand b (ENT_QUOTES=convert simple and double quotes)
  4327. * @param string $c Operand c
  4328. * @return string String decoded
  4329. */
  4330. function dol_html_entity_decode($a,$b,$c='UTF-8')
  4331. {
  4332. return html_entity_decode($a,$b,$c);
  4333. }
  4334. /**
  4335. * Replace htmlentities functions to manage errors http://php.net/manual/en/function.htmlentities.php
  4336. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  4337. *
  4338. * @param string $string The input string.
  4339. * @param int $flags Flags(see PHP doc above)
  4340. * @param string $encoding Encoding
  4341. * @param bool $double_encode When double_encode is turned off PHP will not encode existing html entities
  4342. * @return string $ret Encoded string
  4343. */
  4344. function dol_htmlentities($string, $flags=null, $encoding='UTF-8', $double_encode=false)
  4345. {
  4346. return htmlentities($string, $flags, $encoding, $double_encode);
  4347. }
  4348. /**
  4349. * Check if a string is a correct iso string
  4350. * If not, it will we considered not HTML encoded even if it is by FPDF.
  4351. * Example, if string contains euro symbol that has ascii code 128
  4352. *
  4353. * @param string $s String to check
  4354. * @return int 0 if bad iso, 1 if good iso
  4355. */
  4356. function dol_string_is_good_iso($s)
  4357. {
  4358. $len=dol_strlen($s);
  4359. $ok=1;
  4360. for($scursor=0;$scursor<$len;$scursor++)
  4361. {
  4362. $ordchar=ord($s{$scursor});
  4363. //print $scursor.'-'.$ordchar.'<br>';
  4364. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok=0; break; }
  4365. if ($ordchar > 126 && $ordchar < 160) { $ok=0; break; }
  4366. }
  4367. return $ok;
  4368. }
  4369. /**
  4370. * Return nb of lines of a clear text
  4371. *
  4372. * @param string $s String to check
  4373. * @param int $maxchar Not yet used
  4374. * @return int Number of lines
  4375. * @see dol_nboflines_bis, dolGetFirstLineOfText
  4376. */
  4377. function dol_nboflines($s,$maxchar=0)
  4378. {
  4379. if ($s == '') return 0;
  4380. $arraystring=explode("\n",$s);
  4381. $nb=count($arraystring);
  4382. return $nb;
  4383. }
  4384. /**
  4385. * Return nb of lines of a formated text with \n and <br> (we can't have both \n and br)
  4386. *
  4387. * @param string $text Text
  4388. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  4389. * @param string $charset Give the charset used to encode the $text variable in memory.
  4390. * @return int Number of lines
  4391. * @see dol_nboflines, dolGetFirstLineOfText
  4392. */
  4393. function dol_nboflines_bis($text,$maxlinesize=0,$charset='UTF-8')
  4394. {
  4395. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  4396. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  4397. $text = strtr($text, $repTable);
  4398. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  4399. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  4400. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  4401. $nblines = (int) floor((count($a)+1)/2);
  4402. // count possible auto line breaks
  4403. if($maxlinesize)
  4404. {
  4405. foreach ($a as $line)
  4406. {
  4407. if (dol_strlen($line)>$maxlinesize)
  4408. {
  4409. //$line_dec = html_entity_decode(strip_tags($line));
  4410. $line_dec = html_entity_decode($line);
  4411. if(dol_strlen($line_dec)>$maxlinesize)
  4412. {
  4413. $line_dec=wordwrap($line_dec,$maxlinesize,'\n',true);
  4414. $nblines+=substr_count($line_dec,'\n');
  4415. }
  4416. }
  4417. }
  4418. }
  4419. return $nblines;
  4420. }
  4421. /**
  4422. * Same function than microtime in PHP 5 but compatible with PHP4
  4423. *
  4424. * @return float Time (millisecondes) with microsecondes in decimal part
  4425. * @deprecated Dolibarr does not support PHP4, you should use native function
  4426. * @see microtime()
  4427. */
  4428. function dol_microtime_float()
  4429. {
  4430. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  4431. return microtime(true);
  4432. }
  4433. /**
  4434. * Return if a text is a html content
  4435. *
  4436. * @param string $msg Content to check
  4437. * @param int $option 0=Full detection, 1=Fast check
  4438. * @return boolean true/false
  4439. * @see dol_concatdesc
  4440. */
  4441. function dol_textishtml($msg,$option=0)
  4442. {
  4443. if ($option == 1)
  4444. {
  4445. if (preg_match('/<html/i',$msg)) return true;
  4446. elseif (preg_match('/<body/i',$msg)) return true;
  4447. elseif (preg_match('/<br/i',$msg)) return true;
  4448. return false;
  4449. }
  4450. else
  4451. {
  4452. if (preg_match('/<html/i',$msg)) return true;
  4453. elseif (preg_match('/<body/i',$msg)) return true;
  4454. elseif (preg_match('/<(b|em|i|u)>/i',$msg)) return true;
  4455. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i',$msg)) return true;
  4456. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i',$msg)) return true;
  4457. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i',$msg)) return true;
  4458. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i',$msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  4459. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i',$msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  4460. elseif (preg_match('/<h[0-9]>/i',$msg)) return true;
  4461. elseif (preg_match('/&[A-Z0-9]{1,6};/i',$msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  4462. elseif (preg_match('/&#[0-9]{2,3};/i',$msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  4463. return false;
  4464. }
  4465. }
  4466. /**
  4467. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  4468. * text1 html + text2 html => text1 + '<br>' + text2
  4469. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  4470. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  4471. * text1 txt + text2 txt => text1 + '\n' + text2
  4472. *
  4473. * @param string $text1 Text 1
  4474. * @param string $text2 Text 2
  4475. * @param bool $forxml false=Use <br>, true=Use <br />
  4476. * @return string Text 1 + new line + Text2
  4477. * @see dol_textishtml
  4478. */
  4479. function dol_concatdesc($text1,$text2,$forxml=false)
  4480. {
  4481. $ret='';
  4482. $ret.= (! dol_textishtml($text1) && dol_textishtml($text2))?dol_nl2br($text1, 0, $forxml):$text1;
  4483. $ret.= (! empty($text1) && ! empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2))?($forxml?"<br \>\n":"<br>\n") : "\n") : "";
  4484. $ret.= (dol_textishtml($text1) && ! dol_textishtml($text2))?dol_nl2br($text2, 0, $forxml):$text2;
  4485. return $ret;
  4486. }
  4487. /**
  4488. * Make substition into a string replacing key with vals from $substitutionarray (oldval=>newval)
  4489. *
  4490. * @param string $text Source string in which we must do substitution
  4491. * @param array $substitutionarray Array with key->val to substitute
  4492. * @param Translate $outputlangs Output language
  4493. * @return string Output string after substitutions
  4494. * @see complete_substitutions_array
  4495. */
  4496. function make_substitutions($text, $substitutionarray, $outputlangs=null)
  4497. {
  4498. global $conf, $langs;
  4499. if (! is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  4500. if (empty($outputlangs)) $outputlangs=$langs;
  4501. // Make substitution for language keys
  4502. if (is_object($outputlangs))
  4503. {
  4504. while (preg_match('/__\((.*)\)__/', $text, $reg))
  4505. {
  4506. $msgishtml = 0;
  4507. if (dol_textishtml($text,1)) $msgishtml = 1;
  4508. $text = preg_replace('/__\('.preg_quote($reg[1]).'\)__/', $msgishtml?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])):$outputlangs->transnoentitiesnoconv($reg[1]), $text);
  4509. }
  4510. }
  4511. // Make substitition for array $substitutionarray
  4512. foreach ($substitutionarray as $key => $value)
  4513. {
  4514. if ($key == '__SIGNATURE__' && (! empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value='';
  4515. $text=str_replace("$key","$value",$text); // We must keep the " to work when value is 123.5 for example
  4516. }
  4517. return $text;
  4518. }
  4519. /**
  4520. * Complete the $substitutionarray with more entries.
  4521. * Can also add substitution keys coming from external module that had set the "substitutions=1" into module_part array. In this case, method completesubstitutionarray provided by module is called.
  4522. *
  4523. * @param array $substitutionarray Array substitution old value => new value value
  4524. * @param Translate $outputlangs Output language
  4525. * @param Object $object Source object
  4526. * @param mixed $parameters Add more parameters (useful to pass product lines)
  4527. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  4528. * @return void
  4529. * @see make_substitutions
  4530. */
  4531. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
  4532. {
  4533. global $conf,$user;
  4534. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4535. // Add a substitution key for each object property
  4536. if (is_object($object))
  4537. {
  4538. // TODO
  4539. }
  4540. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  4541. if (is_object($object) && is_array($object->array_options))
  4542. {
  4543. foreach($object->array_options as $key => $val)
  4544. {
  4545. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  4546. $substitutionarray['__EXTRA_'.$keyshort.'__']=$val;
  4547. // For backward compatibiliy
  4548. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  4549. }
  4550. }
  4551. // Check if there is external substitution to do, requested by plugins
  4552. $dirsubstitutions=array_merge(array(),(array) $conf->modules_parts['substitutions']);
  4553. foreach($dirsubstitutions as $reldir)
  4554. {
  4555. $dir=dol_buildpath($reldir,0);
  4556. // Check if directory exists
  4557. if (! dol_is_dir($dir)) continue;
  4558. $substitfiles=dol_dir_list($dir,'files',0,'functions_');
  4559. foreach($substitfiles as $substitfile)
  4560. {
  4561. if (preg_match('/functions_(.*)\.lib\.php/i',$substitfile['name'],$reg))
  4562. {
  4563. $module=$reg[1];
  4564. dol_syslog("Library functions_".$substitfile['name']." found into ".$dir);
  4565. // Include the user's functions file
  4566. require_once $dir.$substitfile['name'];
  4567. // Call the user's function, and only if it is defined
  4568. $function_name=$module."_".$callfunc;
  4569. if (function_exists($function_name)) $function_name($substitutionarray,$outputlangs,$object,$parameters);
  4570. }
  4571. }
  4572. }
  4573. }
  4574. /**
  4575. * Format output for start and end date
  4576. *
  4577. * @param int $date_start Start date
  4578. * @param int $date_end End date
  4579. * @param string $format Output format
  4580. * @param Translate $outputlangs Output language
  4581. * @return void
  4582. */
  4583. function print_date_range($date_start,$date_end,$format = '',$outputlangs='')
  4584. {
  4585. print get_date_range($date_start,$date_end,$format,$outputlangs);
  4586. }
  4587. /**
  4588. * Format output for start and end date
  4589. *
  4590. * @param int $date_start Start date
  4591. * @param int $date_end End date
  4592. * @param string $format Output format
  4593. * @param Translate $outputlangs Output language
  4594. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  4595. * @return string String
  4596. */
  4597. function get_date_range($date_start,$date_end,$format = '',$outputlangs='', $withparenthesis=1)
  4598. {
  4599. global $langs;
  4600. $out='';
  4601. if (! is_object($outputlangs)) $outputlangs=$langs;
  4602. if ($date_start && $date_end)
  4603. {
  4604. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFromTo',dol_print_date($date_start, $format, false, $outputlangs),dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  4605. }
  4606. if ($date_start && ! $date_end)
  4607. {
  4608. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFrom',dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis?')':'');
  4609. }
  4610. if (! $date_start && $date_end)
  4611. {
  4612. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateUntil',dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  4613. }
  4614. return $out;
  4615. }
  4616. /**
  4617. * Return firstname and lastname in correct order
  4618. *
  4619. * @param string $firstname Firstname
  4620. * @param string $lastname Lastname
  4621. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
  4622. * @return string Firstname + lastname or Lastname + firstname
  4623. */
  4624. function dolGetFirstLastname($firstname,$lastname,$nameorder=-1)
  4625. {
  4626. global $conf;
  4627. $ret='';
  4628. // If order not defined, we use the setup
  4629. if ($nameorder < 0) $nameorder=(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION));
  4630. if ($nameorder && ((string) $nameorder != '2'))
  4631. {
  4632. $ret.=$firstname;
  4633. if ($firstname && $lastname) $ret.=' ';
  4634. $ret.=$lastname;
  4635. }
  4636. else if ($nameorder == 2)
  4637. {
  4638. $ret.=$firstname;
  4639. }
  4640. else
  4641. {
  4642. $ret.=$lastname;
  4643. if ($firstname && $lastname) $ret.=' ';
  4644. $ret.=$firstname;
  4645. }
  4646. return $ret;
  4647. }
  4648. /**
  4649. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  4650. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  4651. * Note: Prefer to use setEventMessages instead.
  4652. *
  4653. * @param mixed $mesgs Message string or array
  4654. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  4655. * @return void
  4656. * @see dol_htmloutput_events
  4657. */
  4658. function setEventMessage($mesgs, $style='mesgs')
  4659. {
  4660. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  4661. if (! is_array($mesgs)) // If mesgs is a string
  4662. {
  4663. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  4664. }
  4665. else // If mesgs is an array
  4666. {
  4667. foreach($mesgs as $mesg)
  4668. {
  4669. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  4670. }
  4671. }
  4672. }
  4673. /**
  4674. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  4675. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  4676. *
  4677. * @param string $mesg Message string
  4678. * @param array $mesgs Message array
  4679. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  4680. * @return void
  4681. * @see dol_htmloutput_events
  4682. */
  4683. function setEventMessages($mesg, $mesgs, $style='mesgs')
  4684. {
  4685. if (! in_array((string) $style, array('mesgs','warnings','errors'))) dol_print_error('','Bad parameter style='.$style.' for setEventMessages');
  4686. if (empty($mesgs)) setEventMessage($mesg, $style);
  4687. else
  4688. {
  4689. if (! empty($mesg) && ! in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  4690. setEventMessage($mesgs, $style);
  4691. }
  4692. }
  4693. /**
  4694. * Print formated messages to output (Used to show messages on html output).
  4695. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  4696. * no need to call it explicitely.
  4697. *
  4698. * @return void
  4699. * @see dol_htmloutput_mesg
  4700. */
  4701. function dol_htmloutput_events()
  4702. {
  4703. // Show mesgs
  4704. if (isset($_SESSION['dol_events']['mesgs'])) {
  4705. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  4706. unset($_SESSION['dol_events']['mesgs']);
  4707. }
  4708. // Show errors
  4709. if (isset($_SESSION['dol_events']['errors'])) {
  4710. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  4711. unset($_SESSION['dol_events']['errors']);
  4712. }
  4713. // Show warnings
  4714. if (isset($_SESSION['dol_events']['warnings'])) {
  4715. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  4716. unset($_SESSION['dol_events']['warnings']);
  4717. }
  4718. }
  4719. /**
  4720. * Get formated messages to output (Used to show messages on html output).
  4721. * This include also the translation of the message key.
  4722. *
  4723. * @param string $mesgstring Message string or message key
  4724. * @param string[] $mesgarray Array of message strings or message keys
  4725. * @param string $style Style of message output ('ok' or 'error')
  4726. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  4727. * @return string Return html output
  4728. *
  4729. * @see dol_print_error
  4730. * @see dol_htmloutput_errors
  4731. * @see setEventMessages
  4732. */
  4733. function get_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
  4734. {
  4735. global $conf, $langs;
  4736. $ret=0; $return='';
  4737. $out='';
  4738. $divstart=$divend='';
  4739. // If inline message with no format, we add it.
  4740. if ((empty($conf->use_javascript_ajax) || ! empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && ! preg_match('/<div class=".*">/i',$out))
  4741. {
  4742. $divstart='<div class="'.$style.'">';
  4743. $divend='</div>';
  4744. }
  4745. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  4746. {
  4747. $langs->load("errors");
  4748. $out.=$divstart;
  4749. if (is_array($mesgarray) && count($mesgarray))
  4750. {
  4751. foreach($mesgarray as $message)
  4752. {
  4753. $ret++;
  4754. $out.= $langs->trans($message);
  4755. if ($ret < count($mesgarray)) $out.= "<br>\n";
  4756. }
  4757. }
  4758. if ($mesgstring)
  4759. {
  4760. $langs->load("errors");
  4761. $ret++;
  4762. $out.= $langs->trans($mesgstring);
  4763. }
  4764. $out.=$divend;
  4765. }
  4766. if ($out)
  4767. {
  4768. if (! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  4769. {
  4770. $return = '<script type="text/javascript">
  4771. $(document).ready(function() {
  4772. var block = '.(! empty($conf->global->MAIN_USE_JQUERY_BLOCKUI)?"true":"false").'
  4773. if (block) {
  4774. $.dolEventValid("","'.dol_escape_js($out).'");
  4775. } else {
  4776. /* jnotify(message, preset of message type, keepmessage) */
  4777. $.jnotify("'.dol_escape_js($out).'",
  4778. "'.($style=="ok" ? 3000 : $style).'",
  4779. '.($style=="ok" ? "false" : "true").',
  4780. { remove: function (){} } );
  4781. }
  4782. });
  4783. </script>';
  4784. }
  4785. else
  4786. {
  4787. $return = $out;
  4788. }
  4789. }
  4790. return $return;
  4791. }
  4792. /**
  4793. * Get formated error messages to output (Used to show messages on html output).
  4794. *
  4795. * @param string $mesgstring Error message
  4796. * @param array $mesgarray Error messages array
  4797. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  4798. * @return string Return html output
  4799. *
  4800. * @see dol_print_error
  4801. * @see dol_htmloutput_mesg
  4802. */
  4803. function get_htmloutput_errors($mesgstring='', $mesgarray='', $keepembedded=0)
  4804. {
  4805. return get_htmloutput_mesg($mesgstring, $mesgarray,'error',$keepembedded);
  4806. }
  4807. /**
  4808. * Print formated messages to output (Used to show messages on html output).
  4809. *
  4810. * @param string $mesgstring Message string or message key
  4811. * @param string[] $mesgarray Array of message strings or message keys
  4812. * @param string $style Which style to use ('ok', 'warning', 'error')
  4813. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  4814. * @return void
  4815. *
  4816. * @see dol_print_error
  4817. * @see dol_htmloutput_errors
  4818. * @see setEventMessages
  4819. */
  4820. function dol_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
  4821. {
  4822. if (empty($mesgstring) && (! is_array($mesgarray) || count($mesgarray) == 0)) return;
  4823. $iserror=0;
  4824. $iswarning=0;
  4825. if (is_array($mesgarray))
  4826. {
  4827. foreach($mesgarray as $val)
  4828. {
  4829. if ($val && preg_match('/class="error"/i',$val)) { $iserror++; break; }
  4830. if ($val && preg_match('/class="warning"/i',$val)) { $iswarning++; break; }
  4831. }
  4832. }
  4833. else if ($mesgstring && preg_match('/class="error"/i',$mesgstring)) $iserror++;
  4834. else if ($mesgstring && preg_match('/class="warning"/i',$mesgstring)) $iswarning++;
  4835. if ($style=='error') $iserror++;
  4836. if ($style=='warning') $iswarning++;
  4837. if ($iserror || $iswarning)
  4838. {
  4839. // Remove div from texts
  4840. $mesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$mesgstring);
  4841. $mesgstring=preg_replace('/<div class="(error|warning)">/','',$mesgstring);
  4842. $mesgstring=preg_replace('/<\/div>/','',$mesgstring);
  4843. // Remove div from texts array
  4844. if (is_array($mesgarray))
  4845. {
  4846. $newmesgarray=array();
  4847. foreach($mesgarray as $val)
  4848. {
  4849. $tmpmesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$val);
  4850. $tmpmesgstring=preg_replace('/<div class="(error|warning)">/','',$tmpmesgstring);
  4851. $tmpmesgstring=preg_replace('/<\/div>/','',$tmpmesgstring);
  4852. $newmesgarray[]=$tmpmesgstring;
  4853. }
  4854. $mesgarray=$newmesgarray;
  4855. }
  4856. print get_htmloutput_mesg($mesgstring,$mesgarray,($iserror?'error':'warning'),$keepembedded);
  4857. }
  4858. else print get_htmloutput_mesg($mesgstring,$mesgarray,'ok',$keepembedded);
  4859. }
  4860. /**
  4861. * Print formated error messages to output (Used to show messages on html output).
  4862. *
  4863. * @param string $mesgstring Error message
  4864. * @param array $mesgarray Error messages array
  4865. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  4866. * @return void
  4867. *
  4868. * @see dol_print_error
  4869. * @see dol_htmloutput_mesg
  4870. */
  4871. function dol_htmloutput_errors($mesgstring='', $mesgarray='', $keepembedded=0)
  4872. {
  4873. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  4874. }
  4875. /**
  4876. * Advanced sort array by second index function, which produces ascending (default)
  4877. * or descending output and uses optionally natural case insensitive sorting (which
  4878. * can be optionally case sensitive as well).
  4879. *
  4880. * @param array $array Array to sort (array of array('key','otherkey1','otherkey2'...))
  4881. * @param string $index Key in array to use for sorting criteria
  4882. * @param int $order Sort order ('asc' or 'desc')
  4883. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  4884. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  4885. * @param int $keepindex If 0 and index key of array to sort is a numeric, than index will be rewrote. If 1 or index key is not numeric, key for index is kept after sorting.
  4886. * @return array Sorted array
  4887. */
  4888. function dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
  4889. {
  4890. // Clean parameters
  4891. $order=strtolower($order);
  4892. $sizearray=count($array);
  4893. if (is_array($array) && $sizearray>0)
  4894. {
  4895. $temp = array();
  4896. foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
  4897. if (!$natsort) ($order=='asc') ? asort($temp) : arsort($temp);
  4898. else
  4899. {
  4900. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  4901. if($order!='asc') $temp=array_reverse($temp,TRUE);
  4902. }
  4903. $sorted = array();
  4904. foreach(array_keys($temp) as $key)
  4905. {
  4906. (is_numeric($key) && empty($keepindex)) ? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
  4907. }
  4908. return $sorted;
  4909. }
  4910. return $array;
  4911. }
  4912. /**
  4913. * Check if a string is in UTF8
  4914. *
  4915. * @param string $str String to check
  4916. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  4917. */
  4918. function utf8_check($str)
  4919. {
  4920. // We must use here a binary strlen function (so not dol_strlen)
  4921. $strLength = dol_strlen($str);
  4922. for ($i=0; $i<$strLength; $i++)
  4923. {
  4924. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  4925. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n=1; // 110bbbbb
  4926. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n=2; // 1110bbbb
  4927. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n=3; // 11110bbb
  4928. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n=4; // 111110bb
  4929. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n=5; // 1111110b
  4930. else return false; // Does not match any model
  4931. for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
  4932. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  4933. return false;
  4934. }
  4935. }
  4936. return true;
  4937. }
  4938. /**
  4939. * Return a string encoded into OS filesystem encoding. This function is used to define
  4940. * value to pass to filesystem PHP functions.
  4941. *
  4942. * @param string $str String to encode (UTF-8)
  4943. * @return string Encoded string (UTF-8, ISO-8859-1)
  4944. */
  4945. function dol_osencode($str)
  4946. {
  4947. global $conf;
  4948. $tmp=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  4949. if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1'; // By default for windows
  4950. if (empty($tmp)) $tmp='utf-8'; // By default for other
  4951. if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING;
  4952. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  4953. return $str;
  4954. }
  4955. /**
  4956. * Return an id or code from a code or id.
  4957. * Store also Code-Id into a cache to speed up next request on same key.
  4958. *
  4959. * @param DoliDB $db Database handler
  4960. * @param string $key Code or Id to get Id or Code
  4961. * @param string $tablename Table name without prefix
  4962. * @param string $fieldkey Field for code
  4963. * @param string $fieldid Field for id
  4964. * @return int <0 if KO, Id of code if OK
  4965. * @see $langs->getLabelFromKey
  4966. */
  4967. function dol_getIdFromCode($db,$key,$tablename,$fieldkey='code',$fieldid='id')
  4968. {
  4969. global $cache_codes;
  4970. // If key empty
  4971. if ($key == '') return '';
  4972. // Check in cache
  4973. if (isset($cache_codes[$tablename][$key])) // Can be defined to 0 or ''
  4974. {
  4975. return $cache_codes[$tablename][$key]; // Found in cache
  4976. }
  4977. $sql = "SELECT ".$fieldid." as valuetoget";
  4978. $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
  4979. $sql.= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  4980. dol_syslog('dol_getIdFromCode', LOG_DEBUG);
  4981. $resql = $db->query($sql);
  4982. if ($resql)
  4983. {
  4984. $obj = $db->fetch_object($resql);
  4985. if ($obj) $cache_codes[$tablename][$key]=$obj->valuetoget;
  4986. else $cache_codes[$tablename][$key]='';
  4987. $db->free($resql);
  4988. return $cache_codes[$tablename][$key];
  4989. }
  4990. else
  4991. {
  4992. return -1;
  4993. }
  4994. }
  4995. /**
  4996. * Verify if condition in string is ok or not
  4997. *
  4998. * @param string $strRights String with condition to check
  4999. * @return boolean True or False. Return true if strRights is ''
  5000. */
  5001. function verifCond($strRights)
  5002. {
  5003. global $user,$conf,$langs;
  5004. global $leftmenu;
  5005. global $rights; // To export to dol_eval function
  5006. //print $strRights."<br>\n";
  5007. $rights = true;
  5008. if ($strRights != '')
  5009. {
  5010. //$tab_rights = explode('&&', $strRights);
  5011. //$i = 0;
  5012. //while (($i < count($tab_rights)) && ($rights == true)) {
  5013. $str = 'if(!(' . $strRights . ')) { $rights = false; }';
  5014. dol_eval($str);
  5015. // $i++;
  5016. //}
  5017. }
  5018. return $rights;
  5019. }
  5020. /**
  5021. * Replace eval function to add more security.
  5022. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  5023. *
  5024. * @param string $s String to evaluate
  5025. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  5026. * @return mixed Nothing or return of eval
  5027. */
  5028. function dol_eval($s,$returnvalue=0)
  5029. {
  5030. // Only global variables can be changed by eval function and returned to caller
  5031. global $langs, $user, $conf;
  5032. global $leftmenu;
  5033. global $rights;
  5034. global $object;
  5035. global $soc;
  5036. //print $s."<br>\n";
  5037. if ($returnvalue) return @eval('return '.$s.';');
  5038. else @eval($s);
  5039. }
  5040. /**
  5041. * Return if var element is ok
  5042. *
  5043. * @param string $element Variable to check
  5044. * @return boolean Return true of variable is not empty
  5045. */
  5046. function dol_validElement($element)
  5047. {
  5048. return (trim($element) != '');
  5049. }
  5050. /**
  5051. * Return img flag of country for a language code or country code
  5052. *
  5053. * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR)
  5054. * @return string HTML img string with flag.
  5055. */
  5056. function picto_from_langcode($codelang)
  5057. {
  5058. global $langs;
  5059. if (empty($codelang)) return '';
  5060. if (empty($codelang)) return '';
  5061. if ($codelang == 'auto')
  5062. {
  5063. return img_picto_common($langs->trans('AutoDetectLang'), 'flags/int.png');
  5064. }
  5065. $langtocountryflag = array(
  5066. 'ar_AR' => '',
  5067. 'ca_ES' => 'catalonia',
  5068. 'da_DA' => 'dk',
  5069. 'fr_CA' => 'mq',
  5070. 'sv_SV' => 'se'
  5071. );
  5072. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  5073. else
  5074. {
  5075. $tmparray = explode('_', $codelang);
  5076. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  5077. }
  5078. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png');
  5079. }
  5080. /**
  5081. * Complete or removed entries into a head array (used to build tabs).
  5082. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  5083. * Or by change using hook completeTabsHead
  5084. *
  5085. * @param Conf $conf Object conf
  5086. * @param Translate $langs Object langs
  5087. * @param object|null $object Object object
  5088. * @param array $head Object head
  5089. * @param int $h New position to fill
  5090. * @param string $type Value for object where objectvalue can be
  5091. * 'thirdparty' to add a tab in third party view
  5092. * 'intervention' to add a tab in intervention view
  5093. * 'supplier_order' to add a tab in supplier order view
  5094. * 'supplier_invoice' to add a tab in supplier invoice view
  5095. * 'invoice' to add a tab in customer invoice view
  5096. * 'order' to add a tab in customer order view
  5097. * 'product' to add a tab in product view
  5098. * 'propal' to add a tab in propal view
  5099. * 'user' to add a tab in user view
  5100. * 'group' to add a tab in group view
  5101. * 'member' to add a tab in fundation member view
  5102. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  5103. * 'ecm' to add a tab for another ecm view
  5104. * 'stock' to add a tab for warehouse view
  5105. * @param string $mode 'add' to complete head, 'remove' to remove entries
  5106. * @return void
  5107. */
  5108. function complete_head_from_modules($conf,$langs,$object,&$head,&$h,$type,$mode='add')
  5109. {
  5110. global $hookmanager;
  5111. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  5112. {
  5113. foreach ($conf->modules_parts['tabs'][$type] as $value)
  5114. {
  5115. $values=explode(':',$value);
  5116. if ($mode == 'add' && ! preg_match('/^\-/',$values[1]))
  5117. {
  5118. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  5119. {
  5120. if ($values[0] != $type) continue;
  5121. if (verifCond($values[4]))
  5122. {
  5123. if ($values[3]) $langs->load($values[3]);
  5124. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  5125. {
  5126. $substitutionarray=array();
  5127. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  5128. $label=make_substitutions($reg[1], $substitutionarray);
  5129. }
  5130. else $label=$langs->trans($values[2]);
  5131. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[5]), 1);
  5132. $head[$h][1] = $label;
  5133. $head[$h][2] = str_replace('+','',$values[1]);
  5134. $h++;
  5135. }
  5136. }
  5137. else if (count($values) == 5) // deprecated
  5138. {
  5139. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  5140. if ($values[0] != $type) continue;
  5141. if ($values[3]) $langs->load($values[3]);
  5142. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  5143. {
  5144. $substitutionarray=array();
  5145. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  5146. $label=make_substitutions($reg[1], $substitutionarray);
  5147. }
  5148. else $label=$langs->trans($values[2]);
  5149. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[4]), 1);
  5150. $head[$h][1] = $label;
  5151. $head[$h][2] = str_replace('+','',$values[1]);
  5152. $h++;
  5153. }
  5154. }
  5155. else if ($mode == 'remove' && preg_match('/^\-/',$values[1]))
  5156. {
  5157. if ($values[0] != $type) continue;
  5158. $tabname=str_replace('-','',$values[1]);
  5159. foreach($head as $key => $val)
  5160. {
  5161. $condition = (! empty($values[3]) ? verifCond($values[3]) : 1);
  5162. if ($head[$key][2]==$tabname && $condition)
  5163. {
  5164. unset($head[$key]);
  5165. break;
  5166. }
  5167. }
  5168. }
  5169. }
  5170. }
  5171. // No need to make a return $head. Var is modified as a reference
  5172. if (! empty($hookmanager))
  5173. {
  5174. $parameters=array('object' => $object, 'mode' => $mode, 'head'=>$head);
  5175. $reshook=$hookmanager->executeHooks('completeTabsHead',$parameters);
  5176. if ($reshook > 0)
  5177. {
  5178. $head = $hookmanager->resArray;
  5179. }
  5180. }
  5181. }
  5182. /**
  5183. * Print common footer :
  5184. * conf->global->MAIN_HTML_FOOTER
  5185. * conf->global->MAIN_GOOGLE_AN_ID
  5186. * conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  5187. * conf->logbuffer
  5188. *
  5189. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  5190. * @return void
  5191. */
  5192. function printCommonFooter($zone='private')
  5193. {
  5194. global $conf, $hookmanager;
  5195. global $micro_start_time;
  5196. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  5197. else print "\n".'<!-- Common footer for public page -->'."\n";
  5198. if (! empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  5199. print "\n";
  5200. if (! empty($conf->use_javascript_ajax))
  5201. {
  5202. print '<!-- Reposition management (does not work if a redirect is done after action of submission) -->'."\n";
  5203. print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() {'."\n";
  5204. print '<!-- If page_y set, we set scollbar with it -->'."\n";
  5205. print "page_y=getParameterByName('page_y', 0);";
  5206. print "if (page_y > 0) $('html, body').scrollTop(page_y);\n";
  5207. print '<!-- Set handler to add page_y param on some a href links -->'."\n";
  5208. print 'jQuery(".reposition").click(function() {
  5209. var page_y = $(document).scrollTop();
  5210. /*alert(page_y);*/
  5211. this.href=this.href+\'&page_y=\'+page_y;
  5212. });'."\n";
  5213. print '});'."\n";
  5214. if (empty($conf->dol_use_jmobile))
  5215. {
  5216. print '<!-- Set handler to switch left menu page (menuhider) -->'."\n";
  5217. print 'jQuery(".menuhider").click(function() {';
  5218. print ' console.log("We click on .menuhider");'."\n";
  5219. print " $('.side-nav').toggle();";
  5220. print " $('.login_block').toggle();";
  5221. print '});'."\n";
  5222. }
  5223. print '</script>'."\n";
  5224. }
  5225. // Google Analytics (need Google module)
  5226. if (! empty($conf->google->enabled) && ! empty($conf->global->MAIN_GOOGLE_AN_ID))
  5227. {
  5228. if (($conf->dol_use_jmobile != 4))
  5229. {
  5230. print "\n";
  5231. print '<script type="text/javascript">'."\n";
  5232. print ' var _gaq = _gaq || [];'."\n";
  5233. print ' _gaq.push([\'_setAccount\', \''.$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
  5234. print ' _gaq.push([\'_trackPageview\']);'."\n";
  5235. print ''."\n";
  5236. print ' (function() {'."\n";
  5237. print ' var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
  5238. print ' ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
  5239. print ' var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
  5240. print ' })();'."\n";
  5241. print '</script>'."\n";
  5242. }
  5243. }
  5244. // End of tuning
  5245. if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || ! empty($conf->global->MAIN_SHOW_TUNING_INFO))
  5246. {
  5247. print "\n".'<script type="text/javascript">'."\n";
  5248. print 'window.console && console.log("';
  5249. if (! empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  5250. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED)?$conf->global->MAIN_OPTIMIZE_SPEED:'off');
  5251. if (! empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  5252. {
  5253. $micro_end_time = microtime(true);
  5254. print ' - Build time: '.ceil(1000*($micro_end_time-$micro_start_time)).' ms';
  5255. }
  5256. if (function_exists("memory_get_usage"))
  5257. {
  5258. print ' - Mem: '.memory_get_usage();
  5259. }
  5260. if (function_exists("xdebug_memory_usage"))
  5261. {
  5262. print ' - XDebug time: '.ceil(1000*xdebug_time_index()).' ms';
  5263. print ' - XDebug mem: '.xdebug_memory_usage();
  5264. print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
  5265. }
  5266. if (function_exists("zend_loader_file_encoded"))
  5267. {
  5268. print ' - Zend encoded file: '.(zend_loader_file_encoded()?'yes':'no');
  5269. }
  5270. print '");'."\n";
  5271. print '</script>'."\n";
  5272. // Add Xdebug coverage of code
  5273. if (defined('XDEBUGCOVERAGE'))
  5274. {
  5275. print_r(xdebug_get_code_coverage());
  5276. }
  5277. }
  5278. // If there is some logs in buffer to show
  5279. if (count($conf->logbuffer))
  5280. {
  5281. print "\n";
  5282. print "<!-- Start of log output\n";
  5283. //print '<div class="hidden">'."\n";
  5284. foreach($conf->logbuffer as $logline)
  5285. {
  5286. print $logline."<br>\n";
  5287. }
  5288. //print '</div>'."\n";
  5289. print "End of log output -->\n";
  5290. }
  5291. $parameters=array();
  5292. $reshook=$hookmanager->executeHooks('printCommonFooter',$parameters); // Note that $action and $object may have been modified by some hooks
  5293. }
  5294. /**
  5295. * Split a string with 2 keys into key array.
  5296. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  5297. *
  5298. * @param string $string String to explode
  5299. * @param string $delimiter Delimiter between each couple of data
  5300. * @param string $kv Delimiter between key and value
  5301. * @return array Array of data exploded
  5302. */
  5303. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  5304. {
  5305. if ($a = explode($delimiter, $string))
  5306. {
  5307. $ka = array();
  5308. foreach ($a as $s) { // each part
  5309. if ($s) {
  5310. if ($pos = strpos($s, $kv)) { // key/value delimiter
  5311. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  5312. } else { // key delimiter not found
  5313. $ka[] = trim($s);
  5314. }
  5315. }
  5316. }
  5317. return $ka;
  5318. }
  5319. return array();
  5320. }
  5321. /**
  5322. * Set focus onto field with selector
  5323. *
  5324. * @param string $selector Selector ('#id')
  5325. * @return string HTML code to set focus
  5326. */
  5327. function dol_set_focus($selector)
  5328. {
  5329. print '<!-- Set focus onto a specific field -->'."\n";
  5330. print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("'.$selector.'").focus(); });</script>'."\n";
  5331. }
  5332. /**
  5333. * Return getmypid() or random PID when function is disabled
  5334. * Some web hosts disable this php function for security reasons
  5335. * and sometimes we can't redeclare function
  5336. *
  5337. * @return int
  5338. */
  5339. function dol_getmypid()
  5340. {
  5341. if (! function_exists('getmypid')) {
  5342. return mt_rand(1,32768);
  5343. } else {
  5344. return getmypid();
  5345. }
  5346. }
  5347. /**
  5348. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  5349. *
  5350. * @param string|string[] $fields String or array of strings, filled with the name of all fields in the SQL query we must check (combined with a OR)
  5351. * @param string $value The value to look for.
  5352. * If param $mode is 0, can contains several keywords separated with a space or |
  5353. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  5354. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  5355. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  5356. * If param $mode is 2, can contains a list of id separated by comma like "1,3,4"
  5357. * @param integer $mode 0=value is list of keywords, 1=value is a numeric test (Example ">5.5 <10"), 2=value is a list of id separated with comma (Example '1,3,4')
  5358. * @param integer $nofirstand 1=Do not output the first 'AND'
  5359. * @return string $res The statement to append to the SQL query
  5360. */
  5361. function natural_search($fields, $value, $mode=0, $nofirstand=0)
  5362. {
  5363. global $db,$langs;
  5364. if ($mode == 0)
  5365. {
  5366. $value=preg_replace('/\*/','%',$value); // Replace * with %
  5367. }
  5368. if ($mode == 1)
  5369. {
  5370. $value=preg_replace('/([<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"),'/').'\-])/','\1\2',$value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do
  5371. }
  5372. $value = preg_replace('/\s*\|\s*/','|', $value);
  5373. $crits = explode(' ', $value);
  5374. $res = '';
  5375. if (! is_array($fields)) $fields = array($fields);
  5376. $nboffields = count($fields);
  5377. $end2 = count($crits);
  5378. $j = 0;
  5379. foreach ($crits as $crit)
  5380. {
  5381. $i = 0; $i2 = 0;
  5382. $newres = '';
  5383. foreach ($fields as $field)
  5384. {
  5385. if ($mode == 1)
  5386. {
  5387. $operator='=';
  5388. $newcrit = preg_replace('/([<>=]+)/','',trim($crit));
  5389. preg_match('/([<>=]+)/',trim($crit), $reg);
  5390. if ($reg[1])
  5391. {
  5392. $operator = $reg[1];
  5393. }
  5394. if ($newcrit != '')
  5395. {
  5396. $numnewcrit = price2num($newcrit);
  5397. if (is_numeric($numnewcrit))
  5398. {
  5399. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' '.$operator.' '.$numnewcrit;
  5400. }
  5401. else
  5402. {
  5403. $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false
  5404. }
  5405. $i2++; // a criteria was added to string
  5406. }
  5407. }
  5408. else if ($mode == 2)
  5409. {
  5410. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $db->escape(trim($crit)) . ")";
  5411. $i2++; // a criteria was added to string
  5412. }
  5413. else // $mode=0
  5414. {
  5415. $textcrit = '';
  5416. $tmpcrits = explode('|',$crit);
  5417. $i3 = 0;
  5418. foreach($tmpcrits as $tmpcrit)
  5419. {
  5420. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '') . $field . " LIKE '";
  5421. $tmpcrit=trim($tmpcrit);
  5422. $tmpcrit2=$tmpcrit;
  5423. $tmpbefore='%'; $tmpafter='%';
  5424. if (preg_match('/^[\^\$]/', $tmpcrit))
  5425. {
  5426. $tmpbefore='';
  5427. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  5428. }
  5429. if (preg_match('/[\^\$]$/', $tmpcrit))
  5430. {
  5431. $tmpafter='';
  5432. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  5433. }
  5434. $newres .= $tmpbefore;
  5435. $newres .= $db->escape($tmpcrit2);
  5436. $newres .= $tmpafter;
  5437. $newres .= "'";
  5438. if (empty($tmpcrit2))
  5439. {
  5440. $newres .= ' OR ' . $field . " IS NULL";
  5441. }
  5442. $i3++;
  5443. }
  5444. $i2++; // a criteria was added to string
  5445. }
  5446. $i++;
  5447. }
  5448. if ($newres) $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') .$newres . ($i2 > 1 ? ')' : '');
  5449. $j++;
  5450. }
  5451. $res = ($nofirstand?"":" AND ")."(" . $res . ")";
  5452. //print 'xx'.$res.'yy';
  5453. return $res;
  5454. }
  5455. /**
  5456. * Return the filename of file to get the thumbs
  5457. *
  5458. * @param string $file Original filename (full or relative path)
  5459. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  5460. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  5461. * @return string New file name (full or relative path, including the thumbs/)
  5462. */
  5463. function getImageFileNameForSize($file, $extName, $extImgTarget='')
  5464. {
  5465. $dirName = dirname($file);
  5466. if ($dirName == '.') $dirName='';
  5467. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i','',$file); // We remove extension, whatever is its case
  5468. $fileName = basename($fileName);
  5469. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i',$file)?'.jpg':'');
  5470. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i',$file)?'.jpeg':'');
  5471. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i',$file)?'.gif':'');
  5472. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i',$file)?'.png':'');
  5473. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i',$file)?'.bmp':'');
  5474. if (! $extImgTarget) return $file;
  5475. $subdir='';
  5476. if ($extName) $subdir = 'thumbs/';
  5477. return ($dirName?$dirName.'/':'').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  5478. }
  5479. /**
  5480. * Return URL we can use for advanced preview links
  5481. *
  5482. * @param string $modulepart propal, facture, facture_fourn, ...
  5483. * @param string $relativepath Relative path of docs.
  5484. * @param int $alldata Return array with all components (1 is recommended, then use a simple a href link with the class, target and mime attribute added. 'documentpreview' css class is handled by jquery code into main.inc.php)
  5485. * @param string $param More param on http links
  5486. * @return string|array Output string with href link or array with all components of link
  5487. */
  5488. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
  5489. {
  5490. global $conf, $langs;
  5491. if (empty($conf->use_javascript_ajax)) return '';
  5492. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css');
  5493. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  5494. //$mime_preview[]='archive';
  5495. $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview);
  5496. if ($alldata == 1)
  5497. {
  5498. if ($num_mime !== false) return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath), 'mime'=>dol_mimetype($relativepath), );
  5499. else return array();
  5500. }
  5501. // old behavior
  5502. if ($num_mime !== false) return 'javascript:document_preview(\''.dol_escape_js(DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param?'&'.$param:'')).'\', \''.dol_mimetype($relativepath).'\', \''.dol_escape_js($langs->trans('Preview')).'\')';
  5503. else return '';
  5504. }
  5505. /**
  5506. * Return mime type of a file
  5507. *
  5508. * @param string $file Filename we looking for MIME type
  5509. * @param string $default Default mime type if extension not found in known list
  5510. * @param int $mode 0=Return full mime, 1=otherwise short mime string, 2=image for mime type, 3=source language
  5511. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  5512. * @see image_format_supported (images.lib.php)
  5513. */
  5514. function dol_mimetype($file,$default='application/octet-stream',$mode=0)
  5515. {
  5516. $mime=$default;
  5517. $imgmime='other.png';
  5518. $srclang='';
  5519. $tmpfile=preg_replace('/\.noexe$/','',$file);
  5520. // Text files
  5521. if (preg_match('/\.txt$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; }
  5522. if (preg_match('/\.rtx$/i',$tmpfile)) { $mime='text/richtext'; $imgmime='text.png'; }
  5523. if (preg_match('/\.csv$/i',$tmpfile)) { $mime='text/csv'; $imgmime='text.png'; }
  5524. if (preg_match('/\.tsv$/i',$tmpfile)) { $mime='text/tab-separated-values'; $imgmime='text.png'; }
  5525. if (preg_match('/\.(cf|conf|log)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; }
  5526. if (preg_match('/\.ini$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='ini'; }
  5527. if (preg_match('/\.css$/i',$tmpfile)) { $mime='text/css'; $imgmime='css.png'; $srclang='css'; }
  5528. // Certificate files
  5529. if (preg_match('/\.(crt|cer|key|pub)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; }
  5530. // HTML/XML
  5531. if (preg_match('/\.(html|htm|shtml)$/i',$tmpfile)) { $mime='text/html'; $imgmime='html.png'; $srclang='html'; }
  5532. if (preg_match('/\.(xml|xhtml)$/i',$tmpfile)) { $mime='text/xml'; $imgmime='other.png'; $srclang='xml'; }
  5533. // Languages
  5534. if (preg_match('/\.bas$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='bas'; }
  5535. if (preg_match('/\.(c)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='c'; }
  5536. if (preg_match('/\.(cpp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='cpp'; }
  5537. if (preg_match('/\.(h)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='h'; }
  5538. if (preg_match('/\.(java|jsp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='java'; }
  5539. if (preg_match('/\.php([0-9]{1})?$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; }
  5540. if (preg_match('/\.phtml$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; }
  5541. if (preg_match('/\.(pl|pm)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='pl.png'; $srclang='perl'; }
  5542. if (preg_match('/\.sql$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='sql'; }
  5543. if (preg_match('/\.js$/i',$tmpfile)) { $mime='text/x-javascript'; $imgmime='jscript.png'; $srclang='js'; }
  5544. // Open office
  5545. if (preg_match('/\.odp$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.presentation'; $imgmime='ooffice.png'; }
  5546. if (preg_match('/\.ods$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.spreadsheet'; $imgmime='ooffice.png'; }
  5547. if (preg_match('/\.odt$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.text'; $imgmime='ooffice.png'; }
  5548. // MS Office
  5549. if (preg_match('/\.mdb$/i',$tmpfile)) { $mime='application/msaccess'; $imgmime='mdb.png'; }
  5550. if (preg_match('/\.doc(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; }
  5551. if (preg_match('/\.dot(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; }
  5552. if (preg_match('/\.xlt(x)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; }
  5553. if (preg_match('/\.xla(m)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; }
  5554. if (preg_match('/\.xls$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; }
  5555. if (preg_match('/\.xls(b|m|x)$/i',$tmpfile)) { $mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime='xls.png'; }
  5556. if (preg_match('/\.pps(m|x)?$/i',$tmpfile)) { $mime='application/vnd.ms-powerpoint'; $imgmime='ppt.png'; }
  5557. if (preg_match('/\.ppt(m|x)?$/i',$tmpfile)) { $mime='application/x-mspowerpoint'; $imgmime='ppt.png'; }
  5558. // Other
  5559. if (preg_match('/\.pdf$/i',$tmpfile)) { $mime='application/pdf'; $imgmime='pdf.png'; }
  5560. // Scripts
  5561. if (preg_match('/\.bat$/i',$tmpfile)) { $mime='text/x-bat'; $imgmime='script.png'; $srclang='dos'; }
  5562. if (preg_match('/\.sh$/i',$tmpfile)) { $mime='text/x-sh'; $imgmime='script.png'; $srclang='bash'; }
  5563. if (preg_match('/\.ksh$/i',$tmpfile)) { $mime='text/x-ksh'; $imgmime='script.png'; $srclang='bash'; }
  5564. if (preg_match('/\.bash$/i',$tmpfile)) { $mime='text/x-bash'; $imgmime='script.png'; $srclang='bash'; }
  5565. // Images
  5566. if (preg_match('/\.ico$/i',$tmpfile)) { $mime='image/x-icon'; $imgmime='image.png'; }
  5567. if (preg_match('/\.(jpg|jpeg)$/i',$tmpfile)) { $mime='image/jpeg'; $imgmime='image.png'; }
  5568. if (preg_match('/\.png$/i',$tmpfile)) { $mime='image/png'; $imgmime='image.png'; }
  5569. if (preg_match('/\.gif$/i',$tmpfile)) { $mime='image/gif'; $imgmime='image.png'; }
  5570. if (preg_match('/\.bmp$/i',$tmpfile)) { $mime='image/bmp'; $imgmime='image.png'; }
  5571. if (preg_match('/\.(tif|tiff)$/i',$tmpfile)) { $mime='image/tiff'; $imgmime='image.png'; }
  5572. // Calendar
  5573. if (preg_match('/\.vcs$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; }
  5574. if (preg_match('/\.ics$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; }
  5575. // Other
  5576. if (preg_match('/\.torrent$/i',$tmpfile)) { $mime='application/x-bittorrent'; $imgmime='other.png'; }
  5577. // Audio
  5578. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i',$tmpfile)) { $mime='audio'; $imgmime='audio.png'; }
  5579. // Video
  5580. if (preg_match('/\.ogv$/i',$tmpfile)) { $mime='video/ogg'; $imgmime='video.png'; }
  5581. if (preg_match('/\.webm$/i',$tmpfile)) { $mime='video/webm'; $imgmime='video.png'; }
  5582. if (preg_match('/\.avi$/i',$tmpfile)) { $mime='video/x-msvideo'; $imgmime='video.png'; }
  5583. if (preg_match('/\.divx$/i',$tmpfile)) { $mime='video/divx'; $imgmime='video.png'; }
  5584. if (preg_match('/\.xvid$/i',$tmpfile)) { $mime='video/xvid'; $imgmime='video.png'; }
  5585. if (preg_match('/\.(wmv|mpg|mpeg)$/i',$tmpfile)) { $mime='video'; $imgmime='video.png'; }
  5586. // Archive
  5587. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i',$tmpfile)) { $mime='archive'; $imgmime='archive.png'; } // application/xxx where zzz is zip, ...
  5588. // Exe
  5589. if (preg_match('/\.(exe|com)$/i',$tmpfile)) { $mime='application/octet-stream'; $imgmime='other.png'; }
  5590. // Lib
  5591. if (preg_match('/\.(dll|lib|o|so|a)$/i',$tmpfile)) { $mime='library'; $imgmime='library.png'; }
  5592. // Err
  5593. if (preg_match('/\.err$/i',$tmpfile)) { $mime='error'; $imgmime='error.png'; }
  5594. // Return string
  5595. if ($mode == 1)
  5596. {
  5597. $tmp=explode('/',$mime);
  5598. return (! empty($tmp[1])?$tmp[1]:$tmp[0]);
  5599. }
  5600. if ($mode == 2)
  5601. {
  5602. return $imgmime;
  5603. }
  5604. if ($mode == 3)
  5605. {
  5606. return $srclang;
  5607. }
  5608. return $mime;
  5609. }