functions.lib.php 224 KB

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