functions.lib.php 155 KB

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