functions.lib.php 185 KB

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