functions.lib.php 160 KB

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