functions.lib.php 174 KB

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