functions.lib.php 309 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917
  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-2018 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@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 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. * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
  17. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. * or see http://www.gnu.org/
  31. */
  32. /**
  33. * \file htdocs/core/lib/functions.lib.php
  34. * \brief A set of functions for Dolibarr
  35. * This file contains all frequently used functions.
  36. */
  37. include_once DOL_DOCUMENT_ROOT .'/core/lib/json.lib.php';
  38. /**
  39. * Function to return value of a static property when class
  40. * name is dynamically defined (not hard coded).
  41. * This is because $myclass::$myvar works from PHP 5.3.0+ only
  42. *
  43. * @param string $class Class name
  44. * @param string $member Name of property
  45. * @return mixed Return value of static property
  46. * @deprecated Dolibarr now requires 5.3.0+, use $class::$property syntax
  47. * @see https://php.net/manual/language.oop5.static.php
  48. */
  49. function getStaticMember($class, $member)
  50. {
  51. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  52. // This part is deprecated. Uncomment if for php 5.2.*, and comment next isset class::member
  53. /*if (version_compare(phpversion(), '5.3.0', '<'))
  54. {
  55. if (is_object($class)) $class = get_class($class);
  56. $classObj = new ReflectionClass($class);
  57. $result = null;
  58. $found=0;
  59. foreach($classObj->getStaticProperties() as $prop => $value)
  60. {
  61. if ($prop == $member)
  62. {
  63. $result = $value;
  64. $found++;
  65. break;
  66. }
  67. }
  68. if ($found) return $result;
  69. }*/
  70. if (isset($class::$member)) return $class::$member;
  71. dol_print_error('','Try to get a static member "'.$member.'" in class "'.$class.'" that does not exists or is not static.');
  72. return null;
  73. }
  74. /**
  75. * Return a DoliDB instance (database handler).
  76. *
  77. * @param string $type Type of database (mysql, pgsql...)
  78. * @param string $host Address of database server
  79. * @param string $user Nom de l'utilisateur autorise
  80. * @param string $pass Mot de passe
  81. * @param string $name Nom de la database
  82. * @param int $port Port of database server
  83. * @return DoliDB A DoliDB instance
  84. */
  85. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  86. {
  87. require_once DOL_DOCUMENT_ROOT ."/core/db/".$type.'.class.php';
  88. $class='DoliDB'.ucfirst($type);
  89. $dolidb=new $class($type, $host, $user, $pass, $name, $port);
  90. return $dolidb;
  91. }
  92. /**
  93. * Get list of entity id to use.
  94. *
  95. * @param string $element Current element
  96. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  97. * 'product', 'productprice', 'stock',
  98. * 'propal', 'supplier_proposal', 'facture', 'facture_fourn', 'payment_various',
  99. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  100. * 'commande', 'commande_fournisseur', 'expedition', 'intervention', 'survey',
  101. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  102. * 'email_template', 'event', 'donation'
  103. * 'c_paiement', 'c_payment_term', ...
  104. * @param int $shared 0=Return id of current entity only,
  105. * 1=Return id of current entity + shared entities (default)
  106. * @param object $currentobject Current object if needed
  107. * @return mixed Entity id(s) to use
  108. */
  109. function getEntity($element, $shared=1, $currentobject=null)
  110. {
  111. global $conf, $mc;
  112. if (is_object($mc))
  113. {
  114. return $mc->getEntity($element, $shared, $currentobject);
  115. }
  116. else
  117. {
  118. $out='';
  119. $addzero = array('user', 'usergroup', 'c_email_templates', '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('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='edge'; $version=$reg[2]; }
  179. 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
  180. elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name='chrome'; }
  181. elseif (preg_match('/iceweasel/i', $user_agent)) { $name='iceweasel'; }
  182. elseif (preg_match('/epiphany/i', $user_agent)) { $name='epiphany'; }
  183. 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.
  184. elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name='opera'; $version=$reg[2]; }
  185. 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
  186. 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
  187. elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name='lynxlinks'; $version=$reg[4]; }
  188. if ($tablet) {
  189. $layout = 'tablet';
  190. } elseif ($phone) {
  191. $layout = 'phone';
  192. } else {
  193. $layout = 'classic';
  194. }
  195. return array(
  196. 'browsername' => $name,
  197. 'browserversion' => $version,
  198. 'browseros' => $os,
  199. 'layout' => $layout,
  200. 'phone' => $phone,
  201. 'tablet' => $tablet
  202. );
  203. }
  204. /**
  205. * Function called at end of web php process
  206. *
  207. * @return void
  208. */
  209. function dol_shutdown()
  210. {
  211. global $conf,$user,$langs,$db;
  212. $disconnectdone=false; $depth=0;
  213. if (is_object($db) && ! empty($db->connected)) { $depth=$db->transaction_opened; $disconnectdone=$db->close(); }
  214. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth)?' (Warn: db disconnection forced, transaction depth was '.$depth.')':''), (($disconnectdone && $depth)?LOG_WARNING:LOG_INFO));
  215. }
  216. /**
  217. * Return true if we are in a context of submitting a parameter
  218. *
  219. * @param string $paramname Name or parameter to test
  220. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  221. */
  222. function GETPOSTISSET($paramname)
  223. {
  224. return (isset($_POST[$paramname]) || isset($_GET[$paramname]));
  225. }
  226. /**
  227. * Return value of a param into GET or POST supervariable.
  228. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  229. * Note: The property $user->default_values is loaded by main.php when loading the user.
  230. *
  231. * @param string $paramname Name of parameter to found
  232. * @param string $check Type of check
  233. * ''=no check (deprecated)
  234. * 'none'=no check (only for param that should have very rich content)
  235. * 'int'=check it's numeric (integer or float)
  236. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  237. * 'alpha'=check it's text and sign
  238. * 'aZ'=check it's a-z only
  239. * 'aZ09'=check it's simple alpha string (recommended for keys)
  240. * 'array'=check it's array
  241. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  242. * 'nohtml', 'alphanohtml'=check there is no html content
  243. * 'custom'= custom filter specify $filter and $options)
  244. * @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)
  245. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  246. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  247. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  248. * @return string|string[] Value found (string or array), or '' if check fails
  249. */
  250. function GETPOST($paramname, $check='none', $method=0, $filter=null, $options=null, $noreplace=0)
  251. {
  252. global $mysoc,$user,$conf;
  253. if (empty($paramname)) return 'BadFirstParameterForGETPOST';
  254. if (empty($check))
  255. {
  256. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  257. // Enable this line to know who call the GETPOST with '' $check parameter.
  258. //var_dump(debug_backtrace()[0]);
  259. }
  260. if (empty($method)) $out = isset($_GET[$paramname])?$_GET[$paramname]:(isset($_POST[$paramname])?$_POST[$paramname]:'');
  261. elseif ($method==1) $out = isset($_GET[$paramname])?$_GET[$paramname]:'';
  262. elseif ($method==2) $out = isset($_POST[$paramname])?$_POST[$paramname]:'';
  263. elseif ($method==3) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:'');
  264. elseif ($method==4) $out = isset($_POST[$paramname])?$_POST[$paramname]:(isset($_GET[$paramname])?$_GET[$paramname]:(isset($_COOKIE[$paramname])?$_COOKIE[$paramname]:''));
  265. else return 'BadThirdParameterForGETPOST';
  266. if (empty($method) || $method == 3 || $method == 4)
  267. {
  268. $relativepathstring = $_SERVER["PHP_SELF"];
  269. // Clean $relativepathstring
  270. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
  271. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  272. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  273. //var_dump($relativepathstring);
  274. //var_dump($user->default_values);
  275. // Code for search criteria persistence.
  276. // Retrieve values if restore_lastsearch_values
  277. if (! empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  278. {
  279. if (! empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  280. {
  281. $tmp=json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  282. if (is_array($tmp))
  283. {
  284. foreach($tmp as $key => $val)
  285. {
  286. if ($key == $paramname) // We are on the requested parameter
  287. {
  288. $out=$val;
  289. break;
  290. }
  291. }
  292. }
  293. }
  294. // If there is saved contextpage, page or limit
  295. if ($paramname == 'contextpage' && ! empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  296. {
  297. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  298. }
  299. elseif ($paramname == 'page' && ! empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  300. {
  301. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  302. }
  303. elseif ($paramname == 'limit' && ! empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  304. {
  305. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  306. }
  307. }
  308. // Else, retreive default values if we are not doing a sort
  309. elseif (! isset($_GET['sortfield'])) // 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
  310. {
  311. if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  312. {
  313. // Search default value from $object->field
  314. global $object;
  315. if (is_object($object) && isset($object->fields[$paramname]['default']))
  316. {
  317. $out = $object->fields[$paramname]['default'];
  318. }
  319. }
  320. if (! empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
  321. {
  322. if (! empty($_GET['action']) && $_GET['action'] == 'create' && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  323. {
  324. // Now search in setup to overwrite default values
  325. if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  326. {
  327. if (isset($user->default_values[$relativepathstring]['createform']))
  328. {
  329. foreach($user->default_values[$relativepathstring]['createform'] as $defkey => $defval)
  330. {
  331. $qualified = 0;
  332. if ($defkey != '_noquery_')
  333. {
  334. $tmpqueryarraytohave=explode('&', $defkey);
  335. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  336. $foundintru=0;
  337. foreach($tmpqueryarraytohave as $tmpquerytohave)
  338. {
  339. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  340. }
  341. if (! $foundintru) $qualified=1;
  342. //var_dump($defkey.'-'.$qualified);
  343. }
  344. else $qualified = 1;
  345. if ($qualified)
  346. {
  347. //var_dump($user->default_values[$relativepathstring][$defkey]['createform']);
  348. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname]))
  349. {
  350. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  351. break;
  352. }
  353. }
  354. }
  355. }
  356. }
  357. }
  358. // Management of default search_filters and sort order
  359. //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  360. elseif (! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
  361. {
  362. if (! empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  363. {
  364. //var_dump($user->default_values[$relativepathstring]);
  365. if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ?
  366. {
  367. if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...']
  368. {
  369. foreach($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval)
  370. {
  371. $qualified = 0;
  372. if ($defkey != '_noquery_')
  373. {
  374. $tmpqueryarraytohave=explode('&', $defkey);
  375. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  376. $foundintru=0;
  377. foreach($tmpqueryarraytohave as $tmpquerytohave)
  378. {
  379. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  380. }
  381. if (! $foundintru) $qualified=1;
  382. //var_dump($defkey.'-'.$qualified);
  383. }
  384. else $qualified = 1;
  385. if ($qualified)
  386. {
  387. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  388. foreach($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val)
  389. {
  390. if ($out) $out.=', ';
  391. if ($paramname == 'sortfield')
  392. {
  393. $out.=dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  394. }
  395. if ($paramname == 'sortorder')
  396. {
  397. $out.=dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  398. }
  399. }
  400. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  401. }
  402. }
  403. }
  404. }
  405. elseif (isset($user->default_values[$relativepathstring]['filters']))
  406. {
  407. foreach($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  408. {
  409. $qualified = 0;
  410. if ($defkey != '_noquery_')
  411. {
  412. $tmpqueryarraytohave=explode('&', $defkey);
  413. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  414. $foundintru=0;
  415. foreach($tmpqueryarraytohave as $tmpquerytohave)
  416. {
  417. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  418. }
  419. if (! $foundintru) $qualified=1;
  420. //var_dump($defkey.'-'.$qualified);
  421. }
  422. else $qualified = 1;
  423. if ($qualified)
  424. {
  425. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all']))
  426. {
  427. // We made a search from quick search menu, do we still use default filter ?
  428. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH))
  429. {
  430. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  431. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  432. }
  433. }
  434. else
  435. {
  436. $forbidden_chars_to_replace=array(" ","'","/","\\",":","*","?","\"","<",">","|","[","]",";","="); // we accept _, -, . and ,
  437. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  438. }
  439. break;
  440. }
  441. }
  442. }
  443. }
  444. }
  445. }
  446. }
  447. }
  448. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable paramaters)
  449. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  450. // 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.
  451. if (! is_array($out) && empty($_POST[$paramname]) && empty($noreplace))
  452. {
  453. $maxloop=20; $loopnb=0; // Protection against infinite loop
  454. 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.
  455. {
  456. $loopnb++; $newout = '';
  457. if ($reg[1] == 'DAY') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mday']; }
  458. elseif ($reg[1] == 'MONTH') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['mon']; }
  459. elseif ($reg[1] == 'YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = $tmp['year']; }
  460. 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']; }
  461. elseif ($reg[1] == 'PREVIOUS_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_prev_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; }
  462. elseif ($reg[1] == 'PREVIOUS_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] - 1); }
  463. 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']; }
  464. elseif ($reg[1] == 'NEXT_MONTH') { $tmp=dol_getdate(dol_now(), true); $tmp2=dol_get_next_month($tmp['mon'], $tmp['year']); $newout = $tmp2['month']; }
  465. elseif ($reg[1] == 'NEXT_YEAR') { $tmp=dol_getdate(dol_now(), true); $newout = ($tmp['year'] + 1); }
  466. elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID')
  467. {
  468. $newout = $mysoc->country_id;
  469. }
  470. elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID')
  471. {
  472. $newout = $user->id;
  473. }
  474. elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID')
  475. {
  476. $newout = $user->fk_user;
  477. }
  478. elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID')
  479. {
  480. $newout = $conf->entity;
  481. }
  482. else $newout = ''; // Key not found, we replace with empty string
  483. //var_dump('__'.$reg[1].'__ -> '.$newout);
  484. $out = preg_replace('/__'.preg_quote($reg[1],'/').'__/', $newout, $out);
  485. }
  486. }
  487. // Check is done after replacement
  488. switch ($check)
  489. {
  490. case 'none':
  491. break;
  492. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  493. if (! is_numeric($out)) { $out=''; }
  494. break;
  495. case 'intcomma':
  496. if (preg_match('/[^0-9,-]+/i',$out)) $out='';
  497. break;
  498. case 'alpha':
  499. if (! is_array($out))
  500. {
  501. $out=trim($out);
  502. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  503. // '../' is dangerous because it allows dir transversals
  504. if (preg_match('/"/',$out)) $out='';
  505. else if (preg_match('/\.\.\//',$out)) $out='';
  506. }
  507. break;
  508. case 'san_alpha':
  509. $out=filter_var($out,FILTER_SANITIZE_STRING);
  510. break;
  511. case 'aZ':
  512. if (! is_array($out))
  513. {
  514. $out=trim($out);
  515. if (preg_match('/[^a-z]+/i',$out)) $out='';
  516. }
  517. break;
  518. case 'aZ09':
  519. if (! is_array($out))
  520. {
  521. $out=trim($out);
  522. if (preg_match('/[^a-z0-9_\-\.]+/i',$out)) $out='';
  523. }
  524. break;
  525. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  526. if (! is_array($out))
  527. {
  528. $out=trim($out);
  529. if (preg_match('/[^a-z0-9_\-\.,]+/i',$out)) $out='';
  530. }
  531. break;
  532. case 'array':
  533. if (! is_array($out) || empty($out)) $out=array();
  534. break;
  535. case 'nohtml': // Recommended for most scalar parameters
  536. $out=dol_string_nohtmltag($out, 0);
  537. break;
  538. case 'alphanohtml': // Recommended for search parameters
  539. if (! is_array($out))
  540. {
  541. $out=trim($out);
  542. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  543. // '../' is dangerous because it allows dir transversals
  544. if (preg_match('/"/',$out)) $out='';
  545. else if (preg_match('/\.\.\//',$out)) $out='';
  546. $out=dol_string_nohtmltag($out);
  547. }
  548. break;
  549. case 'custom':
  550. if (empty($filter)) return 'BadFourthParameterForGETPOST';
  551. $out=filter_var($out, $filter, $options);
  552. break;
  553. }
  554. // Code for search criteria persistence.
  555. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  556. if (empty($method) || $method == 3 || $method == 4)
  557. {
  558. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder','sortfield')))
  559. {
  560. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  561. // We save search key only if $out not empty that means:
  562. // - posted value not empty, or
  563. // - if posted 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).
  564. if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep
  565. {
  566. $user->lastsearch_values_tmp[$relativepathstring][$paramname]=$out;
  567. }
  568. }
  569. }
  570. return $out;
  571. }
  572. if (! function_exists('dol_getprefix'))
  573. {
  574. /**
  575. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  576. * The prefix for session is unique in a web context only and is unique for instance and avoid conflict
  577. * between multi-instances, even when having two instances with same root dir or two instances in same virtual servers.
  578. * The prefix for email is unique if MAIL_PREFIX_FOR_EMAIL_ID is set to a value, otherwise value may be same than other instance.
  579. *
  580. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  581. * @return string A calculated prefix
  582. */
  583. function dol_getprefix($mode='')
  584. {
  585. global $conf;
  586. // If prefix is for email
  587. if ($mode == 'email')
  588. {
  589. if (! empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  590. {
  591. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  592. else if (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"];
  593. }
  594. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  595. }
  596. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"]))
  597. {
  598. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  599. // Use this for a "readable" key
  600. //return dol_sanitizeFileName($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  601. }
  602. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  603. }
  604. }
  605. /**
  606. * Make an include_once using default root and alternate root if it fails.
  607. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  608. * To link to a module file from a module file, use include './mymodulefile';
  609. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  610. *
  611. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  612. * @param string $classname Class name (deprecated)
  613. * @return bool True if load is a success, False if it fails
  614. */
  615. function dol_include_once($relpath, $classname='')
  616. {
  617. 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']
  618. $fullpath = dol_buildpath($relpath);
  619. if (!file_exists($fullpath)) {
  620. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_ERR);
  621. return false;
  622. }
  623. if (! empty($classname) && ! class_exists($classname)) {
  624. return include $fullpath;
  625. } else {
  626. return include_once $fullpath;
  627. }
  628. }
  629. /**
  630. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  631. *
  632. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  633. * @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)
  634. * @param int $returnemptyifnotfound 0:If $type==0 and if file was not found into alternate dir, return default path into main dir (no test on it)
  635. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  636. * 2:If $type==0 and if file was not found into alternate dir, test into main dir, return default path if found, empty string if not found
  637. * @return string Full filesystem path (if path=0), Full url path (if mode=1)
  638. */
  639. function dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
  640. {
  641. global $conf;
  642. $path=preg_replace('/^\//','',$path);
  643. if (empty($type)) // For a filesystem path
  644. {
  645. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  646. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  647. {
  648. if ($key == 'main')
  649. {
  650. continue;
  651. }
  652. if (file_exists($dirroot.'/'.$path))
  653. {
  654. $res=$dirroot.'/'.$path;
  655. return $res;
  656. }
  657. }
  658. if ($returnemptyifnotfound) // Not found into alternate dir
  659. {
  660. if ($returnemptyifnotfound == 1 || ! file_exists($res)) return '';
  661. }
  662. }
  663. else // For an url path
  664. {
  665. // We try to get local path of file on filesystem from url
  666. // Note that trying to know if a file on disk exist by forging path on disk from url
  667. // works only for some web server and some setup. This is bugged when
  668. // using proxy, rewriting, virtual path, etc...
  669. $res='';
  670. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  671. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  672. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  673. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  674. {
  675. if ($key == 'main')
  676. {
  677. if ($type == 3)
  678. {
  679. global $dolibarr_main_url_root;
  680. // Define $urlwithroot
  681. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  682. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  683. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  684. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':$urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  685. }
  686. continue;
  687. }
  688. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i',$path,$regs); // Take part before '?'
  689. if (! empty($regs[1]))
  690. {
  691. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  692. if (file_exists($dirroot.'/'.$regs[1]))
  693. {
  694. if ($type == 1)
  695. {
  696. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  697. }
  698. if ($type == 2)
  699. {
  700. $res=(preg_match('/^http/i',$conf->file->dol_url_root[$key])?'':DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  701. }
  702. if ($type == 3)
  703. {
  704. global $dolibarr_main_url_root;
  705. // Define $urlwithroot
  706. $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
  707. $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  708. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  709. $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
  710. }
  711. break;
  712. }
  713. }
  714. }
  715. }
  716. return $res;
  717. }
  718. /**
  719. * Create a clone of instance of object (new instance with same value for properties)
  720. * With native = 0: Property that are reference are also new object (true clone). This means $this->db is not valid.
  721. * With native = 1: Use PHP clone. Property that are reference are same pointer. This means $this->db is still valid.
  722. *
  723. * @param object $object Object to clone
  724. * @param int $native Native method or true method
  725. * @return object Object clone
  726. * @see https://php.net/manual/language.oop5.cloning.php
  727. */
  728. function dol_clone($object, $native=0)
  729. {
  730. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  731. if (empty($native))
  732. {
  733. $myclone=unserialize(serialize($object));
  734. }
  735. else
  736. {
  737. $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)
  738. }
  739. return $myclone;
  740. }
  741. /**
  742. * Optimize a size for some browsers (phone, smarphone, ...)
  743. *
  744. * @param int $size Size we want
  745. * @param string $type Type of optimizing:
  746. * '' = function used to define a size for truncation
  747. * 'width' = function is used to define a width
  748. * @return int New size after optimizing
  749. */
  750. function dol_size($size,$type='')
  751. {
  752. global $conf;
  753. if (empty($conf->dol_optimize_smallscreen)) return $size;
  754. if ($type == 'width' && $size > 250) return 250;
  755. else return 10;
  756. }
  757. /**
  758. * Clean a string to use it as a file name
  759. *
  760. * @param string $str String to clean
  761. * @param string $newstr String to replace bad chars with
  762. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  763. * @return string String cleaned (a-zA-Z_)
  764. *
  765. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizePathName
  766. */
  767. function dol_sanitizeFileName($str,$newstr='_',$unaccent=1)
  768. {
  769. $filesystem_forbidden_chars = array('<','>','/','\\','?','*','|','"','°');
  770. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  771. }
  772. /**
  773. * Clean a string to use it as a path name
  774. *
  775. * @param string $str String to clean
  776. * @param string $newstr String to replace bad chars with
  777. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  778. * @return string String cleaned (a-zA-Z_)
  779. *
  780. * @see dol_string_nospecial, dol_string_unaccent, dol_sanitizeFileName
  781. */
  782. function dol_sanitizePathName($str,$newstr='_',$unaccent=1)
  783. {
  784. $filesystem_forbidden_chars = array('<','>','?','*','|','"','°');
  785. return dol_string_nospecial($unaccent?dol_string_unaccent($str):$str, $newstr, $filesystem_forbidden_chars);
  786. }
  787. /**
  788. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  789. *
  790. * @param string $str String to clean
  791. * @return string Cleaned string
  792. *
  793. * @see dol_sanitizeFilename, dol_string_nospecial
  794. */
  795. function dol_string_unaccent($str)
  796. {
  797. if (utf8_check($str))
  798. {
  799. // See http://www.utf8-chartable.de/
  800. $string = rawurlencode($str);
  801. $replacements = array(
  802. '%C3%80' => 'A','%C3%81' => 'A','%C3%82' => 'A','%C3%83' => 'A','%C3%84' => 'A','%C3%85' => 'A',
  803. '%C3%88' => 'E','%C3%89' => 'E','%C3%8A' => 'E','%C3%8B' => 'E',
  804. '%C3%8C' => 'I','%C3%8D' => 'I','%C3%8E' => 'I','%C3%8F' => 'I',
  805. '%C3%92' => 'O','%C3%93' => 'O','%C3%94' => 'O','%C3%95' => 'O','%C3%96' => 'O',
  806. '%C3%99' => 'U','%C3%9A' => 'U','%C3%9B' => 'U','%C3%9C' => 'U',
  807. '%C3%A0' => 'a','%C3%A1' => 'a','%C3%A2' => 'a','%C3%A3' => 'a','%C3%A4' => 'a','%C3%A5' => 'a',
  808. '%C3%A7' => 'c',
  809. '%C3%A8' => 'e','%C3%A9' => 'e','%C3%AA' => 'e','%C3%AB' => 'e',
  810. '%C3%AC' => 'i','%C3%AD' => 'i','%C3%AE' => 'i','%C3%AF' => 'i',
  811. '%C3%B1' => 'n',
  812. '%C3%B2' => 'o','%C3%B3' => 'o','%C3%B4' => 'o','%C3%B5' => 'o','%C3%B6' => 'o',
  813. '%C3%B9' => 'u','%C3%BA' => 'u','%C3%BB' => 'u','%C3%BC' => 'u',
  814. '%C3%BF' => 'y'
  815. );
  816. $string=strtr($string, $replacements);
  817. return rawurldecode($string);
  818. }
  819. else
  820. {
  821. // See http://www.ascii-code.com/
  822. $string = strtr(
  823. $str,
  824. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  825. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  826. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  827. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  828. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  829. \xF9\xFA\xFB\xFC\xFD\xFF",
  830. "AAAAAAC
  831. EEEEIIIIDN
  832. OOOOOUUUY
  833. aaaaaaceeee
  834. iiiidnooooo
  835. uuuuyy"
  836. );
  837. $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"));
  838. return $string;
  839. }
  840. }
  841. /**
  842. * Clean a string from all punctuation characters to use it as a ref or login.
  843. * This is a more complete function than dol_sanitizeFileName.
  844. *
  845. * @param string $str String to clean
  846. * @param string $newstr String to replace forbidden chars with
  847. * @param array $badcharstoreplace List of forbidden characters
  848. * @return string Cleaned string
  849. *
  850. * @see dol_sanitizeFilename, dol_string_unaccent
  851. */
  852. function dol_string_nospecial($str,$newstr='_',$badcharstoreplace='')
  853. {
  854. $forbidden_chars_to_replace=array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  855. $forbidden_chars_to_remove=array();
  856. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace=$badcharstoreplace;
  857. //$forbidden_chars_to_remove=array("(",")");
  858. return str_replace($forbidden_chars_to_replace,$newstr,str_replace($forbidden_chars_to_remove,"",$str));
  859. }
  860. /**
  861. * Encode string for xml usage
  862. *
  863. * @param string $string String to encode
  864. * @return string String encoded
  865. */
  866. function dolEscapeXML($string)
  867. {
  868. return strtr($string, array('\''=>'&apos;','"'=>'&quot;','&'=>'&amp;','<'=>'&lt;','>'=>'&gt;'));
  869. }
  870. /**
  871. * Returns text escaped for inclusion into javascript code
  872. *
  873. * @param string $stringtoescape String to escape
  874. * @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 \
  875. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  876. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  877. */
  878. function dol_escape_js($stringtoescape, $mode=0, $noescapebackslashn=0)
  879. {
  880. // escape quotes and backslashes, newlines, etc.
  881. $substitjs=array("&#039;"=>"\\'","\r"=>'\\r');
  882. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  883. if (empty($noescapebackslashn)) { $substitjs["\n"]='\\n'; $substitjs['\\']='\\\\'; }
  884. if (empty($mode)) { $substitjs["'"]="\\'"; $substitjs['"']="\\'"; }
  885. else if ($mode == 1) $substitjs["'"]="\\'";
  886. else if ($mode == 2) { $substitjs['"']='\\"'; }
  887. else if ($mode == 3) { $substitjs["'"]="\\'"; $substitjs['"']="\\\""; }
  888. return strtr($stringtoescape, $substitjs);
  889. }
  890. /**
  891. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  892. *
  893. * @param string $stringtoescape String to escape
  894. * @param int $keepb 1=Preserve b tags (otherwise, remove them)
  895. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value)
  896. * @return string Escaped string
  897. * @see dol_string_nohtmltag, dol_string_nospecial, dol_string_unaccent
  898. */
  899. function dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0)
  900. {
  901. // escape quotes and backslashes, newlines, etc.
  902. $tmp=html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
  903. if (! $keepb) $tmp=strtr($tmp, array("<b>"=>'','</b>'=>''));
  904. if (! $keepn) $tmp=strtr($tmp, array("\r"=>'\\r',"\n"=>'\\n'));
  905. return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html tags
  906. }
  907. /**
  908. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  909. *
  910. * @param string $utf8_string String to encode
  911. * @return string String converted
  912. */
  913. function dol_strtolower($utf8_string)
  914. {
  915. return mb_strtolower($utf8_string, "UTF-8");
  916. }
  917. /**
  918. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  919. *
  920. * @param string $utf8_string String to encode
  921. * @return string String converted
  922. */
  923. function dol_strtoupper($utf8_string)
  924. {
  925. return mb_strtoupper($utf8_string, "UTF-8");
  926. }
  927. /**
  928. * Write log message into outputs. Possible outputs can be:
  929. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  930. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  931. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  932. * this, use logging to files instead of syslog (see setup of module).
  933. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  934. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  935. * This function works only if syslog module is enabled.
  936. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  937. *
  938. * @param string $message Line to log. ''=Show nothing
  939. * @param int $level Log level
  940. * 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
  941. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  942. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  943. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  944. * @param string $restricttologhandler Output log only for this log handler
  945. * @return void
  946. */
  947. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename='', $restricttologhandler='')
  948. {
  949. global $conf, $user;
  950. // If syslog module enabled
  951. if (empty($conf->syslog->enabled)) return;
  952. if ($ident < 0)
  953. {
  954. foreach ($conf->loghandlers as $loghandlerinstance)
  955. {
  956. $loghandlerinstance->setIdent($ident);
  957. }
  958. }
  959. if (! empty($message))
  960. {
  961. // Test log level
  962. $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG);
  963. if (!in_array($level, $logLevels, true))
  964. {
  965. throw new Exception('Incorrect log level');
  966. }
  967. if ($level > $conf->global->SYSLOG_LEVEL) return;
  968. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  969. // If adding log inside HTML page is required
  970. if (! empty($_REQUEST['logtohtml']) && (! empty($conf->global->MAIN_ENABLE_LOG_TO_HTML) || ! empty($conf->global->MAIN_LOGTOHTML))) // MAIN_LOGTOHTML kept for backward compatibility
  971. {
  972. $conf->logbuffer[] = dol_print_date(time(),"%Y-%m-%d %H:%M:%S")." ".$message;
  973. }
  974. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  975. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  976. if (! empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && ! empty($_GET["log"]))
  977. {
  978. print "\n\n<!-- Log start\n";
  979. print $message."\n";
  980. print "Log end -->\n";
  981. }
  982. $data = array(
  983. 'message' => $message,
  984. 'script' => (isset($_SERVER['PHP_SELF'])? basename($_SERVER['PHP_SELF'],'.php') : false),
  985. 'level' => $level,
  986. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  987. 'ip' => false
  988. );
  989. // This is when server run behind a reverse proxy
  990. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"])?'':'->'.$_SERVER['REMOTE_ADDR']);
  991. // This is when server run normally on a server
  992. else if (! empty($_SERVER["REMOTE_ADDR"])) $data['ip'] = $_SERVER['REMOTE_ADDR'];
  993. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  994. else if (! empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  995. // 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).
  996. else if (! empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME'])?'':'@'.$_SERVER['USERNAME']);
  997. // 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).
  998. else if (! empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  999. // Loop on each log handler and send output
  1000. foreach ($conf->loghandlers as $loghandlerinstance)
  1001. {
  1002. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  1003. $loghandlerinstance->export($data,$suffixinfilename);
  1004. }
  1005. unset($data);
  1006. }
  1007. if ($ident > 0)
  1008. {
  1009. foreach ($conf->loghandlers as $loghandlerinstance)
  1010. {
  1011. $loghandlerinstance->setIdent($ident);
  1012. }
  1013. }
  1014. }
  1015. /**
  1016. * Show tab header of a card
  1017. *
  1018. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1019. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1020. * @param string $title Title
  1021. * @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.
  1022. * @param string $picto Add a picto on tab title
  1023. * @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.
  1024. * @param string $morehtmlright Add more html content on right of tabs title
  1025. * @param string $morecss More Css
  1026. * @return void
  1027. */
  1028. function dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='')
  1029. {
  1030. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss);
  1031. }
  1032. /**
  1033. * Show tab header of a card
  1034. *
  1035. * @param array $links Array of tabs
  1036. * @param string $active Active tab name
  1037. * @param string $title Title
  1038. * @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.
  1039. * @param string $picto Add a picto on tab title
  1040. * @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.
  1041. * @param string $morehtmlright Add more html content on right of tabs title
  1042. * @param string $morecss More Css
  1043. * @return string
  1044. */
  1045. function dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='')
  1046. {
  1047. global $conf, $langs, $hookmanager;
  1048. $out="\n".'<div class="tabs" data-role="controlgroup" data-type="horizontal">'."\n";
  1049. if ($morehtmlright) $out.='<div class="inline-block floatright tabsElem">'.$morehtmlright.'</div>'; // Output right area first so when space is missing, text is in front of tabs and not under.
  1050. // Show title
  1051. $showtitle=1;
  1052. if (! empty($conf->dol_optimize_smallscreen)) $showtitle=0;
  1053. if (! empty($title) && $showtitle)
  1054. {
  1055. $limittitle=30;
  1056. $out.='<a class="tabTitle">';
  1057. if ($picto) $out.=img_picto($title,($pictoisfullpath?'':'object_').$picto,'',$pictoisfullpath).' ';
  1058. $out.='<span class="tabTitleText">'.dol_trunc($title,$limittitle).'</span>';
  1059. $out.='</a>';
  1060. }
  1061. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1062. $maxkey=-1;
  1063. if (is_array($links) && ! empty($links))
  1064. {
  1065. $keys=array_keys($links);
  1066. if (count($keys)) $maxkey=max($keys);
  1067. }
  1068. if (! empty($conf->dol_optimize_smallscreen)) $conf->global->MAIN_MAXTABS_IN_CARD=2;
  1069. // Show tabs
  1070. $bactive=false;
  1071. // if =0 we don't use the feature
  1072. $limittoshow=(empty($conf->global->MAIN_MAXTABS_IN_CARD)?99:$conf->global->MAIN_MAXTABS_IN_CARD);
  1073. $displaytab=0;
  1074. $nbintab=0;
  1075. $popuptab=0; $outmore='';
  1076. for ($i = 0 ; $i <= $maxkey ; $i++)
  1077. {
  1078. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  1079. {
  1080. // If active tab is already present
  1081. if ($i >= $limittoshow) $limittoshow--;
  1082. }
  1083. }
  1084. for ($i = 0 ; $i <= $maxkey ; $i++)
  1085. {
  1086. if ((is_numeric($active) && $i == $active) || (! empty($links[$i][2]) && ! is_numeric($active) && $active == $links[$i][2]))
  1087. {
  1088. $isactive=true;
  1089. $bactive=true;
  1090. }
  1091. else
  1092. {
  1093. $isactive=false;
  1094. }
  1095. if ($i < $limittoshow || $isactive)
  1096. {
  1097. $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]).' -->';
  1098. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1099. {
  1100. if (!empty($links[$i][0]))
  1101. {
  1102. $out.='<a class="tabimage'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1103. }
  1104. else
  1105. {
  1106. $out.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1107. }
  1108. }
  1109. else if (! empty($links[$i][1]))
  1110. {
  1111. //print "x $i $active ".$links[$i][2]." z";
  1112. if ($isactive)
  1113. {
  1114. $out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabactive tab inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1115. $out.=$links[$i][1];
  1116. $out.='</a>'."\n";
  1117. }
  1118. else
  1119. {
  1120. $out.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="tabunactive tab inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1121. $out.=$links[$i][1];
  1122. $out.='</a>'."\n";
  1123. }
  1124. }
  1125. $out.='</div>';
  1126. }
  1127. else
  1128. {
  1129. // The popup with the other tabs
  1130. if (! $popuptab)
  1131. {
  1132. $popuptab=1;
  1133. $outmore.='<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1134. }
  1135. $outmore.='<div class="popuptab wordwrap" style="display:inherit;">';
  1136. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1137. {
  1138. if (!empty($links[$i][0]))
  1139. $outmore.='<a class="tabimage'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1140. else
  1141. $outmore.='<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1142. }
  1143. else if (! empty($links[$i][1]))
  1144. {
  1145. $outmore.='<a'.(! empty($links[$i][2])?' id="'.$links[$i][2].'"':'').' class="wordwrap inline-block'.($morecss?' '.$morecss:'').'" href="'.$links[$i][0].'">';
  1146. $outmore.=preg_replace('/([a-z])\/([a-z])/i', '\\1 / \\2', $links[$i][1]); // Replace x/y with x / y to allow wrap on long composed texts.
  1147. $outmore.='</a>'."\n";
  1148. }
  1149. $outmore.='</div>';
  1150. $nbintab++;
  1151. }
  1152. $displaytab=$i;
  1153. }
  1154. if ($popuptab) $outmore.='</div>';
  1155. if ($displaytab > $limittoshow)
  1156. {
  1157. $left=($langs->trans("DIRECTION") == 'rtl'?'right':'left');
  1158. $right=($langs->trans("DIRECTION") == 'rtl'?'left':'right');
  1159. $tabsname=str_replace("@", "", $picto);
  1160. $out.='<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1161. $out.='<a href="#" class="tab moretab inline-block tabunactive reposition">'.$langs->trans("More").'... ('.$nbintab.')</a>';
  1162. $out.='<div id="moretabsList'.$tabsname.'" style="position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px">';
  1163. $out.=$outmore;
  1164. $out.='</div>';
  1165. $out.='<div></div>';
  1166. $out.="</div>\n";
  1167. $out.="<script>";
  1168. $out.="$('#moretabs".$tabsname."').mouseenter( function() { console.log('mouseenter ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','auto');});";
  1169. $out.="$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1170. $out.="</script>";
  1171. }
  1172. $out.="</div>\n";
  1173. if (! $notab || $notab == -1) $out.="\n".'<div class="tabBar'.($notab == -1 ? '' : ' tabBarWithBottom').'">'."\n";
  1174. $parameters=array('tabname' => $active, 'out' => $out);
  1175. $reshook=$hookmanager->executeHooks('printTabsHead',$parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1176. if ($reshook > 0)
  1177. {
  1178. $out = $hookmanager->resPrint;
  1179. }
  1180. return $out;
  1181. }
  1182. /**
  1183. * Show tab footer of a card
  1184. *
  1185. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1186. * @return void
  1187. */
  1188. function dol_fiche_end($notab=0)
  1189. {
  1190. print dol_get_fiche_end($notab);
  1191. }
  1192. /**
  1193. * Return tab footer of a card
  1194. *
  1195. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1196. * @return string
  1197. */
  1198. function dol_get_fiche_end($notab=0)
  1199. {
  1200. if (! $notab || $notab == -1) return "\n</div>\n";
  1201. else return '';
  1202. }
  1203. /**
  1204. * Show tab footer of a card.
  1205. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1206. *
  1207. * @param Object $object Object to show
  1208. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1209. * @param string $morehtml More html content to output just before the nav bar
  1210. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1211. * @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). Use 'none' for no prev/next search.
  1212. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1213. * @param string $morehtmlref More html to show after ref
  1214. * @param string $moreparam More param to add in nav link url.
  1215. * @param int $nodbprefix Do not include DB prefix to forge table name
  1216. * @param string $morehtmlleft More html code to show before ref
  1217. * @param string $morehtmlstatus More html code to show under navigation arrows
  1218. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1219. * @param string $morehtmlright More html code to show before navigation arrows
  1220. * @return void
  1221. */
  1222. function dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
  1223. {
  1224. global $conf, $form, $user, $langs;
  1225. $error = 0;
  1226. $maxvisiblephotos=1;
  1227. $showimage=1;
  1228. $entity=(empty($object->entity)?$conf->entity:$object->entity);
  1229. $showbarcode=empty($conf->barcode->enabled)?0:($object->barcode?1:0);
  1230. if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode=0;
  1231. $modulepart='unknown';
  1232. if ($object->element == 'societe') $modulepart='societe';
  1233. if ($object->element == 'contact') $modulepart='contact';
  1234. if ($object->element == 'member') $modulepart='memberphoto';
  1235. if ($object->element == 'user') $modulepart='userphoto';
  1236. if ($object->element == 'product') $modulepart='product';
  1237. if (class_exists("Imagick"))
  1238. {
  1239. if ($object->element == 'propal') $modulepart='propal';
  1240. if ($object->element == 'commande') $modulepart='commande';
  1241. if ($object->element == 'facture') $modulepart='facture';
  1242. if ($object->element == 'fichinter') $modulepart='ficheinter';
  1243. if ($object->element == 'contrat') $modulepart='contract';
  1244. if ($object->element == 'supplier_proposal') $modulepart='supplier_proposal';
  1245. if ($object->element == 'order_supplier') $modulepart='supplier_order';
  1246. if ($object->element == 'invoice_supplier') $modulepart='supplier_invoice';
  1247. if ($object->element == 'expensereport') $modulepart='expensereport';
  1248. }
  1249. if ($object->element == 'product')
  1250. {
  1251. $width=80; $cssclass='photoref';
  1252. $showimage=$object->is_photo_available($conf->product->multidir_output[$entity]);
  1253. $maxvisiblephotos=(isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO)?$conf->global->PRODUCT_MAX_VISIBLE_PHOTO:5);
  1254. if ($conf->browser->layout == 'phone') $maxvisiblephotos=1;
  1255. if ($showimage) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity],'small',$maxvisiblephotos,0,0,0,$width,0).'</div>';
  1256. else
  1257. {
  1258. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1259. $nophoto='';
  1260. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1261. }
  1262. //elseif ($conf->browser->layout != 'phone') { // Show no photo link
  1263. $nophoto='/public/theme/common/nophoto.png';
  1264. $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>';
  1265. //}
  1266. }
  1267. }
  1268. elseif ($object->element == 'ticket')
  1269. {
  1270. $width=80; $cssclass='photoref';
  1271. $showimage=$object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->track_id);
  1272. $maxvisiblephotos=(isset($conf->global->TICKETSUP_MAX_VISIBLE_PHOTO)?$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO:2);
  1273. if ($conf->browser->layout == 'phone') $maxvisiblephotos=1;
  1274. if ($showimage) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('ticket', $conf->ticket->multidir_output[$entity],'small',$maxvisiblephotos,0,0,0,$width,0).'</div>';
  1275. else
  1276. {
  1277. if (!empty($conf->global->TICKETSUP_NODISPLAYIFNOPHOTO)) {
  1278. $nophoto='';
  1279. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1280. }
  1281. //elseif ($conf->browser->layout != 'phone') { // Show no photo link
  1282. $nophoto='/public/theme/common/nophoto.png';
  1283. $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>';
  1284. //}
  1285. }
  1286. }
  1287. else
  1288. {
  1289. if ($showimage)
  1290. {
  1291. if ($modulepart != 'unknown')
  1292. {
  1293. $phototoshow='';
  1294. // Check if a preview file is available
  1295. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick"))
  1296. {
  1297. $objectref = dol_sanitizeFileName($object->ref);
  1298. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity]) . "/";
  1299. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1300. {
  1301. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1302. $subdir.= ((! empty($subdir) && ! preg_match('/\/$/',$subdir))?'/':'').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end
  1303. }
  1304. else
  1305. {
  1306. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1307. }
  1308. if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1309. $filepath = $dir_output . $subdir . "/";
  1310. $file = $filepath . $objectref . ".pdf";
  1311. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1312. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1313. $fileimage = $file.'_preview.png'; // If PDF has 1 page
  1314. $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page
  1315. $relativepathimage = $relativepath.'_preview.png';
  1316. // Si fichier PDF existe
  1317. if (file_exists($file))
  1318. {
  1319. $encfile = urlencode($file);
  1320. // Conversion du PDF en image png si fichier png non existant
  1321. if ( (! file_exists($fileimage) || (filemtime($fileimage) < filemtime($file)))
  1322. && (! file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file)))
  1323. )
  1324. {
  1325. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experienc trouble with pdf thumb generation and imagick, you can disable here.
  1326. {
  1327. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1328. $ret = dol_convert_file($file, 'png', $fileimage);
  1329. if ($ret < 0) $error++;
  1330. }
  1331. }
  1332. $heightforphotref=70;
  1333. if (! empty($conf->dol_optimize_smallscreen)) $heightforphotref=60;
  1334. // Si fichier png PDF d'1 page trouve
  1335. if (file_exists($fileimage))
  1336. {
  1337. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1338. $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1339. $phototoshow.= '</div></div>';
  1340. }
  1341. // Si fichier png PDF de plus d'1 page trouve
  1342. elseif (file_exists($fileimagebis))
  1343. {
  1344. $preview = preg_replace('/\.png/','',$relativepathimage) . "-0.png";
  1345. $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1346. $phototoshow.= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT . '/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
  1347. $phototoshow.= '</div></div>';
  1348. }
  1349. }
  1350. }
  1351. else if (! $phototoshow)
  1352. {
  1353. $phototoshow = $form->showphoto($modulepart,$object,0,0,0,'photoref','small',1,0,$maxvisiblephotos);
  1354. }
  1355. if ($phototoshow)
  1356. {
  1357. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1358. $morehtmlleft.=$phototoshow;
  1359. $morehtmlleft.='</div>';
  1360. }
  1361. }
  1362. if (! $phototoshow) // Show No photo link (picto of pbject)
  1363. {
  1364. $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">';
  1365. if ($object->element == 'action')
  1366. {
  1367. $width=80;
  1368. $cssclass='photorefcenter';
  1369. $nophoto=img_picto('', 'title_agenda', '', false, 1);
  1370. }
  1371. else
  1372. {
  1373. $width=14; $cssclass='photorefcenter';
  1374. $picto = $object->picto;
  1375. if ($object->element == 'project' && ! $object->public) $picto = 'project'; // instead of projectpub
  1376. $nophoto=img_picto('', 'object_'.$picto, '', false, 1);
  1377. }
  1378. $morehtmlleft.='<!-- No photo to show -->';
  1379. $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>';
  1380. $morehtmlleft.='</div>';
  1381. }
  1382. }
  1383. }
  1384. if ($showbarcode) $morehtmlleft.='<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1385. if ($object->element == 'societe')
  1386. {
  1387. if (! empty($conf->use_javascript_ajax) && $user->rights->societe->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1388. {
  1389. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1390. }
  1391. else {
  1392. $morehtmlstatus.=$object->getLibStatut(6);
  1393. }
  1394. }
  1395. elseif ($object->element == 'product')
  1396. {
  1397. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1398. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1399. $morehtmlstatus.=ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1400. } else {
  1401. $morehtmlstatus.='<span class="statusrefsell">'.$object->getLibStatut(5,0).'</span>';
  1402. }
  1403. $morehtmlstatus.=' &nbsp; ';
  1404. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1405. if (! empty($conf->use_javascript_ajax) && $user->rights->produit->creer && ! empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1406. $morehtmlstatus.=ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1407. } else {
  1408. $morehtmlstatus.='<span class="statusrefbuy">'.$object->getLibStatut(5,1).'</span>';
  1409. }
  1410. }
  1411. elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan')))
  1412. {
  1413. $tmptxt=$object->getLibStatut(6, $object->totalpaye);
  1414. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5, $object->totalpaye);
  1415. $morehtmlstatus.=$tmptxt;
  1416. }
  1417. elseif ($object->element == 'contrat' || $object->element == 'contract')
  1418. {
  1419. if ($object->statut == 0) $morehtmlstatus.=$object->getLibStatut(5);
  1420. else $morehtmlstatus.=$object->getLibStatut(4);
  1421. }
  1422. elseif ($object->element == 'facturerec')
  1423. {
  1424. if ($object->frequency == 0) $morehtmlstatus.=$object->getLibStatut(2);
  1425. else $morehtmlstatus.=$object->getLibStatut(5);
  1426. }
  1427. elseif ($object->element == 'project_task')
  1428. {
  1429. $object->fk_statut = 1;
  1430. if ($object->progress > 0) $object->fk_statut = 2;
  1431. if ($object->progress >= 100) $object->fk_statut = 3;
  1432. $tmptxt=$object->getLibStatut(5);
  1433. $morehtmlstatus.=$tmptxt; // No status on task
  1434. }
  1435. else { // Generic case
  1436. $tmptxt=$object->getLibStatut(6);
  1437. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || $conf->browser->layout=='phone') $tmptxt=$object->getLibStatut(5);
  1438. $morehtmlstatus.=$tmptxt;
  1439. }
  1440. // Add if object was dispatched "into accountancy"
  1441. if (! empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport')))
  1442. {
  1443. if (method_exists($object, 'getVentilExportCompta'))
  1444. {
  1445. $accounted = $object->getVentilExportCompta();
  1446. $langs->load("accountancy");
  1447. $morehtmlstatus.='</div><div class="statusref statusrefbis">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted"));
  1448. }
  1449. }
  1450. // Add alias for thirdparty
  1451. if (! empty($object->name_alias)) $morehtmlref.='<div class="refidno">'.$object->name_alias.'</div>';
  1452. // Add label
  1453. if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task')
  1454. {
  1455. if (! empty($object->label)) $morehtmlref.='<div class="refidno">'.$object->label.'</div>';
  1456. }
  1457. if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files')
  1458. {
  1459. $morehtmlref.='<div class="refidno">';
  1460. $morehtmlref.=$object->getBannerAddress('refaddress',$object);
  1461. $morehtmlref.='</div>';
  1462. }
  1463. if (! empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product')))
  1464. {
  1465. $morehtmlref.='<div style="clear: both;"></div><div class="refidno">';
  1466. $morehtmlref.=$langs->trans("TechnicalID").': '.$object->id;
  1467. $morehtmlref.='</div>';
  1468. }
  1469. print '<div class="'.($onlybanner?'arearefnobottom ':'arearef ').'heightref valignmiddle" width="100%">';
  1470. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1471. print '</div>';
  1472. print '<div class="underrefbanner clearboth"></div>';
  1473. }
  1474. /**
  1475. * Show a string with the label tag dedicated to the HTML edit field.
  1476. *
  1477. * @param string $langkey Translation key
  1478. * @param string $fieldkey Key of the html select field the text refers to
  1479. * @param int $fieldrequired 1=Field is mandatory
  1480. * @return string
  1481. * @deprecated Form::editfieldkey
  1482. */
  1483. function fieldLabel($langkey, $fieldkey, $fieldrequired=0)
  1484. {
  1485. global $conf, $langs;
  1486. $ret='';
  1487. if ($fieldrequired) $ret.='<span class="fieldrequired">';
  1488. if (($conf->dol_use_jmobile != 4)) $ret.='<label for="'.$fieldkey.'">';
  1489. $ret.=$langs->trans($langkey);
  1490. if (($conf->dol_use_jmobile != 4)) $ret.='</label>';
  1491. if ($fieldrequired) $ret.='</span>';
  1492. return $ret;
  1493. }
  1494. /**
  1495. * Return string to add class property on html element with pair/impair.
  1496. *
  1497. * @param string $var 0 or 1
  1498. * @param string $moreclass More class to add
  1499. * @return string String to add class onto HTML element
  1500. */
  1501. function dol_bc($var,$moreclass='')
  1502. {
  1503. global $bc;
  1504. $ret=' '.$bc[$var];
  1505. if ($moreclass) $ret=preg_replace('/class=\"/','class="'.$moreclass.' ',$ret);
  1506. return $ret;
  1507. }
  1508. /**
  1509. * Return a formated address (part address/zip/town/state) according to country rules
  1510. *
  1511. * @param Object $object A company or contact object
  1512. * @param int $withcountry 1=Add country into address string
  1513. * @param string $sep Separator to use to build string
  1514. * @param Translate $outputlangs Object lang that contains language for text translation.
  1515. * @param int $mode 0=Standard output, 1=Remove address
  1516. * @return string Formated string
  1517. * @see dol_print_address
  1518. */
  1519. function dol_format_address($object, $withcountry=0, $sep="\n", $outputlangs='', $mode=0)
  1520. {
  1521. global $conf,$langs;
  1522. $ret='';
  1523. $countriesusingstate=array('AU','CA','US','IN','GB','ES','UK','TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1524. // Address
  1525. if (empty($mode)) {
  1526. $ret .= $object->address;
  1527. }
  1528. // Zip/Town/State
  1529. 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
  1530. {
  1531. $ret .= ($ret ? $sep : '' ).$object->town;
  1532. if ($object->state)
  1533. {
  1534. $ret.=($ret?", ":'').$object->state;
  1535. }
  1536. if ($object->zip) $ret .= ($ret?", ":'').$object->zip;
  1537. }
  1538. else if (in_array($object->country_code,array('GB','UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country
  1539. {
  1540. $ret .= ($ret ? $sep : '' ).$object->town;
  1541. if ($object->state)
  1542. {
  1543. $ret.=($ret?", ":'').$object->state;
  1544. }
  1545. if ($object->zip) $ret .= ($ret ? $sep : '' ).$object->zip;
  1546. }
  1547. else if (in_array($object->country_code,array('ES','TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country
  1548. {
  1549. $ret .= ($ret ? $sep : '' ).$object->zip;
  1550. $ret .= ($object->town?(($object->zip?' ':'').$object->town):'');
  1551. if ($object->state)
  1552. {
  1553. $ret.="\n".$object->state;
  1554. }
  1555. }
  1556. else if (in_array($object->country_code,array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1557. {
  1558. $ret .= ($ret ? $sep : '' ).$object->zip;
  1559. $ret .= ($object->town?(($object->zip?' ':'').$object->town):'');
  1560. $ret .= ($object->departement_id?(' ('.($object->departement_id).')'):'');
  1561. }
  1562. else // Other: title firstname name \n address lines \n zip town \n country
  1563. {
  1564. $ret .= $object->zip ? (($ret ? $sep : '' ).$object->zip) : '';
  1565. $ret .= ($object->town?(($object->zip?' ':($ret ? $sep : '' )).$object->town):'');
  1566. if ($object->state && in_array($object->country_code,$countriesusingstate))
  1567. {
  1568. $ret.=($ret?", ":'').$object->state;
  1569. }
  1570. }
  1571. if (! is_object($outputlangs)) $outputlangs=$langs;
  1572. if ($withcountry)
  1573. {
  1574. $langs->load("dict");
  1575. $ret.=($object->country_code?($ret?$sep:'').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)):'');
  1576. }
  1577. return $ret;
  1578. }
  1579. /**
  1580. * Format a string.
  1581. *
  1582. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1583. * @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)
  1584. * @param int $is_gmt See comment of timestamp parameter
  1585. * @return string A formatted string
  1586. */
  1587. function dol_strftime($fmt, $ts=false, $is_gmt=false)
  1588. {
  1589. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1590. return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts);
  1591. }
  1592. else return 'Error date into a not supported range';
  1593. }
  1594. /**
  1595. * Output date in a string format according to outputlangs (or langs if not defined).
  1596. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1597. *
  1598. * @param int $time GM Timestamps date
  1599. * @param string $format Output date format (tag of strftime function)
  1600. * "%d %b %Y",
  1601. * "%d/%m/%Y %H:%M",
  1602. * "%d/%m/%Y %H:%M:%S",
  1603. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1604. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1605. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1606. * false or 'tzserver' => output string is for local PHP server TZ usage
  1607. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  1608. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  1609. * @param Translate $outputlangs Object lang that contains language for text translation.
  1610. * @param boolean $encodetooutput false=no convert into output pagecode
  1611. * @return string Formated date or '' if time is null
  1612. *
  1613. * @see dol_mktime, dol_stringtotime, dol_getdate
  1614. */
  1615. function dol_print_date($time,$format='',$tzoutput='tzserver',$outputlangs='',$encodetooutput=false)
  1616. {
  1617. global $conf,$langs;
  1618. // Clean parameters
  1619. $to_gmt=false;
  1620. $offsettz=$offsetdst=0;
  1621. if ($tzoutput)
  1622. {
  1623. $to_gmt=true; // For backward compatibility
  1624. if (is_string($tzoutput))
  1625. {
  1626. if ($tzoutput == 'tzserver')
  1627. {
  1628. $to_gmt=false;
  1629. $offsettzstring=@date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1630. $offsettz=0;
  1631. $offsetdst=0;
  1632. }
  1633. elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel')
  1634. {
  1635. $to_gmt=true;
  1636. $offsettzstring=(empty($_SESSION['dol_tz_string'])?'UTC':$_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1637. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60; // Will not be used anymore
  1638. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60; // Will not be used anymore
  1639. }
  1640. }
  1641. }
  1642. if (! is_object($outputlangs)) $outputlangs=$langs;
  1643. if (! $format) $format='daytextshort';
  1644. $reduceformat=(! empty($conf->dol_optimize_smallscreen) && in_array($format,array('day','dayhour')))?1:0;
  1645. $formatwithoutreduce = preg_replace('/reduceformat/','',$format);
  1646. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat=1; } // so format 'dayreduceformat' is processed like day
  1647. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1648. // TODO Add format daysmallyear and dayhoursmallyear
  1649. if ($format == 'day') $format=($outputlangs->trans("FormatDateShort")!="FormatDateShort"?$outputlangs->trans("FormatDateShort"):$conf->format_date_short);
  1650. else if ($format == 'hour') $format=($outputlangs->trans("FormatHourShort")!="FormatHourShort"?$outputlangs->trans("FormatHourShort"):$conf->format_hour_short);
  1651. else if ($format == 'hourduration') $format=($outputlangs->trans("FormatHourShortDuration")!="FormatHourShortDuration"?$outputlangs->trans("FormatHourShortDuration"):$conf->format_hour_short_duration);
  1652. else if ($format == 'daytext') $format=($outputlangs->trans("FormatDateText")!="FormatDateText"?$outputlangs->trans("FormatDateText"):$conf->format_date_text);
  1653. else if ($format == 'daytextshort') $format=($outputlangs->trans("FormatDateTextShort")!="FormatDateTextShort"?$outputlangs->trans("FormatDateTextShort"):$conf->format_date_text_short);
  1654. else if ($format == 'dayhour') $format=($outputlangs->trans("FormatDateHourShort")!="FormatDateHourShort"?$outputlangs->trans("FormatDateHourShort"):$conf->format_date_hour_short);
  1655. else if ($format == 'dayhoursec') $format=($outputlangs->trans("FormatDateHourSecShort")!="FormatDateHourSecShort"?$outputlangs->trans("FormatDateHourSecShort"):$conf->format_date_hour_sec_short);
  1656. else if ($format == 'dayhourtext') $format=($outputlangs->trans("FormatDateHourText")!="FormatDateHourText"?$outputlangs->trans("FormatDateHourText"):$conf->format_date_hour_text);
  1657. else if ($format == 'dayhourtextshort') $format=($outputlangs->trans("FormatDateHourTextShort")!="FormatDateHourTextShort"?$outputlangs->trans("FormatDateHourTextShort"):$conf->format_date_hour_text_short);
  1658. // Format not sensitive to language
  1659. else if ($format == 'dayhourlog') $format='%Y%m%d%H%M%S';
  1660. else if ($format == 'dayhourldap') $format='%Y%m%d%H%M%SZ';
  1661. else if ($format == 'dayhourxcard') $format='%Y%m%dT%H%M%SZ';
  1662. else if ($format == 'dayxcard') $format='%Y%m%d';
  1663. else if ($format == 'dayrfc') $format='%Y-%m-%d'; // DATE_RFC3339
  1664. else if ($format == 'dayhourrfc') $format='%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1665. else if ($format == 'standard') $format='%Y-%m-%d %H:%M:%S';
  1666. if ($reduceformat)
  1667. {
  1668. $format=str_replace('%Y','%y',$format);
  1669. $format=str_replace('yyyy','yy',$format);
  1670. }
  1671. // If date undefined or "", we return ""
  1672. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1673. // Clean format
  1674. if (preg_match('/%b/i',$format)) // There is some text to translate
  1675. {
  1676. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1677. $format=str_replace('%b','__b__',$format);
  1678. $format=str_replace('%B','__B__',$format);
  1679. }
  1680. if (preg_match('/%a/i',$format)) // There is some text to translate
  1681. {
  1682. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1683. $format=str_replace('%a','__a__',$format);
  1684. $format=str_replace('%A','__A__',$format);
  1685. }
  1686. // Analyze date
  1687. if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i',$time,$reg)
  1688. || 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
  1689. {
  1690. // TODO Remove this.
  1691. // This part of code should not be used.
  1692. dol_syslog("Functions.lib::dol_print_date function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_ERR);
  1693. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
  1694. $syear = (! empty($reg[1]) ? $reg[1] : '');
  1695. $smonth = (! empty($reg[2]) ? $reg[2] : '');
  1696. $sday = (! empty($reg[3]) ? $reg[3] : '');
  1697. $shour = (! empty($reg[4]) ? $reg[4] : '');
  1698. $smin = (! empty($reg[5]) ? $reg[5] : '');
  1699. $ssec = (! empty($reg[6]) ? $reg[6] : '');
  1700. $time=dol_mktime($shour,$smin,$ssec,$smonth,$sday,$syear,true);
  1701. $ret=adodb_strftime($format, $time+$offsettz+$offsetdst, $to_gmt);
  1702. }
  1703. else
  1704. {
  1705. // Date is a timestamps
  1706. if ($time < 100000000000) // Protection against bad date values
  1707. {
  1708. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1709. $ret=adodb_strftime($format, $timetouse, $to_gmt);
  1710. }
  1711. else $ret='Bad value '.$time.' for date';
  1712. }
  1713. if (preg_match('/__b__/i',$format))
  1714. {
  1715. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1716. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1717. $month=adodb_strftime('%m', $timetouse);
  1718. $month=sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  1719. if ($encodetooutput)
  1720. {
  1721. $monthtext=$outputlangs->transnoentities('Month'.$month);
  1722. $monthtextshort=$outputlangs->transnoentities('MonthShort'.$month);
  1723. }
  1724. else
  1725. {
  1726. $monthtext=$outputlangs->transnoentitiesnoconv('Month'.$month);
  1727. $monthtextshort=$outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1728. }
  1729. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1730. $ret=str_replace('__b__',$monthtextshort,$ret);
  1731. $ret=str_replace('__B__',$monthtext,$ret);
  1732. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1733. //return $ret;
  1734. }
  1735. if (preg_match('/__a__/i',$format))
  1736. {
  1737. $timetouse = $time+$offsettz+$offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1738. $w=adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1739. $dayweek=$outputlangs->transnoentitiesnoconv('Day'.$w);
  1740. $ret=str_replace('__A__',$dayweek,$ret);
  1741. $ret=str_replace('__a__',dol_substr($dayweek,0,3),$ret);
  1742. }
  1743. return $ret;
  1744. }
  1745. /**
  1746. * Return an array with locale date info.
  1747. * PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1748. * WARNING: This function always use PHP server timezone to return locale informations !!!
  1749. * Usage must be avoid.
  1750. * FIXME: Replace this with PHP date function and a parameter $gm
  1751. *
  1752. * @param int $timestamp Timestamp
  1753. * @param boolean $fast Fast mode
  1754. * @return array Array of informations
  1755. * If no fast mode:
  1756. * 'seconds' => $secs,
  1757. * 'minutes' => $min,
  1758. * 'hours' => $hour,
  1759. * 'mday' => $day,
  1760. * 'wday' => $dow, 0=sunday, 6=saturday
  1761. * 'mon' => $month,
  1762. * 'year' => $year,
  1763. * 'yday' => floor($secsInYear/$_day_power),
  1764. * 'weekday' => gmdate('l',$_day_power*(3+$dow)),
  1765. * 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)),
  1766. * If fast mode:
  1767. * 'seconds' => $secs,
  1768. * 'minutes' => $min,
  1769. * 'hours' => $hour,
  1770. * 'mday' => $day,
  1771. * 'mon' => $month,
  1772. * 'year' => $year,
  1773. * 'yday' => floor($secsInYear/$_day_power),
  1774. * 'leap' => $leaf,
  1775. * 'ndays' => $ndays
  1776. * @see dol_print_date, dol_stringtotime, dol_mktime
  1777. */
  1778. function dol_getdate($timestamp,$fast=false)
  1779. {
  1780. global $conf;
  1781. $usealternatemethod=false;
  1782. if ($timestamp <= 0) $usealternatemethod=true; // <= 1970
  1783. if ($timestamp >= 2145913200) $usealternatemethod=true; // >= 2038
  1784. if ($usealternatemethod)
  1785. {
  1786. $arrayinfo=adodb_getdate($timestamp,$fast);
  1787. }
  1788. else
  1789. {
  1790. $arrayinfo=getdate($timestamp);
  1791. }
  1792. return $arrayinfo;
  1793. }
  1794. /**
  1795. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  1796. * Replace function mktime not available under Windows if year < 1970
  1797. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1798. *
  1799. * @param int $hour Hour (can be -1 for undefined)
  1800. * @param int $minute Minute (can be -1 for undefined)
  1801. * @param int $second Second (can be -1 for undefined)
  1802. * @param int $month Month (1 to 12)
  1803. * @param int $day Day (1 to 31)
  1804. * @param int $year Year
  1805. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  1806. * False or 0 or 'server' = local to server TZ
  1807. * 'user' = local to user TZ
  1808. * 'tz,TimeZone' = use specified timezone
  1809. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  1810. * @return int|string Date as a timestamp, '' or false if error
  1811. * @see dol_print_date, dol_stringtotime, dol_getdate
  1812. */
  1813. function dol_mktime($hour,$minute,$second,$month,$day,$year,$gm=false,$check=1)
  1814. {
  1815. global $conf;
  1816. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  1817. // Clean parameters
  1818. if ($hour == -1 || empty($hour)) $hour=0;
  1819. if ($minute == -1 || empty($minute)) $minute=0;
  1820. if ($second == -1 || empty($second)) $second=0;
  1821. // Check parameters
  1822. if ($check)
  1823. {
  1824. if (! $month || ! $day) return '';
  1825. if ($day > 31) return '';
  1826. if ($month > 12) return '';
  1827. if ($hour < 0 || $hour > 24) return '';
  1828. if ($minute< 0 || $minute > 60) return '';
  1829. if ($second< 0 || $second > 60) return '';
  1830. }
  1831. if (method_exists('DateTime','getTimestamp'))
  1832. {
  1833. if (empty($gm) || $gm === 'server')
  1834. {
  1835. $default_timezone=@date_default_timezone_get(); // Example 'Europe/Berlin'
  1836. $localtz = new DateTimeZone($default_timezone);
  1837. }
  1838. else if ($gm === 'user')
  1839. {
  1840. // We use dol_tz_string first because it is more reliable.
  1841. $default_timezone=(empty($_SESSION["dol_tz_string"])?@date_default_timezone_get():$_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  1842. try {
  1843. $localtz = new DateTimeZone($default_timezone);
  1844. }
  1845. catch(Exception $e)
  1846. {
  1847. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  1848. $default_timezone=@date_default_timezone_get();
  1849. }
  1850. }
  1851. else if (strrpos($gm, "tz,") !== false)
  1852. {
  1853. $timezone=str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  1854. try
  1855. {
  1856. $localtz = new DateTimeZone($timezone);
  1857. }
  1858. catch(Exception $e)
  1859. {
  1860. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  1861. }
  1862. }
  1863. if (empty($localtz)) {
  1864. $localtz = new DateTimeZone('UTC');
  1865. }
  1866. //var_dump($localtz);
  1867. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  1868. $dt = new DateTime(null,$localtz);
  1869. $dt->setDate($year,$month,$day);
  1870. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  1871. $date=$dt->getTimestamp(); // should include daylight saving time
  1872. //var_dump($date);
  1873. return $date;
  1874. }
  1875. else
  1876. {
  1877. dol_print_error('','PHP version must be 5.4+');
  1878. return '';
  1879. }
  1880. }
  1881. /**
  1882. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  1883. *
  1884. * @param string $mode 'gmt' => we return GMT timestamp,
  1885. * 'tzserver' => we add the PHP server timezone
  1886. * 'tzref' => we add the company timezone
  1887. * 'tzuser' => we add the user timezone
  1888. * @return int $date Timestamp
  1889. */
  1890. function dol_now($mode='gmt')
  1891. {
  1892. $ret=0;
  1893. // Note that gmmktime and mktime return same value (GMT) when used without parameters
  1894. //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() function instead
  1895. if ($mode == 'gmt') $ret=time(); // Time for now at greenwich.
  1896. else if ($mode == 'tzserver') // Time for now with PHP server timezone added
  1897. {
  1898. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1899. $tzsecond=getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  1900. $ret=(int) (dol_now('gmt')+($tzsecond*3600));
  1901. }
  1902. /*else if ($mode == 'tzref') // Time for now with parent company timezone is added
  1903. {
  1904. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  1905. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  1906. $ret=dol_now('gmt')+($tzsecond*3600);
  1907. }*/
  1908. else if ($mode == 'tzuser') // Time for now with user timezone added
  1909. {
  1910. //print 'time: '.time().'-'.mktime().'-'.gmmktime();
  1911. $offsettz=(empty($_SESSION['dol_tz'])?0:$_SESSION['dol_tz'])*60*60;
  1912. $offsetdst=(empty($_SESSION['dol_dst'])?0:$_SESSION['dol_dst'])*60*60;
  1913. $ret=(int) (dol_now('gmt')+($offsettz+$offsetdst));
  1914. }
  1915. return $ret;
  1916. }
  1917. /**
  1918. * Return string with formated size
  1919. *
  1920. * @param int $size Size to print
  1921. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  1922. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  1923. * @return string Link
  1924. */
  1925. function dol_print_size($size,$shortvalue=0,$shortunit=0)
  1926. {
  1927. global $conf,$langs;
  1928. $level=1024;
  1929. if (! empty($conf->dol_optimize_smallscreen)) $shortunit=1;
  1930. // Set value text
  1931. if (empty($shortvalue) || $size < ($level*10))
  1932. {
  1933. $ret=$size;
  1934. $textunitshort=$langs->trans("b");
  1935. $textunitlong=$langs->trans("Bytes");
  1936. }
  1937. else
  1938. {
  1939. $ret=round($size/$level,0);
  1940. $textunitshort=$langs->trans("Kb");
  1941. $textunitlong=$langs->trans("KiloBytes");
  1942. }
  1943. // Use long or short text unit
  1944. if (empty($shortunit)) { $ret.=' '.$textunitlong; }
  1945. else { $ret.=' '.$textunitshort; }
  1946. return $ret;
  1947. }
  1948. /**
  1949. * Show Url link
  1950. *
  1951. * @param string $url Url to show
  1952. * @param string $target Target for link
  1953. * @param int $max Max number of characters to show
  1954. * @param int $withpicto With picto
  1955. * @return string HTML Link
  1956. */
  1957. function dol_print_url($url,$target='_blank',$max=32,$withpicto=0)
  1958. {
  1959. global $langs;
  1960. if (empty($url)) return '';
  1961. $link='<a href="';
  1962. if (! preg_match('/^http/i',$url)) $link.='http://';
  1963. $link.=$url;
  1964. $link.='"';
  1965. if ($target) $link.=' target="'.$target.'"';
  1966. $link.='>';
  1967. if (! preg_match('/^http/i',$url)) $link.='http://';
  1968. $link.=dol_trunc($url,$max);
  1969. $link.='</a>';
  1970. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("Url"), 'object_globe.png').' ':'').$link.'</div>';
  1971. }
  1972. /**
  1973. * Show EMail link
  1974. *
  1975. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  1976. * @param int $cid Id of contact if known
  1977. * @param int $socid Id of third party if known
  1978. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  1979. * @param int $max Max number of characters to show
  1980. * @param int $showinvalid Show warning if syntax email is wrong
  1981. * @param int $withpicto Show picto
  1982. * @return string HTML Link
  1983. */
  1984. function dol_print_email($email,$cid=0,$socid=0,$addlink=0,$max=64,$showinvalid=1,$withpicto=0)
  1985. {
  1986. global $conf,$user,$langs,$hookmanager;
  1987. $newemail=$email;
  1988. if (empty($email)) return '&nbsp;';
  1989. if (! empty($addlink))
  1990. {
  1991. $newemail='<a style="text-overflow: ellipsis;" href="';
  1992. if (! preg_match('/^mailto:/i',$email)) $newemail.='mailto:';
  1993. $newemail.=$email;
  1994. $newemail.='">';
  1995. $newemail.=dol_trunc($email,$max);
  1996. $newemail.='</a>';
  1997. if ($showinvalid && ! isValidEmail($email))
  1998. {
  1999. $langs->load("errors");
  2000. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  2001. }
  2002. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2003. {
  2004. $type='AC_EMAIL'; $link='';
  2005. 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>';
  2006. if ($link) $newemail='<div>'.$newemail.' '.$link.'</div>';
  2007. }
  2008. }
  2009. else
  2010. {
  2011. if ($showinvalid && ! isValidEmail($email))
  2012. {
  2013. $langs->load("errors");
  2014. $newemail.=img_warning($langs->trans("ErrorBadEMail",$email));
  2015. }
  2016. }
  2017. $rep = '<div class="nospan float" style="margin-right: 10px">'.($withpicto?img_picto($langs->trans("EMail"), 'object_email.png').' ':'').$newemail.'</div>';
  2018. if ($hookmanager) {
  2019. $parameters = array('cid' => $cid, 'socid' => $socid,'addlink' => $addlink, 'picto' => $withpicto);
  2020. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2021. $rep.=$hookmanager->resPrint;
  2022. }
  2023. return $rep;
  2024. }
  2025. /**
  2026. * Show social network link
  2027. *
  2028. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2029. * @param int $cid Id of contact if known
  2030. * @param int $socid Id of third party if known
  2031. * @param string $type 'skype','facebook',...
  2032. * @return string HTML Link
  2033. */
  2034. function dol_print_socialnetworks($value,$cid,$socid,$type)
  2035. {
  2036. global $conf,$user,$langs;
  2037. $newskype=$value;
  2038. if (empty($value)) return '&nbsp;';
  2039. if (! empty($type))
  2040. {
  2041. $newskype ='<div class="divsocialnetwork inline-block valignmiddle">';
  2042. $newskype.=img_picto($langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright');
  2043. $newskype.=$value;
  2044. if ($type == 'skype')
  2045. {
  2046. $newskype.= '&nbsp;';
  2047. $newskype.='<a href="skype:';
  2048. $newskype.=$value;
  2049. $newskype.='?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2050. $newskype.='<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2051. $newskype.='</a><a href="skype:';
  2052. $newskype.=$value;
  2053. $newskype.='?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2054. $newskype.='<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2055. $newskype.='</a>';
  2056. }
  2057. if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type=='skype')
  2058. {
  2059. $addlink='AC_SKYPE'; $link='';
  2060. if (! empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $link='<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$addlink.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"),"calendar").'</a>';
  2061. $newskype.=($link?' '.$link:'');
  2062. }
  2063. $newskype.='</div>';
  2064. }
  2065. else
  2066. {
  2067. $langs->load("errors");
  2068. $newskype.=img_warning($langs->trans("ErrorBadSocialNetworkValue",$value));
  2069. }
  2070. return $newskype;
  2071. }
  2072. /**
  2073. * Format phone numbers according to country
  2074. *
  2075. * @param string $phone Phone number to format
  2076. * @param string $countrycode Country code to use for formatting
  2077. * @param int $cid Id of contact if known
  2078. * @param int $socid Id of third party if known
  2079. * @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)
  2080. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2081. * @param string $withpicto Show picto
  2082. * @param string $titlealt Text to show on alt
  2083. * @param int $adddivfloat Add div float around phone.
  2084. * @return string Formated phone number
  2085. */
  2086. function dol_print_phone($phone,$countrycode='',$cid=0,$socid=0,$addlink='',$separ="&nbsp;",$withpicto='',$titlealt='',$adddivfloat=0)
  2087. {
  2088. global $conf, $user, $langs, $mysoc, $hookmanager;
  2089. // Clean phone parameter
  2090. $phone = preg_replace("/[\s.-]/","",trim($phone));
  2091. if (empty($phone)) { return ''; }
  2092. if (empty($countrycode)) $countrycode=$mysoc->country_code;
  2093. // Short format for small screens
  2094. if ($conf->dol_optimize_smallscreen) $separ='';
  2095. $newphone=$phone;
  2096. if (strtoupper($countrycode) == "FR")
  2097. {
  2098. // France
  2099. if (dol_strlen($phone) == 10) {
  2100. $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);
  2101. }
  2102. elseif (dol_strlen($phone) == 7)
  2103. {
  2104. $newphone=substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,2);
  2105. }
  2106. elseif (dol_strlen($phone) == 9)
  2107. {
  2108. $newphone=substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,2).$separ.substr($newphone,7,2);
  2109. }
  2110. elseif (dol_strlen($phone) == 11)
  2111. {
  2112. $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);
  2113. }
  2114. elseif (dol_strlen($phone) == 12)
  2115. {
  2116. $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);
  2117. }
  2118. }
  2119. elseif (strtoupper($countrycode) == "CA")
  2120. {
  2121. if (dol_strlen($phone) == 10) {
  2122. $newphone=($separ!=''?'(':'').substr($newphone,0,3).($separ!=''?')':'').$separ.substr($newphone,3,3).($separ!=''?'-':'').substr($newphone,6,4);
  2123. }
  2124. }
  2125. elseif (strtoupper($countrycode) == "PT" )
  2126. {//Portugal
  2127. if (dol_strlen($phone) == 13)
  2128. {//ex: +351_ABC_DEF_GHI
  2129. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2130. }
  2131. }
  2132. elseif (strtoupper($countrycode) == "SR" )
  2133. {//Suriname
  2134. if (dol_strlen($phone) == 10)
  2135. {//ex: +597_ABC_DEF
  2136. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3);
  2137. }
  2138. elseif (dol_strlen($phone) == 11)
  2139. {//ex: +597_ABC_DEFG
  2140. $newphone= substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,4);
  2141. }
  2142. }
  2143. elseif (strtoupper($countrycode) == "DE" )
  2144. {//Allemagne
  2145. if (dol_strlen($phone) == 14)
  2146. {//ex: +49_ABCD_EFGH_IJK
  2147. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,4).$separ.substr($newphone,11,3);
  2148. }
  2149. elseif (dol_strlen($phone) == 13)
  2150. {//ex: +49_ABC_DEFG_HIJ
  2151. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,4).$separ.substr($newphone,10,3);
  2152. }
  2153. }
  2154. elseif (strtoupper($countrycode) == "ES")
  2155. {//Espagne
  2156. if (dol_strlen($phone) == 12)
  2157. {//ex: +34_ABC_DEF_GHI
  2158. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2159. }
  2160. }
  2161. elseif (strtoupper($countrycode) == "BF")
  2162. {// Burkina Faso
  2163. if (dol_strlen($phone) == 12)
  2164. {//ex : +22 A BC_DE_FG_HI
  2165. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,1).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  2166. }
  2167. }
  2168. elseif (strtoupper($countrycode) == "RO")
  2169. {// Roumanie
  2170. if (dol_strlen($phone) == 12)
  2171. {//ex : +40 AB_CDE_FG_HI
  2172. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,3).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  2173. }
  2174. }
  2175. elseif (strtoupper($countrycode) == "TR")
  2176. {//Turquie
  2177. if (dol_strlen($phone) == 13)
  2178. {//ex : +90 ABC_DEF_GHIJ
  2179. $newphone= substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,4);
  2180. }
  2181. }
  2182. elseif (strtoupper($countrycode) == "US")
  2183. {//Etat-Unis
  2184. if (dol_strlen($phone) == 12)
  2185. {//ex: +1 ABC_DEF_GHIJ
  2186. $newphone= substr($newphone,0,2).$separ.substr($newphone,2,3).$separ.substr($newphone,5,3).$separ.substr($newphone,8,4);
  2187. }
  2188. }
  2189. elseif (strtoupper($countrycode) == "MX")
  2190. {//Mexique
  2191. if (dol_strlen($phone) == 12)
  2192. {//ex: +52 ABCD_EFG_HI
  2193. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,3).$separ.substr($newphone,10,2);
  2194. }
  2195. elseif (dol_strlen($phone) == 11)
  2196. {//ex: +52 AB_CD_EF_GH
  2197. $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);
  2198. }
  2199. elseif (dol_strlen($phone) == 13)
  2200. {//ex: +52 ABC_DEF_GHIJ
  2201. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,4);
  2202. }
  2203. }
  2204. elseif (strtoupper($countrycode) == "ML")
  2205. {//Mali
  2206. if(dol_strlen($phone) == 12)
  2207. {//ex: +223 AB_CD_EF_GH
  2208. $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);
  2209. }
  2210. }
  2211. elseif (strtoupper($countrycode) == "TH")
  2212. {//Thaïlande
  2213. if(dol_strlen($phone) == 11)
  2214. {//ex: +66_ABC_DE_FGH
  2215. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,2).$separ.substr($newphone,8,3);
  2216. }
  2217. elseif(dol_strlen($phone) == 12)
  2218. {//ex: +66_A_BCD_EF_GHI
  2219. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,1).$separ.substr($newphone,4,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,3);
  2220. }
  2221. }
  2222. elseif (strtoupper($countrycode) == "MU")
  2223. {//Maurice
  2224. if(dol_strlen($phone) == 11)
  2225. {//ex: +230_ABC_DE_FG
  2226. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
  2227. }
  2228. elseif(dol_strlen($phone) == 12)
  2229. {//ex: +230_ABCD_EF_GH
  2230. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,4).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  2231. }
  2232. }
  2233. elseif (strtoupper($countrycode) == "ZA")
  2234. {//Afrique du sud
  2235. if(dol_strlen($phone) == 12)
  2236. {//ex: +27_AB_CDE_FG_HI
  2237. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,3).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  2238. }
  2239. }
  2240. elseif (strtoupper($countrycode) == "SY")
  2241. {//Syrie
  2242. if(dol_strlen($phone) == 12)
  2243. {//ex: +963_AB_CD_EF_GH
  2244. $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);
  2245. }
  2246. elseif(dol_strlen($phone) == 13)
  2247. {//ex: +963_AB_CD_EF_GHI
  2248. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2).$separ.substr($newphone,10,3);
  2249. }
  2250. }
  2251. elseif (strtoupper($countrycode) == "AE")
  2252. {//Emirats Arabes Unis
  2253. if(dol_strlen($phone) == 12)
  2254. {//ex: +971_ABC_DEF_GH
  2255. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,2);
  2256. }
  2257. elseif(dol_strlen($phone) == 13)
  2258. {//ex: +971_ABC_DEF_GHI
  2259. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2260. }
  2261. elseif(dol_strlen($phone) == 14)
  2262. {//ex: +971_ABC_DEF_GHIK
  2263. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,4);
  2264. }
  2265. }
  2266. elseif (strtoupper($countrycode) == "DZ")
  2267. {//Algérie
  2268. if(dol_strlen($phone) == 13)
  2269. {//ex: +213_ABC_DEF_GHI
  2270. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2271. }
  2272. }
  2273. elseif (strtoupper($countrycode) == "BE")
  2274. {//Belgique
  2275. if(dol_strlen($phone) == 11)
  2276. {//ex: +32_ABC_DE_FGH
  2277. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,2).$separ.substr($newphone,8,3);
  2278. }
  2279. elseif(dol_strlen($phone) == 12)
  2280. {//ex: +32_ABC_DEF_GHI
  2281. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2282. }
  2283. }
  2284. elseif (strtoupper($countrycode) == "PF")
  2285. {//Polynésie française
  2286. if(dol_strlen($phone) == 12)
  2287. {//ex: +689_AB_CD_EF_GH
  2288. $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);
  2289. }
  2290. }
  2291. elseif (strtoupper($countrycode) == "CO")
  2292. {//Colombie
  2293. if(dol_strlen($phone) == 13)
  2294. {//ex: +57_ABC_DEF_GH_IJ
  2295. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,2).$separ.substr($newphone,11,2);
  2296. }
  2297. }
  2298. elseif (strtoupper($countrycode) == "JO")
  2299. {//Jordanie
  2300. if(dol_strlen($phone) == 12)
  2301. {//ex: +962_A_BCD_EF_GH
  2302. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,1).$separ.substr($newphone,5,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2);
  2303. }
  2304. }
  2305. elseif (strtoupper($countrycode) == "MG")
  2306. {//Madagascar
  2307. if(dol_strlen($phone) == 13)
  2308. {//ex: +261_AB_CD_EF_GHI
  2309. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,2).$separ.substr($newphone,8,2).$separ.substr($newphone,10,3);
  2310. }
  2311. }
  2312. elseif (strtoupper($countrycode) == "GB")
  2313. {//Royaume uni
  2314. if(dol_strlen($phone) == 13)
  2315. {//ex: +44_ABCD_EFG_HIJ
  2316. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,4).$separ.substr($newphone,7,3).$separ.substr($newphone,10,3);
  2317. }
  2318. }
  2319. elseif (strtoupper($countrycode) == "CH")
  2320. {//Suisse
  2321. if(dol_strlen($phone) == 12)
  2322. {//ex: +41_AB_CDE_FG_HI
  2323. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,3).$separ.substr($newphone,8,2).$separ.substr($newphone,10,2);
  2324. }
  2325. elseif(dol_strlen($phone) == 15)
  2326. {// +41_AB_CDE_FGH_IJKL
  2327. $newphone =$newphone = substr($newphone,0,3).$separ.substr($newphone,3,2).$separ.substr($newphone,5,3).$separ.substr($newphone,8,3).$separ.substr($newphone,11,4);
  2328. }
  2329. }
  2330. elseif (strtoupper($countrycode) == "TN")
  2331. {//Tunisie
  2332. if(dol_strlen($phone) == 12)
  2333. {//ex: +216_AB_CDE_FGH
  2334. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,2).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2335. }
  2336. }
  2337. elseif (strtoupper($countrycode) == "GF")
  2338. {//Guyane francaise
  2339. if(dol_strlen($phone) == 13)
  2340. {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2341. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2).$separ.substr($newphone,11,2);
  2342. }
  2343. }
  2344. elseif (strtoupper($countrycode) == "GP")
  2345. {//Guadeloupe
  2346. if(dol_strlen($phone) == 13)
  2347. {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2348. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2).$separ.substr($newphone,11,2);
  2349. }
  2350. }
  2351. elseif (strtoupper($countrycode) == "MQ")
  2352. {//Martinique
  2353. if(dol_strlen($phone) == 13)
  2354. {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2355. $newphone = substr($newphone,0,4).$separ.substr($newphone,4,3).$separ.substr($newphone,7,2).$separ.substr($newphone,9,2).$separ.substr($newphone,11,2);
  2356. }
  2357. }
  2358. elseif (strtoupper($countrycode) == "IT")
  2359. {//Italie
  2360. if(dol_strlen($phone) == 12)
  2361. {//ex: +39_ABC_DEF_GHI
  2362. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,3);
  2363. }
  2364. elseif(dol_strlen($phone) == 13)
  2365. {//ex: +39_ABC_DEF_GH_IJ
  2366. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,3).$separ.substr($newphone,6,3).$separ.substr($newphone,9,2).$separ.substr($newphone,11,2);
  2367. }
  2368. }
  2369. elseif(strtoupper($countrycode) == "AU")
  2370. {//Australie
  2371. if(dol_strlen($phone) == 12)
  2372. {//ex: +61_A_BCDE_FGHI
  2373. $newphone = substr($newphone,0,3).$separ.substr($newphone,3,1).$separ.substr($newphone,4,4).$separ.substr($newphone,8,4);
  2374. }
  2375. }
  2376. if (! empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2377. {
  2378. if ($conf->browser->layout == '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
  2379. {
  2380. $newphone ='<a href="tel:'.$phone.'"';
  2381. $newphone.='>'.$phone.'</a>';
  2382. }
  2383. else if (! empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  2384. {
  2385. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  2386. // Define urlmask
  2387. $urlmask='ErrorClickToDialModuleNotConfigured';
  2388. if (! empty($conf->global->CLICKTODIAL_URL)) $urlmask=$conf->global->CLICKTODIAL_URL;
  2389. if (! empty($user->clicktodial_url)) $urlmask=$user->clicktodial_url;
  2390. $clicktodial_poste=(! empty($user->clicktodial_poste)?urlencode($user->clicktodial_poste):'');
  2391. $clicktodial_login=(! empty($user->clicktodial_login)?urlencode($user->clicktodial_login):'');
  2392. $clicktodial_password=(! empty($user->clicktodial_password)?urlencode($user->clicktodial_password):'');
  2393. // This line is for backward compatibility
  2394. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2395. // Thoose lines are for substitution
  2396. $substitarray=array('__PHONEFROM__'=>$clicktodial_poste,
  2397. '__PHONETO__'=>urlencode($phone),
  2398. '__LOGIN__'=>$clicktodial_login,
  2399. '__PASS__'=>$clicktodial_password);
  2400. $url = make_substitutions($url, $substitarray);
  2401. $newphonesav=$newphone;
  2402. $newphone ='<a href="'.$url.'"';
  2403. if (! empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone.=' target="_blank"';
  2404. $newphone.='>'.$newphonesav.'</a>';
  2405. }
  2406. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2407. if (! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2408. {
  2409. $type='AC_TEL'; $link='';
  2410. if ($addlink == 'AC_FAX') $type='AC_FAX';
  2411. 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>';
  2412. if ($link) $newphone='<div>'.$newphone.' '.$link.'</div>';
  2413. }
  2414. }
  2415. if (empty($titlealt))
  2416. {
  2417. $titlealt=($withpicto=='fax'?$langs->trans("Fax"):$langs->trans("Phone"));
  2418. }
  2419. $rep='';
  2420. if ($hookmanager) {
  2421. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid,'titlealt' => $titlealt, 'picto' => $withpicto);
  2422. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2423. $rep.=$hookmanager->resPrint;
  2424. }
  2425. if (empty($reshook))
  2426. {
  2427. $picto = '';
  2428. if($withpicto){
  2429. if($withpicto=='fax'){
  2430. $picto = 'phoning_fax';
  2431. }elseif($withpicto=='phone'){
  2432. $picto = 'phoning';
  2433. }elseif($withpicto=='mobile'){
  2434. $picto = 'phoning_mobile';
  2435. }else{
  2436. $picto = '';
  2437. }
  2438. }
  2439. if ($adddivfloat) $rep.='<div class="nospan float" style="margin-right: 10px">';
  2440. else $rep.='<span style="margin-right: 10px;">';
  2441. $rep.=($withpicto?img_picto($titlealt, 'object_'.$picto.'.png').' ':'').$newphone;
  2442. if ($adddivfloat) $rep.='</div>';
  2443. else $rep.='</span>';
  2444. }
  2445. return $rep;
  2446. }
  2447. /**
  2448. * Return an IP formated to be shown on screen
  2449. *
  2450. * @param string $ip IP
  2451. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2452. * @return string Formated IP, with country if GeoIP module is enabled
  2453. */
  2454. function dol_print_ip($ip,$mode=0)
  2455. {
  2456. global $conf,$langs;
  2457. $ret='';
  2458. if (empty($mode)) $ret.=$ip;
  2459. if ($mode != 2)
  2460. {
  2461. $countrycode=dolGetCountryCodeFromIp($ip);
  2462. if ($countrycode) // If success, countrycode is us, fr, ...
  2463. {
  2464. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  2465. {
  2466. $ret.=' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"),DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png','',1);
  2467. }
  2468. else $ret.=' ('.$countrycode.')';
  2469. }
  2470. }
  2471. return $ret;
  2472. }
  2473. /**
  2474. * Return the IP of remote user.
  2475. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2476. * Then HTTP_CLIENT_IP if defined (rare)
  2477. * Then REMOTE_ADDR (not way to be modified by user but may be wrong if using proxy)
  2478. *
  2479. * @return string Ip of remote user.
  2480. */
  2481. function getUserRemoteIP()
  2482. {
  2483. $ip = empty($_SERVER['HTTP_X_FORWARDED_FOR'])? (empty($_SERVER['HTTP_CLIENT_IP'])?(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']):$_SERVER['HTTP_CLIENT_IP']) : $_SERVER['HTTP_X_FORWARDED_FOR'];
  2484. return $ip;
  2485. }
  2486. /**
  2487. * Return a country code from IP. Empty string if not found.
  2488. *
  2489. * @param string $ip IP
  2490. * @return string Country code ('us', 'fr', ...)
  2491. */
  2492. function dolGetCountryCodeFromIp($ip)
  2493. {
  2494. global $conf;
  2495. $countrycode='';
  2496. if (! empty($conf->geoipmaxmind->enabled))
  2497. {
  2498. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2499. //$ip='24.24.24.24';
  2500. //$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)
  2501. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2502. $geoip=new DolGeoIP('country',$datafile);
  2503. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2504. //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
  2505. $countrycode=$geoip->getCountryCodeFromIP($ip);
  2506. }
  2507. return $countrycode;
  2508. }
  2509. /**
  2510. * Return country code for current user.
  2511. * If software is used inside a local network, detection may fails (we need a public ip)
  2512. *
  2513. * @return string Country code (fr, es, it, us, ...)
  2514. */
  2515. function dol_user_country()
  2516. {
  2517. global $conf,$langs,$user;
  2518. //$ret=$user->xxx;
  2519. $ret='';
  2520. if (! empty($conf->geoipmaxmind->enabled))
  2521. {
  2522. $ip=getUserRemoteIP();
  2523. $datafile=$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2524. //$ip='24.24.24.24';
  2525. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2526. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2527. $geoip=new DolGeoIP('country',$datafile);
  2528. $countrycode=$geoip->getCountryCodeFromIP($ip);
  2529. $ret=$countrycode;
  2530. }
  2531. return $ret;
  2532. }
  2533. /**
  2534. * Format address string
  2535. *
  2536. * @param string $address Address
  2537. * @param int $htmlid Html ID (for example 'gmap')
  2538. * @param int $mode thirdparty|contact|member|other
  2539. * @param int $id Id of object
  2540. * @param int $noprint No output. Result is the function return
  2541. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2542. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2543. * @see dol_format_address
  2544. */
  2545. function dol_print_address($address, $htmlid, $mode, $id, $noprint=0, $charfornl='')
  2546. {
  2547. global $conf, $user, $langs, $hookmanager;
  2548. $out = '';
  2549. if ($address)
  2550. {
  2551. if ($hookmanager) {
  2552. $parameters = array('element' => $mode, 'id' => $id);
  2553. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2554. $out.=$hookmanager->resPrint;
  2555. }
  2556. if (empty($reshook))
  2557. {
  2558. if (empty($charfornl)) $out.=nl2br($address);
  2559. else $out.=preg_replace('/[\r\n]+/', $charfornl, $address);
  2560. $showgmap=$showomap=0;
  2561. // TODO Add a hook here
  2562. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap=1;
  2563. if ($mode=='contact' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap=1;
  2564. if ($mode=='member' && ! empty($conf->google->enabled) && ! empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap=1;
  2565. if (($mode=='thirdparty' || $mode =='societe') && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap=1;
  2566. if ($mode=='contact' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap=1;
  2567. if ($mode=='member' && ! empty($conf->openstreetmap->enabled) && ! empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap=1;
  2568. if ($showgmap)
  2569. {
  2570. $url=dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id,1);
  2571. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2572. }
  2573. if ($showomap)
  2574. {
  2575. $url=dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id,1);
  2576. $out.=' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2577. }
  2578. }
  2579. }
  2580. if ($noprint) return $out;
  2581. else print $out;
  2582. }
  2583. /**
  2584. * Return true if email syntax is ok
  2585. *
  2586. * @param string $address email (Ex: "toto@examle.com", "John Do <johndo@example.com>")
  2587. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2588. * @return boolean true if email syntax is OK, false if KO or empty string
  2589. */
  2590. function isValidEmail($address, $acceptsupervisorkey=0)
  2591. {
  2592. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2593. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2594. return false;
  2595. }
  2596. /**
  2597. * Return if the domain name has a valid MX record.
  2598. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  2599. *
  2600. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  2601. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  2602. */
  2603. function isValidMXRecord($domain)
  2604. {
  2605. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr'))
  2606. {
  2607. if (! checkdnsrr(idn_to_ascii($domain), 'MX'))
  2608. {
  2609. return 0;
  2610. }
  2611. if (function_exists('getmxrr'))
  2612. {
  2613. $mxhosts=array();
  2614. $weight=array();
  2615. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  2616. if (count($mxhosts) > 1) return 1;
  2617. if (count($mxhosts) == 1 && ! empty($mxhosts[0])) return 1;
  2618. return 0;
  2619. }
  2620. }
  2621. return -1;
  2622. }
  2623. /**
  2624. * Return true if phone number syntax is ok
  2625. * TODO Decide what to do with this
  2626. *
  2627. * @param string $phone phone (Ex: "0601010101")
  2628. * @return boolean true if phone syntax is OK, false if KO or empty string
  2629. */
  2630. function isValidPhone($phone)
  2631. {
  2632. return true;
  2633. }
  2634. /**
  2635. * Make a strlen call. Works even if mbstring module not enabled
  2636. *
  2637. * @param string $string String to calculate length
  2638. * @param string $stringencoding Encoding of string
  2639. * @return int Length of string
  2640. */
  2641. function dol_strlen($string, $stringencoding='UTF-8')
  2642. {
  2643. if (function_exists('mb_strlen')) return mb_strlen($string,$stringencoding);
  2644. else return strlen($string);
  2645. }
  2646. /**
  2647. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  2648. *
  2649. * @param string $string String to scan
  2650. * @param string $start Start position
  2651. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  2652. * @param string $stringencoding Page code used for input string encoding
  2653. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  2654. * @return string substring
  2655. */
  2656. function dol_substr($string, $start, $length, $stringencoding='', $trunconbytes=0)
  2657. {
  2658. global $langs;
  2659. if (empty($stringencoding)) $stringencoding=$langs->charset_output;
  2660. $ret='';
  2661. if (empty($trunconbytes))
  2662. {
  2663. if (function_exists('mb_substr'))
  2664. {
  2665. $ret=mb_substr($string, $start, $length, $stringencoding);
  2666. }
  2667. else
  2668. {
  2669. $ret=substr($string, $start, $length);
  2670. }
  2671. }
  2672. else
  2673. {
  2674. if (function_exists('mb_strcut'))
  2675. {
  2676. $ret=mb_strcut($string, $start, $length, $stringencoding);
  2677. }
  2678. else
  2679. {
  2680. $ret=substr($string, $start, $length);
  2681. }
  2682. }
  2683. return $ret;
  2684. }
  2685. /**
  2686. * Truncate a string to a particular length adding '...' if string larger than length.
  2687. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2688. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2689. *
  2690. * @param string $string String to truncate
  2691. * @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 ...)
  2692. * @param string $trunc Where to trunc: right, left, middle (size must be a 2 power), wrap
  2693. * @param string $stringencoding Tell what is source string encoding
  2694. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2695. * @param int $display Trunc is used to display data and can be changed for small screen. TODO Remove this param (must be dealt with CSS)
  2696. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  2697. */
  2698. function dol_trunc($string,$size=40,$trunc='right',$stringencoding='UTF-8',$nodot=0, $display=0)
  2699. {
  2700. global $conf;
  2701. if ($size==0 || ! empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2702. if (empty($stringencoding)) $stringencoding='UTF-8';
  2703. // reduce for small screen
  2704. if ($conf->dol_optimize_smallscreen==1 && $display==1) $size = round($size/3);
  2705. // We go always here
  2706. if ($trunc == 'right')
  2707. {
  2708. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2709. 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 ...
  2710. return dol_substr($newstring,0,$size,$stringencoding).($nodot?'':'...');
  2711. else
  2712. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  2713. return $string;
  2714. }
  2715. elseif ($trunc == 'middle')
  2716. {
  2717. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2718. if (dol_strlen($newstring,$stringencoding) > 2 && dol_strlen($newstring,$stringencoding) > ($size+1))
  2719. {
  2720. $size1=round($size/2);
  2721. $size2=round($size/2);
  2722. return dol_substr($newstring,0,$size1,$stringencoding).'...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size2,$size2,$stringencoding);
  2723. }
  2724. else
  2725. return $string;
  2726. }
  2727. elseif ($trunc == 'left')
  2728. {
  2729. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2730. 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 ...
  2731. return '...'.dol_substr($newstring,dol_strlen($newstring,$stringencoding) - $size,$size,$stringencoding);
  2732. else
  2733. return $string;
  2734. }
  2735. elseif ($trunc == 'wrap')
  2736. {
  2737. $newstring=dol_textishtml($string)?dol_string_nohtmltag($string,1):$string;
  2738. if (dol_strlen($newstring,$stringencoding) > ($size+1))
  2739. return dol_substr($newstring,0,$size,$stringencoding)."\n".dol_trunc(dol_substr($newstring,$size,dol_strlen($newstring,$stringencoding)-$size,$stringencoding),$size,$trunc);
  2740. else
  2741. return $string;
  2742. }
  2743. else return 'BadParam3CallingDolTrunc';
  2744. }
  2745. /**
  2746. * Show picto whatever it's its name (generic function)
  2747. *
  2748. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  2749. * @param string $picto Name of image file to show ('filenew', ...)
  2750. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2751. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2752. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2753. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2754. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2755. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  2756. * @param int $srconly Return only content of the src attribute of img.
  2757. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2758. * @param string $alt Force alt for bind people
  2759. * @param string $morecss Add more class css on img tag (For example 'myclascss'). Work only if $moreatt is empty.
  2760. * @return string Return img tag
  2761. * @see #img_object, #img_picto_common
  2762. */
  2763. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0, $alt='', $morecss='')
  2764. {
  2765. global $conf, $langs;
  2766. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2767. $url = DOL_URL_ROOT;
  2768. $theme = $conf->theme;
  2769. $path = 'theme/'.$theme;
  2770. // Define fullpathpicto to use into src
  2771. if ($pictoisfullpath) {
  2772. // Clean parameters
  2773. if (! preg_match('/(\.png|\.gif|\.svg)$/i',$picto)) {
  2774. $picto .= '.png';
  2775. }
  2776. $fullpathpicto = $picto;
  2777. }
  2778. else {
  2779. $pictowithoutext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  2780. //if (in_array($picto, array('switch_off', 'switch_on', 'off', 'on')))
  2781. if (empty($srconly) && in_array($pictowithoutext, array(
  2782. 'bank', 'close_title', 'delete', 'edit', 'ellipsis-h', 'filter', 'grip', 'grip_title', 'list', 'listlight', 'off', 'on', 'play', 'playdisabled', 'printer', 'resize',
  2783. 'note', 'split', 'switch_off', 'switch_on', 'unlink', 'uparrow', '1downarrow', '1uparrow',
  2784. 'jabber','skype','twitter','facebook'
  2785. )
  2786. )) {
  2787. $fakey = $pictowithoutext;
  2788. $facolor = ''; $fasize = '';
  2789. $marginleftonlyshort = 2;
  2790. if ($pictowithoutext == 'switch_off') {
  2791. $fakey = 'fa-toggle-off';
  2792. $facolor = '#999';
  2793. $fasize = '2em';
  2794. }
  2795. elseif ($pictowithoutext == 'switch_on') {
  2796. $fakey = 'fa-toggle-on';
  2797. $facolor = '#227722';
  2798. $fasize = '2em';
  2799. }
  2800. elseif ($pictowithoutext == 'off') {
  2801. $fakey = 'fa-square-o';
  2802. $fasize = '1.3em';
  2803. }
  2804. elseif ($pictowithoutext == 'on') {
  2805. $fakey = 'fa-check-square-o';
  2806. $fasize = '1.3em';
  2807. }
  2808. elseif ($pictowithoutext == 'bank') {
  2809. $fakey = 'fa-bank';
  2810. $facolor = '#444';
  2811. }
  2812. elseif ($pictowithoutext == 'close_title') {
  2813. $fakey = 'fa-window-close';
  2814. }
  2815. elseif ($pictowithoutext == 'delete') {
  2816. $fakey = 'fa-trash';
  2817. $facolor = '#444';
  2818. }
  2819. elseif ($pictowithoutext == 'edit') {
  2820. $fakey = 'fa-pencil';
  2821. $facolor = '#444';
  2822. }
  2823. elseif ($pictowithoutext == 'filter') {
  2824. $fakey = 'fa-'.$pictowithoutext;
  2825. }
  2826. elseif ($pictowithoutext == 'grip_title' || $pictowithoutext == 'grip') {
  2827. $fakey = 'fa-arrows';
  2828. }
  2829. elseif ($pictowithoutext == 'listlight') {
  2830. $fakey = 'fa-download';
  2831. $facolor = '#999';
  2832. $marginleftonlyshort=1;
  2833. }
  2834. elseif ($pictowithoutext == 'printer') {
  2835. $fakey = 'fa-print';
  2836. $fasize = '1.2em';
  2837. $facolor = '#444';
  2838. }
  2839. elseif ($pictowithoutext == 'resize') {
  2840. $fakey = 'fa-crop';
  2841. $facolor = '#444';
  2842. }
  2843. elseif ($pictowithoutext == 'note') {
  2844. $fakey = 'fa-sticky-note-o';
  2845. $facolor = '#999';
  2846. $marginleftonlyshort=1;
  2847. }
  2848. elseif ($pictowithoutext == 'uparrow') {
  2849. $fakey = 'fa-mail-forward';
  2850. $facolor = '#555';
  2851. }
  2852. elseif ($pictowithoutext == '1uparrow') {
  2853. $fakey = 'fa-caret-up';
  2854. $marginleftonlyshort = 1;
  2855. }
  2856. elseif ($pictowithoutext == '1downarrow') {
  2857. $fakey = 'fa-caret-down';
  2858. $marginleftonlyshort = 1;
  2859. }
  2860. elseif ($pictowithoutext == 'unlink') {
  2861. $fakey = 'fa-chain-broken';
  2862. $facolor = '#555';
  2863. }
  2864. elseif ($pictowithoutext == 'playdisabled') {
  2865. $fakey = 'fa-play';
  2866. $facolor = '#ccc';
  2867. } elseif ($pictowithoutext == 'play') {
  2868. $fakey = 'fa-play';
  2869. $facolor = '#444';
  2870. }
  2871. elseif ($pictowithoutext == 'jabber') {
  2872. $fakey = 'fa-comment-o';
  2873. }
  2874. elseif ($pictowithoutext == 'split') {
  2875. $fakey = 'fa-code-fork';
  2876. }
  2877. else {
  2878. $fakey = 'fa-'.$pictowithoutext;
  2879. $facolor = '#444';
  2880. $marginleftonlyshort=0;
  2881. }
  2882. $reg=array();
  2883. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2884. $morecss.= ($morecss?' ':'').$reg[1];
  2885. }
  2886. $enabledisablehtml = '<span class="fa '.$fakey.' '.($marginleftonlyshort?($marginleftonlyshort==1?'marginleftonlyshort':'marginleftonly'):'').' valignmiddle'.($morecss?' '.$morecss:'').'" style="'.($fasize?('font-size: '.$fasize.';'):'').($facolor?(' color: '.$facolor.';'):'').'" alt="'.dol_escape_htmltag($titlealt).'"'.(($notitle || empty($titlealt))?'':' title="'.dol_escape_htmltag($titlealt).'"').($moreatt?' '.$moreatt:'').'>';
  2887. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2888. $enabledisablehtml.= $titlealt;
  2889. }
  2890. $enabledisablehtml.= '</span>';
  2891. return $enabledisablehtml;
  2892. }
  2893. if (! empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  2894. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  2895. }
  2896. else if (! empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  2897. $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
  2898. }
  2899. else if (! empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  2900. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  2901. }
  2902. // If we ask an image into $url/$mymodule/img (instead of default path)
  2903. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  2904. $picto = $regs[1];
  2905. $path = $regs[2]; // $path is $mymodule
  2906. }
  2907. // Clean parameters
  2908. if (! preg_match('/(\.png|\.gif|\.svg)$/i',$picto)) {
  2909. $picto .= '.png';
  2910. }
  2911. // If alt path are defined, define url where img file is, according to physical path
  2912. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  2913. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  2914. if ($type == 'main') {
  2915. continue;
  2916. }
  2917. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  2918. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  2919. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  2920. break;
  2921. }
  2922. }
  2923. // $url is '' or '/custom', $path is current theme or
  2924. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  2925. }
  2926. if ($srconly) {
  2927. return $fullpathpicto;
  2928. }
  2929. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for bind people
  2930. return '<img src="'.$fullpathpicto.'" alt="'.dol_escape_htmltag($alt).'"'.(($notitle || empty($titlealt))?'':' title="'.dol_escape_htmltag($titlealt).'"').($moreatt?' '.$moreatt:' class="inline-block'.($morecss?' '.$morecss:'').'"').'>'; // Alt is used for accessibility, title for popup
  2931. }
  2932. /**
  2933. * Show a picto called object_picto (generic function)
  2934. *
  2935. * @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.
  2936. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  2937. * For external modules use imagename@mymodule to search into directory "img" of module.
  2938. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  2939. * @param int $pictoisfullpath If 1, image path is a full path
  2940. * @param int $srconly Return only content of the src attribute of img.
  2941. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2942. * @return string Return img tag
  2943. * @see #img_picto, #img_picto_common
  2944. */
  2945. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly=0, $notitle=0)
  2946. {
  2947. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  2948. }
  2949. /**
  2950. * Show weather picto
  2951. *
  2952. * @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.
  2953. * @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.
  2954. * @param string $moreatt Add more attribute on img tag
  2955. * @param int $pictoisfullpath If 1, image path is a full path
  2956. * @return string Return img tag
  2957. * @see #img_object, #img_picto
  2958. */
  2959. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  2960. {
  2961. global $conf;
  2962. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  2963. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  2964. return img_picto($titlealt, $path, $moreatt, 1);
  2965. }
  2966. /**
  2967. * Show picto (generic function)
  2968. *
  2969. * @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.
  2970. * @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.
  2971. * @param string $moreatt Add more attribute on img tag
  2972. * @param int $pictoisfullpath If 1, image path is a full path
  2973. * @return string Return img tag
  2974. * @see #img_object, #img_picto
  2975. */
  2976. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  2977. {
  2978. global $conf;
  2979. if (! preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  2980. if ($pictoisfullpath) $path = $picto;
  2981. else
  2982. {
  2983. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  2984. if (! empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  2985. {
  2986. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  2987. if (file_exists($themepath)) $path = $themepath;
  2988. }
  2989. }
  2990. return img_picto($titlealt, $path, $moreatt, 1);
  2991. }
  2992. /**
  2993. * Show logo action
  2994. *
  2995. * @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.
  2996. * @param string $numaction Action id or code to show
  2997. * @return string Return an img tag
  2998. */
  2999. function img_action($titlealt, $numaction)
  3000. {
  3001. global $conf, $langs;
  3002. if (empty($titlealt) || $titlealt == 'default')
  3003. {
  3004. if ($numaction == '-1' || $numaction == 'ST_NO') { $numaction = -1; $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact'); }
  3005. elseif ($numaction == '0' || $numaction == 'ST_NEVER') { $numaction = 0; $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted'); }
  3006. elseif ($numaction == '1' || $numaction == 'ST_TODO') { $numaction = 1; $titlealt = $langs->transnoentitiesnoconv('ChangeToContact'); }
  3007. elseif ($numaction == '2' || $numaction == 'ST_PEND') { $numaction = 2; $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess'); }
  3008. elseif ($numaction == '3' || $numaction == 'ST_DONE') { $numaction = 3; $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone'); }
  3009. else { $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction); $numaction = 0; }
  3010. }
  3011. if (! is_numeric($numaction)) $numaction=0;
  3012. return img_picto($titlealt, 'stcomm'.$numaction.'.png');
  3013. }
  3014. /**
  3015. * Show pdf logo
  3016. *
  3017. * @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.
  3018. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3019. * @return string Retourne tag img
  3020. */
  3021. function img_pdf($titlealt = 'default', $size = 3)
  3022. {
  3023. global $conf, $langs;
  3024. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  3025. return img_picto($titlealt, 'pdf'.$size.'.png');
  3026. }
  3027. /**
  3028. * Show logo +
  3029. *
  3030. * @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.
  3031. * @param string $other Add more attributes on img
  3032. * @return string Return tag img
  3033. */
  3034. function img_edit_add($titlealt = 'default', $other = '')
  3035. {
  3036. global $conf, $langs;
  3037. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  3038. return img_picto($titlealt, 'edit_add.png', $other);
  3039. }
  3040. /**
  3041. * Show logo -
  3042. *
  3043. * @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.
  3044. * @param string $other Add more attributes on img
  3045. * @return string Return tag img
  3046. */
  3047. function img_edit_remove($titlealt = 'default', $other='')
  3048. {
  3049. global $conf, $langs;
  3050. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  3051. return img_picto($titlealt, 'edit_remove.png', $other);
  3052. }
  3053. /**
  3054. * Show logo editer/modifier fiche
  3055. *
  3056. * @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.
  3057. * @param integer $float Si il faut y mettre le style "float: right"
  3058. * @param string $other Add more attributes on img
  3059. * @return string Return tag img
  3060. */
  3061. function img_edit($titlealt = 'default', $float = 0, $other = 'class="pictoedit"')
  3062. {
  3063. global $conf, $langs;
  3064. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  3065. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl'?'left':'right').'"' : "") . ($other?' '.$other:''));
  3066. }
  3067. /**
  3068. * Show logo view card
  3069. *
  3070. * @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.
  3071. * @param integer $float Si il faut y mettre le style "float: right"
  3072. * @param string $other Add more attributes on img
  3073. * @return string Return tag img
  3074. */
  3075. function img_view($titlealt = 'default', $float = 0, $other = '')
  3076. {
  3077. global $conf, $langs;
  3078. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  3079. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3080. return img_picto($titlealt, 'view.png', $moreatt);
  3081. }
  3082. /**
  3083. * Show delete logo
  3084. *
  3085. * @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.
  3086. * @param string $other Add more attributes on img
  3087. * @return string Retourne tag img
  3088. */
  3089. function img_delete($titlealt = 'default', $other = 'class="pictodelete"')
  3090. {
  3091. global $conf, $langs;
  3092. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  3093. return img_picto($titlealt, 'delete.png', $other);
  3094. //return '<span class="fa fa-trash fa-2x fa-fw" style="font-size: 1.7em;" title="'.$titlealt.'"></span>';
  3095. }
  3096. /**
  3097. * Show printer logo
  3098. *
  3099. * @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.
  3100. * @param string $other Add more attributes on img
  3101. * @return string Retourne tag img
  3102. */
  3103. function img_printer($titlealt = "default", $other='')
  3104. {
  3105. global $conf,$langs;
  3106. if ($titlealt=="default") $titlealt=$langs->trans("Print");
  3107. return img_picto($titlealt,'printer.png',$other);
  3108. }
  3109. /**
  3110. * Show split logo
  3111. *
  3112. * @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.
  3113. * @param string $other Add more attributes on img
  3114. * @return string Retourne tag img
  3115. */
  3116. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3117. {
  3118. global $conf, $langs;
  3119. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  3120. return img_picto($titlealt, 'split.png', $other);
  3121. }
  3122. /**
  3123. * Show help logo with cursor "?"
  3124. *
  3125. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3126. * @param int|string $usealttitle Text to use as alt title
  3127. * @return string Return tag img
  3128. */
  3129. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3130. {
  3131. global $conf, $langs;
  3132. if ($usealttitle)
  3133. {
  3134. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  3135. else $usealttitle = $langs->trans('Info');
  3136. }
  3137. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help': ($usehelpcursor == 2 ? ' cursor: pointer':'')).'"');
  3138. }
  3139. /**
  3140. * Show info logo
  3141. *
  3142. * @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.
  3143. * @return string Return img tag
  3144. */
  3145. function img_info($titlealt = 'default')
  3146. {
  3147. global $conf, $langs;
  3148. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  3149. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3150. }
  3151. /**
  3152. * Show warning logo
  3153. *
  3154. * @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.
  3155. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3156. * @return string Return img tag
  3157. */
  3158. function img_warning($titlealt = 'default', $moreatt = '')
  3159. {
  3160. global $conf, $langs;
  3161. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  3162. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3163. return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): ''));
  3164. }
  3165. /**
  3166. * Show error logo
  3167. *
  3168. * @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.
  3169. * @return string Return img tag
  3170. */
  3171. function img_error($titlealt = 'default')
  3172. {
  3173. global $conf, $langs;
  3174. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  3175. return img_picto($titlealt, 'error.png', 'class="valigntextbottom"');
  3176. }
  3177. /**
  3178. * Show next logo
  3179. *
  3180. * @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.
  3181. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3182. * @return string Return img tag
  3183. */
  3184. function img_next($titlealt = 'default', $moreatt='')
  3185. {
  3186. global $conf, $langs;
  3187. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  3188. //return img_picto($titlealt, 'next.png', $moreatt);
  3189. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3190. }
  3191. /**
  3192. * Show previous logo
  3193. *
  3194. * @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.
  3195. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3196. * @return string Return img tag
  3197. */
  3198. function img_previous($titlealt = 'default', $moreatt='')
  3199. {
  3200. global $conf, $langs;
  3201. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  3202. //return img_picto($titlealt, 'previous.png', $moreatt);
  3203. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3204. }
  3205. /**
  3206. * Show down arrow logo
  3207. *
  3208. * @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.
  3209. * @param int $selected Selected
  3210. * @param string $moreclass Add more CSS classes
  3211. * @return string Return img tag
  3212. */
  3213. function img_down($titlealt = 'default', $selected = 0, $moreclass='')
  3214. {
  3215. global $conf, $langs;
  3216. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  3217. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass?" ".$moreclass:"").'"');
  3218. }
  3219. /**
  3220. * Show top arrow logo
  3221. *
  3222. * @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.
  3223. * @param int $selected Selected
  3224. * @param string $moreclass Add more CSS classes
  3225. * @return string Return img tag
  3226. */
  3227. function img_up($titlealt = 'default', $selected = 0, $moreclass='')
  3228. {
  3229. global $conf, $langs;
  3230. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  3231. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass?" ".$moreclass:"").'"');
  3232. }
  3233. /**
  3234. * Show left arrow logo
  3235. *
  3236. * @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.
  3237. * @param int $selected Selected
  3238. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3239. * @return string Return img tag
  3240. */
  3241. function img_left($titlealt = 'default', $selected = 0, $moreatt='')
  3242. {
  3243. global $conf, $langs;
  3244. if ($titlealt == 'default') $titlealt = $langs->trans('Left');
  3245. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3246. }
  3247. /**
  3248. * Show right arrow logo
  3249. *
  3250. * @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.
  3251. * @param int $selected Selected
  3252. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3253. * @return string Return img tag
  3254. */
  3255. function img_right($titlealt = 'default', $selected = 0, $moreatt='')
  3256. {
  3257. global $conf, $langs;
  3258. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  3259. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3260. }
  3261. /**
  3262. * Show tick logo if allowed
  3263. *
  3264. * @param string $allow Allow
  3265. * @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.
  3266. * @return string Return img tag
  3267. */
  3268. function img_allow($allow, $titlealt = 'default')
  3269. {
  3270. global $conf, $langs;
  3271. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  3272. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  3273. return '-';
  3274. }
  3275. /**
  3276. * Return image of a credit card according to its brand name
  3277. *
  3278. * @param string $brand Brand name of credit card
  3279. * @return string Return img tag
  3280. */
  3281. function img_credit_card($brand)
  3282. {
  3283. if ($brand == 'Visa') {$brand='cc-visa';}
  3284. elseif ($brand == 'MasterCard') {$brand='cc-mastercard';}
  3285. elseif ($brand == 'American Express') {$brand='cc-amex';}
  3286. elseif ($brand == 'Discover') {$brand='cc-discover';}
  3287. elseif ($brand == 'JCB') {$brand='cc-jcb';}
  3288. elseif ($brand == 'Diners Club') {$brand='cc-diners-club';}
  3289. elseif (! in_array($brand, array('cc-visa','cc-mastercard','cc-amex','cc-discover','cc-jcb','cc-diners-club'))) {$brand='credit-card';}
  3290. return '<span class="fa fa-'.$brand.' fa-2x fa-fw"></span>';
  3291. }
  3292. /**
  3293. * Show MIME img of a file
  3294. *
  3295. * @param string $file Filename
  3296. * @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.
  3297. * @param string $morecss More css
  3298. * @return string Return img tag
  3299. */
  3300. function img_mime($file, $titlealt = '', $morecss='')
  3301. {
  3302. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3303. $mimetype = dol_mimetype($file, '', 1);
  3304. $mimeimg = dol_mimetype($file, '', 2);
  3305. $mimefa = dol_mimetype($file, '', 4);
  3306. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  3307. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3308. return '<i class="fa fa-'.$mimefa.' paddingright"></i>';
  3309. }
  3310. /**
  3311. * Show phone logo.
  3312. * Use img_picto instead.
  3313. *
  3314. * @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.
  3315. * @param int $option Option
  3316. * @return string Return img tag
  3317. * @deprecated
  3318. * @see img_picto
  3319. */
  3320. function img_phone($titlealt = 'default', $option = 0)
  3321. {
  3322. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  3323. global $conf,$langs;
  3324. if ($titlealt == 'default') $titlealt = $langs->trans('Call');
  3325. if ($option == 1) $img = 'call';
  3326. else $img = 'call_out';
  3327. return img_picto($titlealt, $img);
  3328. }
  3329. /**
  3330. * Show search logo
  3331. *
  3332. * @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.
  3333. * @param string $other Add more attributes on img
  3334. * @return string Retourne tag img
  3335. */
  3336. function img_search($titlealt = 'default', $other = '')
  3337. {
  3338. global $conf, $langs;
  3339. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3340. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3341. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3342. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3343. return $input;
  3344. }
  3345. /**
  3346. * Show search logo
  3347. *
  3348. * @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.
  3349. * @param string $other Add more attributes on img
  3350. * @return string Retourne tag img
  3351. */
  3352. function img_searchclear($titlealt = 'default', $other = '')
  3353. {
  3354. global $conf, $langs;
  3355. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3356. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3357. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3358. $input.= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3359. return $input;
  3360. }
  3361. /**
  3362. * Show information for admin users or standard users
  3363. *
  3364. * @param string $text Text info
  3365. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3366. * @param int $nodiv No div
  3367. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'xxx'=Other
  3368. * @param string $morecss More CSS
  3369. * @return string String with info text
  3370. */
  3371. function info_admin($text, $infoonimgalt = 0, $nodiv=0, $admin='1', $morecss='')
  3372. {
  3373. global $conf, $langs;
  3374. if ($infoonimgalt)
  3375. {
  3376. return img_picto($text, 'info', 'class="hideonsmartphone'.($morecss?' '.$morecss:'').'"');
  3377. }
  3378. return ($nodiv?'':'<div class="'.(empty($admin)?'':($admin=='1'?'info':$admin)).' hideonsmartphone'.($morecss?' '.$morecss:'').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin?$langs->trans('InfoAdmin'):$langs->trans('Note')).'"></span> '.$text.($nodiv?'':'</div>');
  3379. }
  3380. /**
  3381. * Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remontee des bugs.
  3382. * On doit appeler cette fonction quand une erreur technique bloquante est rencontree.
  3383. * Toutefois, il faut essayer de ne l'appeler qu'au sein de pages php, les classes devant
  3384. * renvoyer leur erreur par l'intermediaire de leur propriete "error".
  3385. *
  3386. * @param DoliDB $db Database handler
  3387. * @param mixed $error String or array of errors strings to show
  3388. * @param array $errors Array of errors
  3389. * @return void
  3390. * @see dol_htmloutput_errors
  3391. */
  3392. function dol_print_error($db='',$error='',$errors=null)
  3393. {
  3394. global $conf,$langs,$argv;
  3395. global $dolibarr_main_prod;
  3396. $out = '';
  3397. $syslog = '';
  3398. // Si erreur intervenue avant chargement langue
  3399. if (! $langs)
  3400. {
  3401. require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
  3402. $langs = new Translate('', $conf);
  3403. $langs->load("main");
  3404. }
  3405. // Load translation files required by the page
  3406. $langs->loadLangs(array('main', 'errors'));
  3407. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3408. {
  3409. $out.=$langs->trans("DolibarrHasDetectedError").".<br>\n";
  3410. 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";
  3411. $out.=$langs->trans("InformationToHelpDiagnose").":<br>\n";
  3412. $out.="<b>".$langs->trans("Date").":</b> ".dol_print_date(time(),'dayhourlog')."<br>\n";
  3413. $out.="<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";
  3414. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out.="<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  3415. if (function_exists("phpversion"))
  3416. {
  3417. $out.="<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  3418. }
  3419. $out.="<b>".$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";
  3420. if (function_exists("php_uname"))
  3421. {
  3422. $out.="<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  3423. }
  3424. $out.="<b>".$langs->trans("UserAgent").":</b> ".$_SERVER["HTTP_USER_AGENT"]."<br>\n";
  3425. $out.="<br>\n";
  3426. $out.="<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"],ENT_COMPAT,'UTF-8')."<br>\n";
  3427. $out.="<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"])?dol_htmlentities($_SERVER["HTTP_REFERER"],ENT_COMPAT,'UTF-8'):'')."<br>\n";
  3428. $out.="<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu)?$conf->standard_menu:'')."<br>\n";
  3429. $out.="<br>\n";
  3430. $syslog.="url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  3431. $syslog.=", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  3432. }
  3433. else // Mode CLI
  3434. {
  3435. $out.='> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  3436. $syslog.="pid=".dol_getmypid();
  3437. }
  3438. if (is_object($db))
  3439. {
  3440. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3441. {
  3442. $out.="<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  3443. $out.="<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror()?dol_escape_htmltag($db->lastqueryerror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3444. $out.="<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno()?dol_escape_htmltag($db->lasterrno()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3445. $out.="<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror()?dol_escape_htmltag($db->lasterror()):$langs->trans("ErrorNoRequestInError"))."<br>\n";
  3446. $out.="<br>\n";
  3447. }
  3448. else // Mode CLI
  3449. {
  3450. // No dol_escape_htmltag for output, we are in CLI mode
  3451. $out.='> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  3452. $out.='> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror()?$db->lastqueryerror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3453. $out.='> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno()?$db->lasterrno():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3454. $out.='> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror()?$db->lasterror():$langs->transnoentities("ErrorNoRequestInError"))."\n";
  3455. }
  3456. $syslog.=", sql=".$db->lastquery();
  3457. $syslog.=", db_error=".$db->lasterror();
  3458. }
  3459. if ($error || $errors)
  3460. {
  3461. $langs->load("errors");
  3462. // Merge all into $errors array
  3463. if (is_array($error) && is_array($errors)) $errors=array_merge($error,$errors);
  3464. elseif (is_array($error)) $errors=$error;
  3465. elseif (is_array($errors)) $errors=array_merge(array($error),$errors);
  3466. else $errors=array_merge(array($error));
  3467. foreach($errors as $msg)
  3468. {
  3469. if (empty($msg)) continue;
  3470. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3471. {
  3472. $out.="<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n" ;
  3473. }
  3474. else // Mode CLI
  3475. {
  3476. $out.='> '.$langs->transnoentities("Message").":\n".$msg."\n" ;
  3477. }
  3478. $syslog.=", msg=".$msg;
  3479. }
  3480. }
  3481. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  3482. {
  3483. xdebug_print_function_stack();
  3484. $out.='<b>XDebug informations:</b>'."<br>\n";
  3485. $out.='File: '.xdebug_call_file()."<br>\n";
  3486. $out.='Line: '.xdebug_call_line()."<br>\n";
  3487. $out.='Function: '.xdebug_call_function()."<br>\n";
  3488. $out.="<br>\n";
  3489. }
  3490. if (empty($dolibarr_main_prod)) print $out;
  3491. else
  3492. {
  3493. print $langs->trans("DolibarrHasDetectedError").'. ';
  3494. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  3495. define("MAIN_CORE_ERROR", 1);
  3496. }
  3497. //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.';
  3498. dol_syslog("Error ".$syslog, LOG_ERR);
  3499. }
  3500. /**
  3501. * Show a public email and error code to contact if technical error
  3502. *
  3503. * @param string $prefixcode Prefix of public error code
  3504. * @param string $errormessage Complete error message
  3505. * @param array $errormessages Array of error messages
  3506. * @param string $morecss More css
  3507. * @param string $email Email
  3508. * @return void
  3509. */
  3510. function dol_print_error_email($prefixcode, $errormessage='', $errormessages=array(), $morecss='error', $email='')
  3511. {
  3512. global $langs,$conf;
  3513. if (empty($email)) $email=$conf->global->MAIN_INFO_SOCIETE_MAIL;
  3514. $langs->load("errors");
  3515. $now=dol_now();
  3516. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  3517. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now,'%Y%m%d'));
  3518. if ($errormessage) print '<br><br>'.$errormessage;
  3519. if (is_array($errormessages) && count($errormessages))
  3520. {
  3521. foreach($errormessages as $mesgtoshow)
  3522. {
  3523. print '<br><br>'.$mesgtoshow;
  3524. }
  3525. }
  3526. print '</div></div>';
  3527. }
  3528. /**
  3529. * Show title line of an array
  3530. *
  3531. * @param string $name Label of field
  3532. * @param string $file Url used when we click on sort picto
  3533. * @param string $field Field to use for new sorting
  3534. * @param string $begin ("" by defaut)
  3535. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3536. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  3537. * @param string $sortfield Current field used to sort
  3538. * @param string $sortorder Current sort order
  3539. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  3540. * @param string $tooltip Tooltip
  3541. * @return void
  3542. */
  3543. function print_liste_field_titre($name, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="")
  3544. {
  3545. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip);
  3546. }
  3547. /**
  3548. * Get title line of an array
  3549. *
  3550. * @param string $name Translation key of field
  3551. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  3552. * @param string $file Url used when we click on sort picto
  3553. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  3554. * @param string $begin ("" by defaut)
  3555. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3556. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  3557. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  3558. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  3559. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  3560. * @param string $disablesortlink 1=Disable sort link
  3561. * @param string $tooltip Tooltip
  3562. * @return string
  3563. */
  3564. function getTitleFieldOfList($name, $thead=0, $file="", $field="", $begin="", $moreparam="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $disablesortlink=0, $tooltip='')
  3565. {
  3566. global $conf, $langs, $form;
  3567. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  3568. $sortorder=strtoupper($sortorder);
  3569. $out='';
  3570. $sortimg='';
  3571. $tag='th';
  3572. if ($thead==2) $tag='div';
  3573. $tmpsortfield=explode(',',$sortfield);
  3574. $sortfield1=trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  3575. $tmpfield=explode(',',$field);
  3576. $field1=trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  3577. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  3578. // If field is used as sort criteria we use a specific css class liste_titre_sel
  3579. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  3580. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./","",$field1))) $out.= '<'.$tag.' class="'.$prefix.'liste_titre_sel" '. $moreattrib.'>';
  3581. else $out.= '<'.$tag.' class="'.$prefix.'liste_titre" '. $moreattrib.'>';
  3582. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3583. {
  3584. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  3585. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  3586. $options=preg_replace('/&+/i','&',$options);
  3587. if (! preg_match('/^&/',$options)) $options='&'.$options;
  3588. $sortordertouseinlink='';
  3589. if ($field1 != $sortfield1) // We are on another field than current sorted field
  3590. {
  3591. if (preg_match('/^DESC/i', $sortorder))
  3592. {
  3593. $sortordertouseinlink.=str_repeat('desc,', count(explode(',',$field)));
  3594. }
  3595. else // We reverse the var $sortordertouseinlink
  3596. {
  3597. $sortordertouseinlink.=str_repeat('asc,', count(explode(',',$field)));
  3598. }
  3599. }
  3600. else // We are on field that is the first current sorting criteria
  3601. {
  3602. if (preg_match('/^ASC/i', $sortorder)) // We reverse the var $sortordertouseinlink
  3603. {
  3604. $sortordertouseinlink.=str_repeat('desc,', count(explode(',',$field)));
  3605. }
  3606. else
  3607. {
  3608. $sortordertouseinlink.=str_repeat('asc,', count(explode(',',$field)));
  3609. }
  3610. }
  3611. $sortordertouseinlink=preg_replace('/,$/', '', $sortordertouseinlink);
  3612. $out.= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'">';
  3613. }
  3614. if ($tooltip) $out.=$form->textwithpicto($langs->trans($name), $langs->trans($tooltip));
  3615. else $out.=$langs->trans($name);
  3616. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3617. {
  3618. $out.='</a>';
  3619. }
  3620. if (empty($thead) && $field) // If this is a sort field
  3621. {
  3622. $options=preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i','',$moreparam);
  3623. $options=preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i','',$options);
  3624. $options=preg_replace('/&+/i','&',$options);
  3625. if (! preg_match('/^&/',$options)) $options='&'.$options;
  3626. if (! $sortorder || $field1 != $sortfield1)
  3627. {
  3628. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3629. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3630. }
  3631. else
  3632. {
  3633. if (preg_match('/^DESC/', $sortorder)) {
  3634. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3635. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3636. $sortimg.= '<span class="nowrap">'.img_up("Z-A",0).'</span>';
  3637. }
  3638. if (preg_match('/^ASC/', $sortorder)) {
  3639. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3640. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3641. $sortimg.= '<span class="nowrap">'.img_down("A-Z",0).'</span>';
  3642. }
  3643. }
  3644. }
  3645. $out.=$sortimg;
  3646. $out.='</'.$tag.'>';
  3647. return $out;
  3648. }
  3649. /**
  3650. * Show a title.
  3651. *
  3652. * @param string $title Title to show
  3653. * @return string Title to show
  3654. * @deprecated Use load_fiche_titre instead
  3655. * @see load_fiche_titre
  3656. */
  3657. function print_titre($title)
  3658. {
  3659. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  3660. print '<div class="titre">'.$title.'</div>';
  3661. }
  3662. /**
  3663. * Show a title with picto
  3664. *
  3665. * @param string $title Title to show
  3666. * @param string $mesg Added message to show on right
  3667. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3668. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3669. * @param int $id To force an id on html objects
  3670. * @return void
  3671. * @deprecated Use print load_fiche_titre instead
  3672. */
  3673. function print_fiche_titre($title, $mesg='', $picto='title_generic.png', $pictoisfullpath=0, $id='')
  3674. {
  3675. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3676. }
  3677. /**
  3678. * Load a title with picto
  3679. *
  3680. * @param string $titre Title to show
  3681. * @param string $morehtmlright Added message to show on right
  3682. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3683. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3684. * @param string $id To force an id on html objects
  3685. * @param string $morecssontable More css on table
  3686. * @param string $morehtmlcenter Added message to show on center
  3687. * @return string
  3688. * @see print_barre_liste
  3689. */
  3690. function load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
  3691. {
  3692. global $conf;
  3693. $return='';
  3694. if ($picto == 'setup') $picto='title_generic.png';
  3695. $return.= "\n";
  3696. $return.= '<table '.($id?'id="'.$id.'" ':'').'summary="" class="centpercent notopnoleftnoright'.($morecssontable?' '.$morecssontable:'').'" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into print_barre_list
  3697. if ($picto) $return.= '<td class="nobordernopadding widthpictotitle opacityhigh" valign="middle">'.img_picto('',$picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  3698. $return.= '<td class="nobordernopadding valignmiddle">';
  3699. $return.= '<div class="titre inline-block">'.$titre.'</div>';
  3700. $return.= '</td>';
  3701. if (dol_strlen($morehtmlcenter))
  3702. {
  3703. $return.= '<td class="nobordernopadding" align="center" valign="middle">'.$morehtmlcenter.'</td>';
  3704. }
  3705. if (dol_strlen($morehtmlright))
  3706. {
  3707. $return.= '<td class="nobordernopadding titre_right wordbreak" align="right" valign="middle">'.$morehtmlright.'</td>';
  3708. }
  3709. $return.= '</tr></table>'."\n";
  3710. return $return;
  3711. }
  3712. /**
  3713. * Print a title with navigation controls for pagination
  3714. *
  3715. * @param string $titre Title to show (required)
  3716. * @param int $page Numero of page to show in navigation links (required)
  3717. * @param string $file Url of page (required)
  3718. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  3719. * @param string $sortfield Field to sort on ('' by default)
  3720. * @param string $sortorder Order to sort ('' by default)
  3721. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  3722. * @param int $num Number of records found by select with limit+1
  3723. * @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.
  3724. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3725. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3726. * @param string $morehtmlright More html to show
  3727. * @param string $morecss More css to the table
  3728. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  3729. * @param int $hideselectlimit Force to hide select limit
  3730. * @param int $hidenavigation Force to hide all navigation tools
  3731. * @return void
  3732. */
  3733. function print_barre_liste($titre, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='title_generic.png', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $hideselectlimit=0, $hidenavigation=0)
  3734. {
  3735. global $conf,$langs;
  3736. $savlimit = $limit;
  3737. $savtotalnboflines = $totalnboflines;
  3738. $totalnboflines=abs($totalnboflines);
  3739. if ($picto == 'setup') $picto='title_setup.png';
  3740. if (($conf->browser->name == 'ie') && $picto=='title_generic.png') $picto='title.gif';
  3741. if ($limit < 0) $limit = $conf->liste_limit;
  3742. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  3743. {
  3744. $nextpage = 1;
  3745. }
  3746. else
  3747. {
  3748. $nextpage = 0;
  3749. }
  3750. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  3751. print "\n";
  3752. print "<!-- Begin title '".$titre."' -->\n";
  3753. print '<table border="0" class="centpercent notopnoleftnoright'.($morecss?' '.$morecss:'').'" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into load_fiche_tire
  3754. // Left
  3755. //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
  3756. print '<td class="nobordernopadding valignmiddle">';
  3757. if ($picto && $titre) print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
  3758. print '<div class="titre inline-block">'.$titre;
  3759. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print ' ('.$totalnboflines.')';
  3760. print '</div></td>';
  3761. // Center
  3762. if ($morehtmlcenter)
  3763. {
  3764. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3765. }
  3766. // Right
  3767. print '<td class="nobordernopadding valignmiddle" align="right">';
  3768. if ($sortfield) $options .= "&sortfield=".urlencode($sortfield);
  3769. if ($sortorder) $options .= "&sortorder=".urlencode($sortorder);
  3770. // Show navigation bar
  3771. $pagelist = '';
  3772. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  3773. {
  3774. if ($totalnboflines) // If we know total nb of lines
  3775. {
  3776. // Define nb of extra page links before and after selected page + ... + first or last
  3777. $maxnbofpage=(empty($conf->dol_optimize_smallscreen) ? 4 : 1);
  3778. if ($limit > 0) $nbpages=ceil($totalnboflines/$limit);
  3779. else $nbpages=1;
  3780. $cpt=($page-$maxnbofpage);
  3781. if ($cpt < 0) { $cpt=0; }
  3782. if ($cpt>=1)
  3783. {
  3784. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  3785. if ($cpt > 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3786. else if ($cpt == 2) $pagelist.='<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  3787. }
  3788. do
  3789. {
  3790. if ($cpt==$page)
  3791. {
  3792. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1).'</span></li>';
  3793. }
  3794. else
  3795. {
  3796. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt+1).'</a></li>';
  3797. }
  3798. $cpt++;
  3799. }
  3800. while ($cpt < $nbpages && $cpt<=$page+$maxnbofpage);
  3801. if ($cpt<$nbpages)
  3802. {
  3803. if ($cpt<$nbpages-2) $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="inactive"':'').'>...</span></li>';
  3804. 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>';
  3805. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><a href="'.$file.'?page='.($nbpages-1).$options.'">'.$nbpages.'</a></li>';
  3806. }
  3807. }
  3808. else
  3809. {
  3810. $pagelist.= '<li'.(($conf->dol_use_jmobile != 4)?' class="pagination"':'').'><span '.(($conf->dol_use_jmobile != 4)?'class="active"':'').'>'.($page+1)."</li>";
  3811. }
  3812. }
  3813. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist
  3814. print '</td>';
  3815. print '</tr></table>'."\n";
  3816. print "<!-- End title -->\n\n";
  3817. }
  3818. /**
  3819. * Function to show navigation arrows into lists
  3820. *
  3821. * @param int $page Number of page
  3822. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  3823. * @param string $options Other url paramaters to propagate ("" by default, may include sortfield and sortorder)
  3824. * @param integer $nextpage Do we show a next page button
  3825. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  3826. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  3827. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  3828. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  3829. * @param int $hideselectlimit Force to hide select limit
  3830. * @return void
  3831. */
  3832. function print_fleche_navigation($page, $file, $options='', $nextpage=0, $betweenarrows='', $afterarrows='', $limit=-1, $totalnboflines=0, $hideselectlimit=0)
  3833. {
  3834. global $conf, $langs;
  3835. print '<div class="pagination"><ul>';
  3836. if ((int) $limit >= 0 && empty($hideselectlimit))
  3837. {
  3838. $pagesizechoices='10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  3839. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  3840. //$pagesizechoices.=',2:2';
  3841. if (! empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices=$conf->global->MAIN_PAGESIZE_CHOICES;
  3842. print '<li class="pagination">';
  3843. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  3844. $tmpchoice=explode(',',$pagesizechoices);
  3845. $tmpkey=$limit.':'.$limit;
  3846. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3847. $tmpkey=$conf->liste_limit.':'.$conf->liste_limit;
  3848. if (! in_array($tmpkey, $tmpchoice)) $tmpchoice[]=$tmpkey;
  3849. asort($tmpchoice, SORT_NUMERIC);
  3850. $found=false;
  3851. foreach($tmpchoice as $val)
  3852. {
  3853. $selected='';
  3854. $tmp=explode(':',$val);
  3855. $key=$tmp[0];
  3856. $val=$tmp[1];
  3857. if ($key != '' && $val != '')
  3858. {
  3859. if ((int) $key == (int) $limit)
  3860. {
  3861. $selected = ' selected="selected"';
  3862. $found = true;
  3863. }
  3864. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  3865. }
  3866. }
  3867. print '</select>';
  3868. if ($conf->use_javascript_ajax)
  3869. {
  3870. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  3871. <script type="text/javascript">
  3872. jQuery(document).ready(function () {
  3873. jQuery(".selectlimit").change(function() {
  3874. console.log("Change limit. Send submit");
  3875. $(this).parents(\'form:first\').submit();
  3876. });
  3877. });
  3878. </script>
  3879. ';
  3880. }
  3881. print '</li>';
  3882. }
  3883. if ($page > 0)
  3884. {
  3885. 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>';
  3886. }
  3887. if ($betweenarrows)
  3888. {
  3889. print $betweenarrows;
  3890. }
  3891. if ($nextpage > 0)
  3892. {
  3893. 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>';
  3894. }
  3895. if ($afterarrows)
  3896. {
  3897. print '<li class="paginationafterarrows">';
  3898. print $afterarrows;
  3899. print '</li>';
  3900. }
  3901. print '</ul></div>'."\n";
  3902. }
  3903. /**
  3904. * Return a string with VAT rate label formated for view output
  3905. * Used into pdf and HTML pages
  3906. *
  3907. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  3908. * @param boolean $addpercent Add a percent % sign in output
  3909. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  3910. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  3911. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  3912. */
  3913. function vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0)
  3914. {
  3915. $morelabel='';
  3916. if (preg_match('/%/',$rate))
  3917. {
  3918. $rate=str_replace('%','',$rate);
  3919. $addpercent=true;
  3920. }
  3921. if (preg_match('/\((.*)\)/',$rate,$reg))
  3922. {
  3923. $morelabel=' ('.$reg[1].')';
  3924. $rate=preg_replace('/\s*'.preg_quote($morelabel,'/').'/','',$rate);
  3925. }
  3926. if (preg_match('/\*/',$rate))
  3927. {
  3928. $rate=str_replace('*','',$rate);
  3929. $info_bits |= 1;
  3930. }
  3931. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  3932. if (! preg_match('/\//', $rate)) $ret=price($rate,0,'',0,0).($addpercent?'%':'');
  3933. else
  3934. {
  3935. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  3936. $ret=$rate.($addpercent?'%':'');
  3937. }
  3938. if (($info_bits & 1) && $usestarfornpr >= 0) $ret.=' *';
  3939. $ret.=$morelabel;
  3940. return $ret;
  3941. }
  3942. /**
  3943. * Function to format a value into an amount for visual output
  3944. * Function used into PDF and HTML pages
  3945. *
  3946. * @param float $amount Amount to format
  3947. * @param integer $form Type of format, HTML or not (not by default)
  3948. * @param Translate $outlangs Object langs for output
  3949. * @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 beeing inserted into database or after a computation, so this parameter should be useless.
  3950. * @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_TOT)
  3951. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  3952. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  3953. * @return string Chaine avec montant formate
  3954. *
  3955. * @see price2num() Revert function of price
  3956. */
  3957. function price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
  3958. {
  3959. global $langs,$conf;
  3960. // Clean parameters
  3961. if (empty($amount)) $amount=0; // To have a numeric value if amount not defined or = ''
  3962. $amount = (is_numeric($amount)?$amount:0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  3963. if ($rounding < 0) $rounding=min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
  3964. $nbdecimal=$rounding;
  3965. // Output separators by default (french)
  3966. $dec=','; $thousand=' ';
  3967. // If $outlangs not forced, we use use language
  3968. if (! is_object($outlangs)) $outlangs=$langs;
  3969. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$outlangs->transnoentitiesnoconv("SeparatorDecimal");
  3970. if ($outlangs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$outlangs->transnoentitiesnoconv("SeparatorThousand");
  3971. if ($thousand == 'None') $thousand='';
  3972. else if ($thousand == 'Space') $thousand=' ';
  3973. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  3974. //print "amount=".$amount."-";
  3975. $amount = str_replace(',','.',$amount); // should be useless
  3976. //print $amount."-";
  3977. $datas = explode('.',$amount);
  3978. $decpart = isset($datas[1])?$datas[1]:'';
  3979. $decpart = preg_replace('/0+$/i','',$decpart); // Supprime les 0 de fin de partie decimale
  3980. //print "decpart=".$decpart."<br>";
  3981. $end='';
  3982. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  3983. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal=dol_strlen($decpart);
  3984. // Si on depasse max
  3985. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  3986. {
  3987. $nbdecimal=$conf->global->MAIN_MAX_DECIMALS_SHOWN;
  3988. if (preg_match('/\.\.\./i',$conf->global->MAIN_MAX_DECIMALS_SHOWN))
  3989. {
  3990. // Si un affichage est tronque, on montre des ...
  3991. $end='...';
  3992. }
  3993. }
  3994. // If force rounding
  3995. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  3996. // Format number
  3997. $output=number_format($amount, $nbdecimal, $dec, $thousand);
  3998. if ($form)
  3999. {
  4000. $output=preg_replace('/\s/','&nbsp;',$output);
  4001. $output=preg_replace('/\'/','&#039;',$output);
  4002. }
  4003. // Add symbol of currency if requested
  4004. $cursymbolbefore=$cursymbolafter='';
  4005. if ($currency_code)
  4006. {
  4007. if ($currency_code == 'auto') $currency_code=$conf->currency;
  4008. $listofcurrenciesbefore=array('USD','GBP','AUD','MXN','PEN','CNY');
  4009. $listoflanguagesbefore=array('nl_NL');
  4010. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore))
  4011. {
  4012. $cursymbolbefore.=$outlangs->getCurrencySymbol($currency_code);
  4013. }
  4014. else
  4015. {
  4016. $tmpcur=$outlangs->getCurrencySymbol($currency_code);
  4017. $cursymbolafter.=($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4018. }
  4019. }
  4020. $output=$cursymbolbefore.$output.$end.($cursymbolafter?' ':'').$cursymbolafter;
  4021. return $output;
  4022. }
  4023. /**
  4024. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4025. * Function to use on each input amount before any numeric test or database insert
  4026. *
  4027. * @param float $amount Amount to convert/clean
  4028. * @param string $rounding ''=No rounding
  4029. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4030. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4031. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4032. * Numeric = Nb of digits for rounding
  4033. * @param int $alreadysqlnb Put 1 if you know that content is already universal format number
  4034. * @return string Amount with universal numeric format (Example: '99.99999') or unchanged text if conversion fails. If amount is null or '', it returns ''.
  4035. *
  4036. * @see price Opposite function of price2num
  4037. */
  4038. function price2num($amount,$rounding='',$alreadysqlnb=0)
  4039. {
  4040. global $langs,$conf;
  4041. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4042. // Numbers must be '1234.56'
  4043. // Decimal delimiter for PHP and database SQL requests must be '.'
  4044. $dec=','; $thousand=' ';
  4045. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec=$langs->transnoentitiesnoconv("SeparatorDecimal");
  4046. if ($langs->transnoentitiesnoconv("SeparatorThousand")!= "SeparatorThousand") $thousand=$langs->transnoentitiesnoconv("SeparatorThousand");
  4047. if ($thousand == 'None') $thousand='';
  4048. elseif ($thousand == 'Space') $thousand=' ';
  4049. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4050. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4051. if ($alreadysqlnb != 1) // If not a PHP number or unknown, we change format
  4052. {
  4053. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4054. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4055. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4056. if (is_numeric($amount))
  4057. {
  4058. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4059. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4060. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  4061. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  4062. $amount=number_format($amount,$nbofdec,$dec,$thousand);
  4063. }
  4064. //print "QQ".$amount.'<br>';
  4065. // Now make replace (the main goal of function)
  4066. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  4067. $amount=str_replace(' ','',$amount); // To avoid spaces
  4068. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4069. $amount=str_replace($dec,'.',$amount);
  4070. }
  4071. // Now, make a rounding if required
  4072. if ($rounding)
  4073. {
  4074. $nbofdectoround='';
  4075. if ($rounding == 'MU') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_UNIT;
  4076. elseif ($rounding == 'MT') $nbofdectoround=$conf->global->MAIN_MAX_DECIMALS_TOT;
  4077. elseif ($rounding == 'MS') $nbofdectoround=empty($conf->global->MAIN_MAX_DECIMALS_STOCK)?5:$conf->global->MAIN_MAX_DECIMALS_STOCK;
  4078. elseif (is_numeric($rounding)) $nbofdectoround=$rounding;
  4079. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  4080. if (dol_strlen($nbofdectoround)) $amount = round($amount,$nbofdectoround); // $nbofdectoround can be 0.
  4081. else return 'ErrorBadParameterProvidedToFunction';
  4082. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4083. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4084. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4085. if (is_numeric($amount))
  4086. {
  4087. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4088. $temps=sprintf("%0.10F",$amount-intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4089. $temps=preg_replace('/([\.1-9])0+$/','\\1',$temps); // temps=0. or 0.00002 or 9999.1
  4090. $nbofdec=max(0,dol_strlen($temps)-2); // -2 to remove "0."
  4091. $amount=number_format($amount,min($nbofdec,$nbofdectoround),$dec,$thousand); // Convert amount to format with dolibarr dec and thousand
  4092. }
  4093. //print "TT".$amount.'<br>';
  4094. // Always make replace because each math function (like round) replace
  4095. // with local values and we want a number that has a SQL string format x.y
  4096. if ($thousand != ',' && $thousand != '.') $amount=str_replace(',','.',$amount); // To accept 2 notations for french users
  4097. $amount=str_replace(' ','',$amount); // To avoid spaces
  4098. $amount=str_replace($thousand,'',$amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4099. $amount=str_replace($dec,'.',$amount);
  4100. }
  4101. return $amount;
  4102. }
  4103. /**
  4104. * Output a dimension with best unit
  4105. *
  4106. * @param float $dimension Dimension
  4107. * @param int $unit Unit of dimension (Example: 0=kg, -3=g, 98=ounce, 99=pound, ...)
  4108. * @param string $type 'weight', 'volume', ...
  4109. * @param Translate $outputlangs Translate language object
  4110. * @param int $round -1 = non rounding, x = number of decimal
  4111. * @param string $forceunitoutput 'no' or numeric (-3, -6, ...) compared to $unit (In most case, this value is value defined into $conf->global->MAIN_WEIGHT_DEFAULT_UNIT)
  4112. * @return string String to show dimensions
  4113. */
  4114. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round=-1, $forceunitoutput='no')
  4115. {
  4116. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4117. if (($forceunitoutput == 'no' && $dimension < 1/10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  4118. {
  4119. $dimension = $dimension * 1000000;
  4120. $unit = $unit - 6;
  4121. }
  4122. elseif (($forceunitoutput == 'no' && $dimension < 1/10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  4123. {
  4124. $dimension = $dimension * 1000;
  4125. $unit = $unit - 3;
  4126. }
  4127. elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  4128. {
  4129. $dimension = $dimension / 1000000;
  4130. $unit = $unit + 6;
  4131. }
  4132. elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  4133. {
  4134. $dimension = $dimension / 1000;
  4135. $unit = $unit + 3;
  4136. }
  4137. // Special case when we want output unit into pound or ounce
  4138. /* TODO
  4139. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4140. {
  4141. $dimension = // convert dimension from standard unit into ounce or pound
  4142. $unit = $forceunitoutput;
  4143. }
  4144. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4145. {
  4146. $dimension = // convert dimension from standard unit into ounce or pound
  4147. $unit = $forceunitoutput;
  4148. }*/
  4149. $ret=price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type);
  4150. return $ret;
  4151. }
  4152. /**
  4153. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4154. * Note: This function applies same rules than get_default_tva
  4155. *
  4156. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4157. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4158. * @param Societe $thirdparty_buyer Object of buying third party
  4159. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4160. * @param int $vatnpr If vat rate is NPR or not
  4161. * @return mixed 0 if not found, localtax rate if found
  4162. * @see get_default_tva
  4163. */
  4164. function get_localtax($vatrate, $local, $thirdparty_buyer="", $thirdparty_seller="", $vatnpr=0)
  4165. {
  4166. global $db, $conf, $mysoc;
  4167. if (empty($thirdparty_seller) || ! is_object($thirdparty_seller)) $thirdparty_seller=$mysoc;
  4168. 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);
  4169. $vatratecleaned = $vatrate;
  4170. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4171. {
  4172. $vatratecleaned = trim($reg[1]);
  4173. $vatratecode = $reg[2];
  4174. }
  4175. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4176. {
  4177. return 0;
  4178. }*/
  4179. // Some test to guess with no need to make database access
  4180. if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4181. {
  4182. if ($local == 1)
  4183. {
  4184. if (! $mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  4185. if ($thirdparty_seller->id == $mysoc->id)
  4186. {
  4187. if (! $thirdparty_buyer->localtax1_assuj) return 0;
  4188. }
  4189. else
  4190. {
  4191. if (! $thirdparty_seller->localtax1_assuj) return 0;
  4192. }
  4193. }
  4194. if ($local == 2)
  4195. {
  4196. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4197. if (! $mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0.
  4198. if ($thirdparty_seller->id == $mysoc->id)
  4199. {
  4200. if (! $thirdparty_buyer->localtax2_assuj) return 0;
  4201. }
  4202. else
  4203. {
  4204. if (! $thirdparty_seller->localtax2_assuj) return 0;
  4205. }
  4206. }
  4207. }
  4208. else
  4209. {
  4210. if ($local == 1 && ! $thirdparty_seller->localtax1_assuj) return 0;
  4211. if ($local == 2 && ! $thirdparty_seller->localtax2_assuj) return 0;
  4212. }
  4213. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4214. if (in_array($mysoc->country_code, array('ES')))
  4215. {
  4216. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4217. }
  4218. // Search local taxes
  4219. if (! empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  4220. {
  4221. if ($local==1)
  4222. {
  4223. if ($thirdparty_seller != $mysoc)
  4224. {
  4225. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4226. {
  4227. return $thirdparty_seller->localtax1_value;
  4228. }
  4229. }
  4230. else // i am the seller
  4231. {
  4232. if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4233. {
  4234. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4235. }
  4236. }
  4237. }
  4238. if ($local==2)
  4239. {
  4240. if ($thirdparty_seller != $mysoc)
  4241. {
  4242. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4243. // TODO We should also return value defined on thirdparty only if defined
  4244. {
  4245. return $thirdparty_seller->localtax2_value;
  4246. }
  4247. }
  4248. else // i am the seller
  4249. {
  4250. if (in_array($mysoc->country_code, array('ES')))
  4251. {
  4252. return $thirdparty_buyer->localtax2_value;
  4253. }
  4254. else
  4255. {
  4256. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4257. }
  4258. }
  4259. }
  4260. }
  4261. // By default, search value of local tax on line of common tax
  4262. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4263. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4264. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$thirdparty_seller->country_code."'";
  4265. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4266. if ($vatratecode) $sql.= " AND t.code ='".$vatratecode."'"; // If we have the code, we use it in priority
  4267. else $sql.= " AND t.recuperableonly ='".$vatnpr."'";
  4268. dol_syslog("get_localtax", LOG_DEBUG);
  4269. $resql=$db->query($sql);
  4270. if ($resql)
  4271. {
  4272. $obj = $db->fetch_object($resql);
  4273. if ($local==1) return $obj->localtax1;
  4274. elseif ($local==2) return $obj->localtax2;
  4275. }
  4276. return 0;
  4277. }
  4278. /**
  4279. * Return true if LocalTax (1 or 2) is unique.
  4280. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  4281. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  4282. *
  4283. * @param int $local Local tax to test (1 or 2)
  4284. * @return boolean True if LocalTax have multiple values, False if not
  4285. */
  4286. function isOnlyOneLocalTax($local)
  4287. {
  4288. $tax=get_localtax_by_third($local);
  4289. $valors=explode(":", $tax);
  4290. if (count($valors)>1)
  4291. {
  4292. return false;
  4293. }
  4294. else
  4295. {
  4296. return true;
  4297. }
  4298. }
  4299. /**
  4300. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  4301. *
  4302. * @param int $local LocalTax to get
  4303. * @return number Values of localtax
  4304. */
  4305. function get_localtax_by_third($local)
  4306. {
  4307. global $db, $mysoc;
  4308. $sql ="SELECT t.localtax1, t.localtax2 ";
  4309. $sql.=" FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  4310. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND t.active = 1 AND t.taux=(";
  4311. $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";
  4312. $sql.=" WHERE c.code = '".$mysoc->country_code."' AND tt.active = 1";
  4313. $sql.=" )";
  4314. $resql=$db->query($sql);
  4315. if ($resql)
  4316. {
  4317. $obj = $db->fetch_object($resql);
  4318. if ($local==1) return $obj->localtax1;
  4319. elseif ($local==2) return $obj->localtax2;
  4320. }
  4321. return 0;
  4322. }
  4323. /**
  4324. * Get vat main information from Id.
  4325. * You can call getLocalTaxesFromRate after to get other fields.
  4326. *
  4327. * @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.
  4328. * @param Societe $buyer Company object
  4329. * @param Societe $seller Company object
  4330. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  4331. * @return array array('rowid'=> , 'code'=> ...)
  4332. * @see getLocalTaxesFromRate
  4333. */
  4334. function getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
  4335. {
  4336. global $db, $mysoc;
  4337. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  4338. // Search local taxes
  4339. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
  4340. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4341. if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate;
  4342. else
  4343. {
  4344. $vatratecleaned = $vatrate;
  4345. $vatratecode = '';
  4346. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4347. {
  4348. $vatratecleaned = $reg[1];
  4349. $vatratecode = $reg[2];
  4350. }
  4351. $sql.=", ".MAIN_DB_PREFIX."c_country as c";
  4352. /*if ($mysoc->country_code == 'ES') $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // vat in spain use the buyer country ??
  4353. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";*/
  4354. $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
  4355. $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4356. if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'";
  4357. }
  4358. $resql=$db->query($sql);
  4359. if ($resql)
  4360. {
  4361. $obj = $db->fetch_object($resql);
  4362. 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);
  4363. else return array();
  4364. }
  4365. else dol_print_error($db);
  4366. return array();
  4367. }
  4368. /**
  4369. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  4370. * This does not take into account the seller setup if subject to vat or not, only country.
  4371. * TODO
  4372. * This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  4373. * Instead this function must be called when adding a line to get the array of localtax and type, and then
  4374. * provide it to the function calcul_price_total.
  4375. *
  4376. * @param int|string $vatrate VAT ID or Rate+Code. 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.
  4377. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  4378. * @param Societe $buyer Company object
  4379. * @param Societe $seller Company object
  4380. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  4381. * @return array array(localtax_type1(1-6/0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  4382. * @see getTaxesFromId
  4383. */
  4384. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
  4385. {
  4386. global $db, $mysoc;
  4387. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  4388. // Search local taxes
  4389. $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
  4390. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4391. if ($firstparamisid) $sql.= " WHERE t.rowid = ".(int) $vatrate;
  4392. else
  4393. {
  4394. $vatratecleaned = $vatrate;
  4395. $vatratecode = '';
  4396. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "x.x (yy)"
  4397. {
  4398. $vatratecleaned = $reg[1];
  4399. $vatratecode = $reg[2];
  4400. }
  4401. $sql.=", ".MAIN_DB_PREFIX."c_country as c";
  4402. 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 ??
  4403. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
  4404. $sql.= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4405. if ($vatratecode) $sql.= " AND t.code = '".$vatratecode."'";
  4406. }
  4407. $resql=$db->query($sql);
  4408. if ($resql)
  4409. {
  4410. $obj = $db->fetch_object($resql);
  4411. if ($local == 1)
  4412. {
  4413. return array($obj->localtax1_type, get_localtax($vatrate, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4414. }
  4415. elseif ($local == 2)
  4416. {
  4417. return array($obj->localtax2_type, get_localtax($vatrate, $local, $buyer, $seller),$obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4418. }
  4419. else
  4420. {
  4421. 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);
  4422. }
  4423. }
  4424. return 0;
  4425. }
  4426. /**
  4427. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  4428. * Function called by get_default_tva
  4429. *
  4430. * @param int $idprod Id of product or 0 if not a predefined product
  4431. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4432. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  4433. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  4434. * @see get_product_localtax_for_country
  4435. */
  4436. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice=0)
  4437. {
  4438. global $db,$conf,$mysoc;
  4439. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4440. $ret=0;
  4441. $found=0;
  4442. if ($idprod > 0)
  4443. {
  4444. // Load product
  4445. $product=new Product($db);
  4446. $result=$product->fetch($idprod);
  4447. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4448. {
  4449. if ($idprodfournprice > 0) // We want vat for product for a "supplier" object
  4450. {
  4451. $product->get_buyprice($idprodfournprice,0,0,0);
  4452. $ret=$product->vatrate_supplier;
  4453. if ($product->default_vat_code) $ret.=' ('.$product->default_vat_code.')';
  4454. }
  4455. else
  4456. {
  4457. $ret=$product->tva_tx; // Default vat of product we defined
  4458. if ($product->default_vat_code) $ret.=' ('.$product->default_vat_code.')';
  4459. }
  4460. $found=1;
  4461. }
  4462. else
  4463. {
  4464. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  4465. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  4466. }
  4467. }
  4468. if (! $found)
  4469. {
  4470. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  4471. {
  4472. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  4473. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  4474. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4475. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  4476. $sql.= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  4477. $sql.= $db->plimit(1);
  4478. $resql=$db->query($sql);
  4479. if ($resql)
  4480. {
  4481. $obj=$db->fetch_object($resql);
  4482. if ($obj)
  4483. {
  4484. $ret=$obj->vat_rate;
  4485. if ($obj->default_vat_code) $ret.=' ('.$obj->default_vat_code.')';
  4486. }
  4487. $db->free($sql);
  4488. }
  4489. else dol_print_error($db);
  4490. }
  4491. else $ret=$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  4492. }
  4493. dol_syslog("get_product_vat_for_country: ret=".$ret);
  4494. return $ret;
  4495. }
  4496. /**
  4497. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  4498. *
  4499. * @param int $idprod Id of product
  4500. * @param int $local 1 for localtax1, 2 for localtax 2
  4501. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4502. * @return int <0 if KO, Vat rate if OK
  4503. * @see get_product_vat_for_country
  4504. */
  4505. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  4506. {
  4507. global $db,$mysoc;
  4508. if (! class_exists('Product')) {
  4509. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4510. }
  4511. $ret=0;
  4512. $found=0;
  4513. if ($idprod > 0)
  4514. {
  4515. // Load product
  4516. $product=new Product($db);
  4517. $result=$product->fetch($idprod);
  4518. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4519. {
  4520. /* Not defined yet, so we don't use this
  4521. if ($local==1) $ret=$product->localtax1_tx;
  4522. elseif ($local==2) $ret=$product->localtax2_tx;
  4523. $found=1;
  4524. */
  4525. }
  4526. else
  4527. {
  4528. // TODO Read default product vat according to countrycode and product
  4529. }
  4530. }
  4531. if (! $found)
  4532. {
  4533. // If vat of product for the country not found or not defined, we return higher vat of country.
  4534. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  4535. $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4536. $sql.= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
  4537. $sql.= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  4538. $sql.= $db->plimit(1);
  4539. $resql=$db->query($sql);
  4540. if ($resql)
  4541. {
  4542. $obj=$db->fetch_object($resql);
  4543. if ($obj)
  4544. {
  4545. if ($local==1) $ret=$obj->localtax1;
  4546. elseif ($local==2) $ret=$obj->localtax2;
  4547. }
  4548. }
  4549. else dol_print_error($db);
  4550. }
  4551. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  4552. return $ret;
  4553. }
  4554. /**
  4555. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  4556. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4557. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4558. * 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.
  4559. * 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
  4560. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  4561. * Sinon TVA proposee par defaut=0. Fin de regle.
  4562. *
  4563. * @param Societe $thirdparty_seller Objet societe vendeuse
  4564. * @param Societe $thirdparty_buyer Objet societe acheteuse
  4565. * @param int $idprod Id product
  4566. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  4567. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  4568. * @see get_default_npr, get_default_localtax
  4569. */
  4570. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  4571. {
  4572. global $conf;
  4573. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4574. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  4575. $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;
  4576. $seller_country_code = $thirdparty_seller->country_code;
  4577. $seller_in_cee = isInEEC($thirdparty_seller);
  4578. $buyer_country_code = $thirdparty_buyer->country_code;
  4579. $buyer_in_cee = isInEEC($thirdparty_buyer);
  4580. dol_syslog("get_default_tva: seller use vat=".$seller_use_vat.", seller country=".$seller_country_code.", seller in cee=".$seller_in_cee.", buyer vat number=".$thirdparty_buyer->tva_intra." 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:''));
  4581. // 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)
  4582. // we use the buyer VAT.
  4583. if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  4584. {
  4585. if ($seller_in_cee && $buyer_in_cee && ! $thirdparty_buyer->isACompany())
  4586. {
  4587. //print 'VATRULE 0';
  4588. return get_product_vat_for_country($idprod,$thirdparty_buyer,$idprodfournprice);
  4589. }
  4590. }
  4591. // If seller does not use VAT
  4592. if (! $seller_use_vat)
  4593. {
  4594. //print 'VATRULE 1';
  4595. return 0;
  4596. }
  4597. // 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.
  4598. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4599. if (($seller_country_code == $buyer_country_code)
  4600. || (in_array($seller_country_code,array('FR,MC')) && in_array($buyer_country_code,array('FR','MC')))) // Warning ->country_code not always defined
  4601. {
  4602. //print 'VATRULE 2';
  4603. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4604. }
  4605. // 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.
  4606. // Not supported
  4607. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  4608. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4609. if (($seller_in_cee && $buyer_in_cee))
  4610. {
  4611. $isacompany=$thirdparty_buyer->isACompany();
  4612. if ($isacompany)
  4613. {
  4614. //print 'VATRULE 3';
  4615. return 0;
  4616. }
  4617. else
  4618. {
  4619. //print 'VATRULE 4';
  4620. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4621. }
  4622. }
  4623. // Si (vendeur en France et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4624. if (! empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee) && !$thirdparty_buyer->isACompany()) {
  4625. return get_product_vat_for_country($idprod,$thirdparty_seller,$idprodfournprice);
  4626. }
  4627. // Sinon la TVA proposee par defaut=0. Fin de regle.
  4628. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  4629. //print 'VATRULE 5';
  4630. return 0;
  4631. }
  4632. /**
  4633. * Fonction qui renvoie si tva doit etre tva percue recuperable
  4634. *
  4635. * @param Societe $thirdparty_seller Thirdparty seller
  4636. * @param Societe $thirdparty_buyer Thirdparty buyer
  4637. * @param int $idprod Id product
  4638. * @param int $idprodfournprice Id supplier price for product
  4639. * @return float 0 or 1
  4640. * @see get_default_tva, get_default_localtax
  4641. */
  4642. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
  4643. {
  4644. global $db;
  4645. if ($idprodfournprice > 0)
  4646. {
  4647. if (! class_exists('ProductFournisseur'))
  4648. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
  4649. $prodprice = new ProductFournisseur($db);
  4650. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  4651. return $prodprice->fourn_tva_npr;
  4652. }
  4653. elseif ($idprod > 0)
  4654. {
  4655. if (! class_exists('Product'))
  4656. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  4657. $prod = new Product($db);
  4658. $prod->fetch($idprod);
  4659. return $prod->tva_npr;
  4660. }
  4661. return 0;
  4662. }
  4663. /**
  4664. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4665. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4666. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4667. * Sinon TVA proposee par defaut=0. Fin de regle.
  4668. *
  4669. * @param Societe $thirdparty_seller Thirdparty seller
  4670. * @param Societe $thirdparty_buyer Thirdparty buyer
  4671. * @param int $local Localtax to process (1 or 2)
  4672. * @param int $idprod Id product
  4673. * @return integer localtax, -1 si ne peut etre determine
  4674. * @see get_default_tva, get_default_npr
  4675. */
  4676. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod=0)
  4677. {
  4678. global $mysoc;
  4679. if (!is_object($thirdparty_seller)) return -1;
  4680. if (!is_object($thirdparty_buyer)) return -1;
  4681. if ($local==1) // Localtax 1
  4682. {
  4683. if ($mysoc->country_code == 'ES')
  4684. {
  4685. if (is_numeric($thirdparty_buyer->localtax1_assuj) && ! $thirdparty_buyer->localtax1_assuj) return 0;
  4686. }
  4687. else
  4688. {
  4689. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  4690. if (is_numeric($thirdparty_seller->localtax1_assuj) && ! $thirdparty_seller->localtax1_assuj) return 0;
  4691. if (! is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj=='localtax1off') return 0;
  4692. }
  4693. }
  4694. elseif ($local==2) //I Localtax 2
  4695. {
  4696. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  4697. if (is_numeric($thirdparty_seller->localtax2_assuj) && ! $thirdparty_seller->localtax2_assuj) return 0;
  4698. if (! is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj=='localtax2off') return 0;
  4699. }
  4700. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  4701. {
  4702. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  4703. }
  4704. return 0;
  4705. }
  4706. /**
  4707. * Return yes or no in current language
  4708. *
  4709. * @param string $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  4710. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  4711. * @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.
  4712. * @return string HTML string
  4713. */
  4714. function yn($yesno, $case=1, $color=0)
  4715. {
  4716. global $langs;
  4717. $result='unknown'; $classname='';
  4718. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  4719. {
  4720. $result=$langs->trans('yes');
  4721. if ($case == 1 || $case == 3) $result=$langs->trans("Yes");
  4722. if ($case == 2) $result='<input type="checkbox" value="1" checked disabled>';
  4723. if ($case == 3) $result='<input type="checkbox" value="1" checked disabled> '.$result;
  4724. $classname='ok';
  4725. }
  4726. elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  4727. {
  4728. $result=$langs->trans("no");
  4729. if ($case == 1 || $case == 3) $result=$langs->trans("No");
  4730. if ($case == 2) $result='<input type="checkbox" value="0" disabled>';
  4731. if ($case == 3) $result='<input type="checkbox" value="0" disabled> '.$result;
  4732. if ($color == 2) $classname='ok';
  4733. else $classname='error';
  4734. }
  4735. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  4736. return $result;
  4737. }
  4738. /**
  4739. * Return a path to have a the directory according to object where files are stored.
  4740. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart)
  4741. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, $modulepart) if multidir_output not defined.
  4742. * Example our with new usage: $object is invoice -> 'INYYMM-ABCD'
  4743. * Example our with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  4744. *
  4745. * @param string $num Id of object (deprecated, $object will be used in future)
  4746. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  4747. * @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)
  4748. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  4749. * @param Object $object Object
  4750. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...')
  4751. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  4752. */
  4753. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
  4754. {
  4755. global $conf;
  4756. $path = '';
  4757. $arrayforoldpath=array('cheque','user','category','holiday','supplier_invoice','invoice_supplier','mailing','supplier_payment');
  4758. if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[]='product';
  4759. if (! empty($level) && in_array($modulepart, $arrayforoldpath))
  4760. {
  4761. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  4762. if (empty($alpha)) $num = preg_replace('/([^0-9])/i','',$num);
  4763. else $num = preg_replace('/^.*\-/i','',$num);
  4764. $num = substr("000".$num, -$level);
  4765. if ($level == 1) $path = substr($num,0,1);
  4766. if ($level == 2) $path = substr($num,1,1).'/'.substr($num,0,1);
  4767. if ($level == 3) $path = substr($num,2,1).'/'.substr($num,1,1).'/'.substr($num,0,1);
  4768. }
  4769. else
  4770. {
  4771. // TODO
  4772. // We will enhance here a common way of forging path for document storage
  4773. // Here, object->id, object->ref and modulepart are required.
  4774. //var_dump($modulepart);
  4775. if (in_array($modulepart, array('thirdparty','contact','member','propal','proposal','commande','order','facture','invoice',
  4776. 'supplier_order','supplier_proposal','shipment','contract','expensereport')))
  4777. {
  4778. $path=($object->ref?$object->ref:$object->id);
  4779. }
  4780. }
  4781. if (empty($withoutslash) && ! empty($path)) $path.='/';
  4782. return $path;
  4783. }
  4784. /**
  4785. * Creation of a directory (this can create recursive subdir)
  4786. *
  4787. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  4788. * @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)
  4789. * @param int $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  4790. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  4791. */
  4792. function dol_mkdir($dir, $dataroot='', $newmask=null)
  4793. {
  4794. global $conf;
  4795. dol_syslog("functions.lib::dol_mkdir: dir=".$dir,LOG_INFO);
  4796. $dir_osencoded=dol_osencode($dir);
  4797. if (@is_dir($dir_osencoded)) return 0;
  4798. $nberr=0;
  4799. $nbcreated=0;
  4800. $ccdir='';
  4801. if (! empty($dataroot)) {
  4802. // Remove data root from loop
  4803. $dir = str_replace($dataroot.'/', '', $dir);
  4804. $ccdir = $dataroot.'/';
  4805. }
  4806. $cdir = explode("/", $dir);
  4807. $num=count($cdir);
  4808. for ($i = 0; $i < $num; $i++)
  4809. {
  4810. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  4811. else $ccdir .= $cdir[$i];
  4812. if (preg_match("/^.:$/",$ccdir,$regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  4813. // Attention, le is_dir() peut echouer bien que le rep existe.
  4814. // (ex selon config de open_basedir)
  4815. if ($ccdir)
  4816. {
  4817. $ccdir_osencoded=dol_osencode($ccdir);
  4818. if (! @is_dir($ccdir_osencoded))
  4819. {
  4820. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.",LOG_DEBUG);
  4821. umask(0);
  4822. $dirmaskdec=octdec($newmask);
  4823. if (empty($newmask)) {
  4824. $dirmaskdec = empty( $conf->global->MAIN_UMASK ) ? octdec( '0755' ) : octdec( $conf->global->MAIN_UMASK );
  4825. }
  4826. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  4827. if (! @mkdir($ccdir_osencoded, $dirmaskdec))
  4828. {
  4829. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  4830. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.",LOG_WARNING);
  4831. $nberr++;
  4832. }
  4833. else
  4834. {
  4835. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created",LOG_DEBUG);
  4836. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  4837. $nbcreated++;
  4838. }
  4839. }
  4840. else
  4841. {
  4842. $nberr=0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  4843. }
  4844. }
  4845. }
  4846. return ($nberr ? -$nberr : $nbcreated);
  4847. }
  4848. /**
  4849. * Return picto saying a field is required
  4850. *
  4851. * @return string Chaine avec picto obligatoire
  4852. */
  4853. function picto_required()
  4854. {
  4855. return '<span class="fieldrequired">*</span>';
  4856. }
  4857. /**
  4858. * Clean a string from all HTML tags and entities.
  4859. * This function differs from strip_tags because:
  4860. * - <br> are replaced with \n if removelinefeed=0 or 1
  4861. * - if entities are found, they are decoded BEFORE the strip
  4862. * - you can decide to convert line feed into a space
  4863. *
  4864. * @param string $stringtoclean String to clean
  4865. * @param integer $removelinefeed 1=Replace all new lines by 1 space, 0=Only ending new lines are removed others are replaced with \n, 2=Ending new lines are removed but others are kept with a same number of \n than nb of <br> when there is both "...<br>\n..."
  4866. * @param string $pagecodeto Encoding of input/output string
  4867. * @param integer $strip_tags 0=Use internal strip, 1=Use strip_tags() php function (bugged when text contains a < char that is not for a html tag)
  4868. * @return string String cleaned
  4869. *
  4870. * @see dol_escape_htmltag strip_tags dol_string_onlythesehtmltags dol_string_neverthesehtmltags
  4871. */
  4872. function dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0)
  4873. {
  4874. if ($removelinefeed == 2) $stringtoclean = preg_replace('/<br[^>]*>\n+/ims', '<br>', $stringtoclean);
  4875. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  4876. if ($strip_tags) {
  4877. $temp = strip_tags($temp);
  4878. } else {
  4879. $pattern = "/<[^<>]+>/";
  4880. // Exemple of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  4881. $temp = preg_replace($pattern,"",$temp); // pass 1
  4882. // $temp after pass 1: <a href="/myurl" title="A title">0000-021
  4883. $temp = preg_replace($pattern,"",$temp); // pass 2
  4884. // $temp after pass 2: 0000-021
  4885. }
  4886. $temp = dol_html_entity_decode($temp,ENT_COMPAT,$pagecodeto);
  4887. // Supprime aussi les retours
  4888. if ($removelinefeed == 1) $temp=str_replace(array("\r\n","\r","\n")," ",$temp);
  4889. // et les espaces doubles
  4890. while (strpos($temp," "))
  4891. {
  4892. $temp = str_replace(" "," ",$temp);
  4893. }
  4894. return trim($temp);
  4895. }
  4896. /**
  4897. * Clean a string to keep only desirable HTML tags.
  4898. *
  4899. * @param string $stringtoclean String to clean
  4900. * @return string String cleaned
  4901. *
  4902. * @see dol_escape_htmltag strip_tags dol_string_nohtmltag dol_string_neverthesehtmltags
  4903. */
  4904. function dol_string_onlythesehtmltags($stringtoclean)
  4905. {
  4906. $allowed_tags = array(
  4907. "html", "head", "meta", "body", "article", "a", "b", "br", "div", "em", "font", "img", "ins", "hr", "i", "li", "link",
  4908. "ol", "p", "s", "section", "span", "strong", "title",
  4909. "table", "tr", "th", "td", "u", "ul"
  4910. );
  4911. $allowed_tags_string = join("><", $allowed_tags);
  4912. $allowed_tags_string = preg_replace('/^>/','',$allowed_tags_string);
  4913. $allowed_tags_string = preg_replace('/<$/','',$allowed_tags_string);
  4914. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  4915. return $temp;
  4916. }
  4917. /**
  4918. * Clean a string from some undesirable HTML tags.
  4919. *
  4920. * @param string $stringtoclean String to clean
  4921. * @param array $disallowed_tags Array of tags not allowed
  4922. * @return string String cleaned
  4923. *
  4924. * @see dol_escape_htmltag strip_tags dol_string_nohtmltag dol_string_onlythesehtmltags
  4925. */
  4926. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags=array('textarea'))
  4927. {
  4928. $temp = $stringtoclean;
  4929. foreach($disallowed_tags as $tagtoremove)
  4930. {
  4931. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  4932. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  4933. }
  4934. return $temp;
  4935. }
  4936. /**
  4937. * Return first line of text. Cut will depends if content is HTML or not.
  4938. *
  4939. * @param string $text Input text
  4940. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  4941. * @return string Output text
  4942. * @see dol_nboflines_bis, dol_string_nohtmltag, dol_escape_htmltag
  4943. */
  4944. function dolGetFirstLineOfText($text, $nboflines=1)
  4945. {
  4946. if ($nboflines == 1)
  4947. {
  4948. if (dol_textishtml($text))
  4949. {
  4950. $firstline=preg_replace('/<br[^>]*>.*$/s','',$text); // The s pattern modifier means the . can match newline characters
  4951. $firstline=preg_replace('/<div[^>]*>.*$/s','',$firstline); // The s pattern modifier means the . can match newline characters
  4952. }
  4953. else
  4954. {
  4955. $firstline=preg_replace('/[\n\r].*/','',$text);
  4956. }
  4957. return $firstline.((strlen($firstline) != strlen($text))?'...':'');
  4958. }
  4959. else
  4960. {
  4961. $ishtml=0;
  4962. if (dol_textishtml($text))
  4963. {
  4964. $text=preg_replace('/\n/','',$text);
  4965. $ishtml=1;
  4966. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  4967. }
  4968. else
  4969. {
  4970. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  4971. }
  4972. $text = strtr($text, $repTable);
  4973. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  4974. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  4975. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  4976. $firstline='';
  4977. $i=0;
  4978. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  4979. while (($i < $nba) && ($i < ($nboflines * 2)))
  4980. {
  4981. if ($i % 2 == 0) $firstline .= $a[$i];
  4982. elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) $firstline .= ($ishtml?"<br>\n":"\n");
  4983. $i++;
  4984. }
  4985. unset($a);
  4986. return $firstline.(($i < $nba)?'...':'');
  4987. }
  4988. }
  4989. /**
  4990. * Replace CRLF in string with a HTML BR tag
  4991. *
  4992. * @param string $stringtoencode String to encode
  4993. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  4994. * @param bool $forxml false=Use <br>, true=Use <br />
  4995. * @return string String encoded
  4996. * @see dol_nboflines, dolGetFirstLineOfText
  4997. */
  4998. function dol_nl2br($stringtoencode,$nl2brmode=0,$forxml=false)
  4999. {
  5000. if (!$nl2brmode) {
  5001. return nl2br($stringtoencode, $forxml);
  5002. } else {
  5003. $ret=preg_replace('/(\r\n|\r|\n)/i', ($forxml?'<br />':'<br>'), $stringtoencode);
  5004. return $ret;
  5005. }
  5006. }
  5007. /**
  5008. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5009. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,> are converted.
  5010. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5011. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5012. * For PDF usage, you can show text by 2 ways:
  5013. * - writeHTMLCell -> param must be encoded into HTML.
  5014. * - MultiCell -> param must not be encoded into HTML.
  5015. * Because writeHTMLCell convert also \n into <br>, if function
  5016. * is used to build PDF, nl2brmode must be 1.
  5017. *
  5018. * @param string $stringtoencode String to encode
  5019. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5020. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5021. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5022. * @return string String encoded
  5023. */
  5024. function dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
  5025. {
  5026. $newstring=$stringtoencode;
  5027. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  5028. {
  5029. $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.
  5030. if ($removelasteolbr) $newstring=preg_replace('/<br>$/i','',$newstring); // Remove last <br> (remove only last one)
  5031. $newstring=strtr($newstring,array('&'=>'__and__','<'=>'__lt__','>'=>'__gt__','"'=>'__dquot__'));
  5032. $newstring=dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom); // Make entity encoding
  5033. $newstring=strtr($newstring,array('__and__'=>'&','__lt__'=>'<','__gt__'=>'>','__dquot__'=>'"'));
  5034. }
  5035. else
  5036. {
  5037. if ($removelasteolbr) $newstring=preg_replace('/(\r\n|\r|\n)$/i','',$newstring); // Remove last \n (may remove several)
  5038. $newstring=dol_nl2br(dol_htmlentities($newstring,ENT_COMPAT,$pagecodefrom),$nl2brmode);
  5039. }
  5040. // Other substitutions that htmlentities does not do
  5041. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5042. return $newstring;
  5043. }
  5044. /**
  5045. * This function is called to decode a HTML string (it decodes entities and br tags)
  5046. *
  5047. * @param string $stringtodecode String to decode
  5048. * @param string $pagecodeto Page code for result
  5049. * @return string String decoded
  5050. */
  5051. function dol_htmlentitiesbr_decode($stringtodecode,$pagecodeto='UTF-8')
  5052. {
  5053. $ret=dol_html_entity_decode($stringtodecode,ENT_COMPAT,$pagecodeto);
  5054. $ret=preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i',"<br>",$ret);
  5055. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i',"\r\n",$ret);
  5056. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i',"\n",$ret);
  5057. $ret=preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i',"\n",$ret);
  5058. return $ret;
  5059. }
  5060. /**
  5061. * This function remove all ending \n and br at end
  5062. *
  5063. * @param string $stringtodecode String to decode
  5064. * @return string String decoded
  5065. */
  5066. function dol_htmlcleanlastbr($stringtodecode)
  5067. {
  5068. $ret=preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i',"",$stringtodecode);
  5069. return $ret;
  5070. }
  5071. /**
  5072. * Replace html_entity_decode functions to manage errors
  5073. *
  5074. * @param string $a Operand a
  5075. * @param string $b Operand b (ENT_QUOTES=convert simple and double quotes)
  5076. * @param string $c Operand c
  5077. * @return string String decoded
  5078. */
  5079. function dol_html_entity_decode($a,$b,$c='UTF-8')
  5080. {
  5081. return html_entity_decode($a,$b,$c);
  5082. }
  5083. /**
  5084. * Replace htmlentities functions.
  5085. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5086. *
  5087. * @param string $string The input string to encode
  5088. * @param int $flags Flags (see PHP doc above)
  5089. * @param string $encoding Encoding page code
  5090. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5091. * @return string $ret Encoded string
  5092. */
  5093. function dol_htmlentities($string, $flags=null, $encoding='UTF-8', $double_encode=false)
  5094. {
  5095. return htmlentities($string, $flags, $encoding, $double_encode);
  5096. }
  5097. /**
  5098. * Check if a string is a correct iso string
  5099. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5100. * Example, if string contains euro symbol that has ascii code 128
  5101. *
  5102. * @param string $s String to check
  5103. * @return int 0 if bad iso, 1 if good iso
  5104. */
  5105. function dol_string_is_good_iso($s)
  5106. {
  5107. $len=dol_strlen($s);
  5108. $ok=1;
  5109. for($scursor=0;$scursor<$len;$scursor++)
  5110. {
  5111. $ordchar=ord($s{$scursor});
  5112. //print $scursor.'-'.$ordchar.'<br>';
  5113. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok=0; break; }
  5114. if ($ordchar > 126 && $ordchar < 160) { $ok=0; break; }
  5115. }
  5116. return $ok;
  5117. }
  5118. /**
  5119. * Return nb of lines of a clear text
  5120. *
  5121. * @param string $s String to check
  5122. * @param int $maxchar Not yet used
  5123. * @return int Number of lines
  5124. * @see dol_nboflines_bis, dolGetFirstLineOfText
  5125. */
  5126. function dol_nboflines($s,$maxchar=0)
  5127. {
  5128. if ($s == '') return 0;
  5129. $arraystring=explode("\n",$s);
  5130. $nb=count($arraystring);
  5131. return $nb;
  5132. }
  5133. /**
  5134. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  5135. *
  5136. * @param string $text Text
  5137. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  5138. * @param string $charset Give the charset used to encode the $text variable in memory.
  5139. * @return int Number of lines
  5140. * @see dol_nboflines, dolGetFirstLineOfText
  5141. */
  5142. function dol_nboflines_bis($text,$maxlinesize=0,$charset='UTF-8')
  5143. {
  5144. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5145. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5146. $text = strtr($text, $repTable);
  5147. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5148. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5149. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5150. $nblines = (int) floor((count($a)+1)/2);
  5151. // count possible auto line breaks
  5152. if($maxlinesize)
  5153. {
  5154. foreach ($a as $line)
  5155. {
  5156. if (dol_strlen($line)>$maxlinesize)
  5157. {
  5158. //$line_dec = html_entity_decode(strip_tags($line));
  5159. $line_dec = html_entity_decode($line);
  5160. if(dol_strlen($line_dec)>$maxlinesize)
  5161. {
  5162. $line_dec=wordwrap($line_dec,$maxlinesize,'\n',true);
  5163. $nblines+=substr_count($line_dec,'\n');
  5164. }
  5165. }
  5166. }
  5167. }
  5168. unset($a);
  5169. return $nblines;
  5170. }
  5171. /**
  5172. * Same function than microtime in PHP 5 but compatible with PHP4
  5173. *
  5174. * @return float Time (millisecondes) with microsecondes in decimal part
  5175. * @deprecated Dolibarr does not support PHP4, you should use native function
  5176. * @see microtime()
  5177. */
  5178. function dol_microtime_float()
  5179. {
  5180. dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
  5181. return microtime(true);
  5182. }
  5183. /**
  5184. * Return if a text is a html content
  5185. *
  5186. * @param string $msg Content to check
  5187. * @param int $option 0=Full detection, 1=Fast check
  5188. * @return boolean true/false
  5189. * @see dol_concatdesc
  5190. */
  5191. function dol_textishtml($msg,$option=0)
  5192. {
  5193. if ($option == 1)
  5194. {
  5195. if (preg_match('/<html/i',$msg)) return true;
  5196. elseif (preg_match('/<body/i',$msg)) return true;
  5197. elseif (preg_match('/<br/i',$msg)) return true;
  5198. return false;
  5199. }
  5200. else
  5201. {
  5202. if (preg_match('/<html/i',$msg)) return true;
  5203. elseif (preg_match('/<body/i',$msg)) return true;
  5204. elseif (preg_match('/<(b|em|i|u)>/i',$msg)) return true;
  5205. elseif (preg_match('/<br\/>/i',$msg)) return true;
  5206. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i',$msg)) return true;
  5207. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i',$msg)) return true;
  5208. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i',$msg)) return true;
  5209. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i',$msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  5210. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i',$msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  5211. elseif (preg_match('/<h[0-9]>/i',$msg)) return true;
  5212. elseif (preg_match('/&[A-Z0-9]{1,6};/i',$msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  5213. elseif (preg_match('/&#[0-9]{2,3};/i',$msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  5214. return false;
  5215. }
  5216. }
  5217. /**
  5218. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  5219. * text1 html + text2 html => text1 + '<br>' + text2
  5220. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  5221. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  5222. * text1 txt + text2 txt => text1 + '\n' + text2
  5223. *
  5224. * @param string $text1 Text 1
  5225. * @param string $text2 Text 2
  5226. * @param bool $forxml false=Use <br> instead of \n if html content detected, true=Use <br /> instead of \n if html content detected
  5227. * @return string Text 1 + new line + Text2
  5228. * @see dol_textishtml
  5229. */
  5230. function dol_concatdesc($text1,$text2,$forxml=false)
  5231. {
  5232. $ret='';
  5233. $ret.= (! dol_textishtml($text1) && dol_textishtml($text2))?dol_nl2br($text1, 0, $forxml):$text1;
  5234. $ret.= (! empty($text1) && ! empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2))?($forxml?"<br \>\n":"<br>\n") : "\n") : "";
  5235. $ret.= (dol_textishtml($text1) && ! dol_textishtml($text2))?dol_nl2br($text2, 0, $forxml):$text2;
  5236. return $ret;
  5237. }
  5238. /**
  5239. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  5240. *
  5241. * @param Translate $outputlangs Output language
  5242. * @param int $onlykey 1=Do not calculate some heavy values of keys (performance enhancement when we need only the keys), 2=Values are trunc and html sanitized (to use for help tooltip)
  5243. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  5244. * @param Object $object Object for keys on object
  5245. * @return array Array of substitutions
  5246. * @see setSubstitFromObject
  5247. */
  5248. function getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
  5249. {
  5250. global $db, $conf, $mysoc, $user, $extrafields;
  5251. $substitutionarray=array();
  5252. if (empty($exclude) || ! in_array('user', $exclude))
  5253. {
  5254. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  5255. // this will include signature content first and then replace var found into content of signature
  5256. $signature = $user->signature;
  5257. $substitutionarray=array_merge($substitutionarray, array(
  5258. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  5259. )
  5260. );
  5261. // For backward compatibility
  5262. if ($onlykey != 2)
  5263. {
  5264. $substitutionarray['__SIGNATURE__'] = (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '');
  5265. }
  5266. $substitutionarray=array_merge($substitutionarray, array(
  5267. '__USER_ID__' => (string) $user->id,
  5268. '__USER_LOGIN__' => (string) $user->login,
  5269. '__USER_LASTNAME__' => (string) $user->lastname,
  5270. '__USER_FIRSTNAME__' => (string) $user->firstname,
  5271. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  5272. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  5273. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  5274. )
  5275. );
  5276. }
  5277. if ((empty($exclude) || ! in_array('mycompany', $exclude)) && is_object($mysoc))
  5278. {
  5279. $substitutionarray=array_merge($substitutionarray, array(
  5280. '__MYCOMPANY_NAME__' => $mysoc->name,
  5281. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  5282. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  5283. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  5284. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  5285. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  5286. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  5287. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  5288. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  5289. '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '),
  5290. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  5291. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  5292. '__MYCOMPANY_TOWN__' => $mysoc->town,
  5293. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  5294. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  5295. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  5296. ));
  5297. }
  5298. if (($onlykey || is_object($object)) && (empty($exclude) || ! in_array('object', $exclude)))
  5299. {
  5300. if ($onlykey)
  5301. {
  5302. $substitutionarray['__ID__'] = '__ID__';
  5303. $substitutionarray['__REF__'] = '__REF__';
  5304. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  5305. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  5306. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  5307. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  5308. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  5309. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  5310. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  5311. if (! empty($conf->adherent->enabled))
  5312. {
  5313. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  5314. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  5315. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  5316. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  5317. }
  5318. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  5319. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  5320. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  5321. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  5322. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  5323. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  5324. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  5325. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  5326. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  5327. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  5328. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  5329. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  5330. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  5331. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  5332. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  5333. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  5334. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  5335. if (! empty($conf->expedition->enabled))
  5336. {
  5337. $substitutionarray['__SHIPPINGTRACKNUM__']='Shipping tacking number';
  5338. $substitutionarray['__SHIPPINGTRACKNUMURL__']='Shipping tracking url';
  5339. }
  5340. }
  5341. else
  5342. {
  5343. $substitutionarray['__ID__'] = $object->id;
  5344. $substitutionarray['__REF__'] = $object->ref;
  5345. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5346. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5347. // For backward compatibility
  5348. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5349. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5350. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs): '');
  5351. // TODO Remove this
  5352. $msgishtml = 0;
  5353. $birthday = dol_print_date($object->birth,'day');
  5354. if ($object->id > 0)
  5355. {
  5356. $substitutionarray['__MEMBER_ID__']=$object->id;
  5357. if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  5358. $substitutionarray['__MEMBER_FIRSTNAME__']=$msgishtml?dol_htmlentitiesbr($object->firstname):$object->firstname;
  5359. $substitutionarray['__MEMBER_LASTNAME__']=$msgishtml?dol_htmlentitiesbr($object->lastname):$object->lastname;
  5360. if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__']=$msgishtml?dol_htmlentitiesbr($object->getFullName($outputlangs)):$object->getFullName($outputlangs);
  5361. $substitutionarray['__MEMBER_COMPANY__']=$msgishtml?dol_htmlentitiesbr($object->societe):$object->societe;
  5362. $substitutionarray['__MEMBER_ADDRESS__']=$msgishtml?dol_htmlentitiesbr($object->address):$object->address;
  5363. $substitutionarray['__MEMBER_ZIP__']=$msgishtml?dol_htmlentitiesbr($object->zip):$object->zip;
  5364. $substitutionarray['__MEMBER_TOWN__']=$msgishtml?dol_htmlentitiesbr($object->town):$object->town;
  5365. $substitutionarray['__MEMBER_COUNTRY__']=$msgishtml?dol_htmlentitiesbr($object->country):$object->country;
  5366. $substitutionarray['__MEMBER_EMAIL__']=$msgishtml?dol_htmlentitiesbr($object->email):$object->email;
  5367. $substitutionarray['__MEMBER_BIRTH__']=$msgishtml?dol_htmlentitiesbr($birthday):$birthday;
  5368. $substitutionarray['__MEMBER_PHOTO__']=$msgishtml?dol_htmlentitiesbr($object->photo):$object->photo;
  5369. $substitutionarray['__MEMBER_LOGIN__']=$msgishtml?dol_htmlentitiesbr($object->login):$object->login;
  5370. $substitutionarray['__MEMBER_PASSWORD__']=$msgishtml?dol_htmlentitiesbr($object->pass):$object->pass;
  5371. $substitutionarray['__MEMBER_PHONE__']=$msgishtml?dol_htmlentitiesbr($object->phone):$object->phone;
  5372. $substitutionarray['__MEMBER_PHONEPRO__']=$msgishtml?dol_htmlentitiesbr($object->phone_perso):$object->phone_perso;
  5373. $substitutionarray['__MEMBER_PHONEMOBILE__']=$msgishtml?dol_htmlentitiesbr($object->phone_mobile):$object->phone_mobile;
  5374. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  5375. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  5376. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  5377. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  5378. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  5379. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  5380. }
  5381. if (is_object($object) && $object->element == 'societe')
  5382. {
  5383. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object)?$object->id:'');
  5384. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object)?$object->name:'');
  5385. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object)?$object->name_alias:'');
  5386. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object)?$object->email:'');
  5387. }
  5388. elseif (is_object($object->thirdparty) && $object->thirdparty->id > 0)
  5389. {
  5390. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty)?$object->thirdparty->id:'');
  5391. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty)?$object->thirdparty->name:'');
  5392. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty)?$object->thirdparty->name_alias:'');
  5393. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty)?$object->thirdparty->email:'');
  5394. }
  5395. if (is_object($object->projet) && $object->projet->id > 0)
  5396. {
  5397. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet)?$object->projet->id:'');
  5398. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet)?$object->projet->ref:'');
  5399. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet)?$object->projet->title:'');
  5400. }
  5401. if (is_object($object) && $object->element == 'shipping')
  5402. {
  5403. $substitutionarray['__SHIPPINGTRACKNUM__']=$object->tracking_number;
  5404. $substitutionarray['__SHIPPINGTRACKNUMURL__']=$object->tracking_url;
  5405. }
  5406. if (is_object($object) && $object->element == 'contrat' && is_array($object->lines))
  5407. {
  5408. if ($object->id > 0)
  5409. {
  5410. $dateplannedstart='';
  5411. $datenextexpiration='';
  5412. foreach($object->lines as $line)
  5413. {
  5414. if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue;
  5415. if ($line->statut == 4 && $line->date_fin_prevue && (! $datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue;
  5416. }
  5417. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  5418. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  5419. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  5420. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  5421. }
  5422. }
  5423. // Create dynamic tags for __EXTRAFIELD_FIELD__
  5424. if ($object->table_element && $object->id > 0)
  5425. {
  5426. if (! is_object($extrafields)) $extrafields = new ExtraFields($db);
  5427. $extrafields->fetch_name_optionals_label($object->table_element, true);
  5428. if ($object->fetch_optionals() > 0)
  5429. {
  5430. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
  5431. {
  5432. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  5433. $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
  5434. }
  5435. }
  5436. }
  5437. }
  5438. // Complete substitution array with the url to make online payment
  5439. $paymenturl='';
  5440. if (empty($substitutionarray['__REF__']))
  5441. {
  5442. $paymenturl='';
  5443. }
  5444. else
  5445. {
  5446. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  5447. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  5448. $outputlangs->loadLangs(array('paypal','other'));
  5449. $typeforonlinepayment='free';
  5450. if (is_object($object) && $object->element == 'commande') $typeforonlinepayment='order';
  5451. if (is_object($object) && $object->element == 'facture') $typeforonlinepayment='invoice';
  5452. if (is_object($object) && $object->element == 'member') $typeforonlinepayment='member';
  5453. $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  5454. $paymenturl=$url;
  5455. }
  5456. if ($object->id > 0)
  5457. {
  5458. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__']=($paymenturl?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)):'');
  5459. $substitutionarray['__ONLINE_PAYMENT_URL__']=$paymenturl;
  5460. if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal')
  5461. {
  5462. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  5463. }
  5464. else $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  5465. if (! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande')
  5466. {
  5467. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  5468. }
  5469. else $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  5470. if (! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture')
  5471. {
  5472. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  5473. }
  5474. else $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  5475. }
  5476. }
  5477. }
  5478. if (empty($exclude) || ! in_array('objectamount', $exclude))
  5479. {
  5480. $substitutionarray['__DATE_YMD__'] = is_object($object)?(isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  5481. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object)?(isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  5482. $substitutionarray['__AMOUNT__'] = is_object($object)?$object->total_ttc:'';
  5483. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object)?$object->total_ht:'';
  5484. $substitutionarray['__AMOUNT_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):'';
  5485. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2__'] = is_object($object)?$object->total_localtax1:'';
  5486. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3__'] = is_object($object)?$object->total_localtax2:'';
  5487. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object)?($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5488. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object)?($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5489. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object)?($object->total_vat ? price($object->total_vat, 0, $outputlangs, 0, 0, -1, $conf->currency): ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, 0, -1, $conf->currency) : null)):'';
  5490. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object)? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5491. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object)? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, $conf->currency) : null):'';
  5492. // TODO Add keys for foreign multicurrency
  5493. // For backward compatibility
  5494. if ($onlykey != 2)
  5495. {
  5496. $substitutionarray['__TOTAL_TTC__'] = is_object($object)?$object->total_ttc:'';
  5497. $substitutionarray['__TOTAL_HT__'] = is_object($object)?$object->total_ht:'';
  5498. $substitutionarray['__TOTAL_VAT__'] = is_object($object)?($object->total_vat?$object->total_vat:$object->total_tva):'';
  5499. }
  5500. }
  5501. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  5502. if (empty($exclude) || ! in_array('date', $exclude))
  5503. {
  5504. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5505. $tmp=dol_getdate(dol_now(), true);
  5506. $tmp2=dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5507. $tmp3=dol_get_prev_month($tmp['mon'], $tmp['year']);
  5508. $tmp4=dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5509. $tmp5=dol_get_next_month($tmp['mon'], $tmp['year']);
  5510. $substitutionarray=array_merge($substitutionarray, array(
  5511. '__DAY__' => (string) $tmp['mday'],
  5512. '__DAY_TEXT__' => $outputlangs->trans('Day'.$tmp['wday']), // Monday
  5513. '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'].'Min'), // Mon
  5514. '__DAY_TEXT_MIN__' => $outputlangs->trans('Short'.$tmp['weekday']), // M
  5515. '__MONTH__' => (string) $tmp['mon'],
  5516. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  5517. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  5518. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  5519. '__YEAR__' => (string) $tmp['year'],
  5520. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  5521. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  5522. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  5523. '__NEXT_DAY__' => (string) $tmp4['day'],
  5524. '__NEXT_MONTH__' => (string) $tmp5['month'],
  5525. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  5526. ));
  5527. }
  5528. if (! empty($conf->multicompany->enabled))
  5529. {
  5530. $substitutionarray=array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  5531. }
  5532. if (empty($exclude) || ! in_array('system', $exclude))
  5533. {
  5534. $substitutionarray['__DOL_MAIN_URL_ROOT__']=DOL_MAIN_URL_ROOT;
  5535. $substitutionarray['__(AnyTranslationKey)__']=$outputlangs->trans('TranslationOfKey');
  5536. $substitutionarray['__[AnyConstantKey]__']=$outputlangs->trans('ValueOfConstantKey');
  5537. }
  5538. return $substitutionarray;
  5539. }
  5540. /**
  5541. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  5542. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  5543. * Example of usage:
  5544. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  5545. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  5546. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  5547. *
  5548. * @param string $text Source string in which we must do substitution
  5549. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  5550. * @param Translate $outputlangs Output language
  5551. * @return string Output string after substitutions
  5552. * @see complete_substitutions_array, getCommonSubstitutionArray
  5553. */
  5554. function make_substitutions($text, $substitutionarray, $outputlangs=null)
  5555. {
  5556. global $conf, $langs;
  5557. if (! is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  5558. if (empty($outputlangs)) $outputlangs=$langs;
  5559. // Make substitution for language keys
  5560. if (is_object($outputlangs))
  5561. {
  5562. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg))
  5563. {
  5564. $msgishtml = 0;
  5565. if (dol_textishtml($text,1)) $msgishtml = 1;
  5566. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  5567. $tmp=explode('|',$reg[1]);
  5568. if (! empty($tmp[1])) $outputlangs->load($tmp[1]);
  5569. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])):$outputlangs->transnoentitiesnoconv($reg[1]), $text);
  5570. }
  5571. }
  5572. // Make substitution for constant keys. Must be after the substitution of translation, so if text of translation contains a constant,
  5573. // it is also converted.
  5574. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg))
  5575. {
  5576. $msgishtml = 0;
  5577. if (dol_textishtml($text,1)) $msgishtml = 1;
  5578. $keyfound = $reg[1];
  5579. if (preg_match('/(_pass|password|secret|_key|key$)/i', $keyfound)) $newval = '*****forbidden*****';
  5580. else $newval=empty($conf->global->$keyfound)?'':$conf->global->$keyfound;
  5581. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml?dol_htmlentitiesbr($newval):$newval, $text);
  5582. }
  5583. // Make substitition for array $substitutionarray
  5584. foreach ($substitutionarray as $key => $value)
  5585. {
  5586. if (! isset($value)) continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  5587. if ($key == '__SIGNATURE__' && (! empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value=''; // Protection
  5588. if ($key == '__USER_SIGNATURE__' && (! empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value=''; // Protection
  5589. $text=str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  5590. }
  5591. return $text;
  5592. }
  5593. /**
  5594. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  5595. * In this case, method completesubstitutionarray provided by module is called.
  5596. *
  5597. * @param array $substitutionarray Array substitution old value => new value value
  5598. * @param Translate $outputlangs Output language
  5599. * @param Object $object Source object
  5600. * @param mixed $parameters Add more parameters (useful to pass product lines)
  5601. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  5602. * @return void
  5603. * @see make_substitutions
  5604. */
  5605. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
  5606. {
  5607. global $conf,$user;
  5608. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5609. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  5610. // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
  5611. /*if (is_object($object) && is_array($object->array_options))
  5612. {
  5613. foreach($object->array_options as $key => $val)
  5614. {
  5615. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  5616. $substitutionarray['__EXTRAFIELD_'.$keyshort.'__']=$val;
  5617. // For backward compatibiliy
  5618. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  5619. }
  5620. }*/
  5621. // Check if there is external substitution to do, requested by plugins
  5622. $dirsubstitutions=array_merge(array(),(array) $conf->modules_parts['substitutions']);
  5623. foreach($dirsubstitutions as $reldir)
  5624. {
  5625. $dir=dol_buildpath($reldir,0);
  5626. // Check if directory exists
  5627. if (! dol_is_dir($dir)) continue;
  5628. $substitfiles=dol_dir_list($dir,'files',0,'functions_');
  5629. foreach($substitfiles as $substitfile)
  5630. {
  5631. if (preg_match('/functions_(.*)\.lib\.php/i',$substitfile['name'],$reg))
  5632. {
  5633. $module=$reg[1];
  5634. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  5635. // Include the user's functions file
  5636. require_once $dir.$substitfile['name'];
  5637. // Call the user's function, and only if it is defined
  5638. $function_name=$module."_".$callfunc;
  5639. if (function_exists($function_name)) $function_name($substitutionarray,$outputlangs,$object,$parameters);
  5640. }
  5641. }
  5642. }
  5643. }
  5644. /**
  5645. * Format output for start and end date
  5646. *
  5647. * @param int $date_start Start date
  5648. * @param int $date_end End date
  5649. * @param string $format Output format
  5650. * @param Translate $outputlangs Output language
  5651. * @return void
  5652. */
  5653. function print_date_range($date_start,$date_end,$format = '',$outputlangs='')
  5654. {
  5655. print get_date_range($date_start,$date_end,$format,$outputlangs);
  5656. }
  5657. /**
  5658. * Format output for start and end date
  5659. *
  5660. * @param int $date_start Start date
  5661. * @param int $date_end End date
  5662. * @param string $format Output format
  5663. * @param Translate $outputlangs Output language
  5664. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  5665. * @return string String
  5666. */
  5667. function get_date_range($date_start,$date_end,$format = '',$outputlangs='', $withparenthesis=1)
  5668. {
  5669. global $langs;
  5670. $out='';
  5671. if (! is_object($outputlangs)) $outputlangs=$langs;
  5672. if ($date_start && $date_end)
  5673. {
  5674. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFromTo',dol_print_date($date_start, $format, false, $outputlangs),dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  5675. }
  5676. if ($date_start && ! $date_end)
  5677. {
  5678. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateFrom',dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis?')':'');
  5679. }
  5680. if (! $date_start && $date_end)
  5681. {
  5682. $out.= ($withparenthesis?' (':'').$outputlangs->transnoentitiesnoconv('DateUntil',dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis?')':'');
  5683. }
  5684. return $out;
  5685. }
  5686. /**
  5687. * Return firstname and lastname in correct order
  5688. *
  5689. * @param string $firstname Firstname
  5690. * @param string $lastname Lastname
  5691. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
  5692. * @return string Firstname + lastname or Lastname + firstname
  5693. */
  5694. function dolGetFirstLastname($firstname,$lastname,$nameorder=-1)
  5695. {
  5696. global $conf;
  5697. $ret='';
  5698. // If order not defined, we use the setup
  5699. if ($nameorder < 0) $nameorder=(empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)?1:0);
  5700. if ($nameorder && ((string) $nameorder != '2'))
  5701. {
  5702. $ret.=$firstname;
  5703. if ($firstname && $lastname) $ret.=' ';
  5704. $ret.=$lastname;
  5705. }
  5706. else if ($nameorder == 2)
  5707. {
  5708. $ret.=$firstname;
  5709. }
  5710. else
  5711. {
  5712. $ret.=$lastname;
  5713. if ($firstname && $lastname) $ret.=' ';
  5714. $ret.=$firstname;
  5715. }
  5716. return $ret;
  5717. }
  5718. /**
  5719. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  5720. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5721. * Note: Prefer to use setEventMessages instead.
  5722. *
  5723. * @param mixed $mesgs Message string or array
  5724. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5725. * @return void
  5726. * @see dol_htmloutput_events
  5727. */
  5728. function setEventMessage($mesgs, $style='mesgs')
  5729. {
  5730. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  5731. if (! is_array($mesgs)) // If mesgs is a string
  5732. {
  5733. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  5734. }
  5735. else // If mesgs is an array
  5736. {
  5737. foreach($mesgs as $mesg)
  5738. {
  5739. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  5740. }
  5741. }
  5742. }
  5743. /**
  5744. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  5745. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  5746. *
  5747. * @param string $mesg Message string
  5748. * @param array $mesgs Message array
  5749. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  5750. * @return void
  5751. * @see dol_htmloutput_events
  5752. */
  5753. function setEventMessages($mesg, $mesgs, $style='mesgs')
  5754. {
  5755. if (empty($mesg) && empty($mesgs))
  5756. {
  5757. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  5758. }
  5759. else
  5760. {
  5761. if (! in_array((string) $style, array('mesgs','warnings','errors'))) dol_print_error('','Bad parameter style='.$style.' for setEventMessages');
  5762. if (empty($mesgs)) setEventMessage($mesg, $style);
  5763. else
  5764. {
  5765. if (! empty($mesg) && ! in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  5766. setEventMessage($mesgs, $style);
  5767. }
  5768. }
  5769. }
  5770. /**
  5771. * Print formated messages to output (Used to show messages on html output).
  5772. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  5773. * no need to call it explicitely.
  5774. *
  5775. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  5776. * @return void
  5777. * @see dol_htmloutput_mesg
  5778. */
  5779. function dol_htmloutput_events($disabledoutputofmessages=0)
  5780. {
  5781. // Show mesgs
  5782. if (isset($_SESSION['dol_events']['mesgs'])) {
  5783. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  5784. unset($_SESSION['dol_events']['mesgs']);
  5785. }
  5786. // Show errors
  5787. if (isset($_SESSION['dol_events']['errors'])) {
  5788. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  5789. unset($_SESSION['dol_events']['errors']);
  5790. }
  5791. // Show warnings
  5792. if (isset($_SESSION['dol_events']['warnings'])) {
  5793. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  5794. unset($_SESSION['dol_events']['warnings']);
  5795. }
  5796. }
  5797. /**
  5798. * Get formated messages to output (Used to show messages on html output).
  5799. * This include also the translation of the message key.
  5800. *
  5801. * @param string $mesgstring Message string or message key
  5802. * @param string[] $mesgarray Array of message strings or message keys
  5803. * @param string $style Style of message output ('ok' or 'error')
  5804. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5805. * @return string Return html output
  5806. *
  5807. * @see dol_print_error
  5808. * @see dol_htmloutput_errors
  5809. * @see setEventMessages
  5810. */
  5811. function get_htmloutput_mesg($mesgstring='',$mesgarray='', $style='ok', $keepembedded=0)
  5812. {
  5813. global $conf, $langs;
  5814. $ret=0; $return='';
  5815. $out='';
  5816. $divstart=$divend='';
  5817. // If inline message with no format, we add it.
  5818. if ((empty($conf->use_javascript_ajax) || ! empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && ! preg_match('/<div class=".*">/i',$out))
  5819. {
  5820. $divstart='<div class="'.$style.' clearboth">';
  5821. $divend='</div>';
  5822. }
  5823. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  5824. {
  5825. $langs->load("errors");
  5826. $out.=$divstart;
  5827. if (is_array($mesgarray) && count($mesgarray))
  5828. {
  5829. foreach($mesgarray as $message)
  5830. {
  5831. $ret++;
  5832. $out.= $langs->trans($message);
  5833. if ($ret < count($mesgarray)) $out.= "<br>\n";
  5834. }
  5835. }
  5836. if ($mesgstring)
  5837. {
  5838. $langs->load("errors");
  5839. $ret++;
  5840. $out.= $langs->trans($mesgstring);
  5841. }
  5842. $out.=$divend;
  5843. }
  5844. if ($out)
  5845. {
  5846. if (! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  5847. {
  5848. $return = '<script type="text/javascript">
  5849. $(document).ready(function() {
  5850. var block = '.(! empty($conf->global->MAIN_USE_JQUERY_BLOCKUI)?"true":"false").'
  5851. if (block) {
  5852. $.dolEventValid("","'.dol_escape_js($out).'");
  5853. } else {
  5854. /* jnotify(message, preset of message type, keepmessage) */
  5855. $.jnotify("'.dol_escape_js($out).'",
  5856. "'.($style=="ok" ? 3000 : $style).'",
  5857. '.($style=="ok" ? "false" : "true").',
  5858. { remove: function (){} } );
  5859. }
  5860. });
  5861. </script>';
  5862. }
  5863. else
  5864. {
  5865. $return = $out;
  5866. }
  5867. }
  5868. return $return;
  5869. }
  5870. /**
  5871. * Get formated error messages to output (Used to show messages on html output).
  5872. *
  5873. * @param string $mesgstring Error message
  5874. * @param array $mesgarray Error messages array
  5875. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5876. * @return string Return html output
  5877. *
  5878. * @see dol_print_error
  5879. * @see dol_htmloutput_mesg
  5880. */
  5881. function get_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
  5882. {
  5883. return get_htmloutput_mesg($mesgstring, $mesgarray,'error',$keepembedded);
  5884. }
  5885. /**
  5886. * Print formated messages to output (Used to show messages on html output).
  5887. *
  5888. * @param string $mesgstring Message string or message key
  5889. * @param string[] $mesgarray Array of message strings or message keys
  5890. * @param string $style Which style to use ('ok', 'warning', 'error')
  5891. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  5892. * @return void
  5893. *
  5894. * @see dol_print_error
  5895. * @see dol_htmloutput_errors
  5896. * @see setEventMessages
  5897. */
  5898. function dol_htmloutput_mesg($mesgstring = '',$mesgarray = array(), $style = 'ok', $keepembedded=0)
  5899. {
  5900. if (empty($mesgstring) && (! is_array($mesgarray) || count($mesgarray) == 0)) return;
  5901. $iserror=0;
  5902. $iswarning=0;
  5903. if (is_array($mesgarray))
  5904. {
  5905. foreach($mesgarray as $val)
  5906. {
  5907. if ($val && preg_match('/class="error"/i',$val)) { $iserror++; break; }
  5908. if ($val && preg_match('/class="warning"/i',$val)) { $iswarning++; break; }
  5909. }
  5910. }
  5911. else if ($mesgstring && preg_match('/class="error"/i',$mesgstring)) $iserror++;
  5912. else if ($mesgstring && preg_match('/class="warning"/i',$mesgstring)) $iswarning++;
  5913. if ($style=='error') $iserror++;
  5914. if ($style=='warning') $iswarning++;
  5915. if ($iserror || $iswarning)
  5916. {
  5917. // Remove div from texts
  5918. $mesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$mesgstring);
  5919. $mesgstring=preg_replace('/<div class="(error|warning)">/','',$mesgstring);
  5920. $mesgstring=preg_replace('/<\/div>/','',$mesgstring);
  5921. // Remove div from texts array
  5922. if (is_array($mesgarray))
  5923. {
  5924. $newmesgarray=array();
  5925. foreach($mesgarray as $val)
  5926. {
  5927. $tmpmesgstring=preg_replace('/<\/div><div class="(error|warning)">/','<br>',$val);
  5928. $tmpmesgstring=preg_replace('/<div class="(error|warning)">/','',$tmpmesgstring);
  5929. $tmpmesgstring=preg_replace('/<\/div>/','',$tmpmesgstring);
  5930. $newmesgarray[]=$tmpmesgstring;
  5931. }
  5932. $mesgarray=$newmesgarray;
  5933. }
  5934. print get_htmloutput_mesg($mesgstring,$mesgarray,($iserror?'error':'warning'),$keepembedded);
  5935. }
  5936. else print get_htmloutput_mesg($mesgstring,$mesgarray,'ok',$keepembedded);
  5937. }
  5938. /**
  5939. * Print formated error messages to output (Used to show messages on html output).
  5940. *
  5941. * @param string $mesgstring Error message
  5942. * @param array $mesgarray Error messages array
  5943. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  5944. * @return void
  5945. *
  5946. * @see dol_print_error
  5947. * @see dol_htmloutput_mesg
  5948. */
  5949. function dol_htmloutput_errors($mesgstring='', $mesgarray=array(), $keepembedded=0)
  5950. {
  5951. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  5952. }
  5953. /**
  5954. * Advanced sort array by second index function, which produces ascending (default)
  5955. * or descending output and uses optionally natural case insensitive sorting (which
  5956. * can be optionally case sensitive as well).
  5957. *
  5958. * @param array $array Array to sort (array of array('key','otherkey1','otherkey2'...))
  5959. * @param string $index Key in array to use for sorting criteria
  5960. * @param int $order Sort order ('asc' or 'desc')
  5961. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  5962. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  5963. * @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.
  5964. * @return array Sorted array
  5965. */
  5966. function dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
  5967. {
  5968. // Clean parameters
  5969. $order=strtolower($order);
  5970. if (is_array($array))
  5971. {
  5972. $sizearray=count($array);
  5973. if ($sizearray>0)
  5974. {
  5975. $temp = array();
  5976. foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
  5977. if (!$natsort) ($order=='asc') ? asort($temp) : arsort($temp);
  5978. else
  5979. {
  5980. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  5981. if($order!='asc') $temp=array_reverse($temp, true);
  5982. }
  5983. $sorted = array();
  5984. foreach(array_keys($temp) as $key)
  5985. {
  5986. (is_numeric($key) && empty($keepindex)) ? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
  5987. }
  5988. return $sorted;
  5989. }
  5990. }
  5991. return $array;
  5992. }
  5993. /**
  5994. * Check if a string is in UTF8
  5995. *
  5996. * @param string $str String to check
  5997. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  5998. */
  5999. function utf8_check($str)
  6000. {
  6001. // We must use here a binary strlen function (so not dol_strlen)
  6002. $strLength = dol_strlen($str);
  6003. for ($i=0; $i<$strLength; $i++)
  6004. {
  6005. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  6006. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n=1; // 110bbbbb
  6007. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n=2; // 1110bbbb
  6008. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n=3; // 11110bbb
  6009. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n=4; // 111110bb
  6010. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n=5; // 1111110b
  6011. else return false; // Does not match any model
  6012. for ($j=0; $j<$n; $j++) { // n bytes matching 10bbbbbb follow ?
  6013. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  6014. return false;
  6015. }
  6016. }
  6017. return true;
  6018. }
  6019. /**
  6020. * Return a string encoded into OS filesystem encoding. This function is used to define
  6021. * value to pass to filesystem PHP functions.
  6022. *
  6023. * @param string $str String to encode (UTF-8)
  6024. * @return string Encoded string (UTF-8, ISO-8859-1)
  6025. */
  6026. function dol_osencode($str)
  6027. {
  6028. global $conf;
  6029. $tmp=ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  6030. if (empty($tmp) && ! empty($_SERVER["WINDIR"])) $tmp='iso-8859-1'; // By default for windows
  6031. if (empty($tmp)) $tmp='utf-8'; // By default for other
  6032. if (! empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp=$conf->global->MAIN_FILESYSTEM_ENCODING;
  6033. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  6034. return $str;
  6035. }
  6036. /**
  6037. * Return an id or code from a code or id.
  6038. * Store also Code-Id into a cache to speed up next request on same key.
  6039. *
  6040. * @param DoliDB $db Database handler
  6041. * @param string $key Code or Id to get Id or Code
  6042. * @param string $tablename Table name without prefix
  6043. * @param string $fieldkey Field to search the key into
  6044. * @param string $fieldid Field to get
  6045. * @param int $entityfilter Filter by entity
  6046. * @return int <0 if KO, Id of code if OK
  6047. * @see $langs->getLabelFromKey
  6048. */
  6049. function dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0)
  6050. {
  6051. global $cache_codes;
  6052. // If key empty
  6053. if ($key == '') return '';
  6054. // Check in cache
  6055. if (isset($cache_codes[$tablename][$key][$fieldid])) // Can be defined to 0 or ''
  6056. {
  6057. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  6058. }
  6059. dol_syslog('dol_getIdFromCode (value not found into cache)', LOG_DEBUG);
  6060. $sql = "SELECT ".$fieldid." as valuetoget";
  6061. $sql.= " FROM ".MAIN_DB_PREFIX.$tablename;
  6062. $sql.= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  6063. if (! empty($entityfilter))
  6064. $sql.= " AND entity IN (" . getEntity($tablename) . ")";
  6065. $resql = $db->query($sql);
  6066. if ($resql)
  6067. {
  6068. $obj = $db->fetch_object($resql);
  6069. if ($obj) $cache_codes[$tablename][$key][$fieldid]=$obj->valuetoget;
  6070. else $cache_codes[$tablename][$key][$fieldid]='';
  6071. $db->free($resql);
  6072. return $cache_codes[$tablename][$key][$fieldid];
  6073. }
  6074. else
  6075. {
  6076. return -1;
  6077. }
  6078. }
  6079. /**
  6080. * Verify if condition in string is ok or not
  6081. *
  6082. * @param string $strRights String with condition to check
  6083. * @return boolean True or False. Return True if strRights is ''
  6084. */
  6085. function verifCond($strRights)
  6086. {
  6087. global $user,$conf,$langs;
  6088. global $leftmenu;
  6089. global $rights; // To export to dol_eval function
  6090. //print $strRights."<br>\n";
  6091. $rights = true;
  6092. if ($strRights != '')
  6093. {
  6094. $str = 'if(!(' . $strRights . ')) { $rights = false; }';
  6095. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  6096. }
  6097. return $rights;
  6098. }
  6099. /**
  6100. * Replace eval function to add more security.
  6101. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  6102. *
  6103. * @param string $s String to evaluate
  6104. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  6105. * @param int $hideerrors 1=Hide errors
  6106. * @return mixed Nothing or return of eval
  6107. */
  6108. function dol_eval($s, $returnvalue=0, $hideerrors=1)
  6109. {
  6110. // Only global variables can be changed by eval function and returned to caller
  6111. global $db, $langs, $user, $conf, $website, $websitepage;
  6112. global $action, $mainmenu, $leftmenu;
  6113. global $rights;
  6114. global $object;
  6115. global $mysoc;
  6116. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  6117. global $soc; // For backward compatibility
  6118. //print $s."<br>\n";
  6119. if ($returnvalue)
  6120. {
  6121. if ($hideerrors) return @eval('return '.$s.';');
  6122. else return eval('return '.$s.';');
  6123. }
  6124. else
  6125. {
  6126. if ($hideerrors) @eval($s);
  6127. else eval($s);
  6128. }
  6129. }
  6130. /**
  6131. * Return if var element is ok
  6132. *
  6133. * @param string $element Variable to check
  6134. * @return boolean Return true of variable is not empty
  6135. */
  6136. function dol_validElement($element)
  6137. {
  6138. return (trim($element) != '');
  6139. }
  6140. /**
  6141. * Return img flag of country for a language code or country code
  6142. *
  6143. * @param string $codelang Language code (en_IN, fr_CA...) or Country code (IN, FR)
  6144. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  6145. * @return string HTML img string with flag.
  6146. */
  6147. function picto_from_langcode($codelang, $moreatt = '')
  6148. {
  6149. global $langs;
  6150. if (empty($codelang)) return '';
  6151. if ($codelang == 'auto')
  6152. {
  6153. return '<span class="fa fa-globe"></span>';
  6154. }
  6155. $langtocountryflag = array(
  6156. 'ar_AR' => '',
  6157. 'ca_ES' => 'catalonia',
  6158. 'da_DA' => 'dk',
  6159. 'fr_CA' => 'mq',
  6160. 'sv_SV' => 'se'
  6161. );
  6162. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  6163. else
  6164. {
  6165. $tmparray = explode('_', $codelang);
  6166. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  6167. }
  6168. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  6169. }
  6170. /**
  6171. * Return default language from country code
  6172. *
  6173. * @param string $countrycode Country code like 'US', 'FR', 'CA', ...
  6174. * @return string Value of locale like 'en_US', 'fr_FR', ...
  6175. */
  6176. function getLanguageCodeFromCountryCode($countrycode)
  6177. {
  6178. global $mysoc;
  6179. if (strtoupper($countrycode) == 'MQ') return 'fr_CA';
  6180. if (strtoupper($countrycode) == 'SE') return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  6181. if (strtoupper($countrycode) == 'CH')
  6182. {
  6183. if ($mysoc->country_code == 'FR') return 'fr_CH';
  6184. if ($mysoc->country_code == 'DE') return 'de_CH';
  6185. }
  6186. // Locale list taken from:
  6187. // http://stackoverflow.com/questions/3191664/
  6188. // list-of-all-locales-and-their-short-codes
  6189. $locales = array(
  6190. 'af-ZA',
  6191. 'am-ET',
  6192. 'ar-AE',
  6193. 'ar-BH',
  6194. 'ar-DZ',
  6195. 'ar-EG',
  6196. 'ar-IQ',
  6197. 'ar-JO',
  6198. 'ar-KW',
  6199. 'ar-LB',
  6200. 'ar-LY',
  6201. 'ar-MA',
  6202. 'ar-OM',
  6203. 'ar-QA',
  6204. 'ar-SA',
  6205. 'ar-SY',
  6206. 'ar-TN',
  6207. 'ar-YE',
  6208. 'as-IN',
  6209. 'ba-RU',
  6210. 'be-BY',
  6211. 'bg-BG',
  6212. 'bn-BD',
  6213. 'bn-IN',
  6214. 'bo-CN',
  6215. 'br-FR',
  6216. 'ca-ES',
  6217. 'co-FR',
  6218. 'cs-CZ',
  6219. 'cy-GB',
  6220. 'da-DK',
  6221. 'de-AT',
  6222. 'de-CH',
  6223. 'de-DE',
  6224. 'de-LI',
  6225. 'de-LU',
  6226. 'dv-MV',
  6227. 'el-GR',
  6228. 'en-AU',
  6229. 'en-BZ',
  6230. 'en-CA',
  6231. 'en-GB',
  6232. 'en-IE',
  6233. 'en-IN',
  6234. 'en-JM',
  6235. 'en-MY',
  6236. 'en-NZ',
  6237. 'en-PH',
  6238. 'en-SG',
  6239. 'en-TT',
  6240. 'en-US',
  6241. 'en-ZA',
  6242. 'en-ZW',
  6243. 'es-AR',
  6244. 'es-BO',
  6245. 'es-CL',
  6246. 'es-CO',
  6247. 'es-CR',
  6248. 'es-DO',
  6249. 'es-EC',
  6250. 'es-ES',
  6251. 'es-GT',
  6252. 'es-HN',
  6253. 'es-MX',
  6254. 'es-NI',
  6255. 'es-PA',
  6256. 'es-PE',
  6257. 'es-PR',
  6258. 'es-PY',
  6259. 'es-SV',
  6260. 'es-US',
  6261. 'es-UY',
  6262. 'es-VE',
  6263. 'et-EE',
  6264. 'eu-ES',
  6265. 'fa-IR',
  6266. 'fi-FI',
  6267. 'fo-FO',
  6268. 'fr-BE',
  6269. 'fr-CA',
  6270. 'fr-CH',
  6271. 'fr-FR',
  6272. 'fr-LU',
  6273. 'fr-MC',
  6274. 'fy-NL',
  6275. 'ga-IE',
  6276. 'gd-GB',
  6277. 'gl-ES',
  6278. 'gu-IN',
  6279. 'he-IL',
  6280. 'hi-IN',
  6281. 'hr-BA',
  6282. 'hr-HR',
  6283. 'hu-HU',
  6284. 'hy-AM',
  6285. 'id-ID',
  6286. 'ig-NG',
  6287. 'ii-CN',
  6288. 'is-IS',
  6289. 'it-CH',
  6290. 'it-IT',
  6291. 'ja-JP',
  6292. 'ka-GE',
  6293. 'kk-KZ',
  6294. 'kl-GL',
  6295. 'km-KH',
  6296. 'kn-IN',
  6297. 'ko-KR',
  6298. 'ky-KG',
  6299. 'lb-LU',
  6300. 'lo-LA',
  6301. 'lt-LT',
  6302. 'lv-LV',
  6303. 'mi-NZ',
  6304. 'mk-MK',
  6305. 'ml-IN',
  6306. 'mn-MN',
  6307. 'mr-IN',
  6308. 'ms-BN',
  6309. 'ms-MY',
  6310. 'mt-MT',
  6311. 'nb-NO',
  6312. 'ne-NP',
  6313. 'nl-BE',
  6314. 'nl-NL',
  6315. 'nn-NO',
  6316. 'oc-FR',
  6317. 'or-IN',
  6318. 'pa-IN',
  6319. 'pl-PL',
  6320. 'ps-AF',
  6321. 'pt-BR',
  6322. 'pt-PT',
  6323. 'rm-CH',
  6324. 'ro-RO',
  6325. 'ru-RU',
  6326. 'rw-RW',
  6327. 'sa-IN',
  6328. 'se-FI',
  6329. 'se-NO',
  6330. 'se-SE',
  6331. 'si-LK',
  6332. 'sk-SK',
  6333. 'sl-SI',
  6334. 'sq-AL',
  6335. 'sv-FI',
  6336. 'sv-SE',
  6337. 'sw-KE',
  6338. 'ta-IN',
  6339. 'te-IN',
  6340. 'th-TH',
  6341. 'tk-TM',
  6342. 'tn-ZA',
  6343. 'tr-TR',
  6344. 'tt-RU',
  6345. 'ug-CN',
  6346. 'uk-UA',
  6347. 'ur-PK',
  6348. 'vi-VN',
  6349. 'wo-SN',
  6350. 'xh-ZA',
  6351. 'yo-NG',
  6352. 'zh-CN',
  6353. 'zh-HK',
  6354. 'zh-MO',
  6355. 'zh-SG',
  6356. 'zh-TW',
  6357. 'zu-ZA',
  6358. );
  6359. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  6360. if (in_array($buildprimarykeytotest, $locales)) return strtolower($countrycode).'_'.strtoupper($countrycode);
  6361. foreach ($locales as $locale)
  6362. {
  6363. $locale_language = locale_get_primary_language($locale);
  6364. $locale_region = locale_get_region($locale);
  6365. if (strtoupper($countrycode) == $locale_region)
  6366. {
  6367. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  6368. return strtolower($locale_language).'_'.strtoupper($locale_region);
  6369. }
  6370. }
  6371. return null;
  6372. }
  6373. /**
  6374. * Complete or removed entries into a head array (used to build tabs).
  6375. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  6376. * Or by change using hook completeTabsHead
  6377. *
  6378. * @param Conf $conf Object conf
  6379. * @param Translate $langs Object langs
  6380. * @param object|null $object Object object
  6381. * @param array $head Object head
  6382. * @param int $h New position to fill
  6383. * @param string $type Value for object where objectvalue can be
  6384. * 'thirdparty' to add a tab in third party view
  6385. * 'intervention' to add a tab in intervention view
  6386. * 'supplier_order' to add a tab in supplier order view
  6387. * 'supplier_invoice' to add a tab in supplier invoice view
  6388. * 'invoice' to add a tab in customer invoice view
  6389. * 'order' to add a tab in customer order view
  6390. * 'contract' to add a tabl in contract view
  6391. * 'product' to add a tab in product view
  6392. * 'propal' to add a tab in propal view
  6393. * 'user' to add a tab in user view
  6394. * 'group' to add a tab in group view
  6395. * 'member' to add a tab in fundation member view
  6396. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  6397. * 'ecm' to add a tab for another ecm view
  6398. * 'stock' to add a tab for warehouse view
  6399. * @param string $mode 'add' to complete head, 'remove' to remove entries
  6400. * @return void
  6401. */
  6402. function complete_head_from_modules($conf,$langs,$object,&$head,&$h,$type,$mode='add')
  6403. {
  6404. global $hookmanager;
  6405. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  6406. {
  6407. foreach ($conf->modules_parts['tabs'][$type] as $value)
  6408. {
  6409. $values=explode(':',$value);
  6410. if ($mode == 'add' && ! preg_match('/^\-/',$values[1]))
  6411. {
  6412. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  6413. {
  6414. if ($values[0] != $type) continue;
  6415. if (verifCond($values[4]))
  6416. {
  6417. if ($values[3]) $langs->load($values[3]);
  6418. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  6419. {
  6420. $substitutionarray=array();
  6421. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  6422. $label=make_substitutions($reg[1], $substitutionarray);
  6423. }
  6424. else $label=$langs->trans($values[2]);
  6425. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[5]), 1);
  6426. $head[$h][1] = $label;
  6427. $head[$h][2] = str_replace('+','',$values[1]);
  6428. $h++;
  6429. }
  6430. }
  6431. else if (count($values) == 5) // deprecated
  6432. {
  6433. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  6434. if ($values[0] != $type) continue;
  6435. if ($values[3]) $langs->load($values[3]);
  6436. if (preg_match('/SUBSTITUTION_([^_]+)/i',$values[2],$reg))
  6437. {
  6438. $substitutionarray=array();
  6439. complete_substitutions_array($substitutionarray,$langs,$object,array('needforkey'=>$values[2]));
  6440. $label=make_substitutions($reg[1], $substitutionarray);
  6441. }
  6442. else $label=$langs->trans($values[2]);
  6443. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && ! empty($object->id))?$object->id:''), $values[4]), 1);
  6444. $head[$h][1] = $label;
  6445. $head[$h][2] = str_replace('+','',$values[1]);
  6446. $h++;
  6447. }
  6448. }
  6449. else if ($mode == 'remove' && preg_match('/^\-/',$values[1]))
  6450. {
  6451. if ($values[0] != $type) continue;
  6452. $tabname=str_replace('-','',$values[1]);
  6453. foreach($head as $key => $val)
  6454. {
  6455. $condition = (! empty($values[3]) ? verifCond($values[3]) : 1);
  6456. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  6457. if ($head[$key][2]==$tabname && $condition)
  6458. {
  6459. unset($head[$key]);
  6460. break;
  6461. }
  6462. }
  6463. }
  6464. }
  6465. }
  6466. // No need to make a return $head. Var is modified as a reference
  6467. if (! empty($hookmanager))
  6468. {
  6469. $parameters=array('object' => $object, 'mode' => $mode, 'head' => $head);
  6470. $reshook=$hookmanager->executeHooks('completeTabsHead', $parameters);
  6471. if ($reshook > 0)
  6472. {
  6473. $head = $hookmanager->resArray;
  6474. $h = count($head);
  6475. }
  6476. }
  6477. }
  6478. /**
  6479. * Print common footer :
  6480. * conf->global->MAIN_HTML_FOOTER
  6481. * js for switch of menu hider
  6482. * js for conf->global->MAIN_GOOGLE_AN_ID
  6483. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  6484. * js for conf->logbuffer
  6485. *
  6486. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  6487. * @return void
  6488. */
  6489. function printCommonFooter($zone='private')
  6490. {
  6491. global $conf, $hookmanager, $user;
  6492. global $action;
  6493. global $micro_start_time;
  6494. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  6495. else print "\n".'<!-- Common footer for public page -->'."\n";
  6496. // A div to store page_y POST parameter so we can read it using javascript
  6497. print "\n<!-- A div to store page_y POST paramater -->\n";
  6498. print '<div id="page_y" style="display: none;">'.$_POST['page_y'].'</div>'."\n";
  6499. $parameters=array();
  6500. $reshook=$hookmanager->executeHooks('printCommonFooter',$parameters); // Note that $action and $object may have been modified by some hooks
  6501. if (empty($reshook))
  6502. {
  6503. if (! empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  6504. print "\n";
  6505. if (! empty($conf->use_javascript_ajax))
  6506. {
  6507. print '<script type="text/javascript" language="javascript">'."\n";
  6508. print 'jQuery(document).ready(function() {'."\n";
  6509. if ($zone == 'private' && empty($conf->dol_use_jmobile))
  6510. {
  6511. print "\n";
  6512. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  6513. print 'jQuery(".menuhider").click(function() {';
  6514. print ' console.log("We click on .menuhider");'."\n";
  6515. //print " $('.side-nav').animate({width:'toggle'},200);\n"; // OK with eldy theme but not with md
  6516. print " $('.side-nav').toggle()\n";
  6517. print " $('.login_block').toggle()\n";
  6518. print '});'."\n";
  6519. }
  6520. // Management of focus and mandatory for fields
  6521. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))))
  6522. {
  6523. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  6524. $relativepathstring = $_SERVER["PHP_SELF"];
  6525. // Clean $relativepathstring
  6526. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
  6527. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  6528. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  6529. $tmpqueryarraywehave=explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  6530. if (!empty($user->default_values[$relativepathstring]['focus']))
  6531. {
  6532. foreach($user->default_values[$relativepathstring]['focus'] as $defkey => $defval)
  6533. {
  6534. $qualified = 0;
  6535. if ($defkey != '_noquery_')
  6536. {
  6537. $tmpqueryarraytohave=explode('&', $defkey);
  6538. $foundintru=0;
  6539. foreach($tmpqueryarraytohave as $tmpquerytohave)
  6540. {
  6541. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  6542. }
  6543. if (! $foundintru) $qualified=1;
  6544. //var_dump($defkey.'-'.$qualified);
  6545. }
  6546. else $qualified = 1;
  6547. if ($qualified)
  6548. {
  6549. foreach($defval as $paramkey => $paramval)
  6550. {
  6551. // Set focus on field
  6552. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  6553. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  6554. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  6555. }
  6556. }
  6557. }
  6558. }
  6559. if (!empty($user->default_values[$relativepathstring]['mandatory']))
  6560. {
  6561. foreach($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval)
  6562. {
  6563. $qualified = 0;
  6564. if ($defkey != '_noquery_')
  6565. {
  6566. $tmpqueryarraytohave=explode('&', $defkey);
  6567. $foundintru=0;
  6568. foreach($tmpqueryarraytohave as $tmpquerytohave)
  6569. {
  6570. if (! in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru=1;
  6571. }
  6572. if (! $foundintru) $qualified=1;
  6573. //var_dump($defkey.'-'.$qualified);
  6574. }
  6575. else $qualified = 1;
  6576. if ($qualified)
  6577. {
  6578. foreach($defval as $paramkey => $paramval)
  6579. {
  6580. // Add property 'required' on input
  6581. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6582. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  6583. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
  6584. }
  6585. }
  6586. }
  6587. }
  6588. }
  6589. print '});'."\n";
  6590. // Google Analytics
  6591. // TODO Add a hook here
  6592. if (! empty($conf->google->enabled) && ! empty($conf->global->MAIN_GOOGLE_AN_ID))
  6593. {
  6594. if (($conf->dol_use_jmobile != 4))
  6595. {
  6596. print "\n";
  6597. print "/* JS CODE TO ENABLE for google analtics tag */\n";
  6598. print ' var _gaq = _gaq || [];'."\n";
  6599. print ' _gaq.push([\'_setAccount\', \''.$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
  6600. print ' _gaq.push([\'_trackPageview\']);'."\n";
  6601. print ''."\n";
  6602. print ' (function() {'."\n";
  6603. print ' var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
  6604. print ' ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
  6605. print ' var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
  6606. print ' })();'."\n";
  6607. }
  6608. }
  6609. // End of tuning
  6610. if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || ! empty($conf->global->MAIN_SHOW_TUNING_INFO))
  6611. {
  6612. print "\n";
  6613. print "/* JS CODE TO ENABLE to add memory info */\n";
  6614. print 'window.console && console.log("';
  6615. if (! empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  6616. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED)?$conf->global->MAIN_OPTIMIZE_SPEED:'off');
  6617. if (! empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  6618. {
  6619. $micro_end_time = microtime(true);
  6620. print ' - Build time: '.ceil(1000*($micro_end_time-$micro_start_time)).' ms';
  6621. }
  6622. if (function_exists("memory_get_usage"))
  6623. {
  6624. print ' - Mem: '.memory_get_usage();
  6625. }
  6626. if (function_exists("xdebug_memory_usage"))
  6627. {
  6628. print ' - XDebug time: '.ceil(1000*xdebug_time_index()).' ms';
  6629. print ' - XDebug mem: '.xdebug_memory_usage();
  6630. print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
  6631. }
  6632. if (function_exists("zend_loader_file_encoded"))
  6633. {
  6634. print ' - Zend encoded file: '.(zend_loader_file_encoded()?'yes':'no');
  6635. }
  6636. print '");'."\n";
  6637. }
  6638. print "\n".'</script>'."\n";
  6639. }
  6640. // Add Xdebug coverage of code
  6641. if (defined('XDEBUGCOVERAGE'))
  6642. {
  6643. print_r(xdebug_get_code_coverage());
  6644. }
  6645. // If there is some logs in buffer to show
  6646. if (count($conf->logbuffer))
  6647. {
  6648. print "\n";
  6649. print "<!-- Start of log output\n";
  6650. //print '<div class="hidden">'."\n";
  6651. foreach($conf->logbuffer as $logline)
  6652. {
  6653. print $logline."<br>\n";
  6654. }
  6655. //print '</div>'."\n";
  6656. print "End of log output -->\n";
  6657. }
  6658. }
  6659. }
  6660. /**
  6661. * Split a string with 2 keys into key array.
  6662. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  6663. *
  6664. * @param string $string String to explode
  6665. * @param string $delimiter Delimiter between each couple of data
  6666. * @param string $kv Delimiter between key and value
  6667. * @return array Array of data exploded
  6668. */
  6669. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  6670. {
  6671. if ($a = explode($delimiter, $string))
  6672. {
  6673. $ka = array();
  6674. foreach ($a as $s) { // each part
  6675. if ($s) {
  6676. if ($pos = strpos($s, $kv)) { // key/value delimiter
  6677. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  6678. } else { // key delimiter not found
  6679. $ka[] = trim($s);
  6680. }
  6681. }
  6682. }
  6683. return $ka;
  6684. }
  6685. return array();
  6686. }
  6687. /**
  6688. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  6689. *
  6690. * @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.
  6691. * @return string HTML code to set focus
  6692. */
  6693. function dol_set_focus($selector)
  6694. {
  6695. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  6696. print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  6697. }
  6698. /**
  6699. * Return getmypid() or random PID when function is disabled
  6700. * Some web hosts disable this php function for security reasons
  6701. * and sometimes we can't redeclare function
  6702. *
  6703. * @return int
  6704. */
  6705. function dol_getmypid()
  6706. {
  6707. if (! function_exists('getmypid')) {
  6708. return mt_rand(1,32768);
  6709. } else {
  6710. return getmypid();
  6711. }
  6712. }
  6713. /**
  6714. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  6715. *
  6716. * @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). Example: array("p.field1","p.field2")
  6717. * @param string $value The value to look for.
  6718. * If param $mode is 0, can contains several keywords separated with a space or |
  6719. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  6720. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  6721. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  6722. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  6723. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  6724. * @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')
  6725. * 3=value is list of string separated with comma (Example 'text 1,text 2'), 4=value is a list of ID separated with comma (Example '1,3,4') for search into a multiselect string ('1,2')
  6726. * @param integer $nofirstand 1=Do not output the first 'AND'
  6727. * @return string $res The statement to append to the SQL query
  6728. */
  6729. function natural_search($fields, $value, $mode=0, $nofirstand=0)
  6730. {
  6731. global $db,$langs;
  6732. $value=trim($value);
  6733. if ($mode == 0)
  6734. {
  6735. $value=preg_replace('/\*/','%',$value); // Replace * with %
  6736. }
  6737. if ($mode == 1)
  6738. {
  6739. $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
  6740. }
  6741. $value = preg_replace('/\s*\|\s*/','|', $value);
  6742. $crits = explode(' ', $value);
  6743. $res = '';
  6744. if (! is_array($fields)) $fields = array($fields);
  6745. $nboffields = count($fields);
  6746. $end2 = count($crits);
  6747. $j = 0;
  6748. foreach ($crits as $crit)
  6749. {
  6750. $i = 0; $i2 = 0;
  6751. $newres = '';
  6752. foreach ($fields as $field)
  6753. {
  6754. if ($mode == 1)
  6755. {
  6756. $operator='=';
  6757. $newcrit = preg_replace('/([<>=]+)/','',trim($crit));
  6758. preg_match('/([<>=]+)/',trim($crit), $reg);
  6759. if ($reg[1])
  6760. {
  6761. $operator = $reg[1];
  6762. }
  6763. if ($newcrit != '')
  6764. {
  6765. $numnewcrit = price2num($newcrit);
  6766. if (is_numeric($numnewcrit))
  6767. {
  6768. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' '.$operator.' '.$numnewcrit;
  6769. }
  6770. else
  6771. {
  6772. $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false
  6773. }
  6774. $i2++; // a criteria was added to string
  6775. }
  6776. }
  6777. else if ($mode == 2)
  6778. {
  6779. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $db->escape(trim($crit)) . ")";
  6780. $i2++; // a criteria was added to string
  6781. }
  6782. else if ($mode == 3)
  6783. {
  6784. $tmparray=explode(',',trim($crit));
  6785. if (count($tmparray))
  6786. {
  6787. $listofcodes='';
  6788. foreach($tmparray as $val)
  6789. {
  6790. if ($val)
  6791. {
  6792. $listofcodes.=($listofcodes?',':'');
  6793. $listofcodes.="'".$db->escape(trim($val))."'";
  6794. }
  6795. }
  6796. $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $listofcodes . ")";
  6797. $i2++; // a criteria was added to string
  6798. }
  6799. }
  6800. else if ($mode == 4)
  6801. {
  6802. $tmparray=explode(',',trim($crit));
  6803. if (count($tmparray))
  6804. {
  6805. $listofcodes='';
  6806. foreach($tmparray as $val)
  6807. {
  6808. if ($val)
  6809. {
  6810. $newres .= ($i2 > 0 ? ' OR (' : '(') . $field . ' LIKE \'' . $db->escape(trim($val)) . ',%\'';
  6811. $newres .= ' OR '. $field . ' = \'' . $db->escape(trim($val)) . '\'';
  6812. $newres .= ' OR '. $field . ' LIKE \'%,' . $db->escape(trim($val)) . '\'';
  6813. $newres .= ' OR '. $field . ' LIKE \'%,' . $db->escape(trim($val)) . ',%\'';
  6814. $newres .= ')';
  6815. $i2++;
  6816. }
  6817. }
  6818. }
  6819. }
  6820. else // $mode=0
  6821. {
  6822. $textcrit = '';
  6823. $tmpcrits = explode('|',$crit);
  6824. $i3 = 0;
  6825. foreach($tmpcrits as $tmpcrit)
  6826. {
  6827. if(empty($tmpcrit)) continue;
  6828. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  6829. if (preg_match('/\.(id|rowid)$/', $field)) // Special case for rowid that is sometimes a ref so used as a search field
  6830. {
  6831. $newres .= $field . " = " . (is_numeric(trim($tmpcrit))?trim($tmpcrit):'0');
  6832. }
  6833. else
  6834. {
  6835. $newres .= $field . " LIKE '";
  6836. $tmpcrit=trim($tmpcrit);
  6837. $tmpcrit2=$tmpcrit;
  6838. $tmpbefore='%'; $tmpafter='%';
  6839. if (preg_match('/^[\^\$]/', $tmpcrit))
  6840. {
  6841. $tmpbefore='';
  6842. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  6843. }
  6844. if (preg_match('/[\^\$]$/', $tmpcrit))
  6845. {
  6846. $tmpafter='';
  6847. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  6848. }
  6849. $newres .= $tmpbefore;
  6850. $newres .= $db->escape($tmpcrit2);
  6851. $newres .= $tmpafter;
  6852. $newres .= "'";
  6853. if ($tmpcrit2 == '')
  6854. {
  6855. $newres .= ' OR ' . $field . " IS NULL";
  6856. }
  6857. }
  6858. $i3++;
  6859. }
  6860. $i2++; // a criteria was added to string
  6861. }
  6862. $i++;
  6863. }
  6864. if ($newres) $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') .$newres . ($i2 > 1 ? ')' : '');
  6865. $j++;
  6866. }
  6867. $res = ($nofirstand?"":" AND ")."(" . $res . ")";
  6868. //print 'xx'.$res.'yy';
  6869. return $res;
  6870. }
  6871. /**
  6872. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  6873. *
  6874. * @param Object $object Object
  6875. * @return string Url string
  6876. */
  6877. function showDirectDownloadLink($object)
  6878. {
  6879. global $conf, $langs;
  6880. $out='';
  6881. $url = $object->getLastMainDocLink($object->element);
  6882. if ($url)
  6883. {
  6884. $out.= img_picto('','object_globe.png').' '.$langs->trans("DirectDownloadLink").'<br>';
  6885. $out.= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
  6886. $out.= ajax_autoselect("directdownloadlink", 0);
  6887. }
  6888. return $out;
  6889. }
  6890. /**
  6891. * Return the filename of file to get the thumbs
  6892. *
  6893. * @param string $file Original filename (full or relative path)
  6894. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  6895. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  6896. * @return string New file name (full or relative path, including the thumbs/)
  6897. */
  6898. function getImageFileNameForSize($file, $extName, $extImgTarget='')
  6899. {
  6900. $dirName = dirname($file);
  6901. if ($dirName == '.') $dirName='';
  6902. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i','',$file); // We remove extension, whatever is its case
  6903. $fileName = basename($fileName);
  6904. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i',$file)?'.jpg':'');
  6905. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i',$file)?'.jpeg':'');
  6906. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i',$file)?'.gif':'');
  6907. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i',$file)?'.png':'');
  6908. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i',$file)?'.bmp':'');
  6909. if (! $extImgTarget) return $file;
  6910. $subdir='';
  6911. if ($extName) $subdir = 'thumbs/';
  6912. return ($dirName?$dirName.'/':'').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  6913. }
  6914. /**
  6915. * Return URL we can use for advanced preview links
  6916. *
  6917. * @param string $modulepart propal, facture, facture_fourn, ...
  6918. * @param string $relativepath Relative path of docs.
  6919. * @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)
  6920. * @param string $param More param on http links
  6921. * @return string|array Output string with href link or array with all components of link
  6922. */
  6923. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata=0, $param='')
  6924. {
  6925. global $conf, $langs;
  6926. if (empty($conf->use_javascript_ajax)) return '';
  6927. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'svg+xml');
  6928. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  6929. //$mime_preview[]='archive';
  6930. $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview);
  6931. if ($alldata == 1)
  6932. {
  6933. if ($num_mime !== false) return array('target'=>'_blank', 'css'=>'documentpreview', 'url'=>DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param?'&'.$param:''), 'mime'=>dol_mimetype($relativepath), );
  6934. else return array();
  6935. }
  6936. // old behavior
  6937. 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')).'\')';
  6938. else return '';
  6939. }
  6940. /**
  6941. * Make content of an input box selected when we click into input field.
  6942. *
  6943. * @param string $htmlname Id of html object
  6944. * @param string $addlink Add a 'link to' after
  6945. * @return string
  6946. */
  6947. function ajax_autoselect($htmlname, $addlink='')
  6948. {
  6949. global $langs;
  6950. $out = '<script type="text/javascript">
  6951. jQuery(document).ready(function () {
  6952. jQuery("#'.$htmlname.'").click(function() { jQuery(this).select(); } );
  6953. });
  6954. </script>';
  6955. if ($addlink) $out.=' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  6956. return $out;
  6957. }
  6958. /**
  6959. * Return mime type of a file
  6960. *
  6961. * @param string $file Filename we looking for MIME type
  6962. * @param string $default Default mime type if extension not found in known list
  6963. * @param int $mode 0=Return full mime, 1=otherwise short mime string, 2=image for mime type, 3=source language, 4=css of font fa
  6964. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  6965. * @see image_format_supported (images.lib.php)
  6966. */
  6967. function dol_mimetype($file, $default='application/octet-stream', $mode=0)
  6968. {
  6969. $mime=$default;
  6970. $imgmime='other.png';
  6971. $famime='file-o';
  6972. $srclang='';
  6973. $tmpfile=preg_replace('/\.noexe$/','',$file);
  6974. // Text files
  6975. if (preg_match('/\.txt$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6976. if (preg_match('/\.rtx$/i',$tmpfile)) { $mime='text/richtext'; $imgmime='text.png'; $famime='file-text-o'; }
  6977. if (preg_match('/\.csv$/i',$tmpfile)) { $mime='text/csv'; $imgmime='text.png'; $famime='file-text-o'; }
  6978. if (preg_match('/\.tsv$/i',$tmpfile)) { $mime='text/tab-separated-values'; $imgmime='text.png'; $famime='file-text-o'; }
  6979. if (preg_match('/\.(cf|conf|log)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6980. if (preg_match('/\.ini$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='ini'; $famime='file-text-o'; }
  6981. if (preg_match('/\.css$/i',$tmpfile)) { $mime='text/css'; $imgmime='css.png'; $srclang='css'; $famime='file-text-o'; }
  6982. // Certificate files
  6983. if (preg_match('/\.(crt|cer|key|pub)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $famime='file-text-o'; }
  6984. // HTML/XML
  6985. if (preg_match('/\.(html|htm|shtml)$/i',$tmpfile)) { $mime='text/html'; $imgmime='html.png'; $srclang='html'; $famime='file-text-o'; }
  6986. if (preg_match('/\.(xml|xhtml)$/i',$tmpfile)) { $mime='text/xml'; $imgmime='other.png'; $srclang='xml'; $famime='file-text-o'; }
  6987. // Languages
  6988. if (preg_match('/\.bas$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='bas'; $famime='file-code-o'; }
  6989. if (preg_match('/\.(c)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='c'; $famime='file-code-o'; }
  6990. if (preg_match('/\.(cpp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='cpp'; $famime='file-code-o'; }
  6991. if (preg_match('/\.(h)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='h'; $famime='file-code-o'; }
  6992. if (preg_match('/\.(java|jsp)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='java'; $famime='file-code-o'; }
  6993. if (preg_match('/\.php([0-9]{1})?$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; $famime='file-code-o'; }
  6994. if (preg_match('/\.phtml$/i',$tmpfile)) { $mime='text/plain'; $imgmime='php.png'; $srclang='php'; $famime='file-code-o'; }
  6995. if (preg_match('/\.(pl|pm)$/i',$tmpfile)) { $mime='text/plain'; $imgmime='pl.png'; $srclang='perl'; $famime='file-code-o'; }
  6996. if (preg_match('/\.sql$/i',$tmpfile)) { $mime='text/plain'; $imgmime='text.png'; $srclang='sql'; $famime='file-code-o'; }
  6997. if (preg_match('/\.js$/i',$tmpfile)) { $mime='text/x-javascript'; $imgmime='jscript.png'; $srclang='js'; $famime='file-code-o'; }
  6998. // Open office
  6999. if (preg_match('/\.odp$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.presentation'; $imgmime='ooffice.png'; $famime='file-powerpoint-o'; }
  7000. if (preg_match('/\.ods$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.spreadsheet'; $imgmime='ooffice.png'; $famime='file-excel-o'; }
  7001. if (preg_match('/\.odt$/i',$tmpfile)) { $mime='application/vnd.oasis.opendocument.text'; $imgmime='ooffice.png'; $famime='file-word-o'; }
  7002. // MS Office
  7003. if (preg_match('/\.mdb$/i',$tmpfile)) { $mime='application/msaccess'; $imgmime='mdb.png'; $famime='file-o'; }
  7004. if (preg_match('/\.doc(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; $famime='file-word-o'; }
  7005. if (preg_match('/\.dot(x|m)?$/i',$tmpfile)) { $mime='application/msword'; $imgmime='doc.png'; $famime='file-word-o'; }
  7006. if (preg_match('/\.xlt(x)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7007. if (preg_match('/\.xla(m)?$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7008. if (preg_match('/\.xls$/i',$tmpfile)) { $mime='application/vnd.ms-excel'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7009. if (preg_match('/\.xls(b|m|x)$/i',$tmpfile)) { $mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime='xls.png'; $famime='file-excel-o'; }
  7010. if (preg_match('/\.pps(m|x)?$/i',$tmpfile)) { $mime='application/vnd.ms-powerpoint'; $imgmime='ppt.png'; $famime='file-powerpoint-o'; }
  7011. if (preg_match('/\.ppt(m|x)?$/i',$tmpfile)) { $mime='application/x-mspowerpoint'; $imgmime='ppt.png'; $famime='file-powerpoint-o'; }
  7012. // Other
  7013. if (preg_match('/\.pdf$/i',$tmpfile)) { $mime='application/pdf'; $imgmime='pdf.png'; $famime='file-pdf-o'; }
  7014. // Scripts
  7015. if (preg_match('/\.bat$/i',$tmpfile)) { $mime='text/x-bat'; $imgmime='script.png'; $srclang='dos'; $famime='file-code-o'; }
  7016. if (preg_match('/\.sh$/i',$tmpfile)) { $mime='text/x-sh'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7017. if (preg_match('/\.ksh$/i',$tmpfile)) { $mime='text/x-ksh'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7018. if (preg_match('/\.bash$/i',$tmpfile)) { $mime='text/x-bash'; $imgmime='script.png'; $srclang='bash'; $famime='file-code-o'; }
  7019. // Images
  7020. if (preg_match('/\.ico$/i',$tmpfile)) { $mime='image/x-icon'; $imgmime='image.png'; $famime='file-image-o'; }
  7021. if (preg_match('/\.(jpg|jpeg)$/i',$tmpfile)) { $mime='image/jpeg'; $imgmime='image.png'; $famime='file-image-o'; }
  7022. if (preg_match('/\.png$/i',$tmpfile)) { $mime='image/png'; $imgmime='image.png'; $famime='file-image-o'; }
  7023. if (preg_match('/\.gif$/i',$tmpfile)) { $mime='image/gif'; $imgmime='image.png'; $famime='file-image-o'; }
  7024. if (preg_match('/\.bmp$/i',$tmpfile)) { $mime='image/bmp'; $imgmime='image.png'; $famime='file-image-o'; }
  7025. if (preg_match('/\.(tif|tiff)$/i',$tmpfile)) { $mime='image/tiff'; $imgmime='image.png'; $famime='file-image-o'; }
  7026. if (preg_match('/\.svg$/i',$tmpfile)) { $mime='image/svg+xml';$imgmime='image.png'; $famime='file-image-o'; }
  7027. // Calendar
  7028. if (preg_match('/\.vcs$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; $famime='file-text-o'; }
  7029. if (preg_match('/\.ics$/i',$tmpfile)) { $mime='text/calendar'; $imgmime='other.png'; $famime='file-text-o'; }
  7030. // Other
  7031. if (preg_match('/\.torrent$/i',$tmpfile)) { $mime='application/x-bittorrent'; $imgmime='other.png'; $famime='file-o'; }
  7032. // Audio
  7033. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i',$tmpfile)) { $mime='audio'; $imgmime='audio.png'; $famime='file-audio-o'; }
  7034. // Video
  7035. if (preg_match('/\.ogv$/i',$tmpfile)) { $mime='video/ogg'; $imgmime='video.png'; $famime='file-video-o'; }
  7036. if (preg_match('/\.webm$/i',$tmpfile)) { $mime='video/webm'; $imgmime='video.png'; $famime='file-video-o'; }
  7037. if (preg_match('/\.avi$/i',$tmpfile)) { $mime='video/x-msvideo'; $imgmime='video.png'; $famime='file-video-o'; }
  7038. if (preg_match('/\.divx$/i',$tmpfile)) { $mime='video/divx'; $imgmime='video.png'; $famime='file-video-o'; }
  7039. if (preg_match('/\.xvid$/i',$tmpfile)) { $mime='video/xvid'; $imgmime='video.png'; $famime='file-video-o'; }
  7040. if (preg_match('/\.(wmv|mpg|mpeg)$/i',$tmpfile)) { $mime='video'; $imgmime='video.png'; $famime='file-video-o'; }
  7041. // Archive
  7042. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i',$tmpfile)) { $mime='archive'; $imgmime='archive.png'; $famime='file-archive-o'; } // application/xxx where zzz is zip, ...
  7043. // Exe
  7044. if (preg_match('/\.(exe|com)$/i',$tmpfile)) { $mime='application/octet-stream'; $imgmime='other.png'; $famime='file-o'; }
  7045. // Lib
  7046. if (preg_match('/\.(dll|lib|o|so|a)$/i',$tmpfile)) { $mime='library'; $imgmime='library.png'; $famime='file-o'; }
  7047. // Err
  7048. if (preg_match('/\.err$/i',$tmpfile)) { $mime='error'; $imgmime='error.png'; $famime='file-text-o'; }
  7049. // Return string
  7050. if ($mode == 1)
  7051. {
  7052. $tmp=explode('/',$mime);
  7053. return (! empty($tmp[1])?$tmp[1]:$tmp[0]);
  7054. }
  7055. if ($mode == 2)
  7056. {
  7057. return $imgmime;
  7058. }
  7059. if ($mode == 3)
  7060. {
  7061. return $srclang;
  7062. }
  7063. if ($mode == 4)
  7064. {
  7065. return $famime;
  7066. }
  7067. return $mime;
  7068. }
  7069. /**
  7070. * Return value from dictionary
  7071. *
  7072. * @param string $tablename name of dictionary
  7073. * @param string $field the value to return
  7074. * @param int $id id of line
  7075. * @param bool $checkentity add filter on entity
  7076. * @param string $rowidfield name of the column rowid
  7077. * @return string
  7078. */
  7079. function getDictvalue($tablename, $field, $id, $checkentity=false, $rowidfield='rowid')
  7080. {
  7081. global $dictvalues,$db,$langs;
  7082. if (!isset($dictvalues[$tablename]))
  7083. {
  7084. $dictvalues[$tablename] = array();
  7085. $sql = 'SELECT * FROM '.$tablename.' WHERE 1';
  7086. if ($checkentity) $sql.= ' AND entity IN (0,'.getEntity($tablename).')';
  7087. $resql = $db->query($sql);
  7088. if ($resql)
  7089. {
  7090. while ($obj = $db->fetch_object($resql))
  7091. {
  7092. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  7093. }
  7094. }
  7095. else
  7096. {
  7097. dol_print_error($db);
  7098. }
  7099. }
  7100. if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
  7101. else // Not found
  7102. {
  7103. if ($id > 0) return $id;
  7104. return '';
  7105. }
  7106. }
  7107. /**
  7108. * Return true if the color is light
  7109. *
  7110. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  7111. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  7112. */
  7113. function colorIsLight($stringcolor)
  7114. {
  7115. $res = -1;
  7116. if (!empty($stringcolor))
  7117. {
  7118. $res = 0;
  7119. $tmp=explode(',', $stringcolor);
  7120. if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
  7121. {
  7122. $r = $tmp[0];
  7123. $g = $tmp[1];
  7124. $b = $tmp[2];
  7125. }
  7126. else
  7127. {
  7128. $hexr=$stringcolor[0].$stringcolor[1];
  7129. $hexg=$stringcolor[2].$stringcolor[3];
  7130. $hexb=$stringcolor[4].$stringcolor[5];
  7131. $r = hexdec($hexr);
  7132. $g = hexdec($hexg);
  7133. $b = hexdec($hexb);
  7134. }
  7135. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  7136. if ($bright > 0.6) $res = 1;
  7137. }
  7138. return $res;
  7139. }
  7140. /**
  7141. * Function to test if an entry is enabled or not
  7142. *
  7143. * @param string $type_user 0=We test for internal user, 1=We test for external user
  7144. * @param array $menuentry Array for feature entry to test
  7145. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  7146. * @return int 0=Hide, 1=Show, 2=Show gray
  7147. */
  7148. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  7149. {
  7150. global $conf;
  7151. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  7152. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  7153. if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
  7154. if ($type_user && $menuentry['module'])
  7155. {
  7156. $tmploops=explode('|',$menuentry['module']);
  7157. $found=0;
  7158. foreach($tmploops as $tmploop)
  7159. {
  7160. if (in_array($tmploop, $listofmodulesforexternal)) {
  7161. $found++; break;
  7162. }
  7163. }
  7164. if (! $found) return 0; // Entry is for menus all excluded to external users
  7165. }
  7166. if (! $menuentry['perms'] && $type_user) return 0; // No permissions and user is external
  7167. if (! $menuentry['perms'] && ! empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  7168. if (! $menuentry['perms']) return 2; // No permissions and user is external
  7169. return 1;
  7170. }
  7171. /**
  7172. * Round to next multiple.
  7173. *
  7174. * @param double $n Number to round up
  7175. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  7176. * @return integer Value rounded.
  7177. */
  7178. function roundUpToNextMultiple($n, $x=5)
  7179. {
  7180. return (ceil($n)%$x === 0) ? ceil($n) : round(($n+$x/2)/$x)*$x;
  7181. }