functions.lib.php 209 KB

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