functions.lib.php 297 KB

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