functions.lib.php 426 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  13. * Copyright (C) 2014 Cédric GROSS <c.gross@kreiz-it.fr>
  14. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  15. * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  16. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. * Copyright (C) 2021 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  20. *
  21. * This program is free software; you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation; either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  33. * or see https://www.gnu.org/
  34. */
  35. /**
  36. * \file htdocs/core/lib/functions.lib.php
  37. * \brief A set of functions for Dolibarr
  38. * This file contains all frequently used functions.
  39. */
  40. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  41. /**
  42. * Return dolibarr global constant string value
  43. * @param string $key key to return value, return '' if not set
  44. * @param string $default value to return
  45. * @return string
  46. */
  47. function getDolGlobalString($key, $default = '')
  48. {
  49. global $conf;
  50. // return $conf->global->$key ?? $default;
  51. return (string) (empty($conf->global->$key) ? $default : $conf->global->$key);
  52. }
  53. /**
  54. * Return dolibarr global constant int value
  55. * @param string $key key to return value, return 0 if not set
  56. * @param int $default value to return
  57. * @return int
  58. */
  59. function getDolGlobalInt($key, $default = 0)
  60. {
  61. global $conf;
  62. // return $conf->global->$key ?? $default;
  63. return (int) (empty($conf->global->$key) ? $default : $conf->global->$key);
  64. }
  65. /**
  66. * Return a DoliDB instance (database handler).
  67. *
  68. * @param string $type Type of database (mysql, pgsql...)
  69. * @param string $host Address of database server
  70. * @param string $user Authorized username
  71. * @param string $pass Password
  72. * @param string $name Name of database
  73. * @param int $port Port of database server
  74. * @return DoliDB A DoliDB instance
  75. */
  76. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  77. {
  78. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  79. $class = 'DoliDB'.ucfirst($type);
  80. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  81. return $dolidb;
  82. }
  83. /**
  84. * Get list of entity id to use.
  85. *
  86. * @param string $element Current element
  87. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  88. * 'product', 'productprice', 'stock', 'bom', 'mo',
  89. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  90. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  91. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  92. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  93. * 'email_template', 'event', 'donation'
  94. * 'c_paiement', 'c_payment_term', ...
  95. * @param int $shared 0=Return id of current entity only,
  96. * 1=Return id of current entity + shared entities (default)
  97. * @param object $currentobject Current object if needed
  98. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  99. */
  100. function getEntity($element, $shared = 1, $currentobject = null)
  101. {
  102. global $conf, $mc, $hookmanager, $object, $action, $db;
  103. if (! is_object($hookmanager)) {
  104. $hookmanager = new HookManager($db);
  105. }
  106. // fix different element names (France to English)
  107. switch ($element) {
  108. case 'contrat':
  109. $element = 'contract';
  110. break; // "/contrat/class/contrat.class.php"
  111. case 'order_supplier':
  112. $element = 'supplier_order';
  113. break; // "/fourn/class/fournisseur.commande.class.php"
  114. }
  115. if (is_object($mc)) {
  116. $out = $mc->getEntity($element, $shared, $currentobject);
  117. } else {
  118. $out = '';
  119. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  120. if (in_array($element, $addzero)) {
  121. $out .= '0,';
  122. }
  123. $out .= ((int) $conf->entity);
  124. }
  125. // Manipulate entities to query on the fly
  126. $parameters = array(
  127. 'element' => $element,
  128. 'shared' => $shared,
  129. 'object' => $object,
  130. 'currentobject' => $currentobject,
  131. 'out' => $out
  132. );
  133. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  134. if (is_numeric($reshook)) {
  135. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  136. $out .= ','.$hookmanager->resPrint; // add
  137. } elseif ($reshook == 1) {
  138. $out = $hookmanager->resPrint; // replace
  139. }
  140. }
  141. return $out;
  142. }
  143. /**
  144. * Set entity id to use when to create an object
  145. *
  146. * @param object $currentobject Current object
  147. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  148. */
  149. function setEntity($currentobject)
  150. {
  151. global $conf, $mc;
  152. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  153. return $mc->setEntity($currentobject);
  154. } else {
  155. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  156. }
  157. }
  158. /**
  159. * Return if string has a name dedicated to store a secret
  160. *
  161. * @param string $keyname Name of key to test
  162. * @return boolean True if key is used to store a secret
  163. */
  164. function isASecretKey($keyname)
  165. {
  166. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  167. }
  168. /**
  169. * Return information about user browser
  170. *
  171. * Returns array with the following format:
  172. * array(
  173. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  174. * 'browserversion' => Browser version. Empty if unknown
  175. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  176. * 'layout' => (tablet|phone|classic)
  177. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  178. * 'tablet' => true/false
  179. * )
  180. *
  181. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  182. * @return array Check function documentation
  183. */
  184. function getBrowserInfo($user_agent)
  185. {
  186. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  187. $name = 'unknown';
  188. $version = '';
  189. $os = 'unknown';
  190. $phone = '';
  191. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  192. $detectmobile = new Mobile_Detect(null, $user_agent);
  193. $tablet = $detectmobile->isTablet();
  194. if ($detectmobile->isMobile()) {
  195. $phone = 'unknown';
  196. // If phone/smartphone, we set phone os name.
  197. if ($detectmobile->is('AndroidOS')) {
  198. $os = $phone = 'android';
  199. } elseif ($detectmobile->is('BlackBerryOS')) {
  200. $os = $phone = 'blackberry';
  201. } elseif ($detectmobile->is('iOS')) {
  202. $os = 'ios';
  203. $phone = 'iphone';
  204. } elseif ($detectmobile->is('PalmOS')) {
  205. $os = $phone = 'palm';
  206. } elseif ($detectmobile->is('SymbianOS')) {
  207. $os = 'symbian';
  208. } elseif ($detectmobile->is('webOS')) {
  209. $os = 'webos';
  210. } elseif ($detectmobile->is('MaemoOS')) {
  211. $os = 'maemo';
  212. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  213. $os = 'windows';
  214. }
  215. }
  216. // OS
  217. if (preg_match('/linux/i', $user_agent)) {
  218. $os = 'linux';
  219. } elseif (preg_match('/macintosh/i', $user_agent)) {
  220. $os = 'macintosh';
  221. } elseif (preg_match('/windows/i', $user_agent)) {
  222. $os = 'windows';
  223. }
  224. // Name
  225. $reg = array();
  226. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  227. $name = 'firefox';
  228. $version = $reg[2];
  229. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  230. $name = 'edge';
  231. $version = $reg[2];
  232. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  233. $name = 'chrome';
  234. $version = $reg[2];
  235. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  236. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  237. $name = 'chrome';
  238. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  239. $name = 'iceweasel';
  240. } elseif (preg_match('/epiphany/i', $user_agent)) {
  241. $name = 'epiphany';
  242. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  243. $name = 'safari';
  244. $version = $reg[2];
  245. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  246. // Safari is often present in string for mobile but its not.
  247. $name = 'opera';
  248. $version = $reg[2];
  249. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  250. $name = 'ie';
  251. $version = end($reg);
  252. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  253. // MS products at end
  254. $name = 'ie';
  255. $version = end($reg);
  256. } elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  257. // MS products at end
  258. $name = 'lynxlinks';
  259. $version = $reg[4];
  260. }
  261. if ($tablet) {
  262. $layout = 'tablet';
  263. } elseif ($phone) {
  264. $layout = 'phone';
  265. } else {
  266. $layout = 'classic';
  267. }
  268. return array(
  269. 'browsername' => $name,
  270. 'browserversion' => $version,
  271. 'browseros' => $os,
  272. 'layout' => $layout,
  273. 'phone' => $phone,
  274. 'tablet' => $tablet
  275. );
  276. }
  277. /**
  278. * Function called at end of web php process
  279. *
  280. * @return void
  281. */
  282. function dol_shutdown()
  283. {
  284. global $conf, $user, $langs, $db;
  285. $disconnectdone = false;
  286. $depth = 0;
  287. if (is_object($db) && !empty($db->connected)) {
  288. $depth = $db->transaction_opened;
  289. $disconnectdone = $db->close();
  290. }
  291. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  292. }
  293. /**
  294. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  295. *
  296. * @param string $paramname Name or parameter to test
  297. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  298. */
  299. function GETPOSTISSET($paramname)
  300. {
  301. $isset = false;
  302. $relativepathstring = $_SERVER["PHP_SELF"];
  303. // Clean $relativepathstring
  304. if (constant('DOL_URL_ROOT')) {
  305. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  306. }
  307. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  308. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  309. //var_dump($relativepathstring);
  310. //var_dump($user->default_values);
  311. // Code for search criteria persistence.
  312. // Retrieve values if restore_lastsearch_values
  313. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  314. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  315. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  316. if (is_array($tmp)) {
  317. foreach ($tmp as $key => $val) {
  318. if ($key == $paramname) { // We are on the requested parameter
  319. $isset = true;
  320. break;
  321. }
  322. }
  323. }
  324. }
  325. // If there is saved contextpage, page or limit
  326. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  327. $isset = true;
  328. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  329. $isset = true;
  330. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  331. $isset = true;
  332. }
  333. } else {
  334. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  335. }
  336. return $isset;
  337. }
  338. /**
  339. * Return value of a param into GET or POST supervariable.
  340. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  341. * Note: The property $user->default_values is loaded by main.php when loading the user.
  342. *
  343. * @param string $paramname Name of parameter to found
  344. * @param string $check Type of check
  345. * ''=no check (deprecated)
  346. * 'none'=no check (only for param that should have very rich content)
  347. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  348. * 'int'=check it's numeric (integer or float)
  349. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  350. * 'alpha'=Same than alphanohtml since v13
  351. * 'alphawithlgt'=alpha with lgt
  352. * 'alphanohtml'=check there is no html content and no " and no ../
  353. * 'aZ'=check it's a-z only
  354. * 'aZ09'=check it's simple alpha string (recommended for keys)
  355. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  356. * 'nohtml'=check there is no html content and no " and no ../
  357. * 'restricthtml'=check html content is restricted to some tags only
  358. * 'custom'= custom filter specify $filter and $options)
  359. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  360. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  361. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  362. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  363. * @return string|array Value found (string or array), or '' if check fails
  364. */
  365. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  366. {
  367. global $mysoc, $user, $conf;
  368. if (empty($paramname)) {
  369. return 'BadFirstParameterForGETPOST';
  370. }
  371. if (empty($check)) {
  372. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  373. // Enable this line to know who call the GETPOST with '' $check parameter.
  374. //var_dump(debug_backtrace()[0]);
  375. }
  376. if (empty($method)) {
  377. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  378. } elseif ($method == 1) {
  379. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  380. } elseif ($method == 2) {
  381. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  382. } elseif ($method == 3) {
  383. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  384. } else {
  385. return 'BadThirdParameterForGETPOST';
  386. }
  387. if (empty($method) || $method == 3 || $method == 4) {
  388. $relativepathstring = $_SERVER["PHP_SELF"];
  389. // Clean $relativepathstring
  390. if (constant('DOL_URL_ROOT')) {
  391. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  392. }
  393. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  394. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  395. //var_dump($relativepathstring);
  396. //var_dump($user->default_values);
  397. // Code for search criteria persistence.
  398. // Retrieve values if restore_lastsearch_values
  399. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  400. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  401. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  402. if (is_array($tmp)) {
  403. foreach ($tmp as $key => $val) {
  404. if ($key == $paramname) { // We are on the requested parameter
  405. $out = $val;
  406. break;
  407. }
  408. }
  409. }
  410. }
  411. // If there is saved contextpage, page or limit
  412. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  413. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  414. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  415. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  416. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  417. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  418. }
  419. } elseif (!isset($_GET['sortfield'])) {
  420. // Else, retrieve default values if we are not doing a sort
  421. // 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
  422. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  423. // Search default value from $object->field
  424. global $object;
  425. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  426. $out = $object->fields[$paramname]['default'];
  427. }
  428. }
  429. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  430. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  431. // Now search in setup to overwrite default values
  432. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  433. if (isset($user->default_values[$relativepathstring]['createform'])) {
  434. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  435. $qualified = 0;
  436. if ($defkey != '_noquery_') {
  437. $tmpqueryarraytohave = explode('&', $defkey);
  438. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  439. $foundintru = 0;
  440. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  441. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  442. $foundintru = 1;
  443. }
  444. }
  445. if (!$foundintru) {
  446. $qualified = 1;
  447. }
  448. //var_dump($defkey.'-'.$qualified);
  449. } else {
  450. $qualified = 1;
  451. }
  452. if ($qualified) {
  453. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  454. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  455. break;
  456. }
  457. }
  458. }
  459. }
  460. }
  461. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  462. // Management of default search_filters and sort order
  463. if (!empty($user->default_values)) {
  464. // $user->default_values defined from menu 'Setup - Default values'
  465. //var_dump($user->default_values[$relativepathstring]);
  466. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  467. // Sorted on which fields ? ASC or DESC ?
  468. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  469. // Even if paramname is sortfield, data are stored into ['sortorder...']
  470. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  471. $qualified = 0;
  472. if ($defkey != '_noquery_') {
  473. $tmpqueryarraytohave = explode('&', $defkey);
  474. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  475. $foundintru = 0;
  476. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  477. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  478. $foundintru = 1;
  479. }
  480. }
  481. if (!$foundintru) {
  482. $qualified = 1;
  483. }
  484. //var_dump($defkey.'-'.$qualified);
  485. } else {
  486. $qualified = 1;
  487. }
  488. if ($qualified) {
  489. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  490. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  491. if ($out) {
  492. $out .= ', ';
  493. }
  494. if ($paramname == 'sortfield') {
  495. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  496. }
  497. if ($paramname == 'sortorder') {
  498. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  499. }
  500. }
  501. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  502. }
  503. }
  504. }
  505. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  506. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  507. $qualified = 0;
  508. if ($defkey != '_noquery_') {
  509. $tmpqueryarraytohave = explode('&', $defkey);
  510. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  511. $foundintru = 0;
  512. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  513. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  514. $foundintru = 1;
  515. }
  516. }
  517. if (!$foundintru) {
  518. $qualified = 1;
  519. }
  520. //var_dump($defkey.'-'.$qualified);
  521. } else {
  522. $qualified = 1;
  523. }
  524. if ($qualified) {
  525. // We must keep $_POST and $_GET here
  526. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  527. // We made a search from quick search menu, do we still use default filter ?
  528. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  529. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  530. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  531. }
  532. } else {
  533. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  534. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  535. }
  536. break;
  537. }
  538. }
  539. }
  540. }
  541. }
  542. }
  543. }
  544. }
  545. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  546. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  547. // 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.
  548. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  549. $reg = array();
  550. $maxloop = 20;
  551. $loopnb = 0; // Protection against infinite loop
  552. 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.
  553. $loopnb++;
  554. $newout = '';
  555. if ($reg[1] == 'DAY') {
  556. $tmp = dol_getdate(dol_now(), true);
  557. $newout = $tmp['mday'];
  558. } elseif ($reg[1] == 'MONTH') {
  559. $tmp = dol_getdate(dol_now(), true);
  560. $newout = $tmp['mon'];
  561. } elseif ($reg[1] == 'YEAR') {
  562. $tmp = dol_getdate(dol_now(), true);
  563. $newout = $tmp['year'];
  564. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  565. $tmp = dol_getdate(dol_now(), true);
  566. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  567. $newout = $tmp2['day'];
  568. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  569. $tmp = dol_getdate(dol_now(), true);
  570. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  571. $newout = $tmp2['month'];
  572. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  573. $tmp = dol_getdate(dol_now(), true);
  574. $newout = ($tmp['year'] - 1);
  575. } elseif ($reg[1] == 'NEXT_DAY') {
  576. $tmp = dol_getdate(dol_now(), true);
  577. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  578. $newout = $tmp2['day'];
  579. } elseif ($reg[1] == 'NEXT_MONTH') {
  580. $tmp = dol_getdate(dol_now(), true);
  581. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  582. $newout = $tmp2['month'];
  583. } elseif ($reg[1] == 'NEXT_YEAR') {
  584. $tmp = dol_getdate(dol_now(), true);
  585. $newout = ($tmp['year'] + 1);
  586. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  587. $newout = $mysoc->country_id;
  588. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  589. $newout = $user->id;
  590. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  591. $newout = $user->fk_user;
  592. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  593. $newout = $conf->entity;
  594. } else {
  595. $newout = ''; // Key not found, we replace with empty string
  596. }
  597. //var_dump('__'.$reg[1].'__ -> '.$newout);
  598. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  599. }
  600. }
  601. // Check rule
  602. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09'
  603. if (!is_array($out) || empty($out)) {
  604. $out = array();
  605. } else {
  606. $tmparray = explode(':', $check);
  607. if (!empty($tmparray[1])) {
  608. $tmpcheck = $tmparray[1];
  609. } else {
  610. $tmpcheck = 'alphanohtml';
  611. }
  612. foreach ($out as $outkey => $outval) {
  613. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  614. }
  615. }
  616. } else {
  617. $out = checkVal($out, $check, $filter, $options);
  618. }
  619. // Sanitizing for special parameters.
  620. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL.
  621. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  622. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  623. $out = str_replace(array(':', ';', '@'), '', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  624. do {
  625. $oldstringtoclean = $out;
  626. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  627. } while ($oldstringtoclean != $out);
  628. $out = preg_replace(array('/^[a-z]*\/\/+/i'), '', $out); // We remove schema*// to remove external URL
  629. }
  630. // Code for search criteria persistence.
  631. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  632. if (empty($method) || $method == 3 || $method == 4) {
  633. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  634. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  635. // We save search key only if $out not empty that means:
  636. // - posted value not empty, or
  637. // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not).
  638. if ($out != '') { // $out = '0' or 'abc', it is a search criteria to keep
  639. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  640. }
  641. }
  642. }
  643. return $out;
  644. }
  645. /**
  646. * Return value of a param into GET or POST supervariable.
  647. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  648. * Note: The property $user->default_values is loaded by main.php when loading the user.
  649. *
  650. * @param string $paramname Name of parameter to found
  651. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  652. * @return int Value found (int)
  653. */
  654. function GETPOSTINT($paramname, $method = 0)
  655. {
  656. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  657. }
  658. /**
  659. * Return a value after checking on a rule. A sanitization may also have been done.
  660. *
  661. * @param string $out Value to check/clear.
  662. * @param string $check Type of check/sanitizing
  663. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  664. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  665. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  666. */
  667. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  668. {
  669. global $conf;
  670. // Check is done after replacement
  671. switch ($check) {
  672. case 'none':
  673. break;
  674. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  675. if (!is_numeric($out)) {
  676. $out = '';
  677. }
  678. break;
  679. case 'intcomma':
  680. if (preg_match('/[^0-9,-]+/i', $out)) {
  681. $out = '';
  682. }
  683. break;
  684. case 'san_alpha':
  685. $out = filter_var($out, FILTER_SANITIZE_STRING);
  686. break;
  687. case 'email':
  688. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  689. break;
  690. case 'aZ':
  691. if (!is_array($out)) {
  692. $out = trim($out);
  693. if (preg_match('/[^a-z]+/i', $out)) {
  694. $out = '';
  695. }
  696. }
  697. break;
  698. case 'aZ09':
  699. if (!is_array($out)) {
  700. $out = trim($out);
  701. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  702. $out = '';
  703. }
  704. }
  705. break;
  706. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  707. if (!is_array($out)) {
  708. $out = trim($out);
  709. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  710. $out = '';
  711. }
  712. }
  713. break;
  714. case 'nohtml': // No html
  715. $out = dol_string_nohtmltag($out, 0);
  716. break;
  717. case 'alpha': // No html and no ../ and "
  718. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  719. if (!is_array($out)) {
  720. $out = trim($out);
  721. do {
  722. $oldstringtoclean = $out;
  723. // Remove html tags
  724. $out = dol_string_nohtmltag($out, 0);
  725. // Remove also other dangerous string sequences
  726. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  727. // '../' or '..\' is dangerous because it allows dir transversals
  728. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  729. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  730. } while ($oldstringtoclean != $out);
  731. // keep lines feed
  732. }
  733. break;
  734. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>"
  735. if (!is_array($out)) {
  736. $out = trim($out);
  737. do {
  738. $oldstringtoclean = $out;
  739. // Remove html tags
  740. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  741. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  742. // '../' or '..\' is dangerous because it allows dir transversals
  743. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  744. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  745. } while ($oldstringtoclean != $out);
  746. }
  747. break;
  748. case 'restricthtml': // Recommended for most html textarea
  749. case 'restricthtmlallowunvalid':
  750. do {
  751. $oldstringtoclean = $out;
  752. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  753. try {
  754. $dom = new DOMDocument;
  755. // Add a trick to solve pb with text without parent tag
  756. // like '<h1>Foo</h1><p>bar</p>' that ends up with '<h1>Foo<p>bar</p></h1>'
  757. // like 'abc' that ends up with '<p>abc</p>'
  758. $out = '<div class="tricktoremove">'.$out.'</div>';
  759. $dom->loadHTML($out, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  760. $out = trim($dom->saveHTML());
  761. // Remove the trick added to solve pb with text without parent tag
  762. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  763. $out = preg_replace('/<\/div>$/', '', $out);
  764. } catch (Exception $e) {
  765. //print $e->getMessage();
  766. return 'InvalidHTMLString';
  767. }
  768. }
  769. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  770. // encoded using text entities) so we can then exclude all numeric entities.
  771. $out = preg_replace('/&#39;/i', '&apos;', $out);
  772. // We replace chars from a/A to z/Z encoded with numeric HTML entities with the real char so we won't loose the chars at the next step (preg_replace).
  773. // No need to use a loop here, this step is not to sanitize (this is done at next step, this is to try to save chars, even if they are
  774. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  775. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', 'realCharForNumericEntities', $out);
  776. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  777. $out = preg_replace('/&#x?[0-9]+/i', '', $out); // For example if we have j&#x61vascript with an entities without the ; to hide the 'a' of 'javascript'.
  778. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  779. // We should also exclude non expected HTML attributes and clean content of some attributes.
  780. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  781. // Warning, the function may add a LF so we are forced to trim to compare with old $out without having always a difference and an infinit loop.
  782. $out = dol_string_onlythesehtmlattributes($out);
  783. }
  784. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  785. $out = preg_replace('/&apos;/i', "&#39;", $out);
  786. } while ($oldstringtoclean != $out);
  787. break;
  788. case 'custom':
  789. if (empty($filter)) {
  790. return 'BadFourthParameterForGETPOST';
  791. }
  792. $out = filter_var($out, $filter, $options);
  793. break;
  794. }
  795. return $out;
  796. }
  797. if (!function_exists('dol_getprefix')) {
  798. /**
  799. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  800. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  801. * or two instances in same virtual servers.
  802. *
  803. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  804. * @return string A calculated prefix
  805. */
  806. function dol_getprefix($mode = '')
  807. {
  808. // If prefix is for email (we need to have $conf alreayd loaded for this case)
  809. if ($mode == 'email') {
  810. global $conf;
  811. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  812. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  813. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  814. } elseif (isset($_SERVER["SERVER_NAME"])) {
  815. return $_SERVER["SERVER_NAME"];
  816. }
  817. }
  818. // The recommended value (may be not defined for old versions)
  819. if (!empty($conf->file->instance_unique_id)) {
  820. return $conf->file->instance_unique_id;
  821. }
  822. // For backward compatibility
  823. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  824. }
  825. // If prefix is for session (no need to have $conf loaded)
  826. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  827. $tmp_instance_unique_id = empty($dolibarr_main_instance_unique_id) ? (empty($dolibarr_main_cookie_cryptkey) ? '' : $dolibarr_main_cookie_cryptkey) : $dolibarr_main_instance_unique_id; // Unique id of instance
  828. // The recommended value (may be not defined for old versions)
  829. if (!empty($tmp_instance_unique_id)) {
  830. return $tmp_instance_unique_id;
  831. }
  832. // For backward compatibility
  833. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  834. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  835. }
  836. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  837. }
  838. }
  839. /**
  840. * Make an include_once using default root and alternate root if it fails.
  841. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  842. * To link to a module file from a module file, use include './mymodulefile';
  843. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  844. *
  845. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  846. * @param string $classname Class name (deprecated)
  847. * @return bool True if load is a success, False if it fails
  848. */
  849. function dol_include_once($relpath, $classname = '')
  850. {
  851. global $conf, $langs, $user, $mysoc; // Do not remove this. They must be defined for files we include. Other globals var must be retrieved with $GLOBALS['var']
  852. $fullpath = dol_buildpath($relpath);
  853. if (!file_exists($fullpath)) {
  854. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  855. return false;
  856. }
  857. if (!empty($classname) && !class_exists($classname)) {
  858. return include $fullpath;
  859. } else {
  860. return include_once $fullpath;
  861. }
  862. }
  863. /**
  864. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  865. *
  866. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  867. * @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)
  868. * @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)
  869. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  870. * 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
  871. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  872. */
  873. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  874. {
  875. global $conf;
  876. $path = preg_replace('/^\//', '', $path);
  877. if (empty($type)) { // For a filesystem path
  878. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  879. if (is_array($conf->file->dol_document_root)) {
  880. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  881. if ($key == 'main') {
  882. continue;
  883. }
  884. if (file_exists($dirroot.'/'.$path)) {
  885. $res = $dirroot.'/'.$path;
  886. return $res;
  887. }
  888. }
  889. }
  890. if ($returnemptyifnotfound) {
  891. // Not found into alternate dir
  892. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  893. return '';
  894. }
  895. }
  896. } else {
  897. // For an url path
  898. // We try to get local path of file on filesystem from url
  899. // Note that trying to know if a file on disk exist by forging path on disk from url
  900. // works only for some web server and some setup. This is bugged when
  901. // using proxy, rewriting, virtual path, etc...
  902. $res = '';
  903. if ($type == 1) {
  904. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  905. }
  906. if ($type == 2) {
  907. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  908. }
  909. if ($type == 3) {
  910. $res = DOL_URL_ROOT.'/'.$path;
  911. }
  912. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  913. if ($key == 'main') {
  914. if ($type == 3) {
  915. global $dolibarr_main_url_root;
  916. // Define $urlwithroot
  917. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  918. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  919. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  920. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  921. }
  922. continue;
  923. }
  924. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  925. if (!empty($regs[1])) {
  926. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  927. if (file_exists($dirroot.'/'.$regs[1])) {
  928. if ($type == 1) {
  929. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  930. }
  931. if ($type == 2) {
  932. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  933. }
  934. if ($type == 3) {
  935. global $dolibarr_main_url_root;
  936. // Define $urlwithroot
  937. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  938. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  939. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  940. $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
  941. }
  942. break;
  943. }
  944. }
  945. }
  946. }
  947. return $res;
  948. }
  949. /**
  950. * Create a clone of instance of object (new instance with same value for properties)
  951. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  952. * With native = 1: Use PHP clone. Property that are reference are same pointer. This means $this->db of new object is still valid but point to same this->db than original object.
  953. *
  954. * @param object $object Object to clone
  955. * @param int $native 0=Full isolation method, 1=Native PHP method
  956. * @return object Clone object
  957. * @see https://php.net/manual/language.oop5.cloning.php
  958. */
  959. function dol_clone($object, $native = 0)
  960. {
  961. if (empty($native)) {
  962. $myclone = unserialize(serialize($object)); // serialize then unserialize is hack to be sure to have a new object for all fields
  963. } else {
  964. $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep the reference (refering to the same target/variable)
  965. }
  966. return $myclone;
  967. }
  968. /**
  969. * Optimize a size for some browsers (phone, smarphone, ...)
  970. *
  971. * @param int $size Size we want
  972. * @param string $type Type of optimizing:
  973. * '' = function used to define a size for truncation
  974. * 'width' = function is used to define a width
  975. * @return int New size after optimizing
  976. */
  977. function dol_size($size, $type = '')
  978. {
  979. global $conf;
  980. if (empty($conf->dol_optimize_smallscreen)) {
  981. return $size;
  982. }
  983. if ($type == 'width' && $size > 250) {
  984. return 250;
  985. } else {
  986. return 10;
  987. }
  988. }
  989. /**
  990. * Clean a string to use it as a file name.
  991. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  992. *
  993. * @param string $str String to clean
  994. * @param string $newstr String to replace bad chars with.
  995. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  996. * @return string String cleaned (a-zA-Z_)
  997. *
  998. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  999. */
  1000. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1001. {
  1002. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1003. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1004. // Char '/' and '\' are file delimiters.
  1005. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1006. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1007. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1008. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1009. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1010. return $tmp;
  1011. }
  1012. /**
  1013. * Clean a string to use it as a path name.
  1014. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1015. *
  1016. * @param string $str String to clean
  1017. * @param string $newstr String to replace bad chars with
  1018. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1019. * @return string String cleaned (a-zA-Z_)
  1020. *
  1021. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1022. */
  1023. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1024. {
  1025. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1026. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1027. // Chars '--' can be used into filename to inject special paramaters like --use-compress-program to make command with file as parameter making remote execution of command
  1028. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1029. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1030. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1031. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1032. return $tmp;
  1033. }
  1034. /**
  1035. * Clean a string to use it as an URL (into a href or src attribute)
  1036. *
  1037. * @param string $stringtoclean String to clean
  1038. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1039. * @return string Escaped string.
  1040. */
  1041. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1042. {
  1043. // We clean string because some hacks try to obfuscate evil strings by inserting non printable chars. Example: 'java(ascci09)scr(ascii00)ipt' is processed like 'javascript' (whatever is place of evil ascii char)
  1044. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1045. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1046. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1047. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1048. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1049. if ($type == 1) {
  1050. // removing : should disable links to external url like http:aaa)
  1051. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1052. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1053. }
  1054. do {
  1055. $oldstringtoclean = $stringtoclean;
  1056. // removing '&colon' should disable links to external url like http:aaa)
  1057. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1058. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1059. } while ($oldstringtoclean != $stringtoclean);
  1060. if ($type == 1) {
  1061. // removing '//' should disable links to external url like //aaa or http//)
  1062. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1063. }
  1064. return $stringtoclean;
  1065. }
  1066. /**
  1067. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1068. *
  1069. * @param string $str String to clean
  1070. * @return string Cleaned string
  1071. *
  1072. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1073. */
  1074. function dol_string_unaccent($str)
  1075. {
  1076. global $conf;
  1077. if (utf8_check($str)) {
  1078. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1079. $transliterator = \Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', \Transliterator::FORWARD);
  1080. return $transliterator->transliterate($str);
  1081. }
  1082. // See http://www.utf8-chartable.de/
  1083. $string = rawurlencode($str);
  1084. $replacements = array(
  1085. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1086. '%C3%87' => 'C',
  1087. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1088. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1089. '%C3%91' => 'N',
  1090. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1091. '%C5%A0' => 'S',
  1092. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1093. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1094. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1095. '%C3%A7' => 'c',
  1096. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1097. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1098. '%C3%B1' => 'n',
  1099. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1100. '%C5%A1' => 's',
  1101. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1102. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1103. );
  1104. $string = strtr($string, $replacements);
  1105. return rawurldecode($string);
  1106. } else {
  1107. // See http://www.ascii-code.com/
  1108. $string = strtr(
  1109. $str,
  1110. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1111. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1112. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1113. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1114. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1115. \xF9\xFA\xFB\xFC\xFD\xFF",
  1116. "AAAAAAC
  1117. EEEEIIIIDN
  1118. OOOOOUUUY
  1119. aaaaaaceeee
  1120. iiiidnooooo
  1121. uuuuyy"
  1122. );
  1123. $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"));
  1124. return $string;
  1125. }
  1126. }
  1127. /**
  1128. * Clean a string from all punctuation characters to use it as a ref or login.
  1129. * This is a more complete function than dol_sanitizeFileName.
  1130. *
  1131. * @param string $str String to clean
  1132. * @param string $newstr String to replace forbidden chars with
  1133. * @param array|string $badcharstoreplace List of forbidden characters to replace
  1134. * @param array|string $badcharstoremove List of forbidden characters to remove
  1135. * @return string Cleaned string
  1136. *
  1137. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1138. */
  1139. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1140. {
  1141. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1142. $forbidden_chars_to_remove = array();
  1143. //$forbidden_chars_to_remove=array("(",")");
  1144. if (is_array($badcharstoreplace)) {
  1145. $forbidden_chars_to_replace = $badcharstoreplace;
  1146. }
  1147. if (is_array($badcharstoremove)) {
  1148. $forbidden_chars_to_remove = $badcharstoremove;
  1149. }
  1150. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1151. }
  1152. /**
  1153. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1154. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1155. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1156. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1157. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1158. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1159. * @param string $str String to clean
  1160. * @param int $removetabcrlf Remove also CR-LF
  1161. * @return string Cleaned string
  1162. *
  1163. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1164. */
  1165. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1166. {
  1167. if ($removetabcrlf) {
  1168. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1169. } else {
  1170. return preg_replace('/[\x00-\x08\x11-\x12\x14-\x1F\x7F]/u', '', $str); // /u operator should make UTF8 valid characters being ignored so are not included into the replace
  1171. }
  1172. }
  1173. /**
  1174. * Returns text escaped for inclusion into javascript code
  1175. *
  1176. * @param string $stringtoescape String to escape
  1177. * @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 \
  1178. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1179. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1180. */
  1181. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1182. {
  1183. // escape quotes and backslashes, newlines, etc.
  1184. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1185. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1186. if (empty($noescapebackslashn)) {
  1187. $substitjs["\n"] = '\\n';
  1188. $substitjs['\\'] = '\\\\';
  1189. }
  1190. if (empty($mode)) {
  1191. $substitjs["'"] = "\\'";
  1192. $substitjs['"'] = "\\'";
  1193. } elseif ($mode == 1) {
  1194. $substitjs["'"] = "\\'";
  1195. } elseif ($mode == 2) {
  1196. $substitjs['"'] = '\\"';
  1197. } elseif ($mode == 3) {
  1198. $substitjs["'"] = "\\'";
  1199. $substitjs['"'] = "\\\"";
  1200. }
  1201. return strtr($stringtoescape, $substitjs);
  1202. }
  1203. /**
  1204. * Returns text escaped for inclusion into javascript code
  1205. *
  1206. * @param string $stringtoescape String to escape
  1207. * @return string Escaped string for json content.
  1208. */
  1209. function dol_escape_json($stringtoescape)
  1210. {
  1211. return str_replace('"', '\"', $stringtoescape);
  1212. }
  1213. /**
  1214. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1215. *
  1216. * @param string $stringtoescape String to escape
  1217. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1218. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1219. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes to tag.
  1220. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1221. * @return string Escaped string
  1222. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1223. */
  1224. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1225. {
  1226. if ($noescapetags == 'common') {
  1227. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1228. }
  1229. // escape quotes and backslashes, newlines, etc.
  1230. if ($escapeonlyhtmltags) {
  1231. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1232. } else {
  1233. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1234. }
  1235. if (!$keepb) {
  1236. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1237. }
  1238. if (!$keepn) {
  1239. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1240. }
  1241. if ($escapeonlyhtmltags) {
  1242. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1243. } else {
  1244. // Escape tags to keep
  1245. // TODO Does not works yet when there is attributes to tag
  1246. $tmparrayoftags = array();
  1247. if ($noescapetags) {
  1248. $tmparrayoftags = explode(',', $noescapetags);
  1249. }
  1250. if (count($tmparrayoftags)) {
  1251. foreach ($tmparrayoftags as $tagtoreplace) {
  1252. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1253. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1254. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1255. }
  1256. }
  1257. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1258. if (count($tmparrayoftags)) {
  1259. foreach ($tmparrayoftags as $tagtoreplace) {
  1260. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1261. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1262. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1263. }
  1264. }
  1265. return $result;
  1266. }
  1267. }
  1268. /**
  1269. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1270. *
  1271. * @param string $string String to encode
  1272. * @param string $encoding Character set encoding
  1273. * @return string String converted
  1274. */
  1275. function dol_strtolower($string, $encoding = "UTF-8")
  1276. {
  1277. if (function_exists('mb_strtolower')) {
  1278. return mb_strtolower($string, $encoding);
  1279. } else {
  1280. return strtolower($string);
  1281. }
  1282. }
  1283. /**
  1284. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1285. *
  1286. * @param string $string String to encode
  1287. * @param string $encoding Character set encoding
  1288. * @return string String converted
  1289. */
  1290. function dol_strtoupper($string, $encoding = "UTF-8")
  1291. {
  1292. if (function_exists('mb_strtoupper')) {
  1293. return mb_strtoupper($string, $encoding);
  1294. } else {
  1295. return strtoupper($string);
  1296. }
  1297. }
  1298. /**
  1299. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1300. *
  1301. * @param string $string String to encode
  1302. * @param string $encoding Character set encodign
  1303. * @return string String converted
  1304. */
  1305. function dol_ucfirst($string, $encoding = "UTF-8")
  1306. {
  1307. if (function_exists('mb_substr')) {
  1308. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1309. } else {
  1310. return ucfirst($string);
  1311. }
  1312. }
  1313. /**
  1314. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1315. *
  1316. * @param string $string String to encode
  1317. * @param string $encoding Character set encodign
  1318. * @return string String converted
  1319. */
  1320. function dol_ucwords($string, $encoding = "UTF-8")
  1321. {
  1322. if (function_exists('mb_convert_case')) {
  1323. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1324. } else {
  1325. return ucwords($string);
  1326. }
  1327. }
  1328. /**
  1329. * Write log message into outputs. Possible outputs can be:
  1330. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1331. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1332. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1333. * this, use logging to files instead of syslog (see setup of module).
  1334. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1335. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1336. * This function works only if syslog module is enabled.
  1337. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1338. *
  1339. * @param string $message Line to log. ''=Show nothing
  1340. * @param int $level Log level
  1341. * 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
  1342. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1343. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1344. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1345. * @param string $restricttologhandler Force output of log only to this log handler
  1346. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1347. * @return void
  1348. */
  1349. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1350. {
  1351. global $conf, $user, $debugbar;
  1352. // If syslog module enabled
  1353. if (empty($conf->syslog->enabled)) {
  1354. return;
  1355. }
  1356. // Check if we are into execution of code of a website
  1357. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1358. global $website, $websitekey;
  1359. if (is_object($website) && !empty($website->ref)) {
  1360. $suffixinfilename .= '_website_'.$website->ref;
  1361. } elseif (!empty($websitekey)) {
  1362. $suffixinfilename .= '_website_'.$websitekey;
  1363. }
  1364. }
  1365. if ($ident < 0) {
  1366. foreach ($conf->loghandlers as $loghandlerinstance) {
  1367. $loghandlerinstance->setIdent($ident);
  1368. }
  1369. }
  1370. if (!empty($message)) {
  1371. // Test log level
  1372. $logLevels = array(LOG_EMERG=>'EMERG', LOG_ALERT=>'ALERT', LOG_CRIT=>'CRITICAL', LOG_ERR=>'ERR', LOG_WARNING=>'WARN', LOG_NOTICE=>'NOTICE', LOG_INFO=>'INFO', LOG_DEBUG=>'DEBUG');
  1373. if (!array_key_exists($level, $logLevels)) {
  1374. throw new Exception('Incorrect log level');
  1375. }
  1376. if ($level > $conf->global->SYSLOG_LEVEL) {
  1377. return;
  1378. }
  1379. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1380. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1381. }
  1382. // If adding log inside HTML page is required
  1383. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1384. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1385. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1386. }
  1387. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1388. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1389. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1390. print "\n\n<!-- Log start\n";
  1391. print dol_escape_htmltag($message)."\n";
  1392. print "Log end -->\n";
  1393. }
  1394. $data = array(
  1395. 'message' => $message,
  1396. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1397. 'level' => $level,
  1398. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1399. 'ip' => false
  1400. );
  1401. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1402. if (!empty($remoteip)) {
  1403. $data['ip'] = $remoteip;
  1404. // This is when server run behind a reverse proxy
  1405. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1406. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1407. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1408. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1409. }
  1410. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1411. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1412. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1413. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1414. // 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).
  1415. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1416. } elseif (!empty($_SERVER['LOGNAME'])) {
  1417. // 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).
  1418. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1419. }
  1420. // Loop on each log handler and send output
  1421. foreach ($conf->loghandlers as $loghandlerinstance) {
  1422. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1423. continue;
  1424. }
  1425. $loghandlerinstance->export($data, $suffixinfilename);
  1426. }
  1427. unset($data);
  1428. }
  1429. if ($ident > 0) {
  1430. foreach ($conf->loghandlers as $loghandlerinstance) {
  1431. $loghandlerinstance->setIdent($ident);
  1432. }
  1433. }
  1434. }
  1435. /**
  1436. * Return HTML code to output a button to open a dialog popup box.
  1437. * Such buttons must be included inside a HTML form.
  1438. *
  1439. * @param string $name A name for the html component
  1440. * @param string $label Label of button
  1441. * @param string $buttonstring button string
  1442. * @param string $url Url to open
  1443. * @param string $disabled Disabled text
  1444. * @return string HTML component with button
  1445. */
  1446. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1447. {
  1448. if (strpos($url, '?') > 0) {
  1449. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1450. } else {
  1451. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1452. }
  1453. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1454. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1455. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1456. $out .= '<script type="text/javascript">
  1457. jQuery(document).ready(function () {
  1458. jQuery(".button_'.$name.'").click(function () {
  1459. console.log("Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'")
  1460. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1461. .dialog({
  1462. autoOpen: false,
  1463. modal: true,
  1464. height: (window.innerHeight - 150),
  1465. width: \'80%\',
  1466. title: "'.dol_escape_js($label).'"
  1467. });
  1468. $dialog.dialog(\'open\');
  1469. });
  1470. });
  1471. </script>';
  1472. return $out;
  1473. }
  1474. /**
  1475. * Show tab header of a card
  1476. *
  1477. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1478. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1479. * @param string $title Title
  1480. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1481. * @param string $picto Add a picto on tab title
  1482. * @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.
  1483. * @param string $morehtmlright Add more html content on right of tabs title
  1484. * @param string $morecss More Css
  1485. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1486. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1487. * @return void
  1488. * @deprecated Use print dol_get_fiche_head() instead
  1489. */
  1490. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1491. {
  1492. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1493. }
  1494. /**
  1495. * Show tabs of a record
  1496. *
  1497. * @param array $links Array of tabs. Note that label into $links[$i][1] must be already HTML escaped.
  1498. * @param string $active Active tab name
  1499. * @param string $title Title
  1500. * @param int $notab -1 or 0=Add tab header, 1=no tab header (if you set this to 1, using print dol_get_fiche_end() to close tab is not required), -2=Add tab header with no seaparation under tab (to start a tab just after)
  1501. * @param string $picto Add a picto on tab title
  1502. * @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.
  1503. * @param string $morehtmlright Add more html content on right of tabs title
  1504. * @param string $morecss More CSS on the link <a>
  1505. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1506. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1507. * @return string
  1508. */
  1509. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1510. {
  1511. global $conf, $langs, $hookmanager;
  1512. // Show title
  1513. $showtitle = 1;
  1514. if (!empty($conf->dol_optimize_smallscreen)) {
  1515. $showtitle = 0;
  1516. }
  1517. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1518. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1519. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1520. }
  1521. // Show right part
  1522. if ($morehtmlright) {
  1523. $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.
  1524. }
  1525. // Show title
  1526. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1527. $limittitle = 30;
  1528. $out .= '<a class="tabTitle">';
  1529. if ($picto) {
  1530. $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1531. }
  1532. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1533. $out .= '</a>';
  1534. }
  1535. // Show tabs
  1536. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1537. $maxkey = -1;
  1538. if (is_array($links) && !empty($links)) {
  1539. $keys = array_keys($links);
  1540. if (count($keys)) {
  1541. $maxkey = max($keys);
  1542. }
  1543. }
  1544. // Show tabs
  1545. // if =0 we don't use the feature
  1546. if (empty($limittoshow)) {
  1547. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1548. }
  1549. if (!empty($conf->dol_optimize_smallscreen)) {
  1550. $limittoshow = 2;
  1551. }
  1552. $displaytab = 0;
  1553. $nbintab = 0;
  1554. $popuptab = 0;
  1555. $outmore = '';
  1556. for ($i = 0; $i <= $maxkey; $i++) {
  1557. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1558. // If active tab is already present
  1559. if ($i >= $limittoshow) {
  1560. $limittoshow--;
  1561. }
  1562. }
  1563. }
  1564. for ($i = 0; $i <= $maxkey; $i++) {
  1565. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1566. $isactive = true;
  1567. } else {
  1568. $isactive = false;
  1569. }
  1570. if ($i < $limittoshow || $isactive) {
  1571. // Output entry with a visible tab
  1572. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
  1573. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1574. if (!empty($links[$i][0])) {
  1575. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1576. } else {
  1577. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1578. }
  1579. } elseif (!empty($links[$i][1])) {
  1580. //print "x $i $active ".$links[$i][2]." z";
  1581. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1582. if (!empty($links[$i][0])) {
  1583. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1584. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  1585. }
  1586. $out .= $links[$i][1];
  1587. if (!empty($links[$i][0])) {
  1588. $out .= '</a>'."\n";
  1589. }
  1590. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1591. $out .= '</div>';
  1592. }
  1593. $out .= '</div>';
  1594. } else {
  1595. // Add entry into the combo popup with the other tabs
  1596. if (!$popuptab) {
  1597. $popuptab = 1;
  1598. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1599. }
  1600. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1601. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1602. if (!empty($links[$i][0])) {
  1603. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1604. } else {
  1605. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1606. }
  1607. } elseif (!empty($links[$i][1])) {
  1608. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1609. $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.
  1610. $outmore .= '</a>'."\n";
  1611. }
  1612. $outmore .= '</div>';
  1613. $nbintab++;
  1614. }
  1615. $displaytab = $i;
  1616. }
  1617. if ($popuptab) {
  1618. $outmore .= '</div>';
  1619. }
  1620. if ($popuptab) { // If there is some tabs not shown
  1621. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1622. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1623. $widthofpopup = 200;
  1624. $tabsname = $moretabssuffix;
  1625. if (empty($tabsname)) {
  1626. $tabsname = str_replace("@", "", $picto);
  1627. }
  1628. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1629. $out .= '<div class="tab"><a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
  1630. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1631. $out .= $outmore;
  1632. $out .= '</div>';
  1633. $out .= '<div></div>';
  1634. $out .= "</div>\n";
  1635. $out .= "<script>";
  1636. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1637. var x = this.offsetLeft, y = this.offsetTop;
  1638. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1639. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1640. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1641. }
  1642. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1643. });
  1644. ";
  1645. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1646. $out .= "</script>";
  1647. }
  1648. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1649. $out .= "</div>\n";
  1650. }
  1651. if (!$notab || $notab == -1 || $notab == -2) {
  1652. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1653. }
  1654. $parameters = array('tabname' => $active, 'out' => $out);
  1655. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1656. if ($reshook > 0) {
  1657. $out = $hookmanager->resPrint;
  1658. }
  1659. return $out;
  1660. }
  1661. /**
  1662. * Show tab footer of a card
  1663. *
  1664. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1665. * @return void
  1666. * @deprecated Use print dol_get_fiche_end() instead
  1667. */
  1668. function dol_fiche_end($notab = 0)
  1669. {
  1670. print dol_get_fiche_end($notab);
  1671. }
  1672. /**
  1673. * Return tab footer of a card
  1674. *
  1675. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1676. * @return string
  1677. */
  1678. function dol_get_fiche_end($notab = 0)
  1679. {
  1680. if (!$notab || $notab == -1) {
  1681. return "\n</div>\n";
  1682. } else {
  1683. return '';
  1684. }
  1685. }
  1686. /**
  1687. * Show tab footer of a card.
  1688. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1689. *
  1690. * @param Object $object Object to show
  1691. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1692. * @param string $morehtml More html content to output just before the nav bar
  1693. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1694. * @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.
  1695. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1696. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1697. * @param string $moreparam More param to add in nav link url.
  1698. * @param int $nodbprefix Do not include DB prefix to forge table name
  1699. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1700. * @param string $morehtmlstatus More html code to show under navigation arrows
  1701. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1702. * @param string $morehtmlright More html code to show before navigation arrows
  1703. * @return void
  1704. */
  1705. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1706. {
  1707. global $conf, $form, $user, $langs, $hookmanager, $action;
  1708. $error = 0;
  1709. $maxvisiblephotos = 1;
  1710. $showimage = 1;
  1711. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1712. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1713. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1714. $showbarcode = 0;
  1715. }
  1716. $modulepart = 'unknown';
  1717. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1718. $modulepart = $object->element;
  1719. } elseif ($object->element == 'member') {
  1720. $modulepart = 'memberphoto';
  1721. } elseif ($object->element == 'user') {
  1722. $modulepart = 'userphoto';
  1723. }
  1724. if (class_exists("Imagick")) {
  1725. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1726. $modulepart = $object->element;
  1727. } elseif ($object->element == 'fichinter') {
  1728. $modulepart = 'ficheinter';
  1729. } elseif ($object->element == 'contrat') {
  1730. $modulepart = 'contract';
  1731. } elseif ($object->element == 'order_supplier') {
  1732. $modulepart = 'supplier_order';
  1733. } elseif ($object->element == 'invoice_supplier') {
  1734. $modulepart = 'supplier_invoice';
  1735. }
  1736. }
  1737. if ($object->element == 'product') {
  1738. $width = 80;
  1739. $cssclass = 'photoref';
  1740. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1741. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1742. if ($conf->browser->layout == 'phone') {
  1743. $maxvisiblephotos = 1;
  1744. }
  1745. if ($showimage) {
  1746. $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>';
  1747. } else {
  1748. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1749. $nophoto = '';
  1750. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1751. } else { // Show no photo link
  1752. $nophoto = '/public/theme/common/nophoto.png';
  1753. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1754. }
  1755. }
  1756. } elseif ($object->element == 'ticket') {
  1757. $width = 80;
  1758. $cssclass = 'photoref';
  1759. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1760. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1761. if ($conf->browser->layout == 'phone') {
  1762. $maxvisiblephotos = 1;
  1763. }
  1764. if ($showimage) {
  1765. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1766. if ($object->nbphoto > 0) {
  1767. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1768. } else {
  1769. $showimage = 0;
  1770. }
  1771. }
  1772. if (!$showimage) {
  1773. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1774. $nophoto = '';
  1775. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1776. } else { // Show no photo link
  1777. $nophoto = img_picto('No photo', 'object_ticket');
  1778. $morehtmlleft .= '<!-- No photo to show -->';
  1779. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1780. $morehtmlleft .= $nophoto;
  1781. $morehtmlleft .= '</div></div>';
  1782. }
  1783. }
  1784. } else {
  1785. if ($showimage) {
  1786. if ($modulepart != 'unknown') {
  1787. $phototoshow = '';
  1788. // Check if a preview file is available
  1789. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1790. $objectref = dol_sanitizeFileName($object->ref);
  1791. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1792. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1793. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1794. $subdir .= ((!empty($subdir) && !preg_match('/\/$/', $subdir)) ? '/' : '').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end
  1795. } else {
  1796. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1797. }
  1798. if (empty($subdir)) {
  1799. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1800. }
  1801. $filepath = $dir_output.$subdir."/";
  1802. $filepdf = $filepath.$objectref.".pdf";
  1803. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1804. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1805. $fileimage = $filepdf.'_preview.png';
  1806. $relativepathimage = $relativepath.'_preview.png';
  1807. $pdfexists = file_exists($filepdf);
  1808. // If PDF file exists
  1809. if ($pdfexists) {
  1810. // Conversion du PDF en image png si fichier png non existant
  1811. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1812. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1813. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1814. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1815. if ($ret < 0) {
  1816. $error++;
  1817. }
  1818. }
  1819. }
  1820. }
  1821. if ($pdfexists && !$error) {
  1822. $heightforphotref = 80;
  1823. if (!empty($conf->dol_optimize_smallscreen)) {
  1824. $heightforphotref = 60;
  1825. }
  1826. // If the preview file is found
  1827. if (file_exists($fileimage)) {
  1828. $phototoshow = '<div class="photoref">';
  1829. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1830. $phototoshow .= '</div>';
  1831. }
  1832. }
  1833. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1834. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1835. }
  1836. if ($phototoshow) {
  1837. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1838. $morehtmlleft .= $phototoshow;
  1839. $morehtmlleft .= '</div>';
  1840. }
  1841. }
  1842. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1843. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1844. if ($object->element == 'action') {
  1845. $width = 80;
  1846. $cssclass = 'photorefcenter';
  1847. $nophoto = img_picto('No photo', 'title_agenda');
  1848. } else {
  1849. $width = 14;
  1850. $cssclass = 'photorefcenter';
  1851. $picto = $object->picto;
  1852. if ($object->element == 'project' && !$object->public) {
  1853. $picto = 'project'; // instead of projectpub
  1854. }
  1855. $nophoto = img_picto('No photo', 'object_'.$picto);
  1856. }
  1857. $morehtmlleft .= '<!-- No photo to show -->';
  1858. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1859. $morehtmlleft .= $nophoto;
  1860. $morehtmlleft .= '</div></div>';
  1861. $morehtmlleft .= '</div>';
  1862. }
  1863. }
  1864. }
  1865. if ($showbarcode) {
  1866. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref').'</div>';
  1867. }
  1868. if ($object->element == 'societe') {
  1869. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1870. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1871. } else {
  1872. $morehtmlstatus .= $object->getLibStatut(6);
  1873. }
  1874. } elseif ($object->element == 'product') {
  1875. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1876. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1877. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1878. } else {
  1879. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1880. }
  1881. $morehtmlstatus .= ' &nbsp; ';
  1882. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1883. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1884. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1885. } else {
  1886. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1887. }
  1888. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  1889. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1890. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1891. $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1892. }
  1893. $morehtmlstatus .= $tmptxt;
  1894. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  1895. if ($object->statut == 0) {
  1896. $morehtmlstatus .= $object->getLibStatut(5);
  1897. } else {
  1898. $morehtmlstatus .= $object->getLibStatut(4);
  1899. }
  1900. } elseif ($object->element == 'facturerec') {
  1901. if ($object->frequency == 0) {
  1902. $morehtmlstatus .= $object->getLibStatut(2);
  1903. } else {
  1904. $morehtmlstatus .= $object->getLibStatut(5);
  1905. }
  1906. } elseif ($object->element == 'project_task') {
  1907. $object->fk_statut = 1;
  1908. if ($object->progress > 0) {
  1909. $object->fk_statut = 2;
  1910. }
  1911. if ($object->progress >= 100) {
  1912. $object->fk_statut = 3;
  1913. }
  1914. $tmptxt = $object->getLibStatut(5);
  1915. $morehtmlstatus .= $tmptxt; // No status on task
  1916. } else { // Generic case
  1917. $tmptxt = $object->getLibStatut(6);
  1918. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1919. $tmptxt = $object->getLibStatut(5);
  1920. }
  1921. $morehtmlstatus .= $tmptxt;
  1922. }
  1923. // Add if object was dispatched "into accountancy"
  1924. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  1925. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  1926. if (method_exists($object, 'getVentilExportCompta')) {
  1927. $accounted = $object->getVentilExportCompta();
  1928. $langs->load("accountancy");
  1929. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1930. }
  1931. }
  1932. // Add alias for thirdparty
  1933. if (!empty($object->name_alias)) {
  1934. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1935. }
  1936. // Add label
  1937. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  1938. if (!empty($object->label)) {
  1939. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1940. }
  1941. }
  1942. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  1943. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1944. if ($moreaddress) {
  1945. $morehtmlref .= '<div class="refidno">';
  1946. $morehtmlref .= $moreaddress;
  1947. $morehtmlref .= '</div>';
  1948. }
  1949. }
  1950. if (!empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && ($conf->global->MAIN_SHOW_TECHNICAL_ID == '1' || preg_match('/'.preg_quote($object->element, '/').'/i', $conf->global->MAIN_SHOW_TECHNICAL_ID)) && !empty($object->id)) {
  1951. $morehtmlref .= '<div style="clear: both;"></div>';
  1952. $morehtmlref .= '<div class="refidno">';
  1953. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1954. $morehtmlref .= '</div>';
  1955. }
  1956. $parameters=array('morehtmlref'=>$morehtmlref);
  1957. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  1958. if ($reshook < 0) {
  1959. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1960. } elseif (empty($reshook)) {
  1961. $morehtmlref .= $hookmanager->resPrint;
  1962. } elseif ($reshook > 0) {
  1963. $morehtmlref = $hookmanager->resPrint;
  1964. }
  1965. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1966. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1967. print '</div>';
  1968. print '<div class="underrefbanner clearboth"></div>';
  1969. }
  1970. /**
  1971. * Show a string with the label tag dedicated to the HTML edit field.
  1972. *
  1973. * @param string $langkey Translation key
  1974. * @param string $fieldkey Key of the html select field the text refers to
  1975. * @param int $fieldrequired 1=Field is mandatory
  1976. * @return string
  1977. * @deprecated Form::editfieldkey
  1978. */
  1979. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1980. {
  1981. global $langs;
  1982. $ret = '';
  1983. if ($fieldrequired) {
  1984. $ret .= '<span class="fieldrequired">';
  1985. }
  1986. $ret .= '<label for="'.$fieldkey.'">';
  1987. $ret .= $langs->trans($langkey);
  1988. $ret .= '</label>';
  1989. if ($fieldrequired) {
  1990. $ret .= '</span>';
  1991. }
  1992. return $ret;
  1993. }
  1994. /**
  1995. * Return string to add class property on html element with pair/impair.
  1996. *
  1997. * @param string $var 0 or 1
  1998. * @param string $moreclass More class to add
  1999. * @return string String to add class onto HTML element
  2000. */
  2001. function dol_bc($var, $moreclass = '')
  2002. {
  2003. global $bc;
  2004. $ret = ' '.$bc[$var];
  2005. if ($moreclass) {
  2006. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2007. }
  2008. return $ret;
  2009. }
  2010. /**
  2011. * Return a formated address (part address/zip/town/state) according to country rules.
  2012. * See https://en.wikipedia.org/wiki/Address
  2013. *
  2014. * @param Object $object A company or contact object
  2015. * @param int $withcountry 1=Add country into address string
  2016. * @param string $sep Separator to use to build string
  2017. * @param Translate $outputlangs Object lang that contains language for text translation.
  2018. * @param int $mode 0=Standard output, 1=Remove address
  2019. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2020. * @return string Formated string
  2021. * @see dol_print_address()
  2022. */
  2023. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2024. {
  2025. global $conf, $langs;
  2026. $ret = '';
  2027. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2028. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2029. // Address
  2030. if (empty($mode)) {
  2031. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2032. }
  2033. // Zip/Town/State
  2034. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2035. // US: title firstname name \n address lines \n town, state, zip \n country
  2036. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2037. $ret .= ($ret ? $sep : '').$town;
  2038. if (!empty($object->state)) {
  2039. $ret .= ($ret ? ", " : '').$object->state;
  2040. }
  2041. if (!empty($object->zip)) {
  2042. $ret .= ($ret ? ", " : '').$object->zip;
  2043. }
  2044. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2045. // UK: title firstname name \n address lines \n town state \n zip \n country
  2046. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2047. $ret .= ($ret ? $sep : '').$town;
  2048. if (!empty($object->state)) {
  2049. $ret .= ($ret ? ", " : '').$object->state;
  2050. }
  2051. if (!empty($object->zip)) {
  2052. $ret .= ($ret ? $sep : '').$object->zip;
  2053. }
  2054. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2055. // ES: title firstname name \n address lines \n zip town \n state \n country
  2056. $ret .= ($ret ? $sep : '').$object->zip;
  2057. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2058. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2059. if (!empty($object->state)) {
  2060. $ret .= "\n".$object->state;
  2061. }
  2062. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2063. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2064. // See https://www.sljfaq.org/afaq/addresses.html
  2065. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2066. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2067. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2068. // IT: title firstname name\n address lines \n zip town state_code \n country
  2069. $ret .= ($ret ? $sep : '').$object->zip;
  2070. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2071. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2072. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2073. } else {
  2074. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2075. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2076. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2077. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2078. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2079. $ret .= ($ret ? ", " : '').$object->state;
  2080. }
  2081. }
  2082. if (!is_object($outputlangs)) {
  2083. $outputlangs = $langs;
  2084. }
  2085. if ($withcountry) {
  2086. $langs->load("dict");
  2087. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2088. }
  2089. return $ret;
  2090. }
  2091. /**
  2092. * Format a string.
  2093. *
  2094. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2095. * @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)
  2096. * @param int $is_gmt See comment of timestamp parameter
  2097. * @return string A formatted string
  2098. */
  2099. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2100. {
  2101. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2102. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2103. } else {
  2104. return 'Error date into a not supported range';
  2105. }
  2106. }
  2107. /**
  2108. * Output date in a string format according to outputlangs (or langs if not defined).
  2109. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2110. *
  2111. * @param int $time GM Timestamps date
  2112. * @param string $format Output date format (tag of strftime function)
  2113. * "%d %b %Y",
  2114. * "%d/%m/%Y %H:%M",
  2115. * "%d/%m/%Y %H:%M:%S",
  2116. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2117. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2118. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2119. * false or 'tzserver' => output string is for local PHP server TZ usage
  2120. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2121. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  2122. * @param Translate $outputlangs Object lang that contains language for text translation.
  2123. * @param boolean $encodetooutput false=no convert into output pagecode
  2124. * @return string Formated date or '' if time is null
  2125. *
  2126. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2127. */
  2128. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2129. {
  2130. global $conf, $langs;
  2131. // If date undefined or "", we return ""
  2132. if (dol_strlen($time) == 0) {
  2133. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2134. }
  2135. if ($tzoutput === 'auto') {
  2136. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2137. }
  2138. // Clean parameters
  2139. $to_gmt = false;
  2140. $offsettz = $offsetdst = 0;
  2141. if ($tzoutput) {
  2142. $to_gmt = true; // For backward compatibility
  2143. if (is_string($tzoutput)) {
  2144. if ($tzoutput == 'tzserver') {
  2145. $to_gmt = false;
  2146. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2147. $offsettz = 0; // Timezone offset with server timezone, so 0
  2148. $offsetdst = 0; // Dst offset with server timezone, so 0
  2149. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2150. $to_gmt = true;
  2151. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2152. if (class_exists('DateTimeZone')) {
  2153. $user_date_tz = new DateTimeZone($offsettzstring);
  2154. $user_dt = new DateTime();
  2155. $user_dt->setTimezone($user_date_tz);
  2156. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2157. $offsettz = $user_dt->getOffset();
  2158. } else { // old method (The 'tzuser' was processed like the 'tzuserrel')
  2159. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2160. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2161. }
  2162. }
  2163. }
  2164. }
  2165. if (!is_object($outputlangs)) {
  2166. $outputlangs = $langs;
  2167. }
  2168. if (!$format) {
  2169. $format = 'daytextshort';
  2170. }
  2171. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2172. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2173. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2174. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2175. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2176. if ($formatwithoutreduce != $format) {
  2177. $format = $formatwithoutreduce;
  2178. $reduceformat = 1;
  2179. } // so format 'dayreduceformat' is processed like day
  2180. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2181. // TODO Add format daysmallyear and dayhoursmallyear
  2182. if ($format == 'day') {
  2183. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2184. } elseif ($format == 'hour') {
  2185. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2186. } elseif ($format == 'hourduration') {
  2187. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2188. } elseif ($format == 'daytext') {
  2189. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2190. } elseif ($format == 'daytextshort') {
  2191. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2192. } elseif ($format == 'dayhour') {
  2193. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2194. } elseif ($format == 'dayhoursec') {
  2195. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2196. } elseif ($format == 'dayhourtext') {
  2197. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2198. } elseif ($format == 'dayhourtextshort') {
  2199. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2200. } elseif ($format == 'dayhourlog') {
  2201. // Format not sensitive to language
  2202. $format = '%Y%m%d%H%M%S';
  2203. } elseif ($format == 'dayhourldap') {
  2204. $format = '%Y%m%d%H%M%SZ';
  2205. } elseif ($format == 'dayhourxcard') {
  2206. $format = '%Y%m%dT%H%M%SZ';
  2207. } elseif ($format == 'dayxcard') {
  2208. $format = '%Y%m%d';
  2209. } elseif ($format == 'dayrfc') {
  2210. $format = '%Y-%m-%d'; // DATE_RFC3339
  2211. } elseif ($format == 'dayhourrfc') {
  2212. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2213. } elseif ($format == 'standard') {
  2214. $format = '%Y-%m-%d %H:%M:%S';
  2215. }
  2216. if ($reduceformat) {
  2217. $format = str_replace('%Y', '%y', $format);
  2218. $format = str_replace('yyyy', 'yy', $format);
  2219. }
  2220. // Clean format
  2221. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2222. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2223. $format = str_replace('%b', '__b__', $format);
  2224. $format = str_replace('%B', '__B__', $format);
  2225. }
  2226. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2227. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2228. $format = str_replace('%a', '__a__', $format);
  2229. $format = str_replace('%A', '__A__', $format);
  2230. }
  2231. // Analyze date
  2232. $reg = array();
  2233. if (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
  2234. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2235. return '';
  2236. } elseif (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $time, $reg)) { // Still available to solve problems in extrafields of type date
  2237. // This part of code should not be used anymore.
  2238. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2239. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2240. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2241. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2242. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2243. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2244. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2245. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2246. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2247. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2248. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2249. } else {
  2250. // Date is a timestamps
  2251. if ($time < 100000000000) { // Protection against bad date values
  2252. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2253. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2254. } else {
  2255. $ret = 'Bad value '.$time.' for date';
  2256. }
  2257. }
  2258. if (preg_match('/__b__/i', $format)) {
  2259. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2260. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2261. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2262. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2263. if ($encodetooutput) {
  2264. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2265. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2266. } else {
  2267. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2268. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2269. }
  2270. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2271. $ret = str_replace('__b__', $monthtextshort, $ret);
  2272. $ret = str_replace('__B__', $monthtext, $ret);
  2273. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2274. //return $ret;
  2275. }
  2276. if (preg_match('/__a__/i', $format)) {
  2277. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2278. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2279. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2280. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2281. $ret = str_replace('__A__', $dayweek, $ret);
  2282. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2283. }
  2284. return $ret;
  2285. }
  2286. /**
  2287. * Return an array with locale date info.
  2288. * WARNING: This function use PHP server timezone by default to return locale informations.
  2289. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2290. *
  2291. * @param int $timestamp Timestamp
  2292. * @param boolean $fast Fast mode. deprecated.
  2293. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2294. * @return array Array of informations
  2295. * 'seconds' => $secs,
  2296. * 'minutes' => $min,
  2297. * 'hours' => $hour,
  2298. * 'mday' => $day,
  2299. * 'wday' => $dow, 0=sunday, 6=saturday
  2300. * 'mon' => $month,
  2301. * 'year' => $year,
  2302. * 'yday' => floor($secsInYear/$_day_power)
  2303. * '0' => original timestamp
  2304. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2305. */
  2306. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2307. {
  2308. //$datetimeobj = new DateTime('@'.$timestamp);
  2309. $datetimeobj = new DateTime();
  2310. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2311. if ($forcetimezone) {
  2312. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2313. }
  2314. $arrayinfo = array(
  2315. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2316. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2317. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2318. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2319. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2320. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2321. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2322. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2323. '0'=>$timestamp
  2324. );
  2325. return $arrayinfo;
  2326. }
  2327. /**
  2328. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2329. * Replace function mktime not available under Windows if year < 1970
  2330. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2331. *
  2332. * @param int $hour Hour (can be -1 for undefined)
  2333. * @param int $minute Minute (can be -1 for undefined)
  2334. * @param int $second Second (can be -1 for undefined)
  2335. * @param int $month Month (1 to 12)
  2336. * @param int $day Day (1 to 31)
  2337. * @param int $year Year
  2338. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2339. * False or 0 or 'tzserver' = local to server TZ
  2340. * 'auto'
  2341. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2342. * 'tzuserrel' = local to user TZ taking dst into account at the given date. Use this one to convert date input from user into a GMT date.
  2343. * 'tz,TimeZone' = use specified timezone
  2344. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2345. * @return int|string Date as a timestamp, '' or false if error
  2346. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2347. */
  2348. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2349. {
  2350. global $conf;
  2351. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2352. //print 'gm:'.$gm.' gm==auto:'.($gm == 'auto').'<br>';
  2353. if ($gm === 'auto') {
  2354. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2355. }
  2356. // Clean parameters
  2357. if ($hour == -1 || empty($hour)) {
  2358. $hour = 0;
  2359. }
  2360. if ($minute == -1 || empty($minute)) {
  2361. $minute = 0;
  2362. }
  2363. if ($second == -1 || empty($second)) {
  2364. $second = 0;
  2365. }
  2366. // Check parameters
  2367. if ($check) {
  2368. if (!$month || !$day) {
  2369. return '';
  2370. }
  2371. if ($day > 31) {
  2372. return '';
  2373. }
  2374. if ($month > 12) {
  2375. return '';
  2376. }
  2377. if ($hour < 0 || $hour > 24) {
  2378. return '';
  2379. }
  2380. if ($minute < 0 || $minute > 60) {
  2381. return '';
  2382. }
  2383. if ($second < 0 || $second > 60) {
  2384. return '';
  2385. }
  2386. }
  2387. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2388. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2389. $localtz = new DateTimeZone($default_timezone);
  2390. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2391. // We use dol_tz_string first because it is more reliable.
  2392. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2393. try {
  2394. $localtz = new DateTimeZone($default_timezone);
  2395. } catch (Exception $e) {
  2396. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2397. $default_timezone = @date_default_timezone_get();
  2398. }
  2399. } elseif (strrpos($gm, "tz,") !== false) {
  2400. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2401. try {
  2402. $localtz = new DateTimeZone($timezone);
  2403. } catch (Exception $e) {
  2404. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2405. }
  2406. }
  2407. if (empty($localtz)) {
  2408. $localtz = new DateTimeZone('UTC');
  2409. }
  2410. //var_dump($localtz);
  2411. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2412. $dt = new DateTime(null, $localtz);
  2413. $dt->setDate((int) $year, (int) $month, (int) $day);
  2414. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2415. $date = $dt->getTimestamp(); // should include daylight saving time
  2416. //var_dump($date);
  2417. return $date;
  2418. }
  2419. /**
  2420. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2421. *
  2422. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2423. * 'gmt' => we return GMT timestamp,
  2424. * 'tzserver' => we add the PHP server timezone
  2425. * 'tzref' => we add the company timezone. Not implemented.
  2426. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2427. * @return int $date Timestamp
  2428. */
  2429. function dol_now($mode = 'auto')
  2430. {
  2431. $ret = 0;
  2432. if ($mode === 'auto') {
  2433. $mode = 'gmt';
  2434. }
  2435. if ($mode == 'gmt') {
  2436. $ret = time(); // Time for now at greenwich.
  2437. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2438. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2439. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2440. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2441. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2442. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2443. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2444. // $ret=dol_now('gmt')+($tzsecond*3600);
  2445. //}
  2446. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2447. // Time for now with user timezone added
  2448. //print 'time: '.time();
  2449. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2450. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2451. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2452. }
  2453. return $ret;
  2454. }
  2455. /**
  2456. * Return string with formated size
  2457. *
  2458. * @param int $size Size to print
  2459. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2460. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2461. * @return string Link
  2462. */
  2463. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2464. {
  2465. global $conf, $langs;
  2466. $level = 1024;
  2467. if (!empty($conf->dol_optimize_smallscreen)) {
  2468. $shortunit = 1;
  2469. }
  2470. // Set value text
  2471. if (empty($shortvalue) || $size < ($level * 10)) {
  2472. $ret = $size;
  2473. $textunitshort = $langs->trans("b");
  2474. $textunitlong = $langs->trans("Bytes");
  2475. } else {
  2476. $ret = round($size / $level, 0);
  2477. $textunitshort = $langs->trans("Kb");
  2478. $textunitlong = $langs->trans("KiloBytes");
  2479. }
  2480. // Use long or short text unit
  2481. if (empty($shortunit)) {
  2482. $ret .= ' '.$textunitlong;
  2483. } else {
  2484. $ret .= ' '.$textunitshort;
  2485. }
  2486. return $ret;
  2487. }
  2488. /**
  2489. * Show Url link
  2490. *
  2491. * @param string $url Url to show
  2492. * @param string $target Target for link
  2493. * @param int $max Max number of characters to show
  2494. * @param int $withpicto With picto
  2495. * @return string HTML Link
  2496. */
  2497. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2498. {
  2499. global $langs;
  2500. if (empty($url)) {
  2501. return '';
  2502. }
  2503. $link = '<a href="';
  2504. if (!preg_match('/^http/i', $url)) {
  2505. $link .= 'http://';
  2506. }
  2507. $link .= $url;
  2508. $link .= '"';
  2509. if ($target) {
  2510. $link .= ' target="'.$target.'"';
  2511. }
  2512. $link .= '>';
  2513. if (!preg_match('/^http/i', $url)) {
  2514. $link .= 'http://';
  2515. }
  2516. $link .= dol_trunc($url, $max);
  2517. $link .= '</a>';
  2518. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2519. }
  2520. /**
  2521. * Show EMail link formatted for HTML output.
  2522. *
  2523. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2524. * @param int $cid Id of contact if known
  2525. * @param int $socid Id of third party if known
  2526. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2527. * @param int $max Max number of characters to show
  2528. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2529. * @param int $withpicto Show picto
  2530. * @return string HTML Link
  2531. */
  2532. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2533. {
  2534. global $conf, $user, $langs, $hookmanager;
  2535. $newemail = dol_escape_htmltag($email);
  2536. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2537. $withpicto = 0;
  2538. }
  2539. if (empty($email)) {
  2540. return '&nbsp;';
  2541. }
  2542. if (!empty($addlink)) {
  2543. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2544. if (!preg_match('/^mailto:/i', $email)) {
  2545. $newemail .= 'mailto:';
  2546. }
  2547. $newemail .= $email;
  2548. $newemail .= '">';
  2549. $newemail .= dol_trunc($email, $max);
  2550. $newemail .= '</a>';
  2551. if ($showinvalid && !isValidEmail($email)) {
  2552. $langs->load("errors");
  2553. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2554. }
  2555. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2556. $type = 'AC_EMAIL';
  2557. $link = '';
  2558. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2559. $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>';
  2560. }
  2561. if ($link) {
  2562. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2563. }
  2564. }
  2565. } else {
  2566. if ($showinvalid && !isValidEmail($email)) {
  2567. $langs->load("errors");
  2568. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2569. }
  2570. }
  2571. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2572. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2573. //$rep .= '</div>';
  2574. if ($hookmanager) {
  2575. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2576. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2577. if ($reshook > 0) {
  2578. $rep = '';
  2579. }
  2580. $rep .= $hookmanager->resPrint;
  2581. }
  2582. return $rep;
  2583. }
  2584. /**
  2585. * Get array of social network dictionary
  2586. *
  2587. * @return array Array of Social Networks Dictionary
  2588. */
  2589. function getArrayOfSocialNetworks()
  2590. {
  2591. global $conf, $db;
  2592. $socialnetworks = array();
  2593. // Enable caching of array
  2594. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2595. $cachekey = 'socialnetworks_' . $conf->entity;
  2596. $dataretrieved = dol_getcache($cachekey);
  2597. if (!is_null($dataretrieved)) {
  2598. $socialnetworks = $dataretrieved;
  2599. } else {
  2600. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2601. $sql .= " WHERE entity=".$conf->entity;
  2602. $resql = $db->query($sql);
  2603. if ($resql) {
  2604. while ($obj = $db->fetch_object($resql)) {
  2605. $socialnetworks[$obj->code] = array(
  2606. 'rowid' => $obj->rowid,
  2607. 'label' => $obj->label,
  2608. 'url' => $obj->url,
  2609. 'icon' => $obj->icon,
  2610. 'active' => $obj->active,
  2611. );
  2612. }
  2613. }
  2614. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2615. }
  2616. return $socialnetworks;
  2617. }
  2618. /**
  2619. * Show social network link
  2620. *
  2621. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2622. * @param int $cid Id of contact if known
  2623. * @param int $socid Id of third party if known
  2624. * @param string $type 'skype','facebook',...
  2625. * @param array $dictsocialnetworks socialnetworks availables
  2626. * @return string HTML Link
  2627. */
  2628. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2629. {
  2630. global $conf, $user, $langs;
  2631. $htmllink = $value;
  2632. if (empty($value)) {
  2633. return '&nbsp;';
  2634. }
  2635. if (!empty($type)) {
  2636. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2637. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2638. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2639. if ($type == 'skype') {
  2640. $htmllink .= $value;
  2641. $htmllink .= '&nbsp;';
  2642. $htmllink .= '<a href="skype:';
  2643. $htmllink .= $value;
  2644. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2645. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2646. $htmllink .= '</a><a href="skype:';
  2647. $htmllink .= $value;
  2648. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2649. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2650. $htmllink .= '</a>';
  2651. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2652. $addlink = 'AC_SKYPE';
  2653. $link = '';
  2654. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2655. $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$addlink.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  2656. }
  2657. $htmllink .= ($link ? ' '.$link : '');
  2658. }
  2659. } else {
  2660. if (!empty($dictsocialnetworks[$type]['url'])) {
  2661. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2662. $htmllink .= '&nbsp;<a href="'.$link.'" target="_blank" rel="noopener noreferrer">'.$value.'</a>';
  2663. } else {
  2664. $htmllink .= $value;
  2665. }
  2666. }
  2667. $htmllink .= '</div>';
  2668. } else {
  2669. $langs->load("errors");
  2670. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2671. }
  2672. return $htmllink;
  2673. }
  2674. /**
  2675. * Format phone numbers according to country
  2676. *
  2677. * @param string $phone Phone number to format
  2678. * @param string $countrycode Country code to use for formatting
  2679. * @param int $cid Id of contact if known
  2680. * @param int $socid Id of third party if known
  2681. * @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)
  2682. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2683. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2684. * @param string $titlealt Text to show on alt
  2685. * @param int $adddivfloat Add div float around phone.
  2686. * @return string Formated phone number
  2687. */
  2688. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2689. {
  2690. global $conf, $user, $langs, $mysoc, $hookmanager;
  2691. // Clean phone parameter
  2692. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2693. if (empty($phone)) {
  2694. return '';
  2695. }
  2696. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2697. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2698. }
  2699. if (empty($countrycode)) {
  2700. $countrycode = $mysoc->country_code;
  2701. }
  2702. // Short format for small screens
  2703. if ($conf->dol_optimize_smallscreen) {
  2704. $separ = '';
  2705. }
  2706. $newphone = $phone;
  2707. if (strtoupper($countrycode) == "FR") {
  2708. // France
  2709. if (dol_strlen($phone) == 10) {
  2710. $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);
  2711. } elseif (dol_strlen($phone) == 7) {
  2712. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2713. } elseif (dol_strlen($phone) == 9) {
  2714. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2715. } elseif (dol_strlen($phone) == 11) {
  2716. $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);
  2717. } elseif (dol_strlen($phone) == 12) {
  2718. $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);
  2719. }
  2720. } elseif (strtoupper($countrycode) == "CA") {
  2721. if (dol_strlen($phone) == 10) {
  2722. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2723. }
  2724. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2725. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2726. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2727. }
  2728. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2729. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2730. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2731. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2732. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2733. }
  2734. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2735. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2736. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2737. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2738. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2739. }
  2740. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2741. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2742. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2743. }
  2744. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2745. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2746. $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);
  2747. }
  2748. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2749. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2750. $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);
  2751. }
  2752. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2753. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2754. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2755. }
  2756. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2757. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2758. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2759. }
  2760. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2761. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2762. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2763. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2764. $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);
  2765. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2766. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2767. }
  2768. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2769. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2770. $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);
  2771. }
  2772. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2773. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2774. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2775. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2776. $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);
  2777. }
  2778. } elseif (strtoupper($countrycode) == "MU") {
  2779. //Maurice
  2780. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  2781. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2782. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  2783. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2784. }
  2785. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  2786. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  2787. $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);
  2788. }
  2789. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  2790. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  2791. $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);
  2792. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  2793. $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);
  2794. }
  2795. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  2796. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  2797. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2798. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  2799. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2800. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  2801. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2802. }
  2803. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  2804. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  2805. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2806. }
  2807. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  2808. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  2809. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2810. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  2811. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2812. }
  2813. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  2814. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  2815. $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);
  2816. }
  2817. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  2818. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  2819. $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);
  2820. }
  2821. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  2822. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  2823. $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);
  2824. }
  2825. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  2826. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  2827. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2828. }
  2829. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  2830. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
  2831. $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);
  2832. }
  2833. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  2834. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  2835. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2836. }
  2837. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  2838. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  2839. $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);
  2840. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  2841. $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);
  2842. }
  2843. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  2844. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  2845. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2846. }
  2847. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  2848. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2849. $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);
  2850. }
  2851. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  2852. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2853. $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);
  2854. }
  2855. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  2856. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2857. $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);
  2858. }
  2859. } elseif (strtoupper($countrycode) == "IT") {//Italie
  2860. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  2861. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2862. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  2863. $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);
  2864. }
  2865. } elseif (strtoupper($countrycode) == "AU") {
  2866. //Australie
  2867. if (dol_strlen($phone) == 12) {
  2868. //ex: +61_A_BCDE_FGHI
  2869. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2870. }
  2871. }
  2872. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2873. if ($conf->browser->layout == 'phone' || (!empty($conf->clicktodial->enabled) && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) { // If phone or option for, we use link of phone
  2874. $newphoneform = $newphone;
  2875. $newphone = '<a href="tel:'.$phone.'"';
  2876. $newphone .= '>'.$newphoneform.'</a>';
  2877. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  2878. if (empty($user->clicktodial_loaded)) {
  2879. $user->fetch_clicktodial();
  2880. }
  2881. // Define urlmask
  2882. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2883. if (!empty($conf->global->CLICKTODIAL_URL)) {
  2884. $urlmask = $conf->global->CLICKTODIAL_URL;
  2885. }
  2886. if (!empty($user->clicktodial_url)) {
  2887. $urlmask = $user->clicktodial_url;
  2888. }
  2889. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2890. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2891. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2892. // This line is for backward compatibility
  2893. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2894. // Thoose lines are for substitution
  2895. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2896. '__PHONETO__'=>urlencode($phone),
  2897. '__LOGIN__'=>$clicktodial_login,
  2898. '__PASS__'=>$clicktodial_password);
  2899. $url = make_substitutions($url, $substitarray);
  2900. $newphonesav = $newphone;
  2901. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  2902. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  2903. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  2904. $newphone .= '>'.$newphonesav.'</a>';
  2905. } else {
  2906. // Old method
  2907. $newphone = '<a href="'.$url.'"';
  2908. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  2909. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  2910. }
  2911. $newphone .= '>'.$newphonesav.'</a>';
  2912. }
  2913. }
  2914. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2915. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2916. $type = 'AC_TEL';
  2917. $link = '';
  2918. if ($addlink == 'AC_FAX') {
  2919. $type = 'AC_FAX';
  2920. }
  2921. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  2922. $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>';
  2923. }
  2924. if ($link) {
  2925. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2926. }
  2927. }
  2928. }
  2929. if (empty($titlealt)) {
  2930. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2931. }
  2932. $rep = '';
  2933. if ($hookmanager) {
  2934. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2935. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2936. $rep .= $hookmanager->resPrint;
  2937. }
  2938. if (empty($reshook)) {
  2939. $picto = '';
  2940. if ($withpicto) {
  2941. if ($withpicto == 'fax') {
  2942. $picto = 'phoning_fax';
  2943. } elseif ($withpicto == 'phone') {
  2944. $picto = 'phoning';
  2945. } elseif ($withpicto == 'mobile') {
  2946. $picto = 'phoning_mobile';
  2947. } else {
  2948. $picto = '';
  2949. }
  2950. }
  2951. if ($adddivfloat) {
  2952. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2953. } else {
  2954. $rep .= '<span style="margin-right: 10px;">';
  2955. }
  2956. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2957. if ($adddivfloat) {
  2958. $rep .= '</div>';
  2959. } else {
  2960. $rep .= '</span>';
  2961. }
  2962. }
  2963. return $rep;
  2964. }
  2965. /**
  2966. * Return an IP formated to be shown on screen
  2967. *
  2968. * @param string $ip IP
  2969. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2970. * @return string Formated IP, with country if GeoIP module is enabled
  2971. */
  2972. function dol_print_ip($ip, $mode = 0)
  2973. {
  2974. global $conf, $langs;
  2975. $ret = '';
  2976. if (empty($mode)) {
  2977. $ret .= $ip;
  2978. }
  2979. if ($mode != 2) {
  2980. $countrycode = dolGetCountryCodeFromIp($ip);
  2981. if ($countrycode) { // If success, countrycode is us, fr, ...
  2982. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  2983. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2984. } else {
  2985. $ret .= ' ('.$countrycode.')';
  2986. }
  2987. } else {
  2988. // Nothing
  2989. }
  2990. }
  2991. return $ret;
  2992. }
  2993. /**
  2994. * Return the IP of remote user.
  2995. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2996. * Then HTTP_CLIENT_IP if defined (rare)
  2997. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2998. *
  2999. * @return string Ip of remote user.
  3000. */
  3001. function getUserRemoteIP()
  3002. {
  3003. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3004. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3005. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3006. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3007. } else {
  3008. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3009. }
  3010. } else {
  3011. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3012. }
  3013. } else {
  3014. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3015. }
  3016. return $ip;
  3017. }
  3018. /**
  3019. * Return if we are using a HTTPS connexion
  3020. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3021. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3022. * Then HTTP_X_FORWARDED_SSL
  3023. *
  3024. * @return boolean True if user is using HTTPS
  3025. */
  3026. function isHTTPS()
  3027. {
  3028. $isSecure = false;
  3029. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3030. $isSecure = true;
  3031. } elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
  3032. $isSecure = true;
  3033. }
  3034. return $isSecure;
  3035. }
  3036. /**
  3037. * Return a country code from IP. Empty string if not found.
  3038. *
  3039. * @param string $ip IP
  3040. * @return string Country code ('us', 'fr', ...)
  3041. */
  3042. function dolGetCountryCodeFromIp($ip)
  3043. {
  3044. global $conf;
  3045. $countrycode = '';
  3046. if (!empty($conf->geoipmaxmind->enabled)) {
  3047. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3048. //$ip='24.24.24.24';
  3049. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3050. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3051. $geoip = new DolGeoIP('country', $datafile);
  3052. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3053. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3054. }
  3055. return $countrycode;
  3056. }
  3057. /**
  3058. * Return country code for current user.
  3059. * If software is used inside a local network, detection may fails (we need a public ip)
  3060. *
  3061. * @return string Country code (fr, es, it, us, ...)
  3062. */
  3063. function dol_user_country()
  3064. {
  3065. global $conf, $langs, $user;
  3066. //$ret=$user->xxx;
  3067. $ret = '';
  3068. if (!empty($conf->geoipmaxmind->enabled)) {
  3069. $ip = getUserRemoteIP();
  3070. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3071. //$ip='24.24.24.24';
  3072. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3073. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3074. $geoip = new DolGeoIP('country', $datafile);
  3075. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3076. $ret = $countrycode;
  3077. }
  3078. return $ret;
  3079. }
  3080. /**
  3081. * Format address string
  3082. *
  3083. * @param string $address Address string, already formatted with dol_format_address()
  3084. * @param int $htmlid Html ID (for example 'gmap')
  3085. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3086. * @param int $id Id of object
  3087. * @param int $noprint No output. Result is the function return
  3088. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3089. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3090. * @see dol_format_address()
  3091. */
  3092. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3093. {
  3094. global $conf, $user, $langs, $hookmanager;
  3095. $out = '';
  3096. if ($address) {
  3097. if ($hookmanager) {
  3098. $parameters = array('element' => $element, 'id' => $id);
  3099. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3100. $out .= $hookmanager->resPrint;
  3101. }
  3102. if (empty($reshook)) {
  3103. if (empty($charfornl)) {
  3104. $out .= nl2br($address);
  3105. } else {
  3106. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3107. }
  3108. // TODO Remove this block, we can add this using the hook now
  3109. $showgmap = $showomap = 0;
  3110. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3111. $showgmap = 1;
  3112. }
  3113. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3114. $showgmap = 1;
  3115. }
  3116. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3117. $showgmap = 1;
  3118. }
  3119. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3120. $showomap = 1;
  3121. }
  3122. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3123. $showomap = 1;
  3124. }
  3125. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3126. $showomap = 1;
  3127. }
  3128. if ($showgmap) {
  3129. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3130. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3131. }
  3132. if ($showomap) {
  3133. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3134. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3135. }
  3136. }
  3137. }
  3138. if ($noprint) {
  3139. return $out;
  3140. } else {
  3141. print $out;
  3142. }
  3143. }
  3144. /**
  3145. * Return true if email syntax is ok.
  3146. *
  3147. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3148. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3149. * @return boolean true if email syntax is OK, false if KO or empty string
  3150. * @see isValidMXRecord()
  3151. */
  3152. function isValidEmail($address, $acceptsupervisorkey = 0)
  3153. {
  3154. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3155. return true;
  3156. }
  3157. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3158. return true;
  3159. }
  3160. return false;
  3161. }
  3162. /**
  3163. * Return if the domain name has a valid MX record.
  3164. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3165. *
  3166. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3167. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3168. * @see isValidEmail()
  3169. */
  3170. function isValidMXRecord($domain)
  3171. {
  3172. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3173. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3174. return 0;
  3175. }
  3176. if (function_exists('getmxrr')) {
  3177. $mxhosts = array();
  3178. $weight = array();
  3179. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3180. if (count($mxhosts) > 1) {
  3181. return 1;
  3182. }
  3183. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3184. return 1;
  3185. }
  3186. return 0;
  3187. }
  3188. }
  3189. return -1;
  3190. }
  3191. /**
  3192. * Return true if phone number syntax is ok
  3193. * TODO Decide what to do with this
  3194. *
  3195. * @param string $phone phone (Ex: "0601010101")
  3196. * @return boolean true if phone syntax is OK, false if KO or empty string
  3197. */
  3198. function isValidPhone($phone)
  3199. {
  3200. return true;
  3201. }
  3202. /**
  3203. * Make a strlen call. Works even if mbstring module not enabled
  3204. *
  3205. * @param string $string String to calculate length
  3206. * @param string $stringencoding Encoding of string
  3207. * @return int Length of string
  3208. */
  3209. function dol_strlen($string, $stringencoding = 'UTF-8')
  3210. {
  3211. if (function_exists('mb_strlen')) {
  3212. return mb_strlen($string, $stringencoding);
  3213. } else {
  3214. return strlen($string);
  3215. }
  3216. }
  3217. /**
  3218. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3219. *
  3220. * @param string $string String to scan
  3221. * @param string $start Start position
  3222. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3223. * @param string $stringencoding Page code used for input string encoding
  3224. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3225. * @return string substring
  3226. */
  3227. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3228. {
  3229. global $langs;
  3230. if (empty($stringencoding)) {
  3231. $stringencoding = $langs->charset_output;
  3232. }
  3233. $ret = '';
  3234. if (empty($trunconbytes)) {
  3235. if (function_exists('mb_substr')) {
  3236. $ret = mb_substr($string, $start, $length, $stringencoding);
  3237. } else {
  3238. $ret = substr($string, $start, $length);
  3239. }
  3240. } else {
  3241. if (function_exists('mb_strcut')) {
  3242. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3243. } else {
  3244. $ret = substr($string, $start, $length);
  3245. }
  3246. }
  3247. return $ret;
  3248. }
  3249. /**
  3250. * Truncate a string to a particular length adding '…' if string larger than length.
  3251. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3252. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3253. *
  3254. * @param string $string String to truncate
  3255. * @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 so it does not worse to replace with ...)
  3256. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3257. * @param string $stringencoding Tell what is source string encoding
  3258. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3259. * @param int $display Trunc is used to display data and can be changed for small screen. TODO Remove this param (must be dealt with CSS)
  3260. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3261. */
  3262. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3263. {
  3264. global $conf;
  3265. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3266. return $string;
  3267. }
  3268. if (empty($stringencoding)) {
  3269. $stringencoding = 'UTF-8';
  3270. }
  3271. // reduce for small screen
  3272. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3273. $size = round($size / 3);
  3274. }
  3275. // We go always here
  3276. if ($trunc == 'right') {
  3277. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3278. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3279. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3280. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3281. } else {
  3282. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3283. return $string;
  3284. }
  3285. } elseif ($trunc == 'middle') {
  3286. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3287. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3288. $size1 = round($size / 2);
  3289. $size2 = round($size / 2);
  3290. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3291. } else {
  3292. return $string;
  3293. }
  3294. } elseif ($trunc == 'left') {
  3295. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3296. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3297. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3298. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3299. } else {
  3300. return $string;
  3301. }
  3302. } elseif ($trunc == 'wrap') {
  3303. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3304. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3305. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3306. } else {
  3307. return $string;
  3308. }
  3309. } else {
  3310. return 'BadParam3CallingDolTrunc';
  3311. }
  3312. }
  3313. /**
  3314. * Show picto whatever it's its name (generic function)
  3315. *
  3316. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3317. * @param string $picto Name of image file to show ('filenew', ...)
  3318. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3319. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3320. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3321. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3322. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3323. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3324. * @param int $srconly Return only content of the src attribute of img.
  3325. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3326. * @param string $alt Force alt for bind people
  3327. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3328. * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No margin left. Works for fontawesome picto only.
  3329. * @return string Return img tag
  3330. * @see img_object(), img_picto_common()
  3331. */
  3332. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3333. {
  3334. global $conf, $langs;
  3335. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3336. $url = DOL_URL_ROOT;
  3337. $theme = isset($conf->theme) ? $conf->theme : null;
  3338. $path = 'theme/'.$theme;
  3339. // Define fullpathpicto to use into src
  3340. if ($pictoisfullpath) {
  3341. // Clean parameters
  3342. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3343. $picto .= '.png';
  3344. }
  3345. $fullpathpicto = $picto;
  3346. $reg = array();
  3347. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3348. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3349. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3350. }
  3351. } else {
  3352. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3353. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3354. if (empty($srconly) && in_array($pictowithouttext, array(
  3355. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3356. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3357. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'bug', 'building',
  3358. 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3359. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3360. 'multicurrency',
  3361. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3362. 'edit', 'ellipsis-h', 'email', 'entity', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3363. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3364. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3365. 'help', 'holiday',
  3366. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3367. 'label', 'language', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3368. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3369. 'off', 'on', 'order',
  3370. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'stock', 'resize', 'service', 'stats', 'trip',
  3371. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3372. 'github', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3373. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3374. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3375. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3376. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3377. 'technic', 'ticket',
  3378. 'error', 'warning',
  3379. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource', 'recurring',
  3380. 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3381. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3382. 'uncheck', 'user-cog', 'vat', 'website', 'workstation',
  3383. 'conferenceorbooth', 'eventorganization'
  3384. ))) {
  3385. $fakey = $pictowithouttext;
  3386. $facolor = '';
  3387. $fasize = '';
  3388. $fa = 'fas';
  3389. if (in_array($pictowithouttext, array('bell', 'clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3390. $fa = 'far';
  3391. }
  3392. if (in_array($pictowithouttext, array('black-tie', 'github', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3393. $fa = 'fab';
  3394. }
  3395. $arrayconvpictotofa = array(
  3396. 'account'=>'university', 'accounting_account'=>'clipboard-list', 'accountline'=>'receipt', 'accountancy'=>'search-dollar', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book', 'asset'=>'money-check-alt', 'autofill'=>'fill',
  3397. 'bank_account'=>'university',
  3398. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3399. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3400. 'bom'=>'shapes',
  3401. 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3402. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3403. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3404. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3405. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3406. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3407. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3408. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3409. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3410. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'loan'=>'money-bill-alt',
  3411. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3412. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3413. 'sign-out'=>'sign-out-alt',
  3414. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3415. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3416. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3417. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3418. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3419. 'other'=>'square',
  3420. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3421. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell',
  3422. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3423. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3424. 'refresh'=>'redo', 'region'=>'map-marked', 'resource'=>'laptop-house', 'recurring'=>'history',
  3425. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3426. 'supplier'=>'building', 'technic'=>'cogs',
  3427. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3428. 'title_agenda'=>'calendar-alt',
  3429. 'uncheck'=>'times', 'uparrow'=>'share', 'vat'=>'money-check-alt', 'vcard'=>'address-card',
  3430. 'jabber'=>'comment-o',
  3431. 'website'=>'globe-americas', 'workstation'=>'pallet',
  3432. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3433. );
  3434. if ($pictowithouttext == 'off') {
  3435. $fakey = 'fa-square';
  3436. $fasize = '1.3em';
  3437. } elseif ($pictowithouttext == 'on') {
  3438. $fakey = 'fa-check-square';
  3439. $fasize = '1.3em';
  3440. } elseif ($pictowithouttext == 'listlight') {
  3441. $fakey = 'fa-download';
  3442. $marginleftonlyshort = 1;
  3443. } elseif ($pictowithouttext == 'printer') {
  3444. $fakey = 'fa-print';
  3445. $fasize = '1.2em';
  3446. } elseif ($pictowithouttext == 'note') {
  3447. $fakey = 'fa-sticky-note';
  3448. $marginleftonlyshort = 1;
  3449. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3450. $convertarray = array('1uparrow'=>'caret-up', '1downarrow'=>'caret-down', '1leftarrow'=>'caret-left', '1rightarrow'=>'caret-right', '1uparrow_selected'=>'caret-up', '1downarrow_selected'=>'caret-down', '1leftarrow_selected'=>'caret-left', '1rightarrow_selected'=>'caret-right');
  3451. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3452. if (preg_match('/selected/', $pictowithouttext)) {
  3453. $facolor = '#888';
  3454. }
  3455. $marginleftonlyshort = 1;
  3456. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3457. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3458. } else {
  3459. $fakey = 'fa-'.$pictowithouttext;
  3460. }
  3461. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3462. $morecss .= ' em092';
  3463. }
  3464. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3465. $morecss .= ' em088';
  3466. }
  3467. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3468. $morecss .= ' em080';
  3469. }
  3470. // Define $marginleftonlyshort
  3471. $arrayconvpictotomarginleftonly = array(
  3472. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3473. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3474. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3475. );
  3476. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3477. $marginleftonlyshort = 0;
  3478. }
  3479. // Add CSS
  3480. $arrayconvpictotomorcess = array(
  3481. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3482. 'bank_account'=>'bg-infobox-bank_account',
  3483. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3484. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3485. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3486. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3487. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3488. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3489. 'incoterm'=>'infobox-supplier_proposal',
  3490. 'multicurrency'=>'infobox-bank_account',
  3491. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3492. 'order'=>'infobox-commande',
  3493. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3494. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_red'=>'font-status8',
  3495. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3496. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3497. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  3498. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3499. 'resource'=>'infobox-action',
  3500. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3501. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3502. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3503. 'vat'=>'infobox-bank_account',
  3504. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3505. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3506. );
  3507. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3508. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3509. }
  3510. // Define $color
  3511. $arrayconvpictotocolor = array(
  3512. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3513. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3514. 'dynamicprice'=>'#a69944',
  3515. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3516. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3517. 'lot'=>'#a69944',
  3518. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3519. 'other'=>'#ddd',
  3520. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3521. //'shipment'=>'#a69944',
  3522. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3523. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3524. 'website'=>'#304', 'workstation'=>'#a69944'
  3525. );
  3526. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3527. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3528. }
  3529. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3530. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3531. $morestyle = '';
  3532. $reg = array();
  3533. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3534. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3535. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3536. }
  3537. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3538. $morestyle = $reg[1];
  3539. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3540. }
  3541. $moreatt = trim($moreatt);
  3542. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3543. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3544. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3545. $enabledisablehtml .= $titlealt;
  3546. }*/
  3547. $enabledisablehtml .= '</span>';
  3548. return $enabledisablehtml;
  3549. }
  3550. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3551. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3552. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3553. $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
  3554. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3555. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3556. }
  3557. // If we ask an image into $url/$mymodule/img (instead of default path)
  3558. $regs = array();
  3559. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3560. $picto = $regs[1];
  3561. $path = $regs[2]; // $path is $mymodule
  3562. }
  3563. // Clean parameters
  3564. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3565. $picto .= '.png';
  3566. }
  3567. // If alt path are defined, define url where img file is, according to physical path
  3568. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3569. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3570. if ($type == 'main') {
  3571. continue;
  3572. }
  3573. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3574. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3575. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3576. break;
  3577. }
  3578. }
  3579. // $url is '' or '/custom', $path is current theme or
  3580. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3581. }
  3582. if ($srconly) {
  3583. return $fullpathpicto;
  3584. }
  3585. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3586. return '<img src="'.$fullpathpicto.'"'.($notitle ? '' : ' alt="'.dol_escape_htmltag($alt).'"').(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt.($morecss ? ' class="'.$morecss.'"' : '') : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
  3587. }
  3588. /**
  3589. * Show a picto called object_picto (generic function)
  3590. *
  3591. * @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.
  3592. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3593. * For external modules use imagename@mymodule to search into directory "img" of module.
  3594. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3595. * @param int $pictoisfullpath If 1, image path is a full path
  3596. * @param int $srconly Return only content of the src attribute of img.
  3597. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3598. * @return string Return img tag
  3599. * @see img_picto(), img_picto_common()
  3600. */
  3601. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3602. {
  3603. if (strpos($picto, '^') === 0) {
  3604. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3605. } else {
  3606. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3607. }
  3608. }
  3609. /**
  3610. * Show weather picto
  3611. *
  3612. * @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.
  3613. * @param string|int $picto Name of image file to show (If no extension provided, we use '.png'). Image must be stored into htdocs/theme/common directory. Or level of meteo image (0-4).
  3614. * @param string $moreatt Add more attribute on img tag
  3615. * @param int $pictoisfullpath If 1, image path is a full path
  3616. * @param string $morecss More CSS
  3617. * @return string Return img tag
  3618. * @see img_object(), img_picto()
  3619. */
  3620. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3621. {
  3622. global $conf;
  3623. if (is_numeric($picto)) {
  3624. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3625. //$picto = $leveltopicto[$picto];
  3626. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3627. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3628. $picto .= '.png';
  3629. }
  3630. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3631. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3632. }
  3633. /**
  3634. * Show picto (generic function)
  3635. *
  3636. * @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.
  3637. * @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.
  3638. * @param string $moreatt Add more attribute on img tag
  3639. * @param int $pictoisfullpath If 1, image path is a full path
  3640. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3641. * @return string Return img tag
  3642. * @see img_object(), img_picto()
  3643. */
  3644. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  3645. {
  3646. global $conf;
  3647. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3648. $picto .= '.png';
  3649. }
  3650. if ($pictoisfullpath) {
  3651. $path = $picto;
  3652. } else {
  3653. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3654. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3655. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3656. if (file_exists($themepath)) {
  3657. $path = $themepath;
  3658. }
  3659. }
  3660. }
  3661. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  3662. }
  3663. /**
  3664. * Show logo action
  3665. *
  3666. * @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.
  3667. * @param string $numaction Action id or code to show
  3668. * @param string $picto Name of image file to show ('filenew', ...)
  3669. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3670. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3671. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3672. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3673. * @return string Return an img tag
  3674. */
  3675. function img_action($titlealt, $numaction, $picto = '')
  3676. {
  3677. global $langs;
  3678. if (empty($titlealt) || $titlealt == 'default') {
  3679. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3680. $numaction = -1;
  3681. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3682. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3683. $numaction = 0;
  3684. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3685. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3686. $numaction = 1;
  3687. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3688. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3689. $numaction = 2;
  3690. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3691. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3692. $numaction = 3;
  3693. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3694. } else {
  3695. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3696. $numaction = 0;
  3697. }
  3698. }
  3699. if (!is_numeric($numaction)) {
  3700. $numaction = 0;
  3701. }
  3702. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3703. }
  3704. /**
  3705. * Show pdf logo
  3706. *
  3707. * @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.
  3708. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3709. * @return string Retourne tag img
  3710. */
  3711. function img_pdf($titlealt = 'default', $size = 3)
  3712. {
  3713. global $langs;
  3714. if ($titlealt == 'default') {
  3715. $titlealt = $langs->trans('Show');
  3716. }
  3717. return img_picto($titlealt, 'pdf'.$size.'.png');
  3718. }
  3719. /**
  3720. * Show logo +
  3721. *
  3722. * @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.
  3723. * @param string $other Add more attributes on img
  3724. * @return string Return tag img
  3725. */
  3726. function img_edit_add($titlealt = 'default', $other = '')
  3727. {
  3728. global $langs;
  3729. if ($titlealt == 'default') {
  3730. $titlealt = $langs->trans('Add');
  3731. }
  3732. return img_picto($titlealt, 'edit_add.png', $other);
  3733. }
  3734. /**
  3735. * Show logo -
  3736. *
  3737. * @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.
  3738. * @param string $other Add more attributes on img
  3739. * @return string Return tag img
  3740. */
  3741. function img_edit_remove($titlealt = 'default', $other = '')
  3742. {
  3743. global $langs;
  3744. if ($titlealt == 'default') {
  3745. $titlealt = $langs->trans('Remove');
  3746. }
  3747. return img_picto($titlealt, 'edit_remove.png', $other);
  3748. }
  3749. /**
  3750. * Show logo editer/modifier fiche
  3751. *
  3752. * @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.
  3753. * @param integer $float If you have to put the style "float: right"
  3754. * @param string $other Add more attributes on img
  3755. * @return string Return tag img
  3756. */
  3757. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3758. {
  3759. global $langs;
  3760. if ($titlealt == 'default') {
  3761. $titlealt = $langs->trans('Modify');
  3762. }
  3763. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3764. }
  3765. /**
  3766. * Show logo view card
  3767. *
  3768. * @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.
  3769. * @param integer $float If you have to put the style "float: right"
  3770. * @param string $other Add more attributes on img
  3771. * @return string Return tag img
  3772. */
  3773. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  3774. {
  3775. global $langs;
  3776. if ($titlealt == 'default') {
  3777. $titlealt = $langs->trans('View');
  3778. }
  3779. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3780. return img_picto($titlealt, 'view.png', $moreatt);
  3781. }
  3782. /**
  3783. * Show delete logo
  3784. *
  3785. * @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.
  3786. * @param string $other Add more attributes on img
  3787. * @param string $morecss More CSS
  3788. * @return string Retourne tag img
  3789. */
  3790. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3791. {
  3792. global $langs;
  3793. if ($titlealt == 'default') {
  3794. $titlealt = $langs->trans('Delete');
  3795. }
  3796. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3797. }
  3798. /**
  3799. * Show printer logo
  3800. *
  3801. * @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.
  3802. * @param string $other Add more attributes on img
  3803. * @return string Retourne tag img
  3804. */
  3805. function img_printer($titlealt = "default", $other = '')
  3806. {
  3807. global $langs;
  3808. if ($titlealt == "default") {
  3809. $titlealt = $langs->trans("Print");
  3810. }
  3811. return img_picto($titlealt, 'printer.png', $other);
  3812. }
  3813. /**
  3814. * Show split logo
  3815. *
  3816. * @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.
  3817. * @param string $other Add more attributes on img
  3818. * @return string Retourne tag img
  3819. */
  3820. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3821. {
  3822. global $langs;
  3823. if ($titlealt == 'default') {
  3824. $titlealt = $langs->trans('Split');
  3825. }
  3826. return img_picto($titlealt, 'split.png', $other);
  3827. }
  3828. /**
  3829. * Show help logo with cursor "?"
  3830. *
  3831. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3832. * @param int|string $usealttitle Text to use as alt title
  3833. * @return string Return tag img
  3834. */
  3835. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3836. {
  3837. global $langs;
  3838. if ($usealttitle) {
  3839. if (is_string($usealttitle)) {
  3840. $usealttitle = dol_escape_htmltag($usealttitle);
  3841. } else {
  3842. $usealttitle = $langs->trans('Info');
  3843. }
  3844. }
  3845. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3846. }
  3847. /**
  3848. * Show info logo
  3849. *
  3850. * @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.
  3851. * @return string Return img tag
  3852. */
  3853. function img_info($titlealt = 'default')
  3854. {
  3855. global $langs;
  3856. if ($titlealt == 'default') {
  3857. $titlealt = $langs->trans('Informations');
  3858. }
  3859. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3860. }
  3861. /**
  3862. * Show warning logo
  3863. *
  3864. * @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.
  3865. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3866. * @param string $morecss Add more CSS
  3867. * @return string Return img tag
  3868. */
  3869. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3870. {
  3871. global $langs;
  3872. if ($titlealt == 'default') {
  3873. $titlealt = $langs->trans('Warning');
  3874. }
  3875. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3876. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3877. }
  3878. /**
  3879. * Show error logo
  3880. *
  3881. * @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.
  3882. * @return string Return img tag
  3883. */
  3884. function img_error($titlealt = 'default')
  3885. {
  3886. global $langs;
  3887. if ($titlealt == 'default') {
  3888. $titlealt = $langs->trans('Error');
  3889. }
  3890. return img_picto($titlealt, 'error.png');
  3891. }
  3892. /**
  3893. * Show next logo
  3894. *
  3895. * @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.
  3896. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3897. * @return string Return img tag
  3898. */
  3899. function img_next($titlealt = 'default', $moreatt = '')
  3900. {
  3901. global $langs;
  3902. if ($titlealt == 'default') {
  3903. $titlealt = $langs->trans('Next');
  3904. }
  3905. //return img_picto($titlealt, 'next.png', $moreatt);
  3906. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3907. }
  3908. /**
  3909. * Show previous logo
  3910. *
  3911. * @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.
  3912. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3913. * @return string Return img tag
  3914. */
  3915. function img_previous($titlealt = 'default', $moreatt = '')
  3916. {
  3917. global $langs;
  3918. if ($titlealt == 'default') {
  3919. $titlealt = $langs->trans('Previous');
  3920. }
  3921. //return img_picto($titlealt, 'previous.png', $moreatt);
  3922. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3923. }
  3924. /**
  3925. * Show down arrow logo
  3926. *
  3927. * @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.
  3928. * @param int $selected Selected
  3929. * @param string $moreclass Add more CSS classes
  3930. * @return string Return img tag
  3931. */
  3932. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3933. {
  3934. global $langs;
  3935. if ($titlealt == 'default') {
  3936. $titlealt = $langs->trans('Down');
  3937. }
  3938. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3939. }
  3940. /**
  3941. * Show top arrow logo
  3942. *
  3943. * @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.
  3944. * @param int $selected Selected
  3945. * @param string $moreclass Add more CSS classes
  3946. * @return string Return img tag
  3947. */
  3948. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3949. {
  3950. global $langs;
  3951. if ($titlealt == 'default') {
  3952. $titlealt = $langs->trans('Up');
  3953. }
  3954. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3955. }
  3956. /**
  3957. * Show left arrow logo
  3958. *
  3959. * @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.
  3960. * @param int $selected Selected
  3961. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3962. * @return string Return img tag
  3963. */
  3964. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3965. {
  3966. global $langs;
  3967. if ($titlealt == 'default') {
  3968. $titlealt = $langs->trans('Left');
  3969. }
  3970. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3971. }
  3972. /**
  3973. * Show right arrow logo
  3974. *
  3975. * @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.
  3976. * @param int $selected Selected
  3977. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3978. * @return string Return img tag
  3979. */
  3980. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3981. {
  3982. global $langs;
  3983. if ($titlealt == 'default') {
  3984. $titlealt = $langs->trans('Right');
  3985. }
  3986. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3987. }
  3988. /**
  3989. * Show tick logo if allowed
  3990. *
  3991. * @param string $allow Allow
  3992. * @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.
  3993. * @return string Return img tag
  3994. */
  3995. function img_allow($allow, $titlealt = 'default')
  3996. {
  3997. global $langs;
  3998. if ($titlealt == 'default') {
  3999. $titlealt = $langs->trans('Active');
  4000. }
  4001. if ($allow == 1) {
  4002. return img_picto($titlealt, 'tick.png');
  4003. }
  4004. return '-';
  4005. }
  4006. /**
  4007. * Return image of a credit card according to its brand name
  4008. *
  4009. * @param string $brand Brand name of credit card
  4010. * @param string $morecss More CSS
  4011. * @return string Return img tag
  4012. */
  4013. function img_credit_card($brand, $morecss = null)
  4014. {
  4015. if (is_null($morecss)) {
  4016. $morecss = 'fa-2x';
  4017. }
  4018. if ($brand == 'visa' || $brand == 'Visa') {
  4019. $brand = 'cc-visa';
  4020. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4021. $brand = 'cc-mastercard';
  4022. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4023. $brand = 'cc-amex';
  4024. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4025. $brand = 'cc-discover';
  4026. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4027. $brand = 'cc-jcb';
  4028. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4029. $brand = 'cc-diners-club';
  4030. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4031. $brand = 'credit-card';
  4032. }
  4033. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4034. }
  4035. /**
  4036. * Show MIME img of a file
  4037. *
  4038. * @param string $file Filename
  4039. * @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.
  4040. * @param string $morecss More css
  4041. * @return string Return img tag
  4042. */
  4043. function img_mime($file, $titlealt = '', $morecss = '')
  4044. {
  4045. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4046. $mimetype = dol_mimetype($file, '', 1);
  4047. $mimeimg = dol_mimetype($file, '', 2);
  4048. $mimefa = dol_mimetype($file, '', 4);
  4049. if (empty($titlealt)) {
  4050. $titlealt = 'Mime type: '.$mimetype;
  4051. }
  4052. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4053. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4054. }
  4055. /**
  4056. * Show search logo
  4057. *
  4058. * @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.
  4059. * @param string $other Add more attributes on img
  4060. * @return string Retourne tag img
  4061. */
  4062. function img_search($titlealt = 'default', $other = '')
  4063. {
  4064. global $conf, $langs;
  4065. if ($titlealt == 'default') {
  4066. $titlealt = $langs->trans('Search');
  4067. }
  4068. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4069. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4070. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4071. return $input;
  4072. }
  4073. /**
  4074. * Show search logo
  4075. *
  4076. * @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.
  4077. * @param string $other Add more attributes on img
  4078. * @return string Retourne tag img
  4079. */
  4080. function img_searchclear($titlealt = 'default', $other = '')
  4081. {
  4082. global $conf, $langs;
  4083. if ($titlealt == 'default') {
  4084. $titlealt = $langs->trans('Search');
  4085. }
  4086. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4087. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4088. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4089. return $input;
  4090. }
  4091. /**
  4092. * Show information for admin users or standard users
  4093. *
  4094. * @param string $text Text info
  4095. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4096. * @param int $nodiv No div
  4097. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4098. * @param string $morecss More CSS ('', 'warning', 'error')
  4099. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4100. * @return string String with info text
  4101. */
  4102. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  4103. {
  4104. global $conf, $langs;
  4105. if ($infoonimgalt) {
  4106. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  4107. } else {
  4108. if (empty($conf->use_javascript_ajax)) {
  4109. $textfordropdown = '';
  4110. }
  4111. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4112. $result = ($nodiv ? '' : '<div class="'.$class.' hideonsmartphone'.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  4113. if ($textfordropdown) {
  4114. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4115. $tmpresult .= '<script type="text/javascript">
  4116. jQuery(document).ready(function() {
  4117. jQuery(".'.$class.'text").click(function() {
  4118. console.log("toggle text");
  4119. jQuery(".'.$class.'").toggle();
  4120. });
  4121. });
  4122. </script>';
  4123. $result = $tmpresult.$result;
  4124. }
  4125. }
  4126. return $result;
  4127. }
  4128. /**
  4129. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4130. * This function must be called when a blocking technical error is encountered.
  4131. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4132. *
  4133. * @param DoliDB|string $db Database handler
  4134. * @param string|string[] $error String or array of errors strings to show
  4135. * @param array $errors Array of errors
  4136. * @return void
  4137. * @see dol_htmloutput_errors()
  4138. */
  4139. function dol_print_error($db = '', $error = '', $errors = null)
  4140. {
  4141. global $conf, $langs, $argv;
  4142. global $dolibarr_main_prod;
  4143. $out = '';
  4144. $syslog = '';
  4145. // If error occurs before the $lang object was loaded
  4146. if (!$langs) {
  4147. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4148. $langs = new Translate('', $conf);
  4149. $langs->load("main");
  4150. }
  4151. // Load translation files required by the error messages
  4152. $langs->loadLangs(array('main', 'errors'));
  4153. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4154. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4155. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4156. $out .= "You use an experimental or develop level of features, so please do NOT report any bugs or vulnerability, except if problem is confirmed after moving option MAIN_FEATURES_LEVEL back to 0.<br>\n";
  4157. }
  4158. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4159. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4160. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4161. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4162. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4163. }
  4164. if (function_exists("phpversion")) {
  4165. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4166. }
  4167. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4168. if (function_exists("php_uname")) {
  4169. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4170. }
  4171. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4172. $out .= "<br>\n";
  4173. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4174. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4175. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4176. $out .= "<br>\n";
  4177. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4178. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4179. } else // Mode CLI
  4180. {
  4181. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4182. $syslog .= "pid=".dol_getmypid();
  4183. }
  4184. if (!empty($conf->modules)) {
  4185. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4186. }
  4187. if (is_object($db)) {
  4188. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4189. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4190. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4191. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4192. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4193. $out .= "<br>\n";
  4194. } else // Mode CLI
  4195. {
  4196. // No dol_escape_htmltag for output, we are in CLI mode
  4197. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4198. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4199. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4200. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4201. }
  4202. $syslog .= ", sql=".$db->lastquery();
  4203. $syslog .= ", db_error=".$db->lasterror();
  4204. }
  4205. if ($error || $errors) {
  4206. $langs->load("errors");
  4207. // Merge all into $errors array
  4208. if (is_array($error) && is_array($errors)) {
  4209. $errors = array_merge($error, $errors);
  4210. } elseif (is_array($error)) {
  4211. $errors = $error;
  4212. } elseif (is_array($errors)) {
  4213. $errors = array_merge(array($error), $errors);
  4214. } else {
  4215. $errors = array_merge(array($error));
  4216. }
  4217. foreach ($errors as $msg) {
  4218. if (empty($msg)) {
  4219. continue;
  4220. }
  4221. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4222. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4223. } else // Mode CLI
  4224. {
  4225. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4226. }
  4227. $syslog .= ", msg=".$msg;
  4228. }
  4229. }
  4230. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4231. xdebug_print_function_stack();
  4232. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4233. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4234. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4235. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4236. $out .= "<br>\n";
  4237. }
  4238. // Return a http error code if possible
  4239. if (!headers_sent()) {
  4240. http_response_code(500);
  4241. }
  4242. if (empty($dolibarr_main_prod)) {
  4243. print $out;
  4244. } else {
  4245. if (empty($langs->defaultlang)) {
  4246. $langs->setDefaultLang();
  4247. }
  4248. $langs->loadLangs(array("main", "errors")); // Reload main because language may have been set only on previous line so we have to reload files we need.
  4249. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4250. print 'This website or feature is currently temporarly not available or failed after a technical error.<br><br>This may be due to a maintenance operation. Current status of operation ('.dol_print_date(dol_now(), 'dayhourrfc').') are on next line...<br><br>'."\n";
  4251. print $langs->trans("DolibarrHasDetectedError").'. ';
  4252. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4253. define("MAIN_CORE_ERROR", 1);
  4254. }
  4255. dol_syslog("Error ".$syslog, LOG_ERR);
  4256. }
  4257. /**
  4258. * Show a public email and error code to contact if technical error
  4259. *
  4260. * @param string $prefixcode Prefix of public error code
  4261. * @param string $errormessage Complete error message
  4262. * @param array $errormessages Array of error messages
  4263. * @param string $morecss More css
  4264. * @param string $email Email
  4265. * @return void
  4266. */
  4267. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4268. {
  4269. global $langs, $conf;
  4270. if (empty($email)) {
  4271. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4272. }
  4273. $langs->load("errors");
  4274. $now = dol_now();
  4275. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4276. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4277. if ($errormessage) {
  4278. print '<br><br>'.$errormessage;
  4279. }
  4280. if (is_array($errormessages) && count($errormessages)) {
  4281. foreach ($errormessages as $mesgtoshow) {
  4282. print '<br><br>'.$mesgtoshow;
  4283. }
  4284. }
  4285. print '</div></div>';
  4286. }
  4287. /**
  4288. * Show title line of an array
  4289. *
  4290. * @param string $name Label of field
  4291. * @param string $file Url used when we click on sort picto
  4292. * @param string $field Field to use for new sorting
  4293. * @param string $begin ("" by defaut)
  4294. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4295. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  4296. * @param string $sortfield Current field used to sort
  4297. * @param string $sortorder Current sort order
  4298. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4299. * @param string $tooltip Tooltip
  4300. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4301. * @return void
  4302. */
  4303. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4304. {
  4305. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4306. }
  4307. /**
  4308. * Get title line of an array
  4309. *
  4310. * @param string $name Translation key of field to show or complete HTML string to show
  4311. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4312. * @param string $file Url used when we click on sort picto
  4313. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4314. * @param string $begin ("" by defaut)
  4315. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4316. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  4317. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4318. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4319. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4320. * @param string $disablesortlink 1=Disable sort link
  4321. * @param string $tooltip Tooltip
  4322. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4323. * @return string
  4324. */
  4325. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4326. {
  4327. global $conf, $langs, $form;
  4328. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4329. if ($moreattrib == 'class="right"') {
  4330. $prefix .= 'right '; // For backward compatibility
  4331. }
  4332. $sortorder = strtoupper($sortorder);
  4333. $out = '';
  4334. $sortimg = '';
  4335. $tag = 'th';
  4336. if ($thead == 2) {
  4337. $tag = 'div';
  4338. }
  4339. $tmpsortfield = explode(',', $sortfield);
  4340. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4341. $tmpfield = explode(',', $field);
  4342. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4343. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4344. $prefix = 'wrapcolumntitle '.$prefix;
  4345. }
  4346. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4347. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4348. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4349. $liste_titre = 'liste_titre';
  4350. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4351. $liste_titre = 'liste_titre_sel';
  4352. }
  4353. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4354. //$out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && preg_match('/^[a-zA-Z_0-9\s\.\-:&;]*$/', $name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4355. $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4356. $out .= '>';
  4357. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4358. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4359. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4360. $options = preg_replace('/&+/i', '&', $options);
  4361. if (!preg_match('/^&/', $options)) {
  4362. $options = '&'.$options;
  4363. }
  4364. $sortordertouseinlink = '';
  4365. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4366. if (preg_match('/^DESC/i', $sortorder)) {
  4367. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4368. } else // We reverse the var $sortordertouseinlink
  4369. {
  4370. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4371. }
  4372. } else // We are on field that is the first current sorting criteria
  4373. {
  4374. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4375. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4376. } else {
  4377. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4378. }
  4379. }
  4380. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4381. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4382. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4383. $out .= '>';
  4384. }
  4385. if ($tooltip) {
  4386. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4387. $tmptooltip = explode(':', $tooltip);
  4388. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4389. } else {
  4390. $out .= $langs->trans($name);
  4391. }
  4392. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4393. $out .= '</a>';
  4394. }
  4395. if (empty($thead) && $field) { // If this is a sort field
  4396. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4397. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4398. $options = preg_replace('/&+/i', '&', $options);
  4399. if (!preg_match('/^&/', $options)) {
  4400. $options = '&'.$options;
  4401. }
  4402. if (!$sortorder || $field1 != $sortfield1) {
  4403. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4404. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4405. } else {
  4406. if (preg_match('/^DESC/', $sortorder)) {
  4407. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4408. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4409. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  4410. }
  4411. if (preg_match('/^ASC/', $sortorder)) {
  4412. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4413. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4414. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  4415. }
  4416. }
  4417. }
  4418. $out .= $sortimg;
  4419. $out .= '</'.$tag.'>';
  4420. return $out;
  4421. }
  4422. /**
  4423. * Show a title.
  4424. *
  4425. * @param string $title Title to show
  4426. * @return void
  4427. * @deprecated Use load_fiche_titre instead
  4428. * @see load_fiche_titre()
  4429. */
  4430. function print_titre($title)
  4431. {
  4432. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4433. print '<div class="titre">'.$title.'</div>';
  4434. }
  4435. /**
  4436. * Show a title with picto
  4437. *
  4438. * @param string $title Title to show
  4439. * @param string $mesg Added message to show on right
  4440. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4441. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4442. * @param int $id To force an id on html objects
  4443. * @return void
  4444. * @deprecated Use print load_fiche_titre instead
  4445. */
  4446. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4447. {
  4448. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4449. }
  4450. /**
  4451. * Load a title with picto
  4452. *
  4453. * @param string $titre Title to show
  4454. * @param string $morehtmlright Added message to show on right
  4455. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4456. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4457. * @param string $id To force an id on html objects
  4458. * @param string $morecssontable More css on table
  4459. * @param string $morehtmlcenter Added message to show on center
  4460. * @return string
  4461. * @see print_barre_liste()
  4462. */
  4463. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4464. {
  4465. global $conf;
  4466. $return = '';
  4467. if ($picto == 'setup') {
  4468. $picto = 'generic';
  4469. }
  4470. $return .= "\n";
  4471. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4472. $return .= '<tr class="titre">';
  4473. if ($picto) {
  4474. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4475. }
  4476. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4477. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4478. $return .= '</td>';
  4479. if (dol_strlen($morehtmlcenter)) {
  4480. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4481. }
  4482. if (dol_strlen($morehtmlright)) {
  4483. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4484. }
  4485. $return .= '</tr></table>'."\n";
  4486. return $return;
  4487. }
  4488. /**
  4489. * Print a title with navigation controls for pagination
  4490. *
  4491. * @param string $titre Title to show (required)
  4492. * @param int $page Numero of page to show in navigation links (required)
  4493. * @param string $file Url of page (required)
  4494. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4495. * @param string $sortfield Field to sort on ('' by default)
  4496. * @param string $sortorder Order to sort ('' by default)
  4497. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4498. * @param int $num Number of records found by select with limit+1
  4499. * @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.
  4500. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4501. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4502. * @param string $morehtmlright More html to show (after arrows)
  4503. * @param string $morecss More css to the table
  4504. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4505. * @param int $hideselectlimit Force to hide select limit
  4506. * @param int $hidenavigation Force to hide all navigation tools
  4507. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4508. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4509. * @return void
  4510. */
  4511. function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'generic', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $hideselectlimit = 0, $hidenavigation = 0, $pagenavastextinput = 0, $morehtmlrightbeforearrow = '')
  4512. {
  4513. global $conf, $langs;
  4514. $savlimit = $limit;
  4515. $savtotalnboflines = $totalnboflines;
  4516. $totalnboflines = abs((int) $totalnboflines);
  4517. if ($picto == 'setup') {
  4518. $picto = 'title_setup.png';
  4519. }
  4520. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4521. $picto = 'title.gif';
  4522. }
  4523. if ($limit < 0) {
  4524. $limit = $conf->liste_limit;
  4525. }
  4526. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4527. $nextpage = 1;
  4528. } else {
  4529. $nextpage = 0;
  4530. }
  4531. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4532. print "\n";
  4533. print "<!-- Begin title -->\n";
  4534. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4535. // Left
  4536. if ($picto && $titre) {
  4537. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4538. }
  4539. print '<td class="nobordernopadding valignmiddle col-title">';
  4540. print '<div class="titre inline-block">'.$titre;
  4541. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4542. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4543. }
  4544. print '</div></td>';
  4545. // Center
  4546. if ($morehtmlcenter) {
  4547. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4548. }
  4549. // Right
  4550. print '<td class="nobordernopadding valignmiddle right">';
  4551. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4552. if ($sortfield) {
  4553. $options .= "&sortfield=".urlencode($sortfield);
  4554. }
  4555. if ($sortorder) {
  4556. $options .= "&sortorder=".urlencode($sortorder);
  4557. }
  4558. // Show navigation bar
  4559. $pagelist = '';
  4560. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4561. if ($totalnboflines) { // If we know total nb of lines
  4562. // Define nb of extra page links before and after selected page + ... + first or last
  4563. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4564. if ($limit > 0) {
  4565. $nbpages = ceil($totalnboflines / $limit);
  4566. } else {
  4567. $nbpages = 1;
  4568. }
  4569. $cpt = ($page - $maxnbofpage);
  4570. if ($cpt < 0) {
  4571. $cpt = 0;
  4572. }
  4573. if ($cpt >= 1) {
  4574. if (empty($pagenavastextinput)) {
  4575. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4576. if ($cpt > 2) {
  4577. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4578. } elseif ($cpt == 2) {
  4579. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4580. }
  4581. }
  4582. }
  4583. do {
  4584. if ($pagenavastextinput) {
  4585. if ($cpt == $page) {
  4586. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4587. $pagelist .= '/';
  4588. }
  4589. } else {
  4590. if ($cpt == $page) {
  4591. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4592. } else {
  4593. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4594. }
  4595. }
  4596. $cpt++;
  4597. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4598. if (empty($pagenavastextinput)) {
  4599. if ($cpt < $nbpages) {
  4600. if ($cpt < $nbpages - 2) {
  4601. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4602. } elseif ($cpt == $nbpages - 2) {
  4603. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4604. }
  4605. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4606. }
  4607. } else {
  4608. //var_dump($page.' '.$cpt.' '.$nbpages);
  4609. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4610. }
  4611. } else {
  4612. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4613. }
  4614. }
  4615. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4616. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow); // output the div and ul for previous/last completed with page numbers into $pagelist
  4617. }
  4618. // js to autoselect page field on focus
  4619. if ($pagenavastextinput) {
  4620. print ajax_autoselect('.pageplusone');
  4621. }
  4622. print '</td>';
  4623. print '</tr></table>'."\n";
  4624. print "<!-- End title -->\n\n";
  4625. }
  4626. /**
  4627. * Function to show navigation arrows into lists
  4628. *
  4629. * @param int $page Number of page
  4630. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4631. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4632. * @param integer $nextpage Do we show a next page button
  4633. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4634. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4635. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4636. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4637. * @param int $hideselectlimit Force to hide select limit
  4638. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4639. * @return void
  4640. */
  4641. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4642. {
  4643. global $conf, $langs;
  4644. print '<div class="pagination"><ul>';
  4645. if ($beforearrows) {
  4646. print '<li class="paginationbeforearrows">';
  4647. print $beforearrows;
  4648. print '</li>';
  4649. }
  4650. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4651. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000,25000:25000';
  4652. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4653. //$pagesizechoices.=',2:2';
  4654. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4655. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4656. }
  4657. print '<li class="pagination">';
  4658. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4659. $tmpchoice = explode(',', $pagesizechoices);
  4660. $tmpkey = $limit.':'.$limit;
  4661. if (!in_array($tmpkey, $tmpchoice)) {
  4662. $tmpchoice[] = $tmpkey;
  4663. }
  4664. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4665. if (!in_array($tmpkey, $tmpchoice)) {
  4666. $tmpchoice[] = $tmpkey;
  4667. }
  4668. asort($tmpchoice, SORT_NUMERIC);
  4669. foreach ($tmpchoice as $val) {
  4670. $selected = '';
  4671. $tmp = explode(':', $val);
  4672. $key = $tmp[0];
  4673. $val = $tmp[1];
  4674. if ($key != '' && $val != '') {
  4675. if ((int) $key == (int) $limit) {
  4676. $selected = ' selected="selected"';
  4677. }
  4678. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4679. }
  4680. }
  4681. print '</select>';
  4682. if ($conf->use_javascript_ajax) {
  4683. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4684. <script>
  4685. jQuery(document).ready(function () {
  4686. jQuery(".selectlimit").change(function() {
  4687. console.log("Change limit. Send submit");
  4688. $(this).parents(\'form:first\').submit();
  4689. });
  4690. });
  4691. </script>
  4692. ';
  4693. }
  4694. print '</li>';
  4695. }
  4696. if ($page > 0) {
  4697. print '<li class="pagination paginationpage paginationpageleft"><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>';
  4698. }
  4699. if ($betweenarrows) {
  4700. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4701. print $betweenarrows;
  4702. print '<!--</div>-->';
  4703. }
  4704. if ($nextpage > 0) {
  4705. print '<li class="pagination paginationpage paginationpageright"><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>';
  4706. }
  4707. if ($afterarrows) {
  4708. print '<li class="paginationafterarrows">';
  4709. print $afterarrows;
  4710. print '</li>';
  4711. }
  4712. print '</ul></div>'."\n";
  4713. }
  4714. /**
  4715. * Return a string with VAT rate label formated for view output
  4716. * Used into pdf and HTML pages
  4717. *
  4718. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4719. * @param boolean $addpercent Add a percent % sign in output
  4720. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4721. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4722. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4723. */
  4724. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4725. {
  4726. $morelabel = '';
  4727. if (preg_match('/%/', $rate)) {
  4728. $rate = str_replace('%', '', $rate);
  4729. $addpercent = true;
  4730. }
  4731. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  4732. $morelabel = ' ('.$reg[1].')';
  4733. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4734. }
  4735. if (preg_match('/\*/', $rate)) {
  4736. $rate = str_replace('*', '', $rate);
  4737. $info_bits |= 1;
  4738. }
  4739. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4740. if (!preg_match('/\//', $rate)) {
  4741. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4742. } else {
  4743. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4744. $ret = $rate.($addpercent ? '%' : '');
  4745. }
  4746. if (($info_bits & 1) && $usestarfornpr >= 0) {
  4747. $ret .= ' *';
  4748. }
  4749. $ret .= $morelabel;
  4750. return $ret;
  4751. }
  4752. /**
  4753. * Function to format a value into an amount for visual output
  4754. * Function used into PDF and HTML pages
  4755. *
  4756. * @param float $amount Amount to format
  4757. * @param integer $form Type of format, HTML or not (not by default)
  4758. * @param Translate|string $outlangs Object langs for output
  4759. * @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.
  4760. * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  4761. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4762. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4763. * @return string String with formated amount
  4764. *
  4765. * @see price2num() Revert function of price
  4766. */
  4767. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4768. {
  4769. global $langs, $conf;
  4770. // Clean parameters
  4771. if (empty($amount)) {
  4772. $amount = 0; // To have a numeric value if amount not defined or = ''
  4773. }
  4774. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4775. if ($rounding < 0) {
  4776. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4777. }
  4778. $nbdecimal = $rounding;
  4779. // Output separators by default (french)
  4780. $dec = ',';
  4781. $thousand = ' ';
  4782. // If $outlangs not forced, we use use language
  4783. if (!is_object($outlangs)) {
  4784. $outlangs = $langs;
  4785. }
  4786. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4787. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4788. }
  4789. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4790. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4791. }
  4792. if ($thousand == 'None') {
  4793. $thousand = '';
  4794. } elseif ($thousand == 'Space') {
  4795. $thousand = ' ';
  4796. }
  4797. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4798. //print "amount=".$amount."-";
  4799. $amount = str_replace(',', '.', $amount); // should be useless
  4800. //print $amount."-";
  4801. $datas = explode('.', $amount);
  4802. $decpart = isset($datas[1]) ? $datas[1] : '';
  4803. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4804. //print "decpart=".$decpart."<br>";
  4805. $end = '';
  4806. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4807. if (dol_strlen($decpart) > $nbdecimal) {
  4808. $nbdecimal = dol_strlen($decpart);
  4809. }
  4810. // Si on depasse max
  4811. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  4812. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4813. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  4814. // Si un affichage est tronque, on montre des ...
  4815. $end = '...';
  4816. }
  4817. }
  4818. // If force rounding
  4819. if ($forcerounding >= 0) {
  4820. $nbdecimal = $forcerounding;
  4821. }
  4822. // Format number
  4823. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4824. if ($form) {
  4825. $output = preg_replace('/\s/', '&nbsp;', $output);
  4826. $output = preg_replace('/\'/', '&#039;', $output);
  4827. }
  4828. // Add symbol of currency if requested
  4829. $cursymbolbefore = $cursymbolafter = '';
  4830. if ($currency_code) {
  4831. if ($currency_code == 'auto') {
  4832. $currency_code = $conf->currency;
  4833. }
  4834. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4835. $listoflanguagesbefore = array('nl_NL');
  4836. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  4837. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4838. } else {
  4839. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4840. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4841. }
  4842. }
  4843. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4844. return $output;
  4845. }
  4846. /**
  4847. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4848. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4849. * should be roundtext2num().
  4850. *
  4851. * @param string|float $amount Amount to convert/clean or round
  4852. * @param string|int $rounding ''=No rounding
  4853. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4854. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4855. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4856. * 'CU'=Round to Max unit price of foreign currency accuracy
  4857. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  4858. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  4859. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4860. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  4861. * @return string Amount with universal numeric format (Example: '99.99999').
  4862. * If conversion fails to return a numeric, it returns:
  4863. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  4864. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  4865. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  4866. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  4867. *
  4868. * @see price() Opposite function of price2num
  4869. */
  4870. function price2num($amount, $rounding = '', $option = 0)
  4871. {
  4872. global $langs, $conf;
  4873. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4874. // Numbers must be '1234.56'
  4875. // Decimal delimiter for PHP and database SQL requests must be '.'
  4876. $dec = ',';
  4877. $thousand = ' ';
  4878. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4879. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4880. }
  4881. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4882. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4883. }
  4884. if ($thousand == 'None') {
  4885. $thousand = '';
  4886. } elseif ($thousand == 'Space') {
  4887. $thousand = ' ';
  4888. }
  4889. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4890. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4891. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4892. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4893. if (!is_numeric($amount)) {
  4894. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  4895. }
  4896. if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come from input data, so 1.123 is 1123
  4897. $amount = str_replace($thousand, '', $amount);
  4898. }
  4899. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4900. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4901. // So if number was already a good number, it is converted into local Dolibarr setup.
  4902. if (is_numeric($amount)) {
  4903. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4904. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4905. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4906. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4907. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4908. }
  4909. //print "QQ".$amount."<br>\n";
  4910. // Now make replace (the main goal of function)
  4911. if ($thousand != ',' && $thousand != '.') {
  4912. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4913. }
  4914. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4915. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4916. $amount = str_replace($dec, '.', $amount);
  4917. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  4918. }
  4919. //print ' XX'.$amount.' '.$rounding;
  4920. // Now, $amount is a real PHP float number. We make a rounding if required.
  4921. if ($rounding) {
  4922. $nbofdectoround = '';
  4923. if ($rounding == 'MU') {
  4924. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4925. } elseif ($rounding == 'MT') {
  4926. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4927. } elseif ($rounding == 'MS') {
  4928. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  4929. } elseif ($rounding == 'CU') {
  4930. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  4931. } elseif ($rounding == 'CT') {
  4932. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  4933. } elseif (is_numeric($rounding)) {
  4934. $nbofdectoround = (int) $rounding;
  4935. }
  4936. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  4937. if (dol_strlen($nbofdectoround)) {
  4938. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  4939. } else {
  4940. return 'ErrorBadParameterProvidedToFunction';
  4941. }
  4942. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4943. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4944. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4945. if (is_numeric($amount)) {
  4946. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4947. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4948. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4949. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4950. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4951. }
  4952. //print "TT".$amount.'<br>';
  4953. // Always make replace because each math function (like round) replace
  4954. // with local values and we want a number that has a SQL string format x.y
  4955. if ($thousand != ',' && $thousand != '.') {
  4956. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4957. }
  4958. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4959. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4960. $amount = str_replace($dec, '.', $amount);
  4961. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  4962. }
  4963. return $amount;
  4964. }
  4965. /**
  4966. * Output a dimension with best unit
  4967. *
  4968. * @param float $dimension Dimension
  4969. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4970. * @param string $type 'weight', 'volume', ...
  4971. * @param Translate $outputlangs Translate language object
  4972. * @param int $round -1 = non rounding, x = number of decimal
  4973. * @param string $forceunitoutput 'no' or numeric (-3, -6, ...) compared to $unit (In most case, this value is value defined into $conf->global->MAIN_WEIGHT_DEFAULT_UNIT)
  4974. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  4975. * @return string String to show dimensions
  4976. */
  4977. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  4978. {
  4979. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4980. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  4981. $dimension = $dimension * 1000000;
  4982. $unit = $unit - 6;
  4983. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  4984. $dimension = $dimension * 1000;
  4985. $unit = $unit - 3;
  4986. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  4987. $dimension = $dimension / 1000000;
  4988. $unit = $unit + 6;
  4989. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  4990. $dimension = $dimension / 1000;
  4991. $unit = $unit + 3;
  4992. }
  4993. // Special case when we want output unit into pound or ounce
  4994. /* TODO
  4995. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4996. {
  4997. $dimension = // convert dimension from standard unit into ounce or pound
  4998. $unit = $forceunitoutput;
  4999. }
  5000. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5001. {
  5002. $dimension = // convert dimension from standard unit into ounce or pound
  5003. $unit = $forceunitoutput;
  5004. }*/
  5005. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5006. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5007. return $ret;
  5008. }
  5009. /**
  5010. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5011. * Note: This function applies same rules than get_default_tva
  5012. *
  5013. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5014. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5015. * @param Societe $thirdparty_buyer Object of buying third party
  5016. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5017. * @param int $vatnpr If vat rate is NPR or not
  5018. * @return mixed 0 if not found, localtax rate if found
  5019. * @see get_default_tva()
  5020. */
  5021. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5022. {
  5023. global $db, $conf, $mysoc;
  5024. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5025. $thirdparty_seller = $mysoc;
  5026. }
  5027. 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);
  5028. $vatratecleaned = $vatrate;
  5029. $reg = array();
  5030. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5031. $vatratecleaned = trim($reg[1]);
  5032. $vatratecode = $reg[2];
  5033. }
  5034. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5035. {
  5036. return 0;
  5037. }*/
  5038. // Some test to guess with no need to make database access
  5039. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5040. if ($local == 1) {
  5041. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5042. return 0;
  5043. }
  5044. if ($thirdparty_seller->id == $mysoc->id) {
  5045. if (!$thirdparty_buyer->localtax1_assuj) {
  5046. return 0;
  5047. }
  5048. } else {
  5049. if (!$thirdparty_seller->localtax1_assuj) {
  5050. return 0;
  5051. }
  5052. }
  5053. }
  5054. if ($local == 2) {
  5055. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5056. if (!$mysoc->localtax2_assuj) {
  5057. return 0; // If main vat is 0, IRPF may be different than 0.
  5058. }
  5059. if ($thirdparty_seller->id == $mysoc->id) {
  5060. if (!$thirdparty_buyer->localtax2_assuj) {
  5061. return 0;
  5062. }
  5063. } else {
  5064. if (!$thirdparty_seller->localtax2_assuj) {
  5065. return 0;
  5066. }
  5067. }
  5068. }
  5069. } else {
  5070. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5071. return 0;
  5072. }
  5073. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5074. return 0;
  5075. }
  5076. }
  5077. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5078. if (in_array($mysoc->country_code, array('ES'))) {
  5079. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5080. }
  5081. // Search local taxes
  5082. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5083. if ($local == 1) {
  5084. if ($thirdparty_seller != $mysoc) {
  5085. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5086. return $thirdparty_seller->localtax1_value;
  5087. }
  5088. } else { // i am the seller
  5089. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5090. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5091. }
  5092. }
  5093. }
  5094. if ($local == 2) {
  5095. if ($thirdparty_seller != $mysoc) {
  5096. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5097. // TODO We should also return value defined on thirdparty only if defined
  5098. return $thirdparty_seller->localtax2_value;
  5099. }
  5100. } else { // i am the seller
  5101. if (in_array($mysoc->country_code, array('ES'))) {
  5102. return $thirdparty_buyer->localtax2_value;
  5103. } else {
  5104. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5105. }
  5106. }
  5107. }
  5108. }
  5109. // By default, search value of local tax on line of common tax
  5110. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5111. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5112. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5113. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5114. if (!empty($vatratecode)) {
  5115. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5116. } else {
  5117. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5118. }
  5119. $resql = $db->query($sql);
  5120. if ($resql) {
  5121. $obj = $db->fetch_object($resql);
  5122. if ($obj) {
  5123. if ($local == 1) {
  5124. return $obj->localtax1;
  5125. } elseif ($local == 2) {
  5126. return $obj->localtax2;
  5127. }
  5128. }
  5129. }
  5130. return 0;
  5131. }
  5132. /**
  5133. * Return true if LocalTax (1 or 2) is unique.
  5134. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5135. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5136. *
  5137. * @param int $local Local tax to test (1 or 2)
  5138. * @return boolean True if LocalTax have multiple values, False if not
  5139. */
  5140. function isOnlyOneLocalTax($local)
  5141. {
  5142. $tax = get_localtax_by_third($local);
  5143. $valors = explode(":", $tax);
  5144. if (count($valors) > 1) {
  5145. return false;
  5146. } else {
  5147. return true;
  5148. }
  5149. }
  5150. /**
  5151. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5152. *
  5153. * @param int $local LocalTax to get
  5154. * @return number Values of localtax
  5155. */
  5156. function get_localtax_by_third($local)
  5157. {
  5158. global $db, $mysoc;
  5159. $sql = "SELECT t.localtax1, t.localtax2 ";
  5160. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5161. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5162. $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";
  5163. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5164. $sql .= " )";
  5165. $resql = $db->query($sql);
  5166. if ($resql) {
  5167. $obj = $db->fetch_object($resql);
  5168. if ($local == 1) {
  5169. return $obj->localtax1;
  5170. } elseif ($local == 2) {
  5171. return $obj->localtax2;
  5172. }
  5173. }
  5174. return 0;
  5175. }
  5176. /**
  5177. * Get tax (VAT) main information from Id.
  5178. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5179. *
  5180. * @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.
  5181. * @param Societe $buyer Company object
  5182. * @param Societe $seller Company object
  5183. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5184. * @return array array('rowid'=> , 'code'=> ...)
  5185. * @see getLocalTaxesFromRate()
  5186. */
  5187. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5188. {
  5189. global $db, $mysoc;
  5190. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5191. // Search local taxes
  5192. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5193. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5194. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5195. if ($firstparamisid) {
  5196. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5197. } else {
  5198. $vatratecleaned = $vatrate;
  5199. $vatratecode = '';
  5200. $reg = array();
  5201. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5202. $vatratecleaned = $reg[1];
  5203. $vatratecode = $reg[2];
  5204. }
  5205. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5206. /*if ($mysoc->country_code == 'ES') $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // vat in spain use the buyer country ??
  5207. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5208. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5209. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5210. if ($vatratecode) {
  5211. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5212. }
  5213. }
  5214. $resql = $db->query($sql);
  5215. if ($resql) {
  5216. $obj = $db->fetch_object($resql);
  5217. if ($obj) {
  5218. return array(
  5219. 'rowid'=>$obj->rowid,
  5220. 'code'=>$obj->code,
  5221. 'rate'=>$obj->rate,
  5222. 'localtax1'=>$obj->localtax1,
  5223. 'localtax1_type'=>$obj->localtax1_type,
  5224. 'localtax2'=>$obj->localtax2,
  5225. 'localtax2_type'=>$obj->localtax2_type,
  5226. 'npr'=>$obj->npr,
  5227. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5228. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5229. );
  5230. } else {
  5231. return array();
  5232. }
  5233. } else {
  5234. dol_print_error($db);
  5235. }
  5236. return array();
  5237. }
  5238. /**
  5239. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5240. * This does not take into account the seller setup if subject to vat or not, only country.
  5241. *
  5242. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5243. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5244. * provide the selected value to the function calcul_price_total.
  5245. *
  5246. * @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.
  5247. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5248. * @param Societe $buyer Company object
  5249. * @param Societe $seller Company object
  5250. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5251. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5252. * @see getTaxesFromId()
  5253. */
  5254. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5255. {
  5256. global $db, $mysoc;
  5257. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5258. // Search local taxes
  5259. $sql = "SELECT t.taux as rate, t.code, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
  5260. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5261. if ($firstparamisid) {
  5262. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5263. } else {
  5264. $vatratecleaned = $vatrate;
  5265. $vatratecode = '';
  5266. $reg = array();
  5267. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5268. $vatratecleaned = $reg[1];
  5269. $vatratecode = $reg[2];
  5270. }
  5271. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5272. if ($mysoc->country_code == 'ES') {
  5273. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5274. } else {
  5275. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5276. }
  5277. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5278. if ($vatratecode) {
  5279. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5280. }
  5281. }
  5282. $resql = $db->query($sql);
  5283. if ($resql) {
  5284. $obj = $db->fetch_object($resql);
  5285. if ($obj) {
  5286. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5287. if ($local == 1) {
  5288. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5289. } elseif ($local == 2) {
  5290. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5291. } else {
  5292. return array($obj->localtax1_type, get_localtax($vateratestring, 1, $buyer, $seller), $obj->localtax2_type, get_localtax($vateratestring, 2, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5293. }
  5294. }
  5295. }
  5296. return array();
  5297. }
  5298. /**
  5299. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5300. * Function called by get_default_tva().
  5301. *
  5302. * @param int $idprod Id of product or 0 if not a predefined product
  5303. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5304. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5305. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5306. * @see get_product_localtax_for_country()
  5307. */
  5308. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5309. {
  5310. global $db, $conf, $mysoc;
  5311. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5312. $ret = 0;
  5313. $found = 0;
  5314. if ($idprod > 0) {
  5315. // Load product
  5316. $product = new Product($db);
  5317. $result = $product->fetch($idprod);
  5318. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5319. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5320. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5321. $ret = $product->vatrate_supplier;
  5322. if ($product->default_vat_code) {
  5323. $ret .= ' ('.$product->default_vat_code.')';
  5324. }
  5325. } else {
  5326. $ret = $product->tva_tx; // Default vat of product we defined
  5327. if ($product->default_vat_code) {
  5328. $ret .= ' ('.$product->default_vat_code.')';
  5329. }
  5330. }
  5331. $found = 1;
  5332. } else {
  5333. // TODO Read default product vat according to product and another countrycode.
  5334. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5335. }
  5336. }
  5337. if (!$found) {
  5338. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5339. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5340. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5341. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5342. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5343. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5344. $sql .= $db->plimit(1);
  5345. $resql = $db->query($sql);
  5346. if ($resql) {
  5347. $obj = $db->fetch_object($resql);
  5348. if ($obj) {
  5349. $ret = $obj->vat_rate;
  5350. if ($obj->default_vat_code) {
  5351. $ret .= ' ('.$obj->default_vat_code.')';
  5352. }
  5353. }
  5354. $db->free($resql);
  5355. } else {
  5356. dol_print_error($db);
  5357. }
  5358. } else {
  5359. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5360. }
  5361. }
  5362. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5363. return $ret;
  5364. }
  5365. /**
  5366. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5367. *
  5368. * @param int $idprod Id of product
  5369. * @param int $local 1 for localtax1, 2 for localtax 2
  5370. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5371. * @return int <0 if KO, Vat rate if OK
  5372. * @see get_product_vat_for_country()
  5373. */
  5374. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5375. {
  5376. global $db, $mysoc;
  5377. if (!class_exists('Product')) {
  5378. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5379. }
  5380. $ret = 0;
  5381. $found = 0;
  5382. if ($idprod > 0) {
  5383. // Load product
  5384. $product = new Product($db);
  5385. $result = $product->fetch($idprod);
  5386. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5387. /* Not defined yet, so we don't use this
  5388. if ($local==1) $ret=$product->localtax1_tx;
  5389. elseif ($local==2) $ret=$product->localtax2_tx;
  5390. $found=1;
  5391. */
  5392. } else {
  5393. // TODO Read default product vat according to product and another countrycode.
  5394. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5395. }
  5396. }
  5397. if (!$found) {
  5398. // If vat of product for the country not found or not defined, we return higher vat of country.
  5399. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5400. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5401. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5402. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5403. $sql .= $db->plimit(1);
  5404. $resql = $db->query($sql);
  5405. if ($resql) {
  5406. $obj = $db->fetch_object($resql);
  5407. if ($obj) {
  5408. if ($local == 1) {
  5409. $ret = $obj->localtax1;
  5410. } elseif ($local == 2) {
  5411. $ret = $obj->localtax2;
  5412. }
  5413. }
  5414. } else {
  5415. dol_print_error($db);
  5416. }
  5417. }
  5418. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5419. return $ret;
  5420. }
  5421. /**
  5422. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5423. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5424. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5425. * VATRULE 3: 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.
  5426. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5427. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5428. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5429. *
  5430. * @param Societe $thirdparty_seller Objet societe vendeuse
  5431. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5432. * @param int $idprod Id product
  5433. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5434. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5435. * @see get_default_npr(), get_default_localtax()
  5436. */
  5437. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5438. {
  5439. global $conf;
  5440. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5441. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5442. $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;
  5443. $seller_country_code = $thirdparty_seller->country_code;
  5444. $seller_in_cee = isInEEC($thirdparty_seller);
  5445. $buyer_country_code = $thirdparty_buyer->country_code;
  5446. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5447. dol_syslog("get_default_tva: seller use vat=".$seller_use_vat.", seller country=".$seller_country_code.", seller in cee=".$seller_in_cee.", buyer vat number=".$thirdparty_buyer->tva_intra." buyer country=".$buyer_country_code.", buyer in cee=".$buyer_in_cee.", idprod=".$idprod.", idprodfournprice=".$idprodfournprice.", SERVICE_ARE_ECOMMERCE_200238EC=".(!empty($conf->global->SERVICES_ARE_ECOMMERCE_200238EC) ? $conf->global->SERVICES_ARE_ECOMMERCE_200238EC : ''));
  5448. // 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)
  5449. // we use the buyer VAT.
  5450. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5451. if ($seller_in_cee && $buyer_in_cee) {
  5452. $isacompany = $thirdparty_buyer->isACompany();
  5453. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5454. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5455. if (!isValidVATID($thirdparty_buyer)) {
  5456. $isacompany = 0;
  5457. }
  5458. }
  5459. if (!$isacompany) {
  5460. //print 'VATRULE 0';
  5461. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5462. }
  5463. }
  5464. }
  5465. // If seller does not use VAT
  5466. if (!$seller_use_vat) {
  5467. //print 'VATRULE 1';
  5468. return 0;
  5469. }
  5470. // 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.
  5471. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5472. if (($seller_country_code == $buyer_country_code)
  5473. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5474. //print 'VATRULE 2';
  5475. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5476. }
  5477. // 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.
  5478. // 'VATRULE 3' - Not supported
  5479. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5480. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5481. if (($seller_in_cee && $buyer_in_cee)) {
  5482. $isacompany = $thirdparty_buyer->isACompany();
  5483. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5484. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5485. if (!isValidVATID($thirdparty_buyer)) {
  5486. $isacompany = 0;
  5487. }
  5488. }
  5489. if (!$isacompany) {
  5490. //print 'VATRULE 4';
  5491. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5492. } else {
  5493. //print 'VATRULE 5';
  5494. return 0;
  5495. }
  5496. }
  5497. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5498. // I don't see any use case that need this rule.
  5499. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5500. $isacompany = $thirdparty_buyer->isACompany();
  5501. if (!$isacompany) {
  5502. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5503. //print 'VATRULE extra';
  5504. }
  5505. }
  5506. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5507. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5508. //print 'VATRULE 6';
  5509. return 0;
  5510. }
  5511. /**
  5512. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5513. *
  5514. * @param Societe $thirdparty_seller Thirdparty seller
  5515. * @param Societe $thirdparty_buyer Thirdparty buyer
  5516. * @param int $idprod Id product
  5517. * @param int $idprodfournprice Id supplier price for product
  5518. * @return float 0 or 1
  5519. * @see get_default_tva(), get_default_localtax()
  5520. */
  5521. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5522. {
  5523. global $db;
  5524. if ($idprodfournprice > 0) {
  5525. if (!class_exists('ProductFournisseur')) {
  5526. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5527. }
  5528. $prodprice = new ProductFournisseur($db);
  5529. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5530. return $prodprice->fourn_tva_npr;
  5531. } elseif ($idprod > 0) {
  5532. if (!class_exists('Product')) {
  5533. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5534. }
  5535. $prod = new Product($db);
  5536. $prod->fetch($idprod);
  5537. return $prod->tva_npr;
  5538. }
  5539. return 0;
  5540. }
  5541. /**
  5542. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5543. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5544. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5545. * Sinon TVA proposee par defaut=0. Fin de regle.
  5546. *
  5547. * @param Societe $thirdparty_seller Thirdparty seller
  5548. * @param Societe $thirdparty_buyer Thirdparty buyer
  5549. * @param int $local Localtax to process (1 or 2)
  5550. * @param int $idprod Id product
  5551. * @return integer localtax, -1 si ne peut etre determine
  5552. * @see get_default_tva(), get_default_npr()
  5553. */
  5554. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5555. {
  5556. global $mysoc;
  5557. if (!is_object($thirdparty_seller)) {
  5558. return -1;
  5559. }
  5560. if (!is_object($thirdparty_buyer)) {
  5561. return -1;
  5562. }
  5563. if ($local == 1) { // Localtax 1
  5564. if ($mysoc->country_code == 'ES') {
  5565. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5566. return 0;
  5567. }
  5568. } else {
  5569. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5570. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5571. return 0;
  5572. }
  5573. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5574. return 0;
  5575. }
  5576. }
  5577. } elseif ($local == 2) { //I Localtax 2
  5578. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5579. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5580. return 0;
  5581. }
  5582. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5583. return 0;
  5584. }
  5585. }
  5586. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5587. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5588. }
  5589. return 0;
  5590. }
  5591. /**
  5592. * Return yes or no in current language
  5593. *
  5594. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5595. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5596. * @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.
  5597. * @return string HTML string
  5598. */
  5599. function yn($yesno, $case = 1, $color = 0)
  5600. {
  5601. global $langs;
  5602. $result = 'unknown';
  5603. $classname = '';
  5604. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5605. $result = $langs->trans('yes');
  5606. if ($case == 1 || $case == 3) {
  5607. $result = $langs->trans("Yes");
  5608. }
  5609. if ($case == 2) {
  5610. $result = '<input type="checkbox" value="1" checked disabled>';
  5611. }
  5612. if ($case == 3) {
  5613. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5614. }
  5615. $classname = 'ok';
  5616. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5617. $result = $langs->trans("no");
  5618. if ($case == 1 || $case == 3) {
  5619. $result = $langs->trans("No");
  5620. }
  5621. if ($case == 2) {
  5622. $result = '<input type="checkbox" value="0" disabled>';
  5623. }
  5624. if ($case == 3) {
  5625. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5626. }
  5627. if ($color == 2) {
  5628. $classname = 'ok';
  5629. } else {
  5630. $classname = 'error';
  5631. }
  5632. }
  5633. if ($color) {
  5634. return '<span class="'.$classname.'">'.$result.'</span>';
  5635. }
  5636. return $result;
  5637. }
  5638. /**
  5639. * Return a path to have a the directory according to object where files are stored.
  5640. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5641. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5642. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5643. * Example out with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  5644. *
  5645. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5646. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5647. * @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)
  5648. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5649. * @param Object $object Object to use to get ref to forge the path.
  5650. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5651. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5652. */
  5653. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5654. {
  5655. global $conf;
  5656. if (empty($modulepart) && !empty($object->module)) {
  5657. $modulepart = $object->module;
  5658. }
  5659. $path = '';
  5660. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5661. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5662. $arrayforoldpath[] = 'product';
  5663. }
  5664. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5665. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5666. if (empty($alpha)) {
  5667. $num = preg_replace('/([^0-9])/i', '', $num);
  5668. } else {
  5669. $num = preg_replace('/^.*\-/i', '', $num);
  5670. }
  5671. $num = substr("000".$num, -$level);
  5672. if ($level == 1) {
  5673. $path = substr($num, 0, 1);
  5674. }
  5675. if ($level == 2) {
  5676. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5677. }
  5678. if ($level == 3) {
  5679. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5680. }
  5681. } else {
  5682. // We will enhance here a common way of forging path for document storage.
  5683. // In a future, we may distribute directories on several levels depending on setup and object.
  5684. // Here, $object->id, $object->ref and $modulepart are required.
  5685. //var_dump($modulepart);
  5686. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5687. }
  5688. if (empty($withoutslash) && !empty($path)) {
  5689. $path .= '/';
  5690. }
  5691. return $path;
  5692. }
  5693. /**
  5694. * Creation of a directory (this can create recursive subdir)
  5695. *
  5696. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5697. * @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)
  5698. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5699. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5700. */
  5701. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5702. {
  5703. global $conf;
  5704. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5705. $dir_osencoded = dol_osencode($dir);
  5706. if (@is_dir($dir_osencoded)) {
  5707. return 0;
  5708. }
  5709. $nberr = 0;
  5710. $nbcreated = 0;
  5711. $ccdir = '';
  5712. if (!empty($dataroot)) {
  5713. // Remove data root from loop
  5714. $dir = str_replace($dataroot.'/', '', $dir);
  5715. $ccdir = $dataroot.'/';
  5716. }
  5717. $cdir = explode("/", $dir);
  5718. $num = count($cdir);
  5719. for ($i = 0; $i < $num; $i++) {
  5720. if ($i > 0) {
  5721. $ccdir .= '/'.$cdir[$i];
  5722. } else {
  5723. $ccdir .= $cdir[$i];
  5724. }
  5725. if (preg_match("/^.:$/", $ccdir, $regs)) {
  5726. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5727. }
  5728. // Attention, le is_dir() peut echouer bien que le rep existe.
  5729. // (ex selon config de open_basedir)
  5730. if ($ccdir) {
  5731. $ccdir_osencoded = dol_osencode($ccdir);
  5732. if (!@is_dir($ccdir_osencoded)) {
  5733. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5734. umask(0);
  5735. $dirmaskdec = octdec($newmask);
  5736. if (empty($newmask)) {
  5737. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5738. }
  5739. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5740. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  5741. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5742. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5743. $nberr++;
  5744. } else {
  5745. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5746. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5747. $nbcreated++;
  5748. }
  5749. } else {
  5750. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5751. }
  5752. }
  5753. }
  5754. return ($nberr ? -$nberr : $nbcreated);
  5755. }
  5756. /**
  5757. * Return picto saying a field is required
  5758. *
  5759. * @return string Chaine avec picto obligatoire
  5760. */
  5761. function picto_required()
  5762. {
  5763. return '<span class="fieldrequired">*</span>';
  5764. }
  5765. /**
  5766. * Clean a string from all HTML tags and entities.
  5767. * This function differs from strip_tags because:
  5768. * - <br> are replaced with \n if removelinefeed=0 or 1
  5769. * - if entities are found, they are decoded BEFORE the strip
  5770. * - you can decide to convert line feed into a space
  5771. *
  5772. * @param string $stringtoclean String to clean
  5773. * @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..."
  5774. * @param string $pagecodeto Encoding of input/output string
  5775. * @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 or when tags is not closed like '<img onload=aaa')
  5776. * @param integer $removedoublespaces Replace double space into one space
  5777. * @return string String cleaned
  5778. *
  5779. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5780. */
  5781. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5782. {
  5783. if ($removelinefeed == 2) {
  5784. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5785. }
  5786. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5787. // We remove entities BEFORE stripping (in case of an open separator char that is entity encoded and not the closing other, the strip will fails)
  5788. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5789. $temp = str_replace('< ', '__ltspace__', $temp);
  5790. if ($strip_tags) {
  5791. $temp = strip_tags($temp);
  5792. } else {
  5793. $temp = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  5794. $pattern = "/<[^<>]+>/";
  5795. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5796. $temp = preg_replace($pattern, "", $temp); // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5797. $temp = preg_replace($pattern, "", $temp); // pass 2 - $temp after pass 2: 0000-021
  5798. // Remove '<' into remainging, so remove non closing html tags like '<abc' or '<<abc'. Note: '<123abc' is not a html tag (can be kept), but '<abc123' is (must be removed).
  5799. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  5800. }
  5801. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5802. // Remove also carriage returns
  5803. if ($removelinefeed == 1) {
  5804. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5805. }
  5806. // And double quotes
  5807. if ($removedoublespaces) {
  5808. while (strpos($temp, " ")) {
  5809. $temp = str_replace(" ", " ", $temp);
  5810. }
  5811. }
  5812. $temp = str_replace('__ltspace__', '< ', $temp);
  5813. return trim($temp);
  5814. }
  5815. /**
  5816. * Clean a string to keep only desirable HTML tags.
  5817. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  5818. *
  5819. * @param string $stringtoclean String to clean
  5820. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5821. * @param int $removeclassattribute 1=Remove the class attribute from tags
  5822. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  5823. * @param int $allowiframe Allow iframe tags.
  5824. * @return string String cleaned
  5825. *
  5826. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5827. */
  5828. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  5829. {
  5830. $allowed_tags = array(
  5831. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5832. "ol", "p", "q", "s", "section", "span", "strike", "strong", "title", "table", "tr", "th", "td", "u", "ul", "sup", "sub", "blockquote", "pre", "h1", "h2", "h3", "h4", "h5", "h6"
  5833. );
  5834. if ($allowiframe) {
  5835. $allowed_tags[] = "iframe";
  5836. }
  5837. $allowed_tags_string = join("><", $allowed_tags);
  5838. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5839. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  5840. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5841. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  5842. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5843. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  5844. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  5845. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </> changing string obfuscated with </> that pass injection detection into harmfull string
  5846. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5847. $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/i', '', $temp); // Note: If hacker try to introduce css comment into string to bypass this regex, the string must also be encoded by the dol_htmlentitiesbr during output so it become harmless
  5848. }
  5849. if ($removeclassattribute) { // Clean for remaining html tags
  5850. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5851. }
  5852. // Remove 'javascript:' that we should not find into a text with
  5853. // Warning: This is not reliable to fight against obfuscated javascript, there is a lot of other solution to include js into a common html tag (only filtered by a GETPOST(.., powerfullfilter)).
  5854. if ($cleanalsojavascript) {
  5855. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5856. }
  5857. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  5858. return $temp;
  5859. }
  5860. /**
  5861. * Clean a string from some undesirable HTML tags.
  5862. * Note: Complementary to dol_string_onlythesehtmltags().
  5863. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  5864. *
  5865. * @param string $stringtoclean String to clean
  5866. * @param array $allowed_attributes Array of tags not allowed
  5867. * @return string String cleaned
  5868. *
  5869. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  5870. */
  5871. function dol_string_onlythesehtmlattributes($stringtoclean, $allowed_attributes = array("allow", "allowfullscreen", "alt", "class", "contenteditable", "data-html", "frameborder", "height", "href", "id", "name", "src", "style", "target", "title", "width"))
  5872. {
  5873. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  5874. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  5875. $dom = new DOMDocument(null, 'UTF-8');
  5876. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  5877. if (is_object($dom)) {
  5878. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  5879. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  5880. //var_dump($attrs->item($ii));
  5881. if (! empty($attrs->item($ii)->name)) {
  5882. // Delete attribute if not into allowed_attributes
  5883. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  5884. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  5885. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  5886. $valuetoclean = $attrs->item($ii)->value;
  5887. do {
  5888. $oldvaluetoclean = $valuetoclean;
  5889. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  5890. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  5891. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  5892. $valuetoclean = preg_replace('/display\s*://m', '', $valuetoclean);
  5893. $valuetoclean = preg_replace('/z-index\s*://m', '', $valuetoclean);
  5894. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*://m', '', $valuetoclean);
  5895. }
  5896. } while ($oldvaluetoclean != $valuetoclean);
  5897. $attrs->item($ii)->value = $valuetoclean;
  5898. }
  5899. }
  5900. }
  5901. }
  5902. }
  5903. $return = $dom->saveHTML();
  5904. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  5905. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  5906. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  5907. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  5908. return trim($return);
  5909. } else {
  5910. return $stringtoclean;
  5911. }
  5912. }
  5913. /**
  5914. * Clean a string from some undesirable HTML tags.
  5915. * Note. Not as secured as dol_string_onlythesehtmltags().
  5916. *
  5917. * @param string $stringtoclean String to clean
  5918. * @param array $disallowed_tags Array of tags not allowed
  5919. * @param string $cleanalsosomestyles Clean also some tags
  5920. * @return string String cleaned
  5921. *
  5922. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  5923. */
  5924. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5925. {
  5926. $temp = $stringtoclean;
  5927. foreach ($disallowed_tags as $tagtoremove) {
  5928. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5929. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5930. }
  5931. if ($cleanalsosomestyles) {
  5932. $temp = preg_replace('/position\s*:\s*(absolute|fixed)\s*!\s*important/', '', $temp); // Note: If hacker try to introduce css comment into string to avoid this, string should be encoded by the dol_htmlentitiesbr so be harmless
  5933. }
  5934. return $temp;
  5935. }
  5936. /**
  5937. * Return first line of text. Cut will depends if content is HTML or not.
  5938. *
  5939. * @param string $text Input text
  5940. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5941. * @param string $charset Charset of $text string (UTF-8 by default)
  5942. * @return string Output text
  5943. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5944. */
  5945. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5946. {
  5947. if ($nboflines == 1) {
  5948. if (dol_textishtml($text)) {
  5949. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5950. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5951. } else {
  5952. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5953. }
  5954. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5955. } else {
  5956. $ishtml = 0;
  5957. if (dol_textishtml($text)) {
  5958. $text = preg_replace('/\n/', '', $text);
  5959. $ishtml = 1;
  5960. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5961. } else {
  5962. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5963. }
  5964. $text = strtr($text, $repTable);
  5965. if ($charset == 'UTF-8') {
  5966. $pattern = '/(<br[^>]*>)/Uu';
  5967. } else {
  5968. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5969. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5970. }
  5971. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5972. $firstline = '';
  5973. $i = 0;
  5974. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5975. while (($i < $nba) && ($i < ($nboflines * 2))) {
  5976. if ($i % 2 == 0) {
  5977. $firstline .= $a[$i];
  5978. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  5979. $firstline .= ($ishtml ? "<br>\n" : "\n");
  5980. }
  5981. $i++;
  5982. }
  5983. unset($a);
  5984. return $firstline.(($i < $nba) ? '...' : '');
  5985. }
  5986. }
  5987. /**
  5988. * Replace CRLF in string with a HTML BR tag.
  5989. * WARNING: The content after operation contains some HTML tags (the <br>) so be sure to also have encode the special chars of stringtoencode into HTML before.
  5990. *
  5991. * @param string $stringtoencode String to encode
  5992. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5993. * @param bool $forxml false=Use <br>, true=Use <br />
  5994. * @return string String encoded
  5995. * @see dol_nboflines(), dolGetFirstLineOfText()
  5996. */
  5997. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5998. {
  5999. if (!$nl2brmode) {
  6000. return nl2br($stringtoencode, $forxml);
  6001. } else {
  6002. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6003. return $ret;
  6004. }
  6005. }
  6006. /**
  6007. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6008. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6009. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6010. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6011. * For PDF usage, you can show text by 2 ways:
  6012. * - writeHTMLCell -> param must be encoded into HTML.
  6013. * - MultiCell -> param must not be encoded into HTML.
  6014. * Because writeHTMLCell convert also \n into <br>, if function
  6015. * is used to build PDF, nl2brmode must be 1.
  6016. *
  6017. * @param string $stringtoencode String to encode
  6018. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6019. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6020. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6021. * @return string String encoded
  6022. */
  6023. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6024. {
  6025. $newstring = $stringtoencode;
  6026. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6027. $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.
  6028. if ($removelasteolbr) {
  6029. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6030. }
  6031. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6032. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6033. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6034. } else {
  6035. if ($removelasteolbr) {
  6036. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6037. }
  6038. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6039. }
  6040. // Other substitutions that htmlentities does not do
  6041. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6042. return $newstring;
  6043. }
  6044. /**
  6045. * This function is called to decode a HTML string (it decodes entities and br tags)
  6046. *
  6047. * @param string $stringtodecode String to decode
  6048. * @param string $pagecodeto Page code for result
  6049. * @return string String decoded
  6050. */
  6051. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6052. {
  6053. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6054. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6055. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6056. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6057. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6058. return $ret;
  6059. }
  6060. /**
  6061. * This function remove all ending \n and br at end
  6062. *
  6063. * @param string $stringtodecode String to decode
  6064. * @return string String decoded
  6065. */
  6066. function dol_htmlcleanlastbr($stringtodecode)
  6067. {
  6068. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6069. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6070. return $ret;
  6071. }
  6072. /**
  6073. * Replace html_entity_decode functions to manage errors
  6074. *
  6075. * @param string $a Operand a
  6076. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6077. * @param string $c Operand c
  6078. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6079. * @return string String decoded
  6080. */
  6081. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6082. {
  6083. $newstring = $a;
  6084. if ($keepsomeentities) {
  6085. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6086. }
  6087. $newstring = html_entity_decode($newstring, $b, $c);
  6088. if ($keepsomeentities) {
  6089. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6090. }
  6091. return $newstring;
  6092. }
  6093. /**
  6094. * Replace htmlentities functions.
  6095. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6096. *
  6097. * @param string $string The input string to encode
  6098. * @param int $flags Flags (see PHP doc above)
  6099. * @param string $encoding Encoding page code
  6100. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6101. * @return string $ret Encoded string
  6102. */
  6103. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6104. {
  6105. return htmlentities($string, $flags, $encoding, $double_encode);
  6106. }
  6107. /**
  6108. * Check if a string is a correct iso string
  6109. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6110. * Example, if string contains euro symbol that has ascii code 128
  6111. *
  6112. * @param string $s String to check
  6113. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6114. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6115. */
  6116. function dol_string_is_good_iso($s, $clean = 0)
  6117. {
  6118. $len = dol_strlen($s);
  6119. $out = '';
  6120. $ok = 1;
  6121. for ($scursor = 0; $scursor < $len; $scursor++) {
  6122. $ordchar = ord($s[$scursor]);
  6123. //print $scursor.'-'.$ordchar.'<br>';
  6124. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6125. $ok = 0;
  6126. break;
  6127. } elseif ($ordchar > 126 && $ordchar < 160) {
  6128. $ok = 0;
  6129. break;
  6130. } elseif ($clean) {
  6131. $out .= $s[$scursor];
  6132. }
  6133. }
  6134. if ($clean) {
  6135. return $out;
  6136. }
  6137. return $ok;
  6138. }
  6139. /**
  6140. * Return nb of lines of a clear text
  6141. *
  6142. * @param string $s String to check
  6143. * @param int $maxchar Not yet used
  6144. * @return int Number of lines
  6145. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6146. */
  6147. function dol_nboflines($s, $maxchar = 0)
  6148. {
  6149. if ($s == '') {
  6150. return 0;
  6151. }
  6152. $arraystring = explode("\n", $s);
  6153. $nb = count($arraystring);
  6154. return $nb;
  6155. }
  6156. /**
  6157. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6158. *
  6159. * @param string $text Text
  6160. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6161. * @param string $charset Give the charset used to encode the $text variable in memory.
  6162. * @return int Number of lines
  6163. * @see dol_nboflines(), dolGetFirstLineOfText()
  6164. */
  6165. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6166. {
  6167. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6168. if (dol_textishtml($text)) {
  6169. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6170. }
  6171. $text = strtr($text, $repTable);
  6172. if ($charset == 'UTF-8') {
  6173. $pattern = '/(<br[^>]*>)/Uu';
  6174. } else {
  6175. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6176. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6177. }
  6178. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6179. $nblines = (int) floor((count($a) + 1) / 2);
  6180. // count possible auto line breaks
  6181. if ($maxlinesize) {
  6182. foreach ($a as $line) {
  6183. if (dol_strlen($line) > $maxlinesize) {
  6184. //$line_dec = html_entity_decode(strip_tags($line));
  6185. $line_dec = html_entity_decode($line);
  6186. if (dol_strlen($line_dec) > $maxlinesize) {
  6187. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6188. $nblines += substr_count($line_dec, '\n');
  6189. }
  6190. }
  6191. }
  6192. }
  6193. unset($a);
  6194. return $nblines;
  6195. }
  6196. /**
  6197. * Return if a text is a html content
  6198. *
  6199. * @param string $msg Content to check
  6200. * @param int $option 0=Full detection, 1=Fast check
  6201. * @return boolean true/false
  6202. * @see dol_concatdesc()
  6203. */
  6204. function dol_textishtml($msg, $option = 0)
  6205. {
  6206. if ($option == 1) {
  6207. if (preg_match('/<html/i', $msg)) {
  6208. return true;
  6209. } elseif (preg_match('/<body/i', $msg)) {
  6210. return true;
  6211. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6212. return true;
  6213. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6214. return true;
  6215. } elseif (preg_match('/<br/i', $msg)) {
  6216. return true;
  6217. }
  6218. return false;
  6219. } else {
  6220. if (preg_match('/<html/i', $msg)) {
  6221. return true;
  6222. } elseif (preg_match('/<body/i', $msg)) {
  6223. return true;
  6224. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6225. return true;
  6226. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6227. return true;
  6228. } elseif (preg_match('/<br\/>/i', $msg)) {
  6229. return true;
  6230. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6231. return true;
  6232. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6233. return true;
  6234. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6235. return true; // must accept <img src="http://example.com/aaa.png" />
  6236. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6237. return true; // must accept <a href="http://example.com/aaa.png" />
  6238. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6239. return true;
  6240. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6241. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6242. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6243. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6244. }
  6245. return false;
  6246. }
  6247. }
  6248. /**
  6249. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6250. * text1 html + text2 html => text1 + '<br>' + text2
  6251. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6252. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6253. * text1 txt + text2 txt => text1 + '\n' + text2
  6254. *
  6255. * @param string $text1 Text 1
  6256. * @param string $text2 Text 2
  6257. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6258. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6259. * @return string Text 1 + new line + Text2
  6260. * @see dol_textishtml()
  6261. */
  6262. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6263. {
  6264. if (!empty($invert)) {
  6265. $tmp = $text1;
  6266. $text1 = $text2;
  6267. $text2 = $tmp;
  6268. }
  6269. $ret = '';
  6270. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6271. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6272. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6273. return $ret;
  6274. }
  6275. /**
  6276. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6277. *
  6278. * @param Translate $outputlangs Output language
  6279. * @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)
  6280. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6281. * @param Object $object Object for keys on object
  6282. * @return array Array of substitutions
  6283. * @see setSubstitFromObject()
  6284. */
  6285. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6286. {
  6287. global $db, $conf, $mysoc, $user, $extrafields;
  6288. $substitutionarray = array();
  6289. if (empty($exclude) || !in_array('user', $exclude)) {
  6290. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6291. // this will include signature content first and then replace var found into content of signature
  6292. $signature = $user->signature;
  6293. $substitutionarray = array_merge($substitutionarray, array(
  6294. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6295. ));
  6296. if (is_object($user)) {
  6297. $substitutionarray = array_merge($substitutionarray, array(
  6298. '__USER_ID__' => (string) $user->id,
  6299. '__USER_LOGIN__' => (string) $user->login,
  6300. '__USER_EMAIL__' => (string) $user->email,
  6301. '__USER_LASTNAME__' => (string) $user->lastname,
  6302. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6303. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6304. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6305. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6306. ));
  6307. }
  6308. }
  6309. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6310. $substitutionarray = array_merge($substitutionarray, array(
  6311. '__MYCOMPANY_NAME__' => $mysoc->name,
  6312. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6313. '__MYCOMPANY_PHONE__' => $mysoc->phone,
  6314. '__MYCOMPANY_FAX__' => $mysoc->fax,
  6315. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6316. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6317. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6318. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6319. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6320. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6321. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6322. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6323. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6324. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6325. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6326. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6327. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6328. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6329. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6330. ));
  6331. }
  6332. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6333. if ($onlykey) {
  6334. $substitutionarray['__ID__'] = '__ID__';
  6335. $substitutionarray['__REF__'] = '__REF__';
  6336. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6337. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6338. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6339. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6340. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6341. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6342. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6343. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6344. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6345. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6346. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6347. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6348. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6349. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6350. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6351. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6352. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6353. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6354. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6355. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6356. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6357. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6358. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6359. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6360. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6361. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6362. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6363. }
  6364. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6365. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6366. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6367. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6368. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6369. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6370. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6371. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6372. }
  6373. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature')) {
  6374. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6375. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6376. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6377. }
  6378. if (!empty($conf->projet->enabled)) { // Most objects
  6379. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6380. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6381. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6382. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6383. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6384. }
  6385. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6386. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6387. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6388. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6389. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6390. }
  6391. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6392. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6393. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6394. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6395. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6396. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6397. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  6398. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6399. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6400. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6401. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6402. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6403. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6404. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6405. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6406. }
  6407. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6408. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6409. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6410. }
  6411. } else {
  6412. $substitutionarray['__ID__'] = $object->id;
  6413. $substitutionarray['__REF__'] = $object->ref;
  6414. $substitutionarray['__NEWREF__'] = $object->newref;
  6415. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6416. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6417. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6418. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6419. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6420. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6421. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6422. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6423. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6424. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6425. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6426. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6427. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6428. // For backward compatibility
  6429. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6430. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6431. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6432. $substitutionarray['__SUPPLIER_ORDER_DELAY_DELIVERY__'] = (isset($object->availability_code) ? ($outputlangs->transnoentities("AvailabilityType".$object->availability_code) != ('AvailabilityType'.$object->availability_code) ? $outputlangs->transnoentities("AvailabilityType".$object->availability_code) : $outputlangs->convToOutputCharset(isset($object->availability) ? $object->availability : '')) : '');
  6433. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6434. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6435. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6436. if (method_exists($object, 'getCivilityLabel')) {
  6437. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6438. }
  6439. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6440. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6441. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6442. if (method_exists($object, 'getFullName')) {
  6443. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6444. }
  6445. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6446. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6447. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6448. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6449. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6450. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6451. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6452. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6453. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6454. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6455. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  6456. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  6457. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  6458. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6459. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6460. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  6461. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  6462. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6463. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6464. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6465. }
  6466. if (is_object($object) && $object->element == 'societe') {
  6467. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6468. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6469. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6470. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6471. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6472. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6473. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  6474. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  6475. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6476. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6477. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6478. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6479. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6480. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6481. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6482. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6483. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6484. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6485. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6486. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6487. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6488. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6489. } elseif (is_object($object->thirdparty)) {
  6490. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6491. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6492. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6493. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6494. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6495. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6496. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  6497. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  6498. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6499. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6500. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6501. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6502. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6503. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6504. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6505. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6506. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6507. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6508. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6509. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6510. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6511. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6512. }
  6513. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6514. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6515. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  6516. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  6517. }
  6518. if (is_object($object->project)) {
  6519. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6520. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6521. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6522. }
  6523. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6524. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6525. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6526. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6527. }
  6528. if (is_object($object) && $object->element == 'shipping') {
  6529. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6530. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6531. }
  6532. if (is_object($object) && $object->element == 'reception') {
  6533. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6534. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6535. }
  6536. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6537. $dateplannedstart = '';
  6538. $datenextexpiration = '';
  6539. foreach ($object->lines as $line) {
  6540. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6541. $dateplannedstart = $line->date_ouverture_prevue;
  6542. }
  6543. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6544. $datenextexpiration = $line->date_fin_prevue;
  6545. }
  6546. }
  6547. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6548. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6549. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6550. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6551. }
  6552. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6553. if ($object->table_element && $object->id > 0) {
  6554. if (!is_object($extrafields)) {
  6555. $extrafields = new ExtraFields($db);
  6556. }
  6557. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6558. if ($object->fetch_optionals() > 0) {
  6559. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6560. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6561. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6562. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6563. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6564. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6565. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6566. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6567. $datetime = $object->array_options['options_'.$key];
  6568. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6569. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6570. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6571. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6572. }
  6573. }
  6574. }
  6575. }
  6576. }
  6577. // Complete substitution array with the url to make online payment
  6578. $paymenturl = '';
  6579. if (empty($substitutionarray['__REF__'])) {
  6580. $paymenturl = '';
  6581. } else {
  6582. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6583. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6584. $outputlangs->loadLangs(array('paypal', 'other'));
  6585. $typeforonlinepayment = 'free';
  6586. if (is_object($object) && $object->element == 'commande') {
  6587. $typeforonlinepayment = 'order';
  6588. }
  6589. if (is_object($object) && $object->element == 'facture') {
  6590. $typeforonlinepayment = 'invoice';
  6591. }
  6592. if (is_object($object) && $object->element == 'member') {
  6593. $typeforonlinepayment = 'member';
  6594. }
  6595. if (is_object($object) && $object->element == 'contrat') {
  6596. $typeforonlinepayment = 'contract';
  6597. }
  6598. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6599. $paymenturl = $url;
  6600. }
  6601. if ($object->id > 0) {
  6602. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6603. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6604. if (is_object($object) && $object->element == 'propal') {
  6605. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  6606. }
  6607. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6608. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6609. } else {
  6610. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6611. }
  6612. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6613. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6614. } else {
  6615. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6616. }
  6617. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6618. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6619. } else {
  6620. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6621. }
  6622. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6623. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6624. } else {
  6625. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6626. }
  6627. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6628. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6629. } else {
  6630. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6631. }
  6632. if (is_object($object) && $object->element == 'propal') {
  6633. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6634. }
  6635. if (is_object($object) && $object->element == 'commande') {
  6636. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6637. }
  6638. if (is_object($object) && $object->element == 'facture') {
  6639. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6640. }
  6641. if (is_object($object) && $object->element == 'contrat') {
  6642. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6643. }
  6644. if (is_object($object) && $object->element == 'supplier_proposal') {
  6645. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6646. }
  6647. if (is_object($object) && $object->element == 'shipping') {
  6648. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  6649. }
  6650. }
  6651. if (is_object($object) && $object->element == 'action') {
  6652. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6653. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  6654. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  6655. }
  6656. }
  6657. }
  6658. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  6659. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  6660. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  6661. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  6662. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  6663. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  6664. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  6665. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  6666. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6667. $substitutionarray['__AMOUNT_VAT_TEXT__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, '', true) : dol_convertToWord($object->total_tva, $outputlangs, '', true)) : '';
  6668. $substitutionarray['__AMOUNT_VAT_TEXTCURRENCY__'] = is_object($object) ? (isset($object->total_vat) ? dol_convertToWord($object->total_vat, $outputlangs, $conf->currency, true) : dol_convertToWord($object->total_tva, $outputlangs, $conf->currency, true)) : '';
  6669. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6670. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  6671. }
  6672. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6673. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  6674. }
  6675. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6676. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6677. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? (isset($object->total_vat) ? price($object->total_vat, 0, $outputlangs, 0, -1, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, -1, -1, $conf->currency) : null)) : '';
  6678. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6679. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6680. }
  6681. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6682. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6683. }
  6684. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  6685. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  6686. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  6687. // TODO Add other keys for foreign multicurrency
  6688. // For backward compatibility
  6689. if ($onlykey != 2) {
  6690. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  6691. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  6692. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6693. }
  6694. }
  6695. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  6696. if (empty($exclude) || !in_array('date', $exclude)) {
  6697. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6698. $tmp = dol_getdate(dol_now(), true);
  6699. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6700. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  6701. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6702. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  6703. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  6704. $substitutionarray = array_merge($substitutionarray, array(
  6705. '__DAY__' => (string) $tmp['mday'],
  6706. '__DAY_TEXT__' => $daytext, // Monday
  6707. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  6708. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  6709. '__MONTH__' => (string) $tmp['mon'],
  6710. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  6711. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  6712. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  6713. '__YEAR__' => (string) $tmp['year'],
  6714. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  6715. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  6716. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  6717. '__NEXT_DAY__' => (string) $tmp4['day'],
  6718. '__NEXT_MONTH__' => (string) $tmp5['month'],
  6719. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  6720. ));
  6721. }
  6722. if (!empty($conf->multicompany->enabled)) {
  6723. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  6724. }
  6725. if (empty($exclude) || !in_array('system', $exclude)) {
  6726. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  6727. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  6728. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  6729. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  6730. }
  6731. return $substitutionarray;
  6732. }
  6733. /**
  6734. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  6735. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  6736. * Example of usage:
  6737. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  6738. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  6739. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  6740. *
  6741. * @param string $text Source string in which we must do substitution
  6742. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  6743. * @param Translate $outputlangs Output language
  6744. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  6745. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  6746. * @return string Output string after substitutions
  6747. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  6748. */
  6749. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  6750. {
  6751. global $conf, $langs;
  6752. if (!is_array($substitutionarray)) {
  6753. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  6754. }
  6755. if (empty($outputlangs)) {
  6756. $outputlangs = $langs;
  6757. }
  6758. // Is initial text HTML or simple text ?
  6759. $msgishtml = 0;
  6760. if (dol_textishtml($text, 1)) {
  6761. $msgishtml = 1;
  6762. }
  6763. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  6764. if (is_object($outputlangs)) {
  6765. $reg = array();
  6766. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  6767. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  6768. $tmp = explode('|', $reg[1]);
  6769. if (!empty($tmp[1])) {
  6770. $outputlangs->load($tmp[1]);
  6771. }
  6772. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  6773. if (empty($converttextinhtmlifnecessary)) {
  6774. // convert $newval into HTML is necessary
  6775. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6776. } else {
  6777. if (! $msgishtml) {
  6778. $valueishtml = dol_textishtml($value, 1);
  6779. if ($valueishtml) {
  6780. $text = dol_htmlentitiesbr($text);
  6781. $msgishtml = 1;
  6782. }
  6783. } else {
  6784. $value = dol_nl2br("$value");
  6785. }
  6786. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  6787. }
  6788. }
  6789. }
  6790. // Make substitution for constant keys.
  6791. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  6792. $reg = array();
  6793. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  6794. $keyfound = $reg[1];
  6795. if (isASecretKey($keyfound)) {
  6796. $value = '*****forbidden*****';
  6797. } else {
  6798. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  6799. }
  6800. if (empty($converttextinhtmlifnecessary)) {
  6801. // convert $newval into HTML is necessary
  6802. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6803. } else {
  6804. if (! $msgishtml) {
  6805. $valueishtml = dol_textishtml($value, 1);
  6806. if ($valueishtml) {
  6807. $text = dol_htmlentitiesbr($text);
  6808. $msgishtml = 1;
  6809. }
  6810. } else {
  6811. $value = dol_nl2br("$value");
  6812. }
  6813. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  6814. }
  6815. }
  6816. // Make substitition for array $substitutionarray
  6817. foreach ($substitutionarray as $key => $value) {
  6818. if (!isset($value)) {
  6819. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  6820. }
  6821. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  6822. $value = ''; // Protection
  6823. }
  6824. if (empty($converttextinhtmlifnecessary)) {
  6825. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6826. } else {
  6827. if (! $msgishtml) {
  6828. $valueishtml = dol_textishtml($value, 1);
  6829. if ($valueishtml) {
  6830. $text = dol_htmlentitiesbr($text);
  6831. $msgishtml = 1;
  6832. }
  6833. } else {
  6834. $value = dol_nl2br("$value");
  6835. }
  6836. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6837. }
  6838. }
  6839. return $text;
  6840. }
  6841. /**
  6842. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6843. * In this case, method completesubstitutionarray provided by module is called.
  6844. *
  6845. * @param array $substitutionarray Array substitution old value => new value value
  6846. * @param Translate $outputlangs Output language
  6847. * @param Object $object Source object
  6848. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6849. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6850. * @return void
  6851. * @see make_substitutions()
  6852. */
  6853. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6854. {
  6855. global $conf, $user;
  6856. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6857. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  6858. // Check if there is external substitution to do, requested by plugins
  6859. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  6860. foreach ($dirsubstitutions as $reldir) {
  6861. $dir = dol_buildpath($reldir, 0);
  6862. // Check if directory exists
  6863. if (!dol_is_dir($dir)) {
  6864. continue;
  6865. }
  6866. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  6867. foreach ($substitfiles as $substitfile) {
  6868. $reg = array();
  6869. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  6870. $module = $reg[1];
  6871. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  6872. // Include the user's functions file
  6873. require_once $dir.$substitfile['name'];
  6874. // Call the user's function, and only if it is defined
  6875. $function_name = $module."_".$callfunc;
  6876. if (function_exists($function_name)) {
  6877. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  6878. }
  6879. }
  6880. }
  6881. }
  6882. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  6883. // to list all tags in odt template
  6884. $tags = '';
  6885. foreach ($substitutionarray as $key => $value) {
  6886. $tags .= '{'.$key.'} => '.$value."\n";
  6887. }
  6888. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  6889. }
  6890. }
  6891. /**
  6892. * Format output for start and end date
  6893. *
  6894. * @param int $date_start Start date
  6895. * @param int $date_end End date
  6896. * @param string $format Output format
  6897. * @param Translate $outputlangs Output language
  6898. * @return void
  6899. */
  6900. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  6901. {
  6902. print get_date_range($date_start, $date_end, $format, $outputlangs);
  6903. }
  6904. /**
  6905. * Format output for start and end date
  6906. *
  6907. * @param int $date_start Start date
  6908. * @param int $date_end End date
  6909. * @param string $format Output format
  6910. * @param Translate $outputlangs Output language
  6911. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  6912. * @return string String
  6913. */
  6914. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  6915. {
  6916. global $langs;
  6917. $out = '';
  6918. if (!is_object($outputlangs)) {
  6919. $outputlangs = $langs;
  6920. }
  6921. if ($date_start && $date_end) {
  6922. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6923. }
  6924. if ($date_start && !$date_end) {
  6925. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6926. }
  6927. if (!$date_start && $date_end) {
  6928. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6929. }
  6930. return $out;
  6931. }
  6932. /**
  6933. * Return firstname and lastname in correct order
  6934. *
  6935. * @param string $firstname Firstname
  6936. * @param string $lastname Lastname
  6937. * @param int $nameorder -1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname, 3=Firstname if defined else lastname, 4=Lastname, 5=Lastname if defined else firstname
  6938. * @return string Firstname + lastname or Lastname + firstname
  6939. */
  6940. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  6941. {
  6942. global $conf;
  6943. $ret = '';
  6944. // If order not defined, we use the setup
  6945. if ($nameorder < 0) {
  6946. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  6947. }
  6948. if ($nameorder == 1) {
  6949. $ret .= $firstname;
  6950. if ($firstname && $lastname) {
  6951. $ret .= ' ';
  6952. }
  6953. $ret .= $lastname;
  6954. } elseif ($nameorder == 2 || $nameorder == 3) {
  6955. $ret .= $firstname;
  6956. if (empty($ret) && $nameorder == 3) {
  6957. $ret .= $lastname;
  6958. }
  6959. } else { // 0, 4 or 5
  6960. $ret .= $lastname;
  6961. if (empty($ret) && $nameorder == 5) {
  6962. $ret .= $firstname;
  6963. }
  6964. if ($nameorder == 0) {
  6965. if ($firstname && $lastname) {
  6966. $ret .= ' ';
  6967. }
  6968. $ret .= $firstname;
  6969. }
  6970. }
  6971. return $ret;
  6972. }
  6973. /**
  6974. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  6975. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6976. * Note: Prefer to use setEventMessages instead.
  6977. *
  6978. * @param string|string[] $mesgs Message string or array
  6979. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6980. * @return void
  6981. * @see dol_htmloutput_events()
  6982. */
  6983. function setEventMessage($mesgs, $style = 'mesgs')
  6984. {
  6985. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  6986. if (!is_array($mesgs)) {
  6987. // If mesgs is a string
  6988. if ($mesgs) {
  6989. $_SESSION['dol_events'][$style][] = $mesgs;
  6990. }
  6991. } else {
  6992. // If mesgs is an array
  6993. foreach ($mesgs as $mesg) {
  6994. if ($mesg) {
  6995. $_SESSION['dol_events'][$style][] = $mesg;
  6996. }
  6997. }
  6998. }
  6999. }
  7000. /**
  7001. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7002. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7003. *
  7004. * @param string $mesg Message string
  7005. * @param array $mesgs Message array
  7006. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7007. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7008. * @return void
  7009. * @see dol_htmloutput_events()
  7010. */
  7011. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  7012. {
  7013. if (empty($mesg) && empty($mesgs)) {
  7014. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  7015. } else {
  7016. if ($messagekey) {
  7017. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7018. // TODO
  7019. $mesg .= '';
  7020. }
  7021. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7022. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7023. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7024. }
  7025. if (empty($mesgs)) {
  7026. setEventMessage($mesg, $style);
  7027. } else {
  7028. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7029. setEventMessage($mesg, $style); // Add message string if not already into array
  7030. }
  7031. setEventMessage($mesgs, $style);
  7032. }
  7033. }
  7034. }
  7035. }
  7036. /**
  7037. * Print formated messages to output (Used to show messages on html output).
  7038. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7039. * no need to call it explicitely.
  7040. *
  7041. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7042. * @return void
  7043. * @see dol_htmloutput_mesg()
  7044. */
  7045. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7046. {
  7047. // Show mesgs
  7048. if (isset($_SESSION['dol_events']['mesgs'])) {
  7049. if (empty($disabledoutputofmessages)) {
  7050. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7051. }
  7052. unset($_SESSION['dol_events']['mesgs']);
  7053. }
  7054. // Show errors
  7055. if (isset($_SESSION['dol_events']['errors'])) {
  7056. if (empty($disabledoutputofmessages)) {
  7057. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7058. }
  7059. unset($_SESSION['dol_events']['errors']);
  7060. }
  7061. // Show warnings
  7062. if (isset($_SESSION['dol_events']['warnings'])) {
  7063. if (empty($disabledoutputofmessages)) {
  7064. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7065. }
  7066. unset($_SESSION['dol_events']['warnings']);
  7067. }
  7068. }
  7069. /**
  7070. * Get formated messages to output (Used to show messages on html output).
  7071. * This include also the translation of the message key.
  7072. *
  7073. * @param string $mesgstring Message string or message key
  7074. * @param string[] $mesgarray Array of message strings or message keys
  7075. * @param string $style Style of message output ('ok' or 'error')
  7076. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7077. * @return string Return html output
  7078. *
  7079. * @see dol_print_error()
  7080. * @see dol_htmloutput_errors()
  7081. * @see setEventMessages()
  7082. */
  7083. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7084. {
  7085. global $conf, $langs;
  7086. $ret = 0;
  7087. $return = '';
  7088. $out = '';
  7089. $divstart = $divend = '';
  7090. // If inline message with no format, we add it.
  7091. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7092. $divstart = '<div class="'.$style.' clearboth">';
  7093. $divend = '</div>';
  7094. }
  7095. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7096. $langs->load("errors");
  7097. $out .= $divstart;
  7098. if (is_array($mesgarray) && count($mesgarray)) {
  7099. foreach ($mesgarray as $message) {
  7100. $ret++;
  7101. $out .= $langs->trans($message);
  7102. if ($ret < count($mesgarray)) {
  7103. $out .= "<br>\n";
  7104. }
  7105. }
  7106. }
  7107. if ($mesgstring) {
  7108. $langs->load("errors");
  7109. $ret++;
  7110. $out .= $langs->trans($mesgstring);
  7111. }
  7112. $out .= $divend;
  7113. }
  7114. if ($out) {
  7115. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7116. $return = '<script>
  7117. $(document).ready(function() {
  7118. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7119. if (block) {
  7120. $.dolEventValid("","'.dol_escape_js($out).'");
  7121. } else {
  7122. /* jnotify(message, preset of message type, keepmessage) */
  7123. $.jnotify("'.dol_escape_js($out).'",
  7124. "'.($style == "ok" ? 3000 : $style).'",
  7125. '.($style == "ok" ? "false" : "true").',
  7126. { remove: function (){} } );
  7127. }
  7128. });
  7129. </script>';
  7130. } else {
  7131. $return = $out;
  7132. }
  7133. }
  7134. return $return;
  7135. }
  7136. /**
  7137. * Get formated error messages to output (Used to show messages on html output).
  7138. *
  7139. * @param string $mesgstring Error message
  7140. * @param array $mesgarray Error messages array
  7141. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7142. * @return string Return html output
  7143. *
  7144. * @see dol_print_error()
  7145. * @see dol_htmloutput_mesg()
  7146. */
  7147. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7148. {
  7149. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7150. }
  7151. /**
  7152. * Print formated messages to output (Used to show messages on html output).
  7153. *
  7154. * @param string $mesgstring Message string or message key
  7155. * @param string[] $mesgarray Array of message strings or message keys
  7156. * @param string $style Which style to use ('ok', 'warning', 'error')
  7157. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7158. * @return void
  7159. *
  7160. * @see dol_print_error()
  7161. * @see dol_htmloutput_errors()
  7162. * @see setEventMessages()
  7163. */
  7164. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7165. {
  7166. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7167. return;
  7168. }
  7169. $iserror = 0;
  7170. $iswarning = 0;
  7171. if (is_array($mesgarray)) {
  7172. foreach ($mesgarray as $val) {
  7173. if ($val && preg_match('/class="error"/i', $val)) {
  7174. $iserror++;
  7175. break;
  7176. }
  7177. if ($val && preg_match('/class="warning"/i', $val)) {
  7178. $iswarning++;
  7179. break;
  7180. }
  7181. }
  7182. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7183. $iserror++;
  7184. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7185. $iswarning++;
  7186. }
  7187. if ($style == 'error') {
  7188. $iserror++;
  7189. }
  7190. if ($style == 'warning') {
  7191. $iswarning++;
  7192. }
  7193. if ($iserror || $iswarning) {
  7194. // Remove div from texts
  7195. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7196. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7197. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7198. // Remove div from texts array
  7199. if (is_array($mesgarray)) {
  7200. $newmesgarray = array();
  7201. foreach ($mesgarray as $val) {
  7202. if (is_string($val)) {
  7203. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7204. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7205. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7206. $newmesgarray[] = $tmpmesgstring;
  7207. } else {
  7208. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7209. }
  7210. }
  7211. $mesgarray = $newmesgarray;
  7212. }
  7213. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7214. } else {
  7215. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7216. }
  7217. }
  7218. /**
  7219. * Print formated error messages to output (Used to show messages on html output).
  7220. *
  7221. * @param string $mesgstring Error message
  7222. * @param array $mesgarray Error messages array
  7223. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7224. * @return void
  7225. *
  7226. * @see dol_print_error()
  7227. * @see dol_htmloutput_mesg()
  7228. */
  7229. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7230. {
  7231. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7232. }
  7233. /**
  7234. * Advanced sort array by second index function, which produces ascending (default)
  7235. * or descending output and uses optionally natural case insensitive sorting (which
  7236. * can be optionally case sensitive as well).
  7237. *
  7238. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7239. * @param string $index Key in array to use for sorting criteria
  7240. * @param int $order Sort order ('asc' or 'desc')
  7241. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7242. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7243. * @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.
  7244. * @return array Sorted array
  7245. */
  7246. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7247. {
  7248. // Clean parameters
  7249. $order = strtolower($order);
  7250. if (is_array($array)) {
  7251. $sizearray = count($array);
  7252. if ($sizearray > 0) {
  7253. $temp = array();
  7254. foreach (array_keys($array) as $key) {
  7255. if (is_object($array[$key])) {
  7256. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7257. } else {
  7258. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7259. }
  7260. }
  7261. if (!$natsort) {
  7262. if ($order == 'asc') {
  7263. asort($temp);
  7264. } else {
  7265. arsort($temp);
  7266. }
  7267. } else {
  7268. if ($case_sensitive) {
  7269. natsort($temp);
  7270. } else {
  7271. natcasesort($temp); // natecasesort is not sensible to case
  7272. }
  7273. if ($order != 'asc') {
  7274. $temp = array_reverse($temp, true);
  7275. }
  7276. }
  7277. $sorted = array();
  7278. foreach (array_keys($temp) as $key) {
  7279. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7280. }
  7281. return $sorted;
  7282. }
  7283. }
  7284. return $array;
  7285. }
  7286. /**
  7287. * Check if a string is in UTF8
  7288. *
  7289. * @param string $str String to check
  7290. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7291. */
  7292. function utf8_check($str)
  7293. {
  7294. $str = (string) $str; // Sometimes string is an int.
  7295. // We must use here a binary strlen function (so not dol_strlen)
  7296. $strLength = dol_strlen($str);
  7297. for ($i = 0; $i < $strLength; $i++) {
  7298. if (ord($str[$i]) < 0x80) {
  7299. continue; // 0bbbbbbb
  7300. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7301. $n = 1; // 110bbbbb
  7302. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7303. $n = 2; // 1110bbbb
  7304. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7305. $n = 3; // 11110bbb
  7306. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7307. $n = 4; // 111110bb
  7308. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7309. $n = 5; // 1111110b
  7310. } else {
  7311. return false; // Does not match any model
  7312. }
  7313. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7314. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7315. return false;
  7316. }
  7317. }
  7318. }
  7319. return true;
  7320. }
  7321. /**
  7322. * Check if a string is in ASCII
  7323. *
  7324. * @param string $str String to check
  7325. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7326. */
  7327. function ascii_check($str)
  7328. {
  7329. if (function_exists('mb_check_encoding')) {
  7330. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7331. if (!mb_check_encoding($str, 'ASCII')) {
  7332. return false;
  7333. }
  7334. } else {
  7335. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7336. return false; // Contains a byte > 7f
  7337. }
  7338. }
  7339. return true;
  7340. }
  7341. /**
  7342. * Return a string encoded into OS filesystem encoding. This function is used to define
  7343. * value to pass to filesystem PHP functions.
  7344. *
  7345. * @param string $str String to encode (UTF-8)
  7346. * @return string Encoded string (UTF-8, ISO-8859-1)
  7347. */
  7348. function dol_osencode($str)
  7349. {
  7350. global $conf;
  7351. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7352. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7353. $tmp = 'iso-8859-1'; // By default for windows
  7354. }
  7355. if (empty($tmp)) {
  7356. $tmp = 'utf-8'; // By default for other
  7357. }
  7358. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7359. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7360. }
  7361. if ($tmp == 'iso-8859-1') {
  7362. return utf8_decode($str);
  7363. }
  7364. return $str;
  7365. }
  7366. /**
  7367. * Return an id or code from a code or id.
  7368. * Store also Code-Id into a cache to speed up next request on same key.
  7369. *
  7370. * @param DoliDB $db Database handler
  7371. * @param string $key Code or Id to get Id or Code
  7372. * @param string $tablename Table name without prefix
  7373. * @param string $fieldkey Field to search the key into
  7374. * @param string $fieldid Field to get
  7375. * @param int $entityfilter Filter by entity
  7376. * @return int <0 if KO, Id of code if OK
  7377. * @see $langs->getLabelFromKey
  7378. */
  7379. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  7380. {
  7381. global $cache_codes;
  7382. // If key empty
  7383. if ($key == '') {
  7384. return '';
  7385. }
  7386. // Check in cache
  7387. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7388. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7389. }
  7390. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7391. $sql = "SELECT ".$fieldid." as valuetoget";
  7392. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7393. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7394. if (!empty($entityfilter)) {
  7395. $sql .= " AND entity IN (".getEntity($tablename).")";
  7396. }
  7397. $resql = $db->query($sql);
  7398. if ($resql) {
  7399. $obj = $db->fetch_object($resql);
  7400. if ($obj) {
  7401. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7402. } else {
  7403. $cache_codes[$tablename][$key][$fieldid] = '';
  7404. }
  7405. $db->free($resql);
  7406. return $cache_codes[$tablename][$key][$fieldid];
  7407. } else {
  7408. return -1;
  7409. }
  7410. }
  7411. /**
  7412. * Verify if condition in string is ok or not
  7413. *
  7414. * @param string $strToEvaluate String with condition to check
  7415. * @return boolean True or False. Note: It returns True if $strToEvaluate is ''
  7416. */
  7417. function verifCond($strToEvaluate)
  7418. {
  7419. global $user, $conf, $langs;
  7420. global $leftmenu;
  7421. global $rights; // To export to dol_eval function
  7422. //print $strToEvaluate."<br>\n";
  7423. $rights = true;
  7424. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  7425. $str = 'if(!('.$strToEvaluate.')) { $rights = false; }';
  7426. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  7427. }
  7428. return $rights;
  7429. }
  7430. /**
  7431. * Replace eval function to add more security.
  7432. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7433. *
  7434. * @param string $s String to evaluate
  7435. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7436. * @param int $hideerrors 1=Hide errors
  7437. * @return mixed Nothing or return result of eval
  7438. */
  7439. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  7440. {
  7441. // Only global variables can be changed by eval function and returned to caller
  7442. global $db, $langs, $user, $conf, $website, $websitepage;
  7443. global $action, $mainmenu, $leftmenu;
  7444. global $rights;
  7445. global $object;
  7446. global $mysoc;
  7447. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7448. global $soc; // For backward compatibility
  7449. // Replace dangerous char (used for RCE), we allow only PHP variable testing.
  7450. if (strpos($s, '`') !== false) {
  7451. return 'Bad string syntax to evaluate: '.$s;
  7452. }
  7453. // We block use of php exec or php file functions
  7454. $forbiddenphpstrings = array('$$');
  7455. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7456. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI");
  7457. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask"));
  7458. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  7459. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  7460. do {
  7461. $oldstringtoclean = $s;
  7462. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7463. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  7464. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7465. } while ($oldstringtoclean != $s);
  7466. if (strpos($s, '__forbiddenstring__') !== false) {
  7467. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7468. return 'Bad string syntax to evaluate: '.$s;
  7469. }
  7470. //print $s."<br>\n";
  7471. if ($returnvalue) {
  7472. if ($hideerrors) {
  7473. return @eval('return '.$s.';');
  7474. } else {
  7475. return eval('return '.$s.';');
  7476. }
  7477. } else {
  7478. if ($hideerrors) {
  7479. @eval($s);
  7480. } else {
  7481. eval($s);
  7482. }
  7483. }
  7484. }
  7485. /**
  7486. * Return if var element is ok
  7487. *
  7488. * @param string $element Variable to check
  7489. * @return boolean Return true of variable is not empty
  7490. */
  7491. function dol_validElement($element)
  7492. {
  7493. return (trim($element) != '');
  7494. }
  7495. /**
  7496. * Return img flag of country for a language code or country code.
  7497. *
  7498. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7499. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7500. * @param int $notitlealt No title alt
  7501. * @return string HTML img string with flag.
  7502. */
  7503. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  7504. {
  7505. if (empty($codelang)) {
  7506. return '';
  7507. }
  7508. if ($codelang == 'auto') {
  7509. return '<span class="fa fa-language"></span>';
  7510. }
  7511. $langtocountryflag = array(
  7512. 'ar_AR' => '',
  7513. 'ca_ES' => 'catalonia',
  7514. 'da_DA' => 'dk',
  7515. 'fr_CA' => 'mq',
  7516. 'sv_SV' => 'se',
  7517. 'sw_SW' => 'unknown',
  7518. 'AQ' => 'unknown',
  7519. 'CW' => 'unknown',
  7520. 'IM' => 'unknown',
  7521. 'JE' => 'unknown',
  7522. 'MF' => 'unknown',
  7523. 'BL' => 'unknown',
  7524. 'SX' => 'unknown'
  7525. );
  7526. if (isset($langtocountryflag[$codelang])) {
  7527. $flagImage = $langtocountryflag[$codelang];
  7528. } else {
  7529. $tmparray = explode('_', $codelang);
  7530. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7531. }
  7532. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  7533. }
  7534. /**
  7535. * Return default language from country code.
  7536. * Return null if not found.
  7537. *
  7538. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  7539. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  7540. */
  7541. function getLanguageCodeFromCountryCode($countrycode)
  7542. {
  7543. global $mysoc;
  7544. if (empty($countrycode)) {
  7545. return null;
  7546. }
  7547. if (strtoupper($countrycode) == 'MQ') {
  7548. return 'fr_CA';
  7549. }
  7550. if (strtoupper($countrycode) == 'SE') {
  7551. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7552. }
  7553. if (strtoupper($countrycode) == 'CH') {
  7554. if ($mysoc->country_code == 'FR') {
  7555. return 'fr_CH';
  7556. }
  7557. if ($mysoc->country_code == 'DE') {
  7558. return 'de_CH';
  7559. }
  7560. if ($mysoc->country_code == 'IT') {
  7561. return 'it_CH';
  7562. }
  7563. }
  7564. // Locale list taken from:
  7565. // http://stackoverflow.com/questions/3191664/
  7566. // list-of-all-locales-and-their-short-codes
  7567. $locales = array(
  7568. 'af-ZA',
  7569. 'am-ET',
  7570. 'ar-AE',
  7571. 'ar-BH',
  7572. 'ar-DZ',
  7573. 'ar-EG',
  7574. 'ar-IQ',
  7575. 'ar-JO',
  7576. 'ar-KW',
  7577. 'ar-LB',
  7578. 'ar-LY',
  7579. 'ar-MA',
  7580. 'ar-OM',
  7581. 'ar-QA',
  7582. 'ar-SA',
  7583. 'ar-SY',
  7584. 'ar-TN',
  7585. 'ar-YE',
  7586. //'as-IN', // Moved after en-IN
  7587. 'ba-RU',
  7588. 'be-BY',
  7589. 'bg-BG',
  7590. 'bn-BD',
  7591. //'bn-IN', // Moved after en-IN
  7592. 'bo-CN',
  7593. 'br-FR',
  7594. 'ca-ES',
  7595. 'co-FR',
  7596. 'cs-CZ',
  7597. 'cy-GB',
  7598. 'da-DK',
  7599. 'de-AT',
  7600. 'de-CH',
  7601. 'de-DE',
  7602. 'de-LI',
  7603. 'de-LU',
  7604. 'dv-MV',
  7605. 'el-GR',
  7606. 'en-AU',
  7607. 'en-BZ',
  7608. 'en-CA',
  7609. 'en-GB',
  7610. 'en-IE',
  7611. 'en-IN',
  7612. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  7613. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  7614. 'en-JM',
  7615. 'en-MY',
  7616. 'en-NZ',
  7617. 'en-PH',
  7618. 'en-SG',
  7619. 'en-TT',
  7620. 'en-US',
  7621. 'en-ZA',
  7622. 'en-ZW',
  7623. 'es-AR',
  7624. 'es-BO',
  7625. 'es-CL',
  7626. 'es-CO',
  7627. 'es-CR',
  7628. 'es-DO',
  7629. 'es-EC',
  7630. 'es-ES',
  7631. 'es-GT',
  7632. 'es-HN',
  7633. 'es-MX',
  7634. 'es-NI',
  7635. 'es-PA',
  7636. 'es-PE',
  7637. 'es-PR',
  7638. 'es-PY',
  7639. 'es-SV',
  7640. 'es-US',
  7641. 'es-UY',
  7642. 'es-VE',
  7643. 'et-EE',
  7644. 'eu-ES',
  7645. 'fa-IR',
  7646. 'fi-FI',
  7647. 'fo-FO',
  7648. 'fr-BE',
  7649. 'fr-CA',
  7650. 'fr-CH',
  7651. 'fr-FR',
  7652. 'fr-LU',
  7653. 'fr-MC',
  7654. 'fy-NL',
  7655. 'ga-IE',
  7656. 'gd-GB',
  7657. 'gl-ES',
  7658. 'gu-IN',
  7659. 'he-IL',
  7660. 'hi-IN',
  7661. 'hr-BA',
  7662. 'hr-HR',
  7663. 'hu-HU',
  7664. 'hy-AM',
  7665. 'id-ID',
  7666. 'ig-NG',
  7667. 'ii-CN',
  7668. 'is-IS',
  7669. 'it-CH',
  7670. 'it-IT',
  7671. 'ja-JP',
  7672. 'ka-GE',
  7673. 'kk-KZ',
  7674. 'kl-GL',
  7675. 'km-KH',
  7676. 'kn-IN',
  7677. 'ko-KR',
  7678. 'ky-KG',
  7679. 'lb-LU',
  7680. 'lo-LA',
  7681. 'lt-LT',
  7682. 'lv-LV',
  7683. 'mi-NZ',
  7684. 'mk-MK',
  7685. 'ml-IN',
  7686. 'mn-MN',
  7687. 'mr-IN',
  7688. 'ms-BN',
  7689. 'ms-MY',
  7690. 'mt-MT',
  7691. 'nb-NO',
  7692. 'ne-NP',
  7693. 'nl-BE',
  7694. 'nl-NL',
  7695. 'nn-NO',
  7696. 'oc-FR',
  7697. 'or-IN',
  7698. 'pa-IN',
  7699. 'pl-PL',
  7700. 'ps-AF',
  7701. 'pt-BR',
  7702. 'pt-PT',
  7703. 'rm-CH',
  7704. 'ro-MD',
  7705. 'ro-RO',
  7706. 'ru-RU',
  7707. 'rw-RW',
  7708. 'sa-IN',
  7709. 'se-FI',
  7710. 'se-NO',
  7711. 'se-SE',
  7712. 'si-LK',
  7713. 'sk-SK',
  7714. 'sl-SI',
  7715. 'sq-AL',
  7716. 'sv-FI',
  7717. 'sv-SE',
  7718. 'sw-KE',
  7719. 'ta-IN',
  7720. 'te-IN',
  7721. 'th-TH',
  7722. 'tk-TM',
  7723. 'tn-ZA',
  7724. 'tr-TR',
  7725. 'tt-RU',
  7726. 'ug-CN',
  7727. 'uk-UA',
  7728. 'ur-PK',
  7729. 'vi-VN',
  7730. 'wo-SN',
  7731. 'xh-ZA',
  7732. 'yo-NG',
  7733. 'zh-CN',
  7734. 'zh-HK',
  7735. 'zh-MO',
  7736. 'zh-SG',
  7737. 'zh-TW',
  7738. 'zu-ZA',
  7739. );
  7740. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  7741. if (in_array($buildprimarykeytotest, $locales)) {
  7742. return strtolower($countrycode).'_'.strtoupper($countrycode);
  7743. }
  7744. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  7745. foreach ($locales as $locale) {
  7746. $locale_language = locale_get_primary_language($locale);
  7747. $locale_region = locale_get_region($locale);
  7748. if (strtoupper($countrycode) == $locale_region) {
  7749. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  7750. return strtolower($locale_language).'_'.strtoupper($locale_region);
  7751. }
  7752. }
  7753. } else {
  7754. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  7755. }
  7756. return null;
  7757. }
  7758. /**
  7759. * Complete or removed entries into a head array (used to build tabs).
  7760. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  7761. * Or by change using hook completeTabsHead
  7762. *
  7763. * @param Conf $conf Object conf
  7764. * @param Translate $langs Object langs
  7765. * @param object|null $object Object object
  7766. * @param array $head Object head
  7767. * @param int $h New position to fill
  7768. * @param string $type Value for object where objectvalue can be
  7769. * 'thirdparty' to add a tab in third party view
  7770. * 'intervention' to add a tab in intervention view
  7771. * 'supplier_order' to add a tab in supplier order view
  7772. * 'supplier_invoice' to add a tab in supplier invoice view
  7773. * 'invoice' to add a tab in customer invoice view
  7774. * 'order' to add a tab in customer order view
  7775. * 'contract' to add a tabl in contract view
  7776. * 'product' to add a tab in product view
  7777. * 'propal' to add a tab in propal view
  7778. * 'user' to add a tab in user view
  7779. * 'group' to add a tab in group view
  7780. * 'member' to add a tab in fundation member view
  7781. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  7782. * 'ecm' to add a tab for another ecm view
  7783. * 'stock' to add a tab for warehouse view
  7784. * @param string $mode 'add' to complete head, 'remove' to remove entries
  7785. * @return void
  7786. */
  7787. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  7788. {
  7789. global $hookmanager;
  7790. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  7791. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  7792. $values = explode(':', $value);
  7793. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  7794. if (count($values) == 6) { // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  7795. if ($values[0] != $type) {
  7796. continue;
  7797. }
  7798. if (verifCond($values[4])) {
  7799. if ($values[3]) {
  7800. $langs->load($values[3]);
  7801. }
  7802. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7803. $substitutionarray = array();
  7804. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7805. $label = make_substitutions($reg[1], $substitutionarray);
  7806. } else {
  7807. $label = $langs->trans($values[2]);
  7808. }
  7809. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  7810. $head[$h][1] = $label;
  7811. $head[$h][2] = str_replace('+', '', $values[1]);
  7812. $h++;
  7813. }
  7814. } elseif (count($values) == 5) { // deprecated
  7815. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  7816. if ($values[0] != $type) {
  7817. continue;
  7818. }
  7819. if ($values[3]) {
  7820. $langs->load($values[3]);
  7821. }
  7822. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7823. $substitutionarray = array();
  7824. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7825. $label = make_substitutions($reg[1], $substitutionarray);
  7826. } else {
  7827. $label = $langs->trans($values[2]);
  7828. }
  7829. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  7830. $head[$h][1] = $label;
  7831. $head[$h][2] = str_replace('+', '', $values[1]);
  7832. $h++;
  7833. }
  7834. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  7835. if ($values[0] != $type) {
  7836. continue;
  7837. }
  7838. $tabname = str_replace('-', '', $values[1]);
  7839. foreach ($head as $key => $val) {
  7840. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  7841. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  7842. if ($head[$key][2] == $tabname && $condition) {
  7843. unset($head[$key]);
  7844. break;
  7845. }
  7846. }
  7847. }
  7848. }
  7849. }
  7850. // No need to make a return $head. Var is modified as a reference
  7851. if (!empty($hookmanager)) {
  7852. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  7853. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  7854. if ($reshook > 0) { // Hook ask to replace completely the array
  7855. $head = $hookmanager->resArray;
  7856. } else { // Hook
  7857. $head = array_merge($head, $hookmanager->resArray);
  7858. }
  7859. $h = count($head);
  7860. }
  7861. }
  7862. /**
  7863. * Print common footer :
  7864. * conf->global->MAIN_HTML_FOOTER
  7865. * js for switch of menu hider
  7866. * js for conf->global->MAIN_GOOGLE_AN_ID
  7867. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  7868. * js for conf->logbuffer
  7869. *
  7870. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  7871. * @return void
  7872. */
  7873. function printCommonFooter($zone = 'private')
  7874. {
  7875. global $conf, $hookmanager, $user, $debugbar;
  7876. global $action;
  7877. global $micro_start_time;
  7878. if ($zone == 'private') {
  7879. print "\n".'<!-- Common footer for private page -->'."\n";
  7880. } else {
  7881. print "\n".'<!-- Common footer for public page -->'."\n";
  7882. }
  7883. // A div to store page_y POST parameter so we can read it using javascript
  7884. print "\n<!-- A div to store page_y POST parameter -->\n";
  7885. print '<div id="page_y" style="display: none;">'.(empty($_POST['page_y']) ? '' : $_POST['page_y']).'</div>'."\n";
  7886. $parameters = array();
  7887. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  7888. if (empty($reshook)) {
  7889. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  7890. print $conf->global->MAIN_HTML_FOOTER."\n";
  7891. }
  7892. print "\n";
  7893. if (!empty($conf->use_javascript_ajax)) {
  7894. print '<script>'."\n";
  7895. print 'jQuery(document).ready(function() {'."\n";
  7896. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  7897. print "\n";
  7898. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  7899. print 'jQuery("li.menuhider").click(function(event) {';
  7900. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  7901. print ' console.log("We click on .menuhider");'."\n";
  7902. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  7903. print '});'."\n";
  7904. }
  7905. // Management of focus and mandatory for fields
  7906. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  7907. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  7908. $relativepathstring = $_SERVER["PHP_SELF"];
  7909. // Clean $relativepathstring
  7910. if (constant('DOL_URL_ROOT')) {
  7911. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  7912. }
  7913. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  7914. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  7915. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  7916. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  7917. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  7918. $qualified = 0;
  7919. if ($defkey != '_noquery_') {
  7920. $tmpqueryarraytohave = explode('&', $defkey);
  7921. $foundintru = 0;
  7922. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7923. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7924. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7925. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7926. $foundintru = 1;
  7927. }
  7928. }
  7929. if (!$foundintru) {
  7930. $qualified = 1;
  7931. }
  7932. //var_dump($defkey.'-'.$qualified);
  7933. } else {
  7934. $qualified = 1;
  7935. }
  7936. if ($qualified) {
  7937. foreach ($defval as $paramkey => $paramval) {
  7938. // Set focus on field
  7939. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  7940. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  7941. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  7942. }
  7943. }
  7944. }
  7945. }
  7946. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  7947. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  7948. $qualified = 0;
  7949. if ($defkey != '_noquery_') {
  7950. $tmpqueryarraytohave = explode('&', $defkey);
  7951. $foundintru = 0;
  7952. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7953. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7954. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7955. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7956. $foundintru = 1;
  7957. }
  7958. }
  7959. if (!$foundintru) {
  7960. $qualified = 1;
  7961. }
  7962. //var_dump($defkey.'-'.$qualified);
  7963. } else {
  7964. $qualified = 1;
  7965. }
  7966. if ($qualified) {
  7967. foreach ($defval as $paramkey => $paramval) {
  7968. // Add property 'required' on input
  7969. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7970. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7971. print '// required on a select works only if key is "", so we add the required attributes but also we reset the key -1 or 0 to an empty string'."\n";
  7972. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7973. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  7974. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  7975. }
  7976. }
  7977. }
  7978. }
  7979. }
  7980. print '});'."\n";
  7981. // End of tuning
  7982. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  7983. print "\n";
  7984. print "/* JS CODE TO ENABLE to add memory info */\n";
  7985. print 'window.console && console.log("';
  7986. if (!empty($conf->global->MEMCACHED_SERVER)) {
  7987. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  7988. }
  7989. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  7990. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  7991. $micro_end_time = microtime(true);
  7992. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  7993. }
  7994. if (function_exists("memory_get_usage")) {
  7995. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  7996. }
  7997. if (function_exists("memory_get_peak_usage")) {
  7998. print ' - Real mem peak: '.memory_get_peak_usage(true);
  7999. }
  8000. if (function_exists("zend_loader_file_encoded")) {
  8001. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8002. }
  8003. print '");'."\n";
  8004. }
  8005. print "\n".'</script>'."\n";
  8006. // Google Analytics
  8007. // TODO Add a hook here
  8008. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8009. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8010. foreach ($tmptagarray as $tmptag) {
  8011. print "\n";
  8012. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8013. print "
  8014. <!-- Global site tag (gtag.js) - Google Analytics -->
  8015. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  8016. <script>
  8017. window.dataLayer = window.dataLayer || [];
  8018. function gtag(){dataLayer.push(arguments);}
  8019. gtag('js', new Date());
  8020. gtag('config', '".trim($tmptag)."');
  8021. </script>";
  8022. print "\n";
  8023. }
  8024. }
  8025. }
  8026. // Add Xdebug coverage of code
  8027. if (defined('XDEBUGCOVERAGE')) {
  8028. print_r(xdebug_get_code_coverage());
  8029. }
  8030. // Add DebugBar data
  8031. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8032. $debugbar['time']->stopMeasure('pageaftermaster');
  8033. print '<!-- Output debugbar data -->'."\n";
  8034. $renderer = $debugbar->getRenderer();
  8035. print $debugbar->getRenderer()->render();
  8036. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8037. print "\n";
  8038. print "<!-- Start of log output\n";
  8039. //print '<div class="hidden">'."\n";
  8040. foreach ($conf->logbuffer as $logline) {
  8041. print $logline."<br>\n";
  8042. }
  8043. //print '</div>'."\n";
  8044. print "End of log output -->\n";
  8045. }
  8046. }
  8047. }
  8048. /**
  8049. * Split a string with 2 keys into key array.
  8050. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8051. *
  8052. * @param string $string String to explode
  8053. * @param string $delimiter Delimiter between each couple of data
  8054. * @param string $kv Delimiter between key and value
  8055. * @return array Array of data exploded
  8056. */
  8057. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8058. {
  8059. if ($a = explode($delimiter, $string)) {
  8060. $ka = array();
  8061. foreach ($a as $s) { // each part
  8062. if ($s) {
  8063. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8064. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8065. } else { // key delimiter not found
  8066. $ka[] = trim($s);
  8067. }
  8068. }
  8069. }
  8070. return $ka;
  8071. }
  8072. return array();
  8073. }
  8074. /**
  8075. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  8076. *
  8077. * @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.
  8078. * @return void
  8079. */
  8080. function dol_set_focus($selector)
  8081. {
  8082. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8083. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8084. }
  8085. /**
  8086. * Return getmypid() or random PID when function is disabled
  8087. * Some web hosts disable this php function for security reasons
  8088. * and sometimes we can't redeclare function
  8089. *
  8090. * @return int
  8091. */
  8092. function dol_getmypid()
  8093. {
  8094. if (!function_exists('getmypid')) {
  8095. return mt_rand(1, 32768);
  8096. } else {
  8097. return getmypid();
  8098. }
  8099. }
  8100. /**
  8101. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8102. *
  8103. * @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")
  8104. * @param string $value The value to look for.
  8105. * If param $mode is 0, can contains several keywords separated with a space or |
  8106. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8107. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8108. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8109. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8110. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8111. * @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')
  8112. * 3=value is list of string separated with comma (Example 'text 1,text 2'), 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
  8113. * @param integer $nofirstand 1=Do not output the first 'AND'
  8114. * @return string $res The statement to append to the SQL query
  8115. */
  8116. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8117. {
  8118. global $db, $langs;
  8119. $value = trim($value);
  8120. if ($mode == 0) {
  8121. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8122. }
  8123. if ($mode == 1) {
  8124. $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
  8125. }
  8126. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8127. $crits = explode(' ', $value);
  8128. $res = '';
  8129. if (!is_array($fields)) {
  8130. $fields = array($fields);
  8131. }
  8132. $j = 0;
  8133. foreach ($crits as $crit) {
  8134. $crit = trim($crit);
  8135. $i = 0;
  8136. $i2 = 0;
  8137. $newres = '';
  8138. foreach ($fields as $field) {
  8139. if ($mode == 1) {
  8140. $operator = '=';
  8141. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8142. $reg = array();
  8143. preg_match('/([<>=]+)/', $crit, $reg);
  8144. if ($reg[1]) {
  8145. $operator = $reg[1];
  8146. }
  8147. if ($newcrit != '') {
  8148. $numnewcrit = price2num($newcrit);
  8149. if (is_numeric($numnewcrit)) {
  8150. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  8151. } else {
  8152. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8153. }
  8154. $i2++; // a criteria was added to string
  8155. }
  8156. } elseif ($mode == 2 || $mode == -2) {
  8157. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8158. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8159. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8160. if ($mode == -2) {
  8161. $newres .= ' OR '.$field.' IS NULL';
  8162. }
  8163. $i2++; // a criteria was added to string
  8164. } elseif ($mode == 3 || $mode == -3) {
  8165. $tmparray = explode(',', $crit);
  8166. if (count($tmparray)) {
  8167. $listofcodes = '';
  8168. foreach ($tmparray as $val) {
  8169. $val = trim($val);
  8170. if ($val) {
  8171. $listofcodes .= ($listofcodes ? ',' : '');
  8172. $listofcodes .= "'".$db->escape($val)."'";
  8173. }
  8174. }
  8175. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8176. $i2++; // a criteria was added to string
  8177. }
  8178. if ($mode == -3) {
  8179. $newres .= ' OR '.$field.' IS NULL';
  8180. }
  8181. } elseif ($mode == 4) {
  8182. $tmparray = explode(',', $crit);
  8183. if (count($tmparray)) {
  8184. $listofcodes = '';
  8185. foreach ($tmparray as $val) {
  8186. $val = trim($val);
  8187. if ($val) {
  8188. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8189. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8190. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8191. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8192. $newres .= ')';
  8193. $i2++;
  8194. }
  8195. }
  8196. }
  8197. } else // $mode=0
  8198. {
  8199. $tmpcrits = explode('|', $crit);
  8200. $i3 = 0;
  8201. foreach ($tmpcrits as $tmpcrit) {
  8202. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8203. continue;
  8204. }
  8205. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8206. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8207. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? ((float) trim($tmpcrit)) : '0');
  8208. } else {
  8209. $newres .= $field." LIKE '";
  8210. $tmpcrit = trim($tmpcrit);
  8211. $tmpcrit2 = $tmpcrit;
  8212. $tmpbefore = '%';
  8213. $tmpafter = '%';
  8214. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8215. $tmpbefore = '';
  8216. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8217. }
  8218. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8219. $tmpafter = '';
  8220. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8221. }
  8222. $newres .= $tmpbefore;
  8223. $newres .= $db->escape($tmpcrit2);
  8224. $newres .= $tmpafter;
  8225. $newres .= "'";
  8226. if ($tmpcrit2 == '') {
  8227. $newres .= " OR ".$field." IS NULL";
  8228. }
  8229. }
  8230. $i3++;
  8231. }
  8232. $i2++; // a criteria was added to string
  8233. }
  8234. $i++;
  8235. }
  8236. if ($newres) {
  8237. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8238. }
  8239. $j++;
  8240. }
  8241. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8242. //print 'xx'.$res.'yy';
  8243. return $res;
  8244. }
  8245. /**
  8246. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8247. *
  8248. * @param Object $object Object
  8249. * @return string Url string
  8250. */
  8251. function showDirectDownloadLink($object)
  8252. {
  8253. global $conf, $langs;
  8254. $out = '';
  8255. $url = $object->getLastMainDocLink($object->element);
  8256. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8257. if ($url) {
  8258. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8259. $out .= ajax_autoselect("directdownloadlink", 0);
  8260. } else {
  8261. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8262. }
  8263. return $out;
  8264. }
  8265. /**
  8266. * Return the filename of file to get the thumbs
  8267. *
  8268. * @param string $file Original filename (full or relative path)
  8269. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8270. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8271. * @return string New file name (full or relative path, including the thumbs/)
  8272. */
  8273. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8274. {
  8275. $dirName = dirname($file);
  8276. if ($dirName == '.') {
  8277. $dirName = '';
  8278. }
  8279. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8280. $fileName = basename($fileName);
  8281. if (empty($extImgTarget)) {
  8282. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8283. }
  8284. if (empty($extImgTarget)) {
  8285. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8286. }
  8287. if (empty($extImgTarget)) {
  8288. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8289. }
  8290. if (empty($extImgTarget)) {
  8291. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8292. }
  8293. if (empty($extImgTarget)) {
  8294. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8295. }
  8296. if (empty($extImgTarget)) {
  8297. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8298. }
  8299. if (!$extImgTarget) {
  8300. return $file;
  8301. }
  8302. $subdir = '';
  8303. if ($extName) {
  8304. $subdir = 'thumbs/';
  8305. }
  8306. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8307. }
  8308. /**
  8309. * Return URL we can use for advanced preview links
  8310. *
  8311. * @param string $modulepart propal, facture, facture_fourn, ...
  8312. * @param string $relativepath Relative path of docs.
  8313. * @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)
  8314. * @param string $param More param on http links
  8315. * @return string|array Output string with href link or array with all components of link
  8316. */
  8317. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8318. {
  8319. global $conf, $langs;
  8320. if (empty($conf->use_javascript_ajax)) {
  8321. return '';
  8322. }
  8323. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8324. if ($alldata == 1) {
  8325. if ($isAllowedForPreview) {
  8326. 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));
  8327. } else {
  8328. return array();
  8329. }
  8330. }
  8331. // old behavior, return a string
  8332. if ($isAllowedForPreview) {
  8333. 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')).'\')';
  8334. } else {
  8335. return '';
  8336. }
  8337. }
  8338. /**
  8339. * Make content of an input box selected when we click into input field.
  8340. *
  8341. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8342. * @param string $addlink Add a 'link to' after
  8343. * @param string $textonlink Text to show on link or 'image'
  8344. * @return string
  8345. */
  8346. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  8347. {
  8348. global $langs;
  8349. $out = '<script>
  8350. jQuery(document).ready(function () {
  8351. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8352. });
  8353. </script>';
  8354. if ($addlink) {
  8355. if ($textonlink === 'image') {
  8356. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  8357. } else {
  8358. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  8359. }
  8360. }
  8361. return $out;
  8362. }
  8363. /**
  8364. * Return if a file is qualified for preview
  8365. *
  8366. * @param string $file Filename we looking for information
  8367. * @return int 1 If allowed, 0 otherwise
  8368. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8369. */
  8370. function dolIsAllowedForPreview($file)
  8371. {
  8372. global $conf;
  8373. // Check .noexe extension in filename
  8374. if (preg_match('/\.noexe$/i', $file)) {
  8375. return 0;
  8376. }
  8377. // Check mime types
  8378. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8379. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8380. $mime_preview[] = 'svg+xml';
  8381. }
  8382. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8383. //$mime_preview[]='archive';
  8384. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8385. if ($num_mime !== false) {
  8386. return 1;
  8387. }
  8388. // By default, not allowed for preview
  8389. return 0;
  8390. }
  8391. /**
  8392. * Return mime type of a file
  8393. *
  8394. * @param string $file Filename we looking for MIME type
  8395. * @param string $default Default mime type if extension not found in known list
  8396. * @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
  8397. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8398. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8399. */
  8400. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8401. {
  8402. $mime = $default;
  8403. $imgmime = 'other.png';
  8404. $famime = 'file-o';
  8405. $srclang = '';
  8406. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8407. // Plain text files
  8408. if (preg_match('/\.txt$/i', $tmpfile)) {
  8409. $mime = 'text/plain';
  8410. $imgmime = 'text.png';
  8411. $famime = 'file-text-o';
  8412. }
  8413. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8414. $mime = 'text/richtext';
  8415. $imgmime = 'text.png';
  8416. $famime = 'file-text-o';
  8417. }
  8418. if (preg_match('/\.csv$/i', $tmpfile)) {
  8419. $mime = 'text/csv';
  8420. $imgmime = 'text.png';
  8421. $famime = 'file-text-o';
  8422. }
  8423. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8424. $mime = 'text/tab-separated-values';
  8425. $imgmime = 'text.png';
  8426. $famime = 'file-text-o';
  8427. }
  8428. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8429. $mime = 'text/plain';
  8430. $imgmime = 'text.png';
  8431. $famime = 'file-text-o';
  8432. }
  8433. if (preg_match('/\.ini$/i', $tmpfile)) {
  8434. $mime = 'text/plain';
  8435. $imgmime = 'text.png';
  8436. $srclang = 'ini';
  8437. $famime = 'file-text-o';
  8438. }
  8439. if (preg_match('/\.md$/i', $tmpfile)) {
  8440. $mime = 'text/plain';
  8441. $imgmime = 'text.png';
  8442. $srclang = 'md';
  8443. $famime = 'file-text-o';
  8444. }
  8445. if (preg_match('/\.css$/i', $tmpfile)) {
  8446. $mime = 'text/css';
  8447. $imgmime = 'css.png';
  8448. $srclang = 'css';
  8449. $famime = 'file-text-o';
  8450. }
  8451. if (preg_match('/\.lang$/i', $tmpfile)) {
  8452. $mime = 'text/plain';
  8453. $imgmime = 'text.png';
  8454. $srclang = 'lang';
  8455. $famime = 'file-text-o';
  8456. }
  8457. // Certificate files
  8458. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8459. $mime = 'text/plain';
  8460. $imgmime = 'text.png';
  8461. $famime = 'file-text-o';
  8462. }
  8463. // XML based (HTML/XML/XAML)
  8464. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8465. $mime = 'text/html';
  8466. $imgmime = 'html.png';
  8467. $srclang = 'html';
  8468. $famime = 'file-text-o';
  8469. }
  8470. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8471. $mime = 'text/xml';
  8472. $imgmime = 'other.png';
  8473. $srclang = 'xml';
  8474. $famime = 'file-text-o';
  8475. }
  8476. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8477. $mime = 'text/xml';
  8478. $imgmime = 'other.png';
  8479. $srclang = 'xaml';
  8480. $famime = 'file-text-o';
  8481. }
  8482. // Languages
  8483. if (preg_match('/\.bas$/i', $tmpfile)) {
  8484. $mime = 'text/plain';
  8485. $imgmime = 'text.png';
  8486. $srclang = 'bas';
  8487. $famime = 'file-code-o';
  8488. }
  8489. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8490. $mime = 'text/plain';
  8491. $imgmime = 'text.png';
  8492. $srclang = 'c';
  8493. $famime = 'file-code-o';
  8494. }
  8495. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8496. $mime = 'text/plain';
  8497. $imgmime = 'text.png';
  8498. $srclang = 'cpp';
  8499. $famime = 'file-code-o';
  8500. }
  8501. if (preg_match('/\.cs$/i', $tmpfile)) {
  8502. $mime = 'text/plain';
  8503. $imgmime = 'text.png';
  8504. $srclang = 'cs';
  8505. $famime = 'file-code-o';
  8506. }
  8507. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8508. $mime = 'text/plain';
  8509. $imgmime = 'text.png';
  8510. $srclang = 'h';
  8511. $famime = 'file-code-o';
  8512. }
  8513. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8514. $mime = 'text/plain';
  8515. $imgmime = 'text.png';
  8516. $srclang = 'java';
  8517. $famime = 'file-code-o';
  8518. }
  8519. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8520. $mime = 'text/plain';
  8521. $imgmime = 'php.png';
  8522. $srclang = 'php';
  8523. $famime = 'file-code-o';
  8524. }
  8525. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8526. $mime = 'text/plain';
  8527. $imgmime = 'php.png';
  8528. $srclang = 'php';
  8529. $famime = 'file-code-o';
  8530. }
  8531. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8532. $mime = 'text/plain';
  8533. $imgmime = 'pl.png';
  8534. $srclang = 'perl';
  8535. $famime = 'file-code-o';
  8536. }
  8537. if (preg_match('/\.sql$/i', $tmpfile)) {
  8538. $mime = 'text/plain';
  8539. $imgmime = 'text.png';
  8540. $srclang = 'sql';
  8541. $famime = 'file-code-o';
  8542. }
  8543. if (preg_match('/\.js$/i', $tmpfile)) {
  8544. $mime = 'text/x-javascript';
  8545. $imgmime = 'jscript.png';
  8546. $srclang = 'js';
  8547. $famime = 'file-code-o';
  8548. }
  8549. // Open office
  8550. if (preg_match('/\.odp$/i', $tmpfile)) {
  8551. $mime = 'application/vnd.oasis.opendocument.presentation';
  8552. $imgmime = 'ooffice.png';
  8553. $famime = 'file-powerpoint-o';
  8554. }
  8555. if (preg_match('/\.ods$/i', $tmpfile)) {
  8556. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8557. $imgmime = 'ooffice.png';
  8558. $famime = 'file-excel-o';
  8559. }
  8560. if (preg_match('/\.odt$/i', $tmpfile)) {
  8561. $mime = 'application/vnd.oasis.opendocument.text';
  8562. $imgmime = 'ooffice.png';
  8563. $famime = 'file-word-o';
  8564. }
  8565. // MS Office
  8566. if (preg_match('/\.mdb$/i', $tmpfile)) {
  8567. $mime = 'application/msaccess';
  8568. $imgmime = 'mdb.png';
  8569. $famime = 'file-o';
  8570. }
  8571. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  8572. $mime = 'application/msword';
  8573. $imgmime = 'doc.png';
  8574. $famime = 'file-word-o';
  8575. }
  8576. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  8577. $mime = 'application/msword';
  8578. $imgmime = 'doc.png';
  8579. $famime = 'file-word-o';
  8580. }
  8581. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  8582. $mime = 'application/vnd.ms-excel';
  8583. $imgmime = 'xls.png';
  8584. $famime = 'file-excel-o';
  8585. }
  8586. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  8587. $mime = 'application/vnd.ms-excel';
  8588. $imgmime = 'xls.png';
  8589. $famime = 'file-excel-o';
  8590. }
  8591. if (preg_match('/\.xls$/i', $tmpfile)) {
  8592. $mime = 'application/vnd.ms-excel';
  8593. $imgmime = 'xls.png';
  8594. $famime = 'file-excel-o';
  8595. }
  8596. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  8597. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  8598. $imgmime = 'xls.png';
  8599. $famime = 'file-excel-o';
  8600. }
  8601. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  8602. $mime = 'application/vnd.ms-powerpoint';
  8603. $imgmime = 'ppt.png';
  8604. $famime = 'file-powerpoint-o';
  8605. }
  8606. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  8607. $mime = 'application/x-mspowerpoint';
  8608. $imgmime = 'ppt.png';
  8609. $famime = 'file-powerpoint-o';
  8610. }
  8611. // Other
  8612. if (preg_match('/\.pdf$/i', $tmpfile)) {
  8613. $mime = 'application/pdf';
  8614. $imgmime = 'pdf.png';
  8615. $famime = 'file-pdf-o';
  8616. }
  8617. // Scripts
  8618. if (preg_match('/\.bat$/i', $tmpfile)) {
  8619. $mime = 'text/x-bat';
  8620. $imgmime = 'script.png';
  8621. $srclang = 'dos';
  8622. $famime = 'file-code-o';
  8623. }
  8624. if (preg_match('/\.sh$/i', $tmpfile)) {
  8625. $mime = 'text/x-sh';
  8626. $imgmime = 'script.png';
  8627. $srclang = 'bash';
  8628. $famime = 'file-code-o';
  8629. }
  8630. if (preg_match('/\.ksh$/i', $tmpfile)) {
  8631. $mime = 'text/x-ksh';
  8632. $imgmime = 'script.png';
  8633. $srclang = 'bash';
  8634. $famime = 'file-code-o';
  8635. }
  8636. if (preg_match('/\.bash$/i', $tmpfile)) {
  8637. $mime = 'text/x-bash';
  8638. $imgmime = 'script.png';
  8639. $srclang = 'bash';
  8640. $famime = 'file-code-o';
  8641. }
  8642. // Images
  8643. if (preg_match('/\.ico$/i', $tmpfile)) {
  8644. $mime = 'image/x-icon';
  8645. $imgmime = 'image.png';
  8646. $famime = 'file-image-o';
  8647. }
  8648. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  8649. $mime = 'image/jpeg';
  8650. $imgmime = 'image.png';
  8651. $famime = 'file-image-o';
  8652. }
  8653. if (preg_match('/\.png$/i', $tmpfile)) {
  8654. $mime = 'image/png';
  8655. $imgmime = 'image.png';
  8656. $famime = 'file-image-o';
  8657. }
  8658. if (preg_match('/\.gif$/i', $tmpfile)) {
  8659. $mime = 'image/gif';
  8660. $imgmime = 'image.png';
  8661. $famime = 'file-image-o';
  8662. }
  8663. if (preg_match('/\.bmp$/i', $tmpfile)) {
  8664. $mime = 'image/bmp';
  8665. $imgmime = 'image.png';
  8666. $famime = 'file-image-o';
  8667. }
  8668. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  8669. $mime = 'image/tiff';
  8670. $imgmime = 'image.png';
  8671. $famime = 'file-image-o';
  8672. }
  8673. if (preg_match('/\.svg$/i', $tmpfile)) {
  8674. $mime = 'image/svg+xml';
  8675. $imgmime = 'image.png';
  8676. $famime = 'file-image-o';
  8677. }
  8678. if (preg_match('/\.webp$/i', $tmpfile)) {
  8679. $mime = 'image/webp';
  8680. $imgmime = 'image.png';
  8681. $famime = 'file-image-o';
  8682. }
  8683. // Calendar
  8684. if (preg_match('/\.vcs$/i', $tmpfile)) {
  8685. $mime = 'text/calendar';
  8686. $imgmime = 'other.png';
  8687. $famime = 'file-text-o';
  8688. }
  8689. if (preg_match('/\.ics$/i', $tmpfile)) {
  8690. $mime = 'text/calendar';
  8691. $imgmime = 'other.png';
  8692. $famime = 'file-text-o';
  8693. }
  8694. // Other
  8695. if (preg_match('/\.torrent$/i', $tmpfile)) {
  8696. $mime = 'application/x-bittorrent';
  8697. $imgmime = 'other.png';
  8698. $famime = 'file-o';
  8699. }
  8700. // Audio
  8701. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  8702. $mime = 'audio';
  8703. $imgmime = 'audio.png';
  8704. $famime = 'file-audio-o';
  8705. }
  8706. // Video
  8707. if (preg_match('/\.mp4$/i', $tmpfile)) {
  8708. $mime = 'video/mp4';
  8709. $imgmime = 'video.png';
  8710. $famime = 'file-video-o';
  8711. }
  8712. if (preg_match('/\.ogv$/i', $tmpfile)) {
  8713. $mime = 'video/ogg';
  8714. $imgmime = 'video.png';
  8715. $famime = 'file-video-o';
  8716. }
  8717. if (preg_match('/\.webm$/i', $tmpfile)) {
  8718. $mime = 'video/webm';
  8719. $imgmime = 'video.png';
  8720. $famime = 'file-video-o';
  8721. }
  8722. if (preg_match('/\.avi$/i', $tmpfile)) {
  8723. $mime = 'video/x-msvideo';
  8724. $imgmime = 'video.png';
  8725. $famime = 'file-video-o';
  8726. }
  8727. if (preg_match('/\.divx$/i', $tmpfile)) {
  8728. $mime = 'video/divx';
  8729. $imgmime = 'video.png';
  8730. $famime = 'file-video-o';
  8731. }
  8732. if (preg_match('/\.xvid$/i', $tmpfile)) {
  8733. $mime = 'video/xvid';
  8734. $imgmime = 'video.png';
  8735. $famime = 'file-video-o';
  8736. }
  8737. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  8738. $mime = 'video';
  8739. $imgmime = 'video.png';
  8740. $famime = 'file-video-o';
  8741. }
  8742. // Archive
  8743. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  8744. $mime = 'archive';
  8745. $imgmime = 'archive.png';
  8746. $famime = 'file-archive-o';
  8747. } // application/xxx where zzz is zip, ...
  8748. // Exe
  8749. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  8750. $mime = 'application/octet-stream';
  8751. $imgmime = 'other.png';
  8752. $famime = 'file-o';
  8753. }
  8754. // Lib
  8755. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  8756. $mime = 'library';
  8757. $imgmime = 'library.png';
  8758. $famime = 'file-o';
  8759. }
  8760. // Err
  8761. if (preg_match('/\.err$/i', $tmpfile)) {
  8762. $mime = 'error';
  8763. $imgmime = 'error.png';
  8764. $famime = 'file-text-o';
  8765. }
  8766. // Return string
  8767. if ($mode == 1) {
  8768. $tmp = explode('/', $mime);
  8769. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  8770. }
  8771. if ($mode == 2) {
  8772. return $imgmime;
  8773. }
  8774. if ($mode == 3) {
  8775. return $srclang;
  8776. }
  8777. if ($mode == 4) {
  8778. return $famime;
  8779. }
  8780. return $mime;
  8781. }
  8782. /**
  8783. * Return the value of a filed into a dictionary for the record $id.
  8784. * This also set all the values into a cache for a next search.
  8785. *
  8786. * @param string $tablename Name of dictionary
  8787. * @param string $field The name of field where to find the value to return
  8788. * @param int $id Id of line record
  8789. * @param bool $checkentity Add filter on entity
  8790. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  8791. * @return string The value of field $field. This also set $dictvalues cache.
  8792. */
  8793. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  8794. {
  8795. global $conf, $db;
  8796. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  8797. if (is_null($dictvalues)) {
  8798. $dictvalues = array();
  8799. $sql = "SELECT * FROM ".$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  8800. if ($checkentity) {
  8801. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  8802. }
  8803. $resql = $db->query($sql);
  8804. if ($resql) {
  8805. while ($obj = $db->fetch_object($resql)) {
  8806. $dictvalues[$obj->{$rowidfield}] = $obj;
  8807. }
  8808. } else {
  8809. dol_print_error($db);
  8810. }
  8811. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  8812. }
  8813. if (!empty($dictvalues[$id])) {
  8814. // Found
  8815. return $dictvalues[$id]->{$field};
  8816. } else {
  8817. // Not found
  8818. return '';
  8819. }
  8820. }
  8821. /**
  8822. * Return true if the color is light
  8823. *
  8824. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  8825. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  8826. */
  8827. function colorIsLight($stringcolor)
  8828. {
  8829. $stringcolor = str_replace('#', '', $stringcolor);
  8830. $res = -1;
  8831. if (!empty($stringcolor)) {
  8832. $res = 0;
  8833. $tmp = explode(',', $stringcolor);
  8834. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  8835. $r = $tmp[0];
  8836. $g = $tmp[1];
  8837. $b = $tmp[2];
  8838. } else {
  8839. $hexr = $stringcolor[0].$stringcolor[1];
  8840. $hexg = $stringcolor[2].$stringcolor[3];
  8841. $hexb = $stringcolor[4].$stringcolor[5];
  8842. $r = hexdec($hexr);
  8843. $g = hexdec($hexg);
  8844. $b = hexdec($hexb);
  8845. }
  8846. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  8847. if ($bright > 0.6) {
  8848. $res = 1;
  8849. }
  8850. }
  8851. return $res;
  8852. }
  8853. /**
  8854. * Function to test if an entry is enabled or not
  8855. *
  8856. * @param string $type_user 0=We test for internal user, 1=We test for external user
  8857. * @param array $menuentry Array for feature entry to test
  8858. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  8859. * @return int 0=Hide, 1=Show, 2=Show gray
  8860. */
  8861. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  8862. {
  8863. global $conf;
  8864. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  8865. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  8866. if (empty($menuentry['enabled'])) {
  8867. return 0; // Entry disabled by condition
  8868. }
  8869. if ($type_user && $menuentry['module']) {
  8870. $tmploops = explode('|', $menuentry['module']);
  8871. $found = 0;
  8872. foreach ($tmploops as $tmploop) {
  8873. if (in_array($tmploop, $listofmodulesforexternal)) {
  8874. $found++;
  8875. break;
  8876. }
  8877. }
  8878. if (!$found) {
  8879. return 0; // Entry is for menus all excluded to external users
  8880. }
  8881. }
  8882. if (!$menuentry['perms'] && $type_user) {
  8883. return 0; // No permissions and user is external
  8884. }
  8885. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  8886. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  8887. }
  8888. if (!$menuentry['perms']) {
  8889. return 2; // No permissions and user is external
  8890. }
  8891. return 1;
  8892. }
  8893. /**
  8894. * Round to next multiple.
  8895. *
  8896. * @param double $n Number to round up
  8897. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  8898. * @return integer Value rounded.
  8899. */
  8900. function roundUpToNextMultiple($n, $x = 5)
  8901. {
  8902. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  8903. }
  8904. /**
  8905. * Function dolGetBadge
  8906. *
  8907. * @param string $label label of badge no html : use in alt attribute for accessibility
  8908. * @param string $html optional : label of badge with html
  8909. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  8910. * @param string $mode default '' , 'pill', 'dot'
  8911. * @param string $url the url for link
  8912. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  8913. * @return string Html badge
  8914. */
  8915. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  8916. {
  8917. $attr = array(
  8918. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  8919. );
  8920. if (empty($html)) {
  8921. $html = $label;
  8922. }
  8923. if (!empty($url)) {
  8924. $attr['href'] = $url;
  8925. }
  8926. if ($mode === 'dot') {
  8927. $attr['class'] .= ' classfortooltip';
  8928. $attr['title'] = $html;
  8929. $attr['aria-label'] = $label;
  8930. $html = '';
  8931. }
  8932. // Override attr
  8933. if (!empty($params['attr']) && is_array($params['attr'])) {
  8934. foreach ($params['attr'] as $key => $value) {
  8935. if ($key == 'class') {
  8936. $attr['class'] .= ' '.$value;
  8937. } elseif ($key == 'classOverride') {
  8938. $attr['class'] = $value;
  8939. } else {
  8940. $attr[$key] = $value;
  8941. }
  8942. }
  8943. }
  8944. // TODO: add hook
  8945. // escape all attribute
  8946. $attr = array_map('dol_escape_htmltag', $attr);
  8947. $TCompiledAttr = array();
  8948. foreach ($attr as $key => $value) {
  8949. $TCompiledAttr[] = $key.'="'.$value.'"';
  8950. }
  8951. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  8952. $tag = !empty($url) ? 'a' : 'span';
  8953. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  8954. }
  8955. /**
  8956. * Output the badge of a status.
  8957. *
  8958. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  8959. * @param string $statusLabelShort Short label of badge no html
  8960. * @param string $html Optional : label of badge with html
  8961. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  8962. * @param int $displayMode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
  8963. * @param string $url The url for link
  8964. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  8965. * @return string Html status string
  8966. */
  8967. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  8968. {
  8969. global $conf;
  8970. $return = '';
  8971. $dolGetBadgeParams = array();
  8972. if (!empty($params['badgeParams'])) {
  8973. $dolGetBadgeParams = $params['badgeParams'];
  8974. }
  8975. // TODO : add a hook
  8976. if ($displayMode == 0) {
  8977. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  8978. } elseif ($displayMode == 1) {
  8979. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  8980. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  8981. // Use status with images (for backward compatibility)
  8982. $return = '';
  8983. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  8984. $htmlLabelShort = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : (!empty($statusLabelShort) ? $statusLabelShort : $statusLabel)).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  8985. // For small screen, we always use the short label instead of long label.
  8986. if (!empty($conf->dol_optimize_smallscreen)) {
  8987. if ($displayMode == 0) {
  8988. $displayMode = 1;
  8989. } elseif ($displayMode == 4) {
  8990. $displayMode = 2;
  8991. } elseif ($displayMode == 6) {
  8992. $displayMode = 5;
  8993. }
  8994. }
  8995. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  8996. $statusImg = array(
  8997. 'status0' => 'statut0',
  8998. 'status1' => 'statut1',
  8999. 'status2' => 'statut2',
  9000. 'status3' => 'statut3',
  9001. 'status4' => 'statut4',
  9002. 'status5' => 'statut5',
  9003. 'status6' => 'statut6',
  9004. 'status7' => 'statut7',
  9005. 'status8' => 'statut8',
  9006. 'status9' => 'statut9'
  9007. );
  9008. if (!empty($statusImg[$statusType])) {
  9009. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  9010. } else {
  9011. $htmlImg = img_picto($statusLabel, $statusType);
  9012. }
  9013. if ($displayMode === 2) {
  9014. $return = $htmlImg.' '.$htmlLabelShort;
  9015. } elseif ($displayMode === 3) {
  9016. $return = $htmlImg;
  9017. } elseif ($displayMode === 4) {
  9018. $return = $htmlImg.' '.$htmlLabel;
  9019. } elseif ($displayMode === 5) {
  9020. $return = $htmlLabelShort.' '.$htmlImg;
  9021. } else { // $displayMode >= 6
  9022. $return = $htmlLabel.' '.$htmlImg;
  9023. }
  9024. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9025. // Use new badge
  9026. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9027. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9028. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9029. if ($displayMode == 3) {
  9030. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9031. } elseif ($displayMode === 5) {
  9032. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9033. } else {
  9034. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9035. }
  9036. }
  9037. return $return;
  9038. }
  9039. /**
  9040. * Function dolGetButtonAction
  9041. *
  9042. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  9043. * @param string $html optional : content with html
  9044. * @param string $actionType default, delete, danger
  9045. * @param string $url the url for link
  9046. * @param string $id attribute id of button
  9047. * @param int $userRight user action right
  9048. * // phpcs:disable
  9049. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  9050. * 'attr' => [ // to add or override button attributes
  9051. * 'xxxxx' => '', // your xxxxx attribute you want
  9052. * 'class' => '', // to add more css class to the button class attribute
  9053. * 'classOverride' => '' // to replace class attribute of the button
  9054. * ],
  9055. * 'confirm' => [
  9056. * 'url' => 'http://', // Overide Url to go when user click on action btn, if empty default url is $url.?confirm=yes, for no js compatibility use $url for fallback confirm.
  9057. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  9058. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  9059. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  9060. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  9061. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  9062. * ],
  9063. * ]
  9064. * // phpcs:enable
  9065. * @return string html button
  9066. */
  9067. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  9068. {
  9069. global $hookmanager, $action, $object, $langs;
  9070. $class = 'butAction';
  9071. if ($actionType == 'danger' || $actionType == 'delete') {
  9072. $class = 'butActionDelete';
  9073. if (strpos($url, 'token=') === false) $url .= '&token='.newToken();
  9074. }
  9075. $attr = array(
  9076. 'class' => $class,
  9077. 'href' => empty($url) ? '' : $url,
  9078. 'title' => $label
  9079. );
  9080. if (empty($html)) {
  9081. $html = $label;
  9082. } else {
  9083. $attr['aria-label'] = $label;
  9084. }
  9085. if (empty($userRight)) {
  9086. $attr['class'] = 'butActionRefused';
  9087. $attr['href'] = '';
  9088. }
  9089. if (!empty($id)) {
  9090. $attr['id'] = $id;
  9091. }
  9092. // Override attr
  9093. if (!empty($params['attr']) && is_array($params['attr'])) {
  9094. foreach ($params['attr'] as $key => $value) {
  9095. if ($key == 'class') {
  9096. $attr['class'] .= ' '.$value;
  9097. } elseif ($key == 'classOverride') {
  9098. $attr['class'] = $value;
  9099. } else {
  9100. $attr[$key] = $value;
  9101. }
  9102. }
  9103. }
  9104. // Js Confirm button
  9105. if ($userRight && !empty($params['confirm'])) {
  9106. if (!is_array($params['confirm'])) {
  9107. $params['confirm'] = array(
  9108. 'url' => $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes'
  9109. );
  9110. }
  9111. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9112. $attr['data-confirm-url'] = $params['confirm']['url'];
  9113. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9114. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9115. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9116. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9117. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9118. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9119. $attr['class'].= ' butActionConfirm';
  9120. }
  9121. if (isset($attr['href']) && empty($attr['href'])) {
  9122. unset($attr['href']);
  9123. }
  9124. // escape all attribute
  9125. $attr = array_map('dol_escape_htmltag', $attr);
  9126. $TCompiledAttr = array();
  9127. foreach ($attr as $key => $value) {
  9128. $TCompiledAttr[] = $key.'="'.$value.'"';
  9129. }
  9130. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9131. $tag = !empty($attr['href']) ? 'a' : 'span';
  9132. $parameters = array(
  9133. 'TCompiledAttr' => $TCompiledAttr,
  9134. 'compiledAttributes' => $compiledAttributes,
  9135. 'attr' => $attr,
  9136. 'tag' => $tag,
  9137. 'label' => $label,
  9138. 'html' => $html,
  9139. 'actionType' => $actionType,
  9140. 'url' => $url,
  9141. 'id' => $id,
  9142. 'userRight' => $userRight,
  9143. 'params' => $params
  9144. );
  9145. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9146. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9147. if (empty($reshook)) {
  9148. return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
  9149. } else {
  9150. return $hookmanager->resPrint;
  9151. }
  9152. }
  9153. /**
  9154. * Add space between dolGetButtonTitle
  9155. *
  9156. * @param string $moreClass more css class label
  9157. * @return string html of title separator
  9158. */
  9159. function dolGetButtonTitleSeparator($moreClass = "")
  9160. {
  9161. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9162. }
  9163. /**
  9164. * get field error icon
  9165. *
  9166. * @param string $fieldValidationErrorMsg message to add in tooltip
  9167. * @return string html output
  9168. */
  9169. function getFieldErrorIcon($fieldValidationErrorMsg)
  9170. {
  9171. $out = '';
  9172. if (!empty($fieldValidationErrorMsg)) {
  9173. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9174. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9175. $out.= '</span>';
  9176. }
  9177. return $out;
  9178. }
  9179. /**
  9180. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9181. *
  9182. * @param string $label label of button
  9183. * @param string $helpText optional : content for help tooltip
  9184. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9185. * @param string $url the url for link
  9186. * @param string $id attribute id of button
  9187. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  9188. * @param array $params various params for future : recommended rather than adding more function arguments
  9189. * @return string html button
  9190. */
  9191. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9192. {
  9193. global $langs, $conf, $user;
  9194. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9195. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9196. return '';
  9197. }
  9198. $class = 'btnTitle';
  9199. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots'))) {
  9200. $class .= ' btnTitlePlus';
  9201. }
  9202. $useclassfortooltip = 1;
  9203. if (!empty($params['morecss'])) {
  9204. $class .= ' '.$params['morecss'];
  9205. }
  9206. $attr = array(
  9207. 'class' => $class,
  9208. 'href' => empty($url) ? '' : $url
  9209. );
  9210. if (!empty($helpText)) {
  9211. $attr['title'] = dol_escape_htmltag($helpText);
  9212. } elseif (empty($attr['title']) && $label) {
  9213. $attr['title'] = $label;
  9214. $useclassfortooltip = 0;
  9215. }
  9216. if ($status == 2) {
  9217. $attr['class'] .= ' btnTitleSelected';
  9218. } elseif ($status <= 0) {
  9219. $attr['class'] .= ' refused';
  9220. $attr['href'] = '';
  9221. if ($status == -1) { // disable
  9222. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9223. } elseif ($status == 0) { // Not enough permissions
  9224. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9225. }
  9226. }
  9227. if (!empty($attr['title']) && $useclassfortooltip) {
  9228. $attr['class'] .= ' classfortooltip';
  9229. }
  9230. if (!empty($id)) {
  9231. $attr['id'] = $id;
  9232. }
  9233. // Override attr
  9234. if (!empty($params['attr']) && is_array($params['attr'])) {
  9235. foreach ($params['attr'] as $key => $value) {
  9236. if ($key == 'class') {
  9237. $attr['class'] .= ' '.$value;
  9238. } elseif ($key == 'classOverride') {
  9239. $attr['class'] = $value;
  9240. } else {
  9241. $attr[$key] = $value;
  9242. }
  9243. }
  9244. }
  9245. if (isset($attr['href']) && empty($attr['href'])) {
  9246. unset($attr['href']);
  9247. }
  9248. // TODO : add a hook
  9249. // escape all attribute
  9250. $attr = array_map('dol_escape_htmltag', $attr);
  9251. $TCompiledAttr = array();
  9252. foreach ($attr as $key => $value) {
  9253. $TCompiledAttr[] = $key.'="'.$value.'"';
  9254. }
  9255. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9256. $tag = (empty($attr['href']) ? 'span' : 'a');
  9257. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9258. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9259. if (!empty($params['forcenohideoftext'])) {
  9260. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9261. }
  9262. $button .= '</'.$tag.'>';
  9263. return $button;
  9264. }
  9265. /**
  9266. * Get an array with properties of an element.
  9267. * Called by fetchObjectByElement.
  9268. *
  9269. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9270. * @return array (module, classpath, element, subelement, classfile, classname)
  9271. */
  9272. function getElementProperties($element_type)
  9273. {
  9274. $regs = array();
  9275. $classfile = $classname = $classpath = '';
  9276. // Parse element/subelement (ex: project_task)
  9277. $module = $element_type;
  9278. $element = $element_type;
  9279. $subelement = $element_type;
  9280. // If we ask an resource form external module (instead of default path)
  9281. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9282. $element = $subelement = $regs[1];
  9283. $module = $regs[2];
  9284. }
  9285. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9286. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9287. $module = $element = $regs[1];
  9288. $subelement = $regs[2];
  9289. }
  9290. // For compat
  9291. if ($element_type == "action") {
  9292. $classpath = 'comm/action/class';
  9293. $subelement = 'Actioncomm';
  9294. $module = 'agenda';
  9295. }
  9296. // To work with non standard path
  9297. if ($element_type == 'facture' || $element_type == 'invoice') {
  9298. $classpath = 'compta/facture/class';
  9299. $module = 'facture';
  9300. $subelement = 'facture';
  9301. }
  9302. if ($element_type == 'commande' || $element_type == 'order') {
  9303. $classpath = 'commande/class';
  9304. $module = 'commande';
  9305. $subelement = 'commande';
  9306. }
  9307. if ($element_type == 'propal') {
  9308. $classpath = 'comm/propal/class';
  9309. }
  9310. if ($element_type == 'supplier_proposal') {
  9311. $classpath = 'supplier_proposal/class';
  9312. }
  9313. if ($element_type == 'shipping') {
  9314. $classpath = 'expedition/class';
  9315. $subelement = 'expedition';
  9316. $module = 'expedition_bon';
  9317. }
  9318. if ($element_type == 'delivery') {
  9319. $classpath = 'delivery/class';
  9320. $subelement = 'delivery';
  9321. $module = 'delivery_note';
  9322. }
  9323. if ($element_type == 'contract') {
  9324. $classpath = 'contrat/class';
  9325. $module = 'contrat';
  9326. $subelement = 'contrat';
  9327. }
  9328. if ($element_type == 'member') {
  9329. $classpath = 'adherents/class';
  9330. $module = 'adherent';
  9331. $subelement = 'adherent';
  9332. }
  9333. if ($element_type == 'cabinetmed_cons') {
  9334. $classpath = 'cabinetmed/class';
  9335. $module = 'cabinetmed';
  9336. $subelement = 'cabinetmedcons';
  9337. }
  9338. if ($element_type == 'fichinter') {
  9339. $classpath = 'fichinter/class';
  9340. $module = 'ficheinter';
  9341. $subelement = 'fichinter';
  9342. }
  9343. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9344. $classpath = 'resource/class';
  9345. $module = 'resource';
  9346. $subelement = 'dolresource';
  9347. }
  9348. if ($element_type == 'propaldet') {
  9349. $classpath = 'comm/propal/class';
  9350. $module = 'propal';
  9351. $subelement = 'propaleligne';
  9352. }
  9353. if ($element_type == 'order_supplier') {
  9354. $classpath = 'fourn/class';
  9355. $module = 'fournisseur';
  9356. $subelement = 'commandefournisseur';
  9357. $classfile = 'fournisseur.commande';
  9358. }
  9359. if ($element_type == 'invoice_supplier') {
  9360. $classpath = 'fourn/class';
  9361. $module = 'fournisseur';
  9362. $subelement = 'facturefournisseur';
  9363. $classfile = 'fournisseur.facture';
  9364. }
  9365. if ($element_type == "service") {
  9366. $classpath = 'product/class';
  9367. $subelement = 'product';
  9368. }
  9369. if (empty($classfile)) {
  9370. $classfile = strtolower($subelement);
  9371. }
  9372. if (empty($classname)) {
  9373. $classname = ucfirst($subelement);
  9374. }
  9375. if (empty($classpath)) {
  9376. $classpath = $module.'/class';
  9377. }
  9378. $element_properties = array(
  9379. 'module' => $module,
  9380. 'classpath' => $classpath,
  9381. 'element' => $element,
  9382. 'subelement' => $subelement,
  9383. 'classfile' => $classfile,
  9384. 'classname' => $classname
  9385. );
  9386. return $element_properties;
  9387. }
  9388. /**
  9389. * Fetch an object from its id and element_type
  9390. * Inclusion of classes is automatic
  9391. *
  9392. * @param int $element_id Element id
  9393. * @param string $element_type Element type
  9394. * @param string $element_ref Element ref (Use this or element_id but not both)
  9395. * @return int|object object || 0 || -1 if error
  9396. */
  9397. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9398. {
  9399. global $conf, $db;
  9400. $element_prop = getElementProperties($element_type);
  9401. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9402. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9403. $objecttmp = new $element_prop['classname']($db);
  9404. $ret = $objecttmp->fetch($element_id, $element_ref);
  9405. if ($ret >= 0) {
  9406. return $objecttmp;
  9407. }
  9408. }
  9409. return 0;
  9410. }
  9411. /**
  9412. * Return if a file can contains executable content
  9413. *
  9414. * @param string $filename File name to test
  9415. * @return boolean True if yes, False if no
  9416. */
  9417. function isAFileWithExecutableContent($filename)
  9418. {
  9419. if (preg_match('/\.(htm|html|js|phar|php|php\d+|phtml|pht|pl|py|cgi|ksh|sh|shtml|bash|bat|cmd|wpk|exe|dmg)$/i', $filename)) {
  9420. return true;
  9421. }
  9422. return false;
  9423. }
  9424. /**
  9425. * Return the value of token currently saved into session with name 'newtoken'.
  9426. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9427. *
  9428. * @return string
  9429. */
  9430. function newToken()
  9431. {
  9432. return $_SESSION['newtoken'];
  9433. }
  9434. /**
  9435. * Return the value of token currently saved into session with name 'token'.
  9436. *
  9437. * @return string
  9438. */
  9439. function currentToken()
  9440. {
  9441. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  9442. }
  9443. /**
  9444. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9445. *
  9446. * @param string $header The first left header of the table (automatic translated)
  9447. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9448. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9449. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9450. * @param integer $number (optional) The number that is shown right after the first header, when not set the link is shown on the right side of the header as "FullList"
  9451. * @return void
  9452. *
  9453. * @see finishSimpleTable()
  9454. */
  9455. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9456. {
  9457. global $langs;
  9458. print '<div class="div-table-responsive-no-min">';
  9459. print '<table class="noborder centpercent">';
  9460. print '<tr class="liste_titre">';
  9461. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9462. print $langs->trans($header);
  9463. // extra space between the first header and the number
  9464. if ($number > -1) {
  9465. print ' ';
  9466. }
  9467. if (!empty($link)) {
  9468. if (!empty($arguments)) {
  9469. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9470. } else {
  9471. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9472. }
  9473. }
  9474. if ($number > -1) {
  9475. print '<span class="badge">'.$number.'</span>';
  9476. }
  9477. if (!empty($link)) {
  9478. print '</a>';
  9479. }
  9480. print '</th>';
  9481. if ($number < 0 && !empty($link)) {
  9482. print '<th class="right">';
  9483. if (!empty($arguments)) {
  9484. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9485. } else {
  9486. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9487. }
  9488. print $langs->trans("FullList");
  9489. print '</a>';
  9490. print '</th>';
  9491. }
  9492. print '</tr>';
  9493. }
  9494. /**
  9495. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9496. *
  9497. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9498. * @return void
  9499. *
  9500. * @see startSimpleTable()
  9501. */
  9502. function finishSimpleTable($addLineBreak = false)
  9503. {
  9504. print '</table>';
  9505. print '</div>';
  9506. if ($addLineBreak) {
  9507. print '<br>';
  9508. }
  9509. }
  9510. /**
  9511. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9512. *
  9513. * @param integer $tableColumnCount The complete count columns of the table
  9514. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9515. * @param integer $nbofloop (optional) The maximum count of rows thaht the table show (when it is zero (0) no summary line will show, expect "$noneWord" when $num === 0)
  9516. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9517. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9518. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9519. * @return void
  9520. */
  9521. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9522. {
  9523. global $langs;
  9524. if ($num === 0) {
  9525. print '<tr class="oddeven">';
  9526. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9527. print '</tr>';
  9528. return;
  9529. }
  9530. if ($nbofloop === 0) {
  9531. // don't show a summary line
  9532. return;
  9533. }
  9534. if ($num === 0) {
  9535. $colspan = $tableColumnCount;
  9536. } elseif ($num > $nbofloop) {
  9537. $colspan = $tableColumnCount;
  9538. } else {
  9539. $colspan = $tableColumnCount - 1;
  9540. }
  9541. if ($extraRightColumn) {
  9542. $colspan--;
  9543. }
  9544. print '<tr class="liste_total">';
  9545. if ($nbofloop > 0 && $num > $nbofloop) {
  9546. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9547. } else {
  9548. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  9549. print '<td class="right" width="100">'.price($total).'</td>';
  9550. }
  9551. if ($extraRightColumn) {
  9552. print '<td></td>';
  9553. }
  9554. print '</tr>';
  9555. }
  9556. /**
  9557. * Return a file on output using a low memory. It can return very large files with no need of memory.
  9558. * WARNING: This close output buffers.
  9559. *
  9560. * @param string $fullpath_original_file_osencoded Full path of file to return.
  9561. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  9562. * @return void
  9563. */
  9564. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  9565. {
  9566. global $conf;
  9567. if ($method == -1) {
  9568. $method = 0;
  9569. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  9570. $method = 1;
  9571. }
  9572. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  9573. $method = 2;
  9574. }
  9575. }
  9576. // Be sure we don't have output buffering enabled to have readfile working correctly
  9577. while (ob_get_level()) {
  9578. ob_end_flush();
  9579. }
  9580. // Solution 0
  9581. if ($method == 0) {
  9582. readfile($fullpath_original_file_osencoded);
  9583. } elseif ($method == 1) {
  9584. // Solution 1
  9585. $handle = fopen($fullpath_original_file_osencoded, "rb");
  9586. while (!feof($handle)) {
  9587. print fread($handle, 8192);
  9588. }
  9589. fclose($handle);
  9590. } elseif ($method == 2) {
  9591. // Solution 2
  9592. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  9593. $handle2 = fopen("php://output", "wb");
  9594. stream_copy_to_stream($handle1, $handle2);
  9595. fclose($handle1);
  9596. fclose($handle2);
  9597. }
  9598. }
  9599. /**
  9600. * Create a button to copy $valuetocopy in the clipboard.
  9601. * Code that handle the click is inside lib_foot.jsp.php.
  9602. *
  9603. * @param string $valuetocopy The value to print
  9604. * @param int $showonlyonhover Show the copy-paste button only on hover
  9605. * @param string $texttoshow Replace the value to show with this text
  9606. * @return string The string to print for the button
  9607. */
  9608. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  9609. {
  9610. /*
  9611. global $conf;
  9612. if (!empty($conf->dol_no_mouse_hover)) {
  9613. $showonlyonhover = 0;
  9614. }*/
  9615. $tag = 'span'; // Using div does not work when using the js copy code.
  9616. if ($texttoshow) {
  9617. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint">'.dol_escape_htmltag($texttoshow, 1, 1).'</span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  9618. } else {
  9619. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  9620. }
  9621. return $result;
  9622. }
  9623. /**
  9624. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  9625. *
  9626. * @param string $stringtodecode String to decode (json or serialize coded)
  9627. * @return mixed The decoded object.
  9628. */
  9629. function jsonOrUnserialize($stringtodecode)
  9630. {
  9631. $result = json_decode($stringtodecode);
  9632. if ($result === null) {
  9633. $result = unserialize($stringtodecode);
  9634. }
  9635. return $result;
  9636. }
  9637. /**
  9638. * Return if a $sqlfilters parameter is valid and will pass the preg_replace_callback() to replace Generic filter string with SQL filter string
  9639. * Example of usage:
  9640. * if ($sqlfilters) {
  9641. * $errormessage = '';
  9642. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9643. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9644. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9645. * }
  9646. * }
  9647. *
  9648. * @param string $sqlfilters sqlfilter string
  9649. * @param string $error Error message
  9650. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  9651. */
  9652. function dolCheckFilters($sqlfilters, &$error = '')
  9653. {
  9654. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  9655. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  9656. $tmp = $sqlfilters;
  9657. $i = 0; $nb = strlen($tmp);
  9658. $counter = 0;
  9659. while ($i < $nb) {
  9660. if ($tmp[$i] == '(') {
  9661. $counter++;
  9662. }
  9663. if ($tmp[$i] == ')') {
  9664. $counter--;
  9665. }
  9666. if ($counter < 0) {
  9667. $error = "Bad sqlfilters=".$sqlfilters;
  9668. dol_syslog($error, LOG_WARNING);
  9669. return false;
  9670. }
  9671. $i++;
  9672. }
  9673. return true;
  9674. }
  9675. /**
  9676. * Function to forge a SQL criteria from a Generic filter string.
  9677. * Example of usage:
  9678. * if ($sqlfilters) {
  9679. * $errormessage = '';
  9680. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9681. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9682. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9683. * }
  9684. * }
  9685. *
  9686. * @param array $matches Array of found string by regex search.
  9687. * Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.date_creation:<:'2016-01-01 12:30:00'" or "t.nature:is:NULL"
  9688. * @return string Forged criteria. Example: "t.field like 'abc%'"
  9689. */
  9690. function dolForgeCriteriaCallback($matches)
  9691. {
  9692. global $db;
  9693. //dol_syslog("Convert matches ".$matches[1]);
  9694. if (empty($matches[1])) {
  9695. return '';
  9696. }
  9697. $tmp = explode(':', $matches[1], 3);
  9698. if (count($tmp) < 3) {
  9699. return '';
  9700. }
  9701. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  9702. $operator = strtoupper(preg_replace('/[^a-z<>=]/i', '', trim($tmp[1])));
  9703. $tmpescaped = trim($tmp[2]);
  9704. $regbis = array();
  9705. if ($operator == 'IN') {
  9706. $tmpescaped = "(".$db->sanitize($tmpescaped, 1).")";
  9707. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  9708. $tmpescaped = "'".$db->escape($regbis[1])."'";
  9709. } else {
  9710. $tmpescaped = $db->sanitize($db->escape($tmpescaped));
  9711. }
  9712. return $db->escape($operand).' '.$db->escape($operator)." ".$tmpescaped;
  9713. }