functions.lib.php 237 KB

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