functions.lib.php 185 KB

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