functions.lib.php 256 KB

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