functions.lib.php 212 KB

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