functions.lib.php 426 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683
  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. if (utf8_check($str)) {
  1077. // See http://www.utf8-chartable.de/
  1078. $string = rawurlencode($str);
  1079. $replacements = array(
  1080. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1081. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1082. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1083. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1084. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1085. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1086. '%C3%A7' => 'c',
  1087. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1088. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1089. '%C3%B1' => 'n',
  1090. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1091. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1092. '%C3%BF' => 'y'
  1093. );
  1094. $string = strtr($string, $replacements);
  1095. return rawurldecode($string);
  1096. } else {
  1097. // See http://www.ascii-code.com/
  1098. $string = strtr(
  1099. $str,
  1100. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1101. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1102. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1103. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1104. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1105. \xF9\xFA\xFB\xFC\xFD\xFF",
  1106. "AAAAAAC
  1107. EEEEIIIIDN
  1108. OOOOOUUUY
  1109. aaaaaaceeee
  1110. iiiidnooooo
  1111. uuuuyy"
  1112. );
  1113. $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"));
  1114. return $string;
  1115. }
  1116. }
  1117. /**
  1118. * Clean a string from all punctuation characters to use it as a ref or login.
  1119. * This is a more complete function than dol_sanitizeFileName.
  1120. *
  1121. * @param string $str String to clean
  1122. * @param string $newstr String to replace forbidden chars with
  1123. * @param array|string $badcharstoreplace List of forbidden characters to replace
  1124. * @param array|string $badcharstoremove List of forbidden characters to remove
  1125. * @return string Cleaned string
  1126. *
  1127. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1128. */
  1129. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1130. {
  1131. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1132. $forbidden_chars_to_remove = array();
  1133. //$forbidden_chars_to_remove=array("(",")");
  1134. if (is_array($badcharstoreplace)) {
  1135. $forbidden_chars_to_replace = $badcharstoreplace;
  1136. }
  1137. if (is_array($badcharstoremove)) {
  1138. $forbidden_chars_to_remove = $badcharstoremove;
  1139. }
  1140. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1141. }
  1142. /**
  1143. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1144. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1145. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1146. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1147. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1148. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1149. * @param string $str String to clean
  1150. * @param int $removetabcrlf Remove also CR-LF
  1151. * @return string Cleaned string
  1152. *
  1153. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1154. */
  1155. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1156. {
  1157. if ($removetabcrlf) {
  1158. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1159. } else {
  1160. 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
  1161. }
  1162. }
  1163. /**
  1164. * Returns text escaped for inclusion into javascript code
  1165. *
  1166. * @param string $stringtoescape String to escape
  1167. * @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 \
  1168. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1169. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1170. */
  1171. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1172. {
  1173. // escape quotes and backslashes, newlines, etc.
  1174. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1175. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1176. if (empty($noescapebackslashn)) {
  1177. $substitjs["\n"] = '\\n';
  1178. $substitjs['\\'] = '\\\\';
  1179. }
  1180. if (empty($mode)) {
  1181. $substitjs["'"] = "\\'";
  1182. $substitjs['"'] = "\\'";
  1183. } elseif ($mode == 1) {
  1184. $substitjs["'"] = "\\'";
  1185. } elseif ($mode == 2) {
  1186. $substitjs['"'] = '\\"';
  1187. } elseif ($mode == 3) {
  1188. $substitjs["'"] = "\\'";
  1189. $substitjs['"'] = "\\\"";
  1190. }
  1191. return strtr($stringtoescape, $substitjs);
  1192. }
  1193. /**
  1194. * Returns text escaped for inclusion into javascript code
  1195. *
  1196. * @param string $stringtoescape String to escape
  1197. * @return string Escaped string for json content.
  1198. */
  1199. function dol_escape_json($stringtoescape)
  1200. {
  1201. return str_replace('"', '\"', $stringtoescape);
  1202. }
  1203. /**
  1204. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1205. *
  1206. * @param string $stringtoescape String to escape
  1207. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1208. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1209. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes to tag.
  1210. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1211. * @return string Escaped string
  1212. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1213. */
  1214. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1215. {
  1216. if ($noescapetags == 'common') {
  1217. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1218. }
  1219. // escape quotes and backslashes, newlines, etc.
  1220. if ($escapeonlyhtmltags) {
  1221. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1222. } else {
  1223. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1224. }
  1225. if (!$keepb) {
  1226. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1227. }
  1228. if (!$keepn) {
  1229. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1230. }
  1231. if ($escapeonlyhtmltags) {
  1232. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1233. } else {
  1234. // Escape tags to keep
  1235. // TODO Does not works yet when there is attributes to tag
  1236. $tmparrayoftags = array();
  1237. if ($noescapetags) {
  1238. $tmparrayoftags = explode(',', $noescapetags);
  1239. }
  1240. if (count($tmparrayoftags)) {
  1241. foreach ($tmparrayoftags as $tagtoreplace) {
  1242. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1243. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1244. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1245. }
  1246. }
  1247. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1248. if (count($tmparrayoftags)) {
  1249. foreach ($tmparrayoftags as $tagtoreplace) {
  1250. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1251. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1252. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1253. }
  1254. }
  1255. return $result;
  1256. }
  1257. }
  1258. /**
  1259. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1260. *
  1261. * @param string $string String to encode
  1262. * @param string $encoding Character set encoding
  1263. * @return string String converted
  1264. */
  1265. function dol_strtolower($string, $encoding = "UTF-8")
  1266. {
  1267. if (function_exists('mb_strtolower')) {
  1268. return mb_strtolower($string, $encoding);
  1269. } else {
  1270. return strtolower($string);
  1271. }
  1272. }
  1273. /**
  1274. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1275. *
  1276. * @param string $string String to encode
  1277. * @param string $encoding Character set encoding
  1278. * @return string String converted
  1279. */
  1280. function dol_strtoupper($string, $encoding = "UTF-8")
  1281. {
  1282. if (function_exists('mb_strtoupper')) {
  1283. return mb_strtoupper($string, $encoding);
  1284. } else {
  1285. return strtoupper($string);
  1286. }
  1287. }
  1288. /**
  1289. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1290. *
  1291. * @param string $string String to encode
  1292. * @param string $encoding Character set encodign
  1293. * @return string String converted
  1294. */
  1295. function dol_ucfirst($string, $encoding = "UTF-8")
  1296. {
  1297. if (function_exists('mb_substr')) {
  1298. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1299. } else {
  1300. return ucfirst($string);
  1301. }
  1302. }
  1303. /**
  1304. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1305. *
  1306. * @param string $string String to encode
  1307. * @param string $encoding Character set encodign
  1308. * @return string String converted
  1309. */
  1310. function dol_ucwords($string, $encoding = "UTF-8")
  1311. {
  1312. if (function_exists('mb_convert_case')) {
  1313. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1314. } else {
  1315. return ucwords($string);
  1316. }
  1317. }
  1318. /**
  1319. * Write log message into outputs. Possible outputs can be:
  1320. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1321. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1322. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1323. * this, use logging to files instead of syslog (see setup of module).
  1324. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1325. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1326. * This function works only if syslog module is enabled.
  1327. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1328. *
  1329. * @param string $message Line to log. ''=Show nothing
  1330. * @param int $level Log level
  1331. * 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
  1332. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1333. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1334. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1335. * @param string $restricttologhandler Force output of log only to this log handler
  1336. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1337. * @return void
  1338. */
  1339. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1340. {
  1341. global $conf, $user, $debugbar;
  1342. // If syslog module enabled
  1343. if (empty($conf->syslog->enabled)) {
  1344. return;
  1345. }
  1346. // Check if we are into execution of code of a website
  1347. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1348. global $website, $websitekey;
  1349. if (is_object($website) && !empty($website->ref)) {
  1350. $suffixinfilename .= '_website_'.$website->ref;
  1351. } elseif (!empty($websitekey)) {
  1352. $suffixinfilename .= '_website_'.$websitekey;
  1353. }
  1354. }
  1355. if ($ident < 0) {
  1356. foreach ($conf->loghandlers as $loghandlerinstance) {
  1357. $loghandlerinstance->setIdent($ident);
  1358. }
  1359. }
  1360. if (!empty($message)) {
  1361. // Test log level
  1362. $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');
  1363. if (!array_key_exists($level, $logLevels)) {
  1364. throw new Exception('Incorrect log level');
  1365. }
  1366. if ($level > $conf->global->SYSLOG_LEVEL) {
  1367. return;
  1368. }
  1369. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1370. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1371. }
  1372. // If adding log inside HTML page is required
  1373. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1374. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1375. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1376. }
  1377. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1378. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1379. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1380. print "\n\n<!-- Log start\n";
  1381. print dol_escape_htmltag($message)."\n";
  1382. print "Log end -->\n";
  1383. }
  1384. $data = array(
  1385. 'message' => $message,
  1386. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1387. 'level' => $level,
  1388. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1389. 'ip' => false
  1390. );
  1391. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1392. if (!empty($remoteip)) {
  1393. $data['ip'] = $remoteip;
  1394. // This is when server run behind a reverse proxy
  1395. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1396. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1397. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1398. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1399. }
  1400. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1401. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1402. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1403. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1404. // 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).
  1405. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1406. } elseif (!empty($_SERVER['LOGNAME'])) {
  1407. // 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).
  1408. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1409. }
  1410. // Loop on each log handler and send output
  1411. foreach ($conf->loghandlers as $loghandlerinstance) {
  1412. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1413. continue;
  1414. }
  1415. $loghandlerinstance->export($data, $suffixinfilename);
  1416. }
  1417. unset($data);
  1418. }
  1419. if ($ident > 0) {
  1420. foreach ($conf->loghandlers as $loghandlerinstance) {
  1421. $loghandlerinstance->setIdent($ident);
  1422. }
  1423. }
  1424. }
  1425. /**
  1426. * Return HTML code to output a button to open a dialog popup box.
  1427. * Such buttons must be included inside a HTML form.
  1428. *
  1429. * @param string $name A name for the html component
  1430. * @param string $label Label of button
  1431. * @param string $buttonstring button string
  1432. * @param string $url Url to open
  1433. * @param string $disabled Disabled text
  1434. * @return string HTML component with button
  1435. */
  1436. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1437. {
  1438. if (strpos($url, '?') > 0) {
  1439. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1440. } else {
  1441. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1442. }
  1443. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1444. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1445. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1446. $out .= '<script type="text/javascript">
  1447. jQuery(document).ready(function () {
  1448. jQuery(".button_'.$name.'").click(function () {
  1449. console.log("Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'")
  1450. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1451. .dialog({
  1452. autoOpen: false,
  1453. modal: true,
  1454. height: (window.innerHeight - 150),
  1455. width: \'80%\',
  1456. title: "'.dol_escape_js($label).'"
  1457. });
  1458. $dialog.dialog(\'open\');
  1459. });
  1460. });
  1461. </script>';
  1462. return $out;
  1463. }
  1464. /**
  1465. * Show tab header of a card
  1466. *
  1467. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1468. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1469. * @param string $title Title
  1470. * @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)
  1471. * @param string $picto Add a picto on tab title
  1472. * @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.
  1473. * @param string $morehtmlright Add more html content on right of tabs title
  1474. * @param string $morecss More Css
  1475. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1476. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1477. * @return void
  1478. * @deprecated Use print dol_get_fiche_head() instead
  1479. */
  1480. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1481. {
  1482. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1483. }
  1484. /**
  1485. * Show tabs of a record
  1486. *
  1487. * @param array $links Array of tabs
  1488. * @param string $active Active tab name
  1489. * @param string $title Title
  1490. * @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)
  1491. * @param string $picto Add a picto on tab title
  1492. * @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.
  1493. * @param string $morehtmlright Add more html content on right of tabs title
  1494. * @param string $morecss More CSS on the link <a>
  1495. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1496. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1497. * @return string
  1498. */
  1499. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1500. {
  1501. global $conf, $langs, $hookmanager;
  1502. // Show title
  1503. $showtitle = 1;
  1504. if (!empty($conf->dol_optimize_smallscreen)) {
  1505. $showtitle = 0;
  1506. }
  1507. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1508. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1509. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1510. }
  1511. // Show right part
  1512. if ($morehtmlright) {
  1513. $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.
  1514. }
  1515. // Show title
  1516. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1517. $limittitle = 30;
  1518. $out .= '<a class="tabTitle">';
  1519. if ($picto) {
  1520. $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1521. }
  1522. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1523. $out .= '</a>';
  1524. }
  1525. // Show tabs
  1526. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1527. $maxkey = -1;
  1528. if (is_array($links) && !empty($links)) {
  1529. $keys = array_keys($links);
  1530. if (count($keys)) {
  1531. $maxkey = max($keys);
  1532. }
  1533. }
  1534. // Show tabs
  1535. // if =0 we don't use the feature
  1536. if (empty($limittoshow)) {
  1537. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1538. }
  1539. if (!empty($conf->dol_optimize_smallscreen)) {
  1540. $limittoshow = 2;
  1541. }
  1542. $displaytab = 0;
  1543. $nbintab = 0;
  1544. $popuptab = 0;
  1545. $outmore = '';
  1546. for ($i = 0; $i <= $maxkey; $i++) {
  1547. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1548. // If active tab is already present
  1549. if ($i >= $limittoshow) {
  1550. $limittoshow--;
  1551. }
  1552. }
  1553. }
  1554. for ($i = 0; $i <= $maxkey; $i++) {
  1555. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1556. $isactive = true;
  1557. } else {
  1558. $isactive = false;
  1559. }
  1560. if ($i < $limittoshow || $isactive) {
  1561. // Add a new entry
  1562. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : $links[$i][2]).' -->';
  1563. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1564. if (!empty($links[$i][0])) {
  1565. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1566. } else {
  1567. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1568. }
  1569. } elseif (!empty($links[$i][1])) {
  1570. //print "x $i $active ".$links[$i][2]." z";
  1571. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1572. if (!empty($links[$i][0])) {
  1573. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1574. }
  1575. $out .= $links[$i][1];
  1576. if (!empty($links[$i][0])) {
  1577. $out .= '</a>'."\n";
  1578. }
  1579. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1580. $out .= '</div>';
  1581. }
  1582. $out .= '</div>';
  1583. } else {
  1584. // The popup with the other tabs
  1585. if (!$popuptab) {
  1586. $popuptab = 1;
  1587. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1588. }
  1589. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1590. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1591. if (!empty($links[$i][0])) {
  1592. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1593. } else {
  1594. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1595. }
  1596. } elseif (!empty($links[$i][1])) {
  1597. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1598. $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.
  1599. $outmore .= '</a>'."\n";
  1600. }
  1601. $outmore .= '</div>';
  1602. $nbintab++;
  1603. }
  1604. $displaytab = $i;
  1605. }
  1606. if ($popuptab) {
  1607. $outmore .= '</div>';
  1608. }
  1609. if ($popuptab) { // If there is some tabs not shown
  1610. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1611. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1612. $widthofpopup = 200;
  1613. $tabsname = $moretabssuffix;
  1614. if (empty($tabsname)) {
  1615. $tabsname = str_replace("@", "", $picto);
  1616. }
  1617. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1618. $out .= '<a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a>'; // Do not use "reposition" class in the "More".
  1619. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1620. $out .= $outmore;
  1621. $out .= '</div>';
  1622. $out .= '<div></div>';
  1623. $out .= "</div>\n";
  1624. $out .= "<script>";
  1625. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1626. var x = this.offsetLeft, y = this.offsetTop;
  1627. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1628. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1629. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1630. }
  1631. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1632. });
  1633. ";
  1634. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1635. $out .= "</script>";
  1636. }
  1637. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1638. $out .= "</div>\n";
  1639. }
  1640. if (!$notab || $notab == -1 || $notab == -2) {
  1641. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1642. }
  1643. $parameters = array('tabname' => $active, 'out' => $out);
  1644. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1645. if ($reshook > 0) {
  1646. $out = $hookmanager->resPrint;
  1647. }
  1648. return $out;
  1649. }
  1650. /**
  1651. * Show tab footer of a card
  1652. *
  1653. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1654. * @return void
  1655. * @deprecated Use print dol_get_fiche_end() instead
  1656. */
  1657. function dol_fiche_end($notab = 0)
  1658. {
  1659. print dol_get_fiche_end($notab);
  1660. }
  1661. /**
  1662. * Return tab footer of a card
  1663. *
  1664. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1665. * @return string
  1666. */
  1667. function dol_get_fiche_end($notab = 0)
  1668. {
  1669. if (!$notab || $notab == -1) {
  1670. return "\n</div>\n";
  1671. } else {
  1672. return '';
  1673. }
  1674. }
  1675. /**
  1676. * Show tab footer of a card.
  1677. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1678. *
  1679. * @param Object $object Object to show
  1680. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1681. * @param string $morehtml More html content to output just before the nav bar
  1682. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1683. * @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.
  1684. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1685. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1686. * @param string $moreparam More param to add in nav link url.
  1687. * @param int $nodbprefix Do not include DB prefix to forge table name
  1688. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1689. * @param string $morehtmlstatus More html code to show under navigation arrows
  1690. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1691. * @param string $morehtmlright More html code to show before navigation arrows
  1692. * @return void
  1693. */
  1694. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1695. {
  1696. global $conf, $form, $user, $langs, $hookmanager, $action;
  1697. $error = 0;
  1698. $maxvisiblephotos = 1;
  1699. $showimage = 1;
  1700. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1701. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1702. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1703. $showbarcode = 0;
  1704. }
  1705. $modulepart = 'unknown';
  1706. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1707. $modulepart = $object->element;
  1708. } elseif ($object->element == 'member') {
  1709. $modulepart = 'memberphoto';
  1710. } elseif ($object->element == 'user') {
  1711. $modulepart = 'userphoto';
  1712. }
  1713. if (class_exists("Imagick")) {
  1714. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1715. $modulepart = $object->element;
  1716. } elseif ($object->element == 'fichinter') {
  1717. $modulepart = 'ficheinter';
  1718. } elseif ($object->element == 'contrat') {
  1719. $modulepart = 'contract';
  1720. } elseif ($object->element == 'order_supplier') {
  1721. $modulepart = 'supplier_order';
  1722. } elseif ($object->element == 'invoice_supplier') {
  1723. $modulepart = 'supplier_invoice';
  1724. }
  1725. }
  1726. if ($object->element == 'product') {
  1727. $width = 80;
  1728. $cssclass = 'photoref';
  1729. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1730. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1731. if ($conf->browser->layout == 'phone') {
  1732. $maxvisiblephotos = 1;
  1733. }
  1734. if ($showimage) {
  1735. $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>';
  1736. } else {
  1737. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1738. $nophoto = '';
  1739. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1740. } else { // Show no photo link
  1741. $nophoto = '/public/theme/common/nophoto.png';
  1742. $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>';
  1743. }
  1744. }
  1745. } elseif ($object->element == 'ticket') {
  1746. $width = 80;
  1747. $cssclass = 'photoref';
  1748. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1749. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1750. if ($conf->browser->layout == 'phone') {
  1751. $maxvisiblephotos = 1;
  1752. }
  1753. if ($showimage) {
  1754. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1755. if ($object->nbphoto > 0) {
  1756. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1757. } else {
  1758. $showimage = 0;
  1759. }
  1760. }
  1761. if (!$showimage) {
  1762. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1763. $nophoto = '';
  1764. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1765. } else { // Show no photo link
  1766. $nophoto = img_picto('No photo', 'object_ticket');
  1767. $morehtmlleft .= '<!-- No photo to show -->';
  1768. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1769. $morehtmlleft .= $nophoto;
  1770. $morehtmlleft .= '</div></div>';
  1771. }
  1772. }
  1773. } else {
  1774. if ($showimage) {
  1775. if ($modulepart != 'unknown') {
  1776. $phototoshow = '';
  1777. // Check if a preview file is available
  1778. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1779. $objectref = dol_sanitizeFileName($object->ref);
  1780. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1781. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1782. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1783. $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
  1784. } else {
  1785. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1786. }
  1787. if (empty($subdir)) {
  1788. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1789. }
  1790. $filepath = $dir_output.$subdir."/";
  1791. $filepdf = $filepath.$objectref.".pdf";
  1792. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1793. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1794. $fileimage = $filepdf.'_preview.png';
  1795. $relativepathimage = $relativepath.'_preview.png';
  1796. $pdfexists = file_exists($filepdf);
  1797. // If PDF file exists
  1798. if ($pdfexists) {
  1799. // Conversion du PDF en image png si fichier png non existant
  1800. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1801. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1802. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1803. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1804. if ($ret < 0) {
  1805. $error++;
  1806. }
  1807. }
  1808. }
  1809. }
  1810. if ($pdfexists && !$error) {
  1811. $heightforphotref = 80;
  1812. if (!empty($conf->dol_optimize_smallscreen)) {
  1813. $heightforphotref = 60;
  1814. }
  1815. // If the preview file is found
  1816. if (file_exists($fileimage)) {
  1817. $phototoshow = '<div class="photoref">';
  1818. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1819. $phototoshow .= '</div>';
  1820. }
  1821. }
  1822. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1823. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1824. }
  1825. if ($phototoshow) {
  1826. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1827. $morehtmlleft .= $phototoshow;
  1828. $morehtmlleft .= '</div>';
  1829. }
  1830. }
  1831. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1832. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1833. if ($object->element == 'action') {
  1834. $width = 80;
  1835. $cssclass = 'photorefcenter';
  1836. $nophoto = img_picto('No photo', 'title_agenda');
  1837. } else {
  1838. $width = 14;
  1839. $cssclass = 'photorefcenter';
  1840. $picto = $object->picto;
  1841. if ($object->element == 'project' && !$object->public) {
  1842. $picto = 'project'; // instead of projectpub
  1843. }
  1844. $nophoto = img_picto('No photo', 'object_'.$picto);
  1845. }
  1846. $morehtmlleft .= '<!-- No photo to show -->';
  1847. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1848. $morehtmlleft .= $nophoto;
  1849. $morehtmlleft .= '</div></div>';
  1850. $morehtmlleft .= '</div>';
  1851. }
  1852. }
  1853. }
  1854. if ($showbarcode) {
  1855. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref').'</div>';
  1856. }
  1857. if ($object->element == 'societe') {
  1858. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1859. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1860. } else {
  1861. $morehtmlstatus .= $object->getLibStatut(6);
  1862. }
  1863. } elseif ($object->element == 'product') {
  1864. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1865. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1866. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1867. } else {
  1868. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1869. }
  1870. $morehtmlstatus .= ' &nbsp; ';
  1871. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1872. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1873. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1874. } else {
  1875. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1876. }
  1877. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  1878. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1879. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1880. $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1881. }
  1882. $morehtmlstatus .= $tmptxt;
  1883. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  1884. if ($object->statut == 0) {
  1885. $morehtmlstatus .= $object->getLibStatut(5);
  1886. } else {
  1887. $morehtmlstatus .= $object->getLibStatut(4);
  1888. }
  1889. } elseif ($object->element == 'facturerec') {
  1890. if ($object->frequency == 0) {
  1891. $morehtmlstatus .= $object->getLibStatut(2);
  1892. } else {
  1893. $morehtmlstatus .= $object->getLibStatut(5);
  1894. }
  1895. } elseif ($object->element == 'project_task') {
  1896. $object->fk_statut = 1;
  1897. if ($object->progress > 0) {
  1898. $object->fk_statut = 2;
  1899. }
  1900. if ($object->progress >= 100) {
  1901. $object->fk_statut = 3;
  1902. }
  1903. $tmptxt = $object->getLibStatut(5);
  1904. $morehtmlstatus .= $tmptxt; // No status on task
  1905. } else { // Generic case
  1906. $tmptxt = $object->getLibStatut(6);
  1907. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  1908. $tmptxt = $object->getLibStatut(5);
  1909. }
  1910. $morehtmlstatus .= $tmptxt;
  1911. }
  1912. // Add if object was dispatched "into accountancy"
  1913. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  1914. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  1915. if (method_exists($object, 'getVentilExportCompta')) {
  1916. $accounted = $object->getVentilExportCompta();
  1917. $langs->load("accountancy");
  1918. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1919. }
  1920. }
  1921. // Add alias for thirdparty
  1922. if (!empty($object->name_alias)) {
  1923. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1924. }
  1925. // Add label
  1926. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  1927. if (!empty($object->label)) {
  1928. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1929. }
  1930. }
  1931. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  1932. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1933. if ($moreaddress) {
  1934. $morehtmlref .= '<div class="refidno">';
  1935. $morehtmlref .= $moreaddress;
  1936. $morehtmlref .= '</div>';
  1937. }
  1938. }
  1939. 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)) {
  1940. $morehtmlref .= '<div style="clear: both;"></div>';
  1941. $morehtmlref .= '<div class="refidno">';
  1942. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1943. $morehtmlref .= '</div>';
  1944. }
  1945. $parameters=array('morehtmlref'=>$morehtmlref);
  1946. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  1947. if ($reshook < 0) {
  1948. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1949. } elseif (empty($reshook)) {
  1950. $morehtmlref .= $hookmanager->resPrint;
  1951. } elseif ($reshook > 0) {
  1952. $morehtmlref = $hookmanager->resPrint;
  1953. }
  1954. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1955. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1956. print '</div>';
  1957. print '<div class="underrefbanner clearboth"></div>';
  1958. }
  1959. /**
  1960. * Show a string with the label tag dedicated to the HTML edit field.
  1961. *
  1962. * @param string $langkey Translation key
  1963. * @param string $fieldkey Key of the html select field the text refers to
  1964. * @param int $fieldrequired 1=Field is mandatory
  1965. * @return string
  1966. * @deprecated Form::editfieldkey
  1967. */
  1968. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1969. {
  1970. global $langs;
  1971. $ret = '';
  1972. if ($fieldrequired) {
  1973. $ret .= '<span class="fieldrequired">';
  1974. }
  1975. $ret .= '<label for="'.$fieldkey.'">';
  1976. $ret .= $langs->trans($langkey);
  1977. $ret .= '</label>';
  1978. if ($fieldrequired) {
  1979. $ret .= '</span>';
  1980. }
  1981. return $ret;
  1982. }
  1983. /**
  1984. * Return string to add class property on html element with pair/impair.
  1985. *
  1986. * @param string $var 0 or 1
  1987. * @param string $moreclass More class to add
  1988. * @return string String to add class onto HTML element
  1989. */
  1990. function dol_bc($var, $moreclass = '')
  1991. {
  1992. global $bc;
  1993. $ret = ' '.$bc[$var];
  1994. if ($moreclass) {
  1995. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  1996. }
  1997. return $ret;
  1998. }
  1999. /**
  2000. * Return a formated address (part address/zip/town/state) according to country rules.
  2001. * See https://en.wikipedia.org/wiki/Address
  2002. *
  2003. * @param Object $object A company or contact object
  2004. * @param int $withcountry 1=Add country into address string
  2005. * @param string $sep Separator to use to build string
  2006. * @param Translate $outputlangs Object lang that contains language for text translation.
  2007. * @param int $mode 0=Standard output, 1=Remove address
  2008. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2009. * @return string Formated string
  2010. * @see dol_print_address()
  2011. */
  2012. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2013. {
  2014. global $conf, $langs;
  2015. $ret = '';
  2016. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2017. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2018. // Address
  2019. if (empty($mode)) {
  2020. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2021. }
  2022. // Zip/Town/State
  2023. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2024. // US: title firstname name \n address lines \n town, state, zip \n country
  2025. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2026. $ret .= ($ret ? $sep : '').$town;
  2027. if (!empty($object->state)) {
  2028. $ret .= ($ret ? ", " : '').$object->state;
  2029. }
  2030. if (!empty($object->zip)) {
  2031. $ret .= ($ret ? ", " : '').$object->zip;
  2032. }
  2033. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2034. // UK: title firstname name \n address lines \n town state \n zip \n country
  2035. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2036. $ret .= ($ret ? $sep : '').$town;
  2037. if (!empty($object->state)) {
  2038. $ret .= ($ret ? ", " : '').$object->state;
  2039. }
  2040. if (!empty($object->zip)) {
  2041. $ret .= ($ret ? $sep : '').$object->zip;
  2042. }
  2043. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2044. // ES: title firstname name \n address lines \n zip town \n state \n country
  2045. $ret .= ($ret ? $sep : '').$object->zip;
  2046. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2047. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2048. if (!empty($object->state)) {
  2049. $ret .= "\n".$object->state;
  2050. }
  2051. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2052. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2053. // See https://www.sljfaq.org/afaq/addresses.html
  2054. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2055. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2056. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2057. // IT: title firstname name\n address lines \n zip town state_code \n country
  2058. $ret .= ($ret ? $sep : '').$object->zip;
  2059. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2060. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2061. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2062. } else {
  2063. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2064. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2065. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2066. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2067. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2068. $ret .= ($ret ? ", " : '').$object->state;
  2069. }
  2070. }
  2071. if (!is_object($outputlangs)) {
  2072. $outputlangs = $langs;
  2073. }
  2074. if ($withcountry) {
  2075. $langs->load("dict");
  2076. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2077. }
  2078. return $ret;
  2079. }
  2080. /**
  2081. * Format a string.
  2082. *
  2083. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2084. * @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)
  2085. * @param int $is_gmt See comment of timestamp parameter
  2086. * @return string A formatted string
  2087. */
  2088. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2089. {
  2090. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2091. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2092. } else {
  2093. return 'Error date into a not supported range';
  2094. }
  2095. }
  2096. /**
  2097. * Output date in a string format according to outputlangs (or langs if not defined).
  2098. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2099. *
  2100. * @param int $time GM Timestamps date
  2101. * @param string $format Output date format (tag of strftime function)
  2102. * "%d %b %Y",
  2103. * "%d/%m/%Y %H:%M",
  2104. * "%d/%m/%Y %H:%M:%S",
  2105. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2106. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2107. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2108. * false or 'tzserver' => output string is for local PHP server TZ usage
  2109. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2110. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  2111. * @param Translate $outputlangs Object lang that contains language for text translation.
  2112. * @param boolean $encodetooutput false=no convert into output pagecode
  2113. * @return string Formated date or '' if time is null
  2114. *
  2115. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2116. */
  2117. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2118. {
  2119. global $conf, $langs;
  2120. // If date undefined or "", we return ""
  2121. if (dol_strlen($time) == 0) {
  2122. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2123. }
  2124. if ($tzoutput === 'auto') {
  2125. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2126. }
  2127. // Clean parameters
  2128. $to_gmt = false;
  2129. $offsettz = $offsetdst = 0;
  2130. if ($tzoutput) {
  2131. $to_gmt = true; // For backward compatibility
  2132. if (is_string($tzoutput)) {
  2133. if ($tzoutput == 'tzserver') {
  2134. $to_gmt = false;
  2135. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2136. $offsettz = 0; // Timezone offset with server timezone, so 0
  2137. $offsetdst = 0; // Dst offset with server timezone, so 0
  2138. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2139. $to_gmt = true;
  2140. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2141. if (class_exists('DateTimeZone')) {
  2142. $user_date_tz = new DateTimeZone($offsettzstring);
  2143. $user_dt = new DateTime();
  2144. $user_dt->setTimezone($user_date_tz);
  2145. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2146. $offsettz = $user_dt->getOffset();
  2147. } else { // old method (The 'tzuser' was processed like the 'tzuserrel')
  2148. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2149. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2150. }
  2151. }
  2152. }
  2153. }
  2154. if (!is_object($outputlangs)) {
  2155. $outputlangs = $langs;
  2156. }
  2157. if (!$format) {
  2158. $format = 'daytextshort';
  2159. }
  2160. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2161. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2162. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2163. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2164. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2165. if ($formatwithoutreduce != $format) {
  2166. $format = $formatwithoutreduce;
  2167. $reduceformat = 1;
  2168. } // so format 'dayreduceformat' is processed like day
  2169. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2170. // TODO Add format daysmallyear and dayhoursmallyear
  2171. if ($format == 'day') {
  2172. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2173. } elseif ($format == 'hour') {
  2174. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2175. } elseif ($format == 'hourduration') {
  2176. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2177. } elseif ($format == 'daytext') {
  2178. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2179. } elseif ($format == 'daytextshort') {
  2180. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2181. } elseif ($format == 'dayhour') {
  2182. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2183. } elseif ($format == 'dayhoursec') {
  2184. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2185. } elseif ($format == 'dayhourtext') {
  2186. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2187. } elseif ($format == 'dayhourtextshort') {
  2188. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2189. } elseif ($format == 'dayhourlog') {
  2190. // Format not sensitive to language
  2191. $format = '%Y%m%d%H%M%S';
  2192. } elseif ($format == 'dayhourldap') {
  2193. $format = '%Y%m%d%H%M%SZ';
  2194. } elseif ($format == 'dayhourxcard') {
  2195. $format = '%Y%m%dT%H%M%SZ';
  2196. } elseif ($format == 'dayxcard') {
  2197. $format = '%Y%m%d';
  2198. } elseif ($format == 'dayrfc') {
  2199. $format = '%Y-%m-%d'; // DATE_RFC3339
  2200. } elseif ($format == 'dayhourrfc') {
  2201. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2202. } elseif ($format == 'standard') {
  2203. $format = '%Y-%m-%d %H:%M:%S';
  2204. }
  2205. if ($reduceformat) {
  2206. $format = str_replace('%Y', '%y', $format);
  2207. $format = str_replace('yyyy', 'yy', $format);
  2208. }
  2209. // Clean format
  2210. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2211. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2212. $format = str_replace('%b', '__b__', $format);
  2213. $format = str_replace('%B', '__B__', $format);
  2214. }
  2215. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2216. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2217. $format = str_replace('%a', '__a__', $format);
  2218. $format = str_replace('%A', '__A__', $format);
  2219. }
  2220. // Analyze date
  2221. $reg = array();
  2222. 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
  2223. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2224. return '';
  2225. } 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
  2226. // This part of code should not be used anymore.
  2227. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2228. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2229. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2230. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2231. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2232. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2233. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2234. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2235. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2236. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2237. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2238. } else {
  2239. // Date is a timestamps
  2240. if ($time < 100000000000) { // Protection against bad date values
  2241. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2242. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2243. } else {
  2244. $ret = 'Bad value '.$time.' for date';
  2245. }
  2246. }
  2247. if (preg_match('/__b__/i', $format)) {
  2248. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2249. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2250. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2251. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2252. if ($encodetooutput) {
  2253. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2254. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2255. } else {
  2256. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2257. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2258. }
  2259. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2260. $ret = str_replace('__b__', $monthtextshort, $ret);
  2261. $ret = str_replace('__B__', $monthtext, $ret);
  2262. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2263. //return $ret;
  2264. }
  2265. if (preg_match('/__a__/i', $format)) {
  2266. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2267. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2268. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2269. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2270. $ret = str_replace('__A__', $dayweek, $ret);
  2271. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2272. }
  2273. return $ret;
  2274. }
  2275. /**
  2276. * Return an array with locale date info.
  2277. * WARNING: This function use PHP server timezone by default to return locale informations.
  2278. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2279. *
  2280. * @param int $timestamp Timestamp
  2281. * @param boolean $fast Fast mode. deprecated.
  2282. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2283. * @return array Array of informations
  2284. * 'seconds' => $secs,
  2285. * 'minutes' => $min,
  2286. * 'hours' => $hour,
  2287. * 'mday' => $day,
  2288. * 'wday' => $dow, 0=sunday, 6=saturday
  2289. * 'mon' => $month,
  2290. * 'year' => $year,
  2291. * 'yday' => floor($secsInYear/$_day_power)
  2292. * '0' => original timestamp
  2293. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2294. */
  2295. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2296. {
  2297. //$datetimeobj = new DateTime('@'.$timestamp);
  2298. $datetimeobj = new DateTime();
  2299. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2300. if ($forcetimezone) {
  2301. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2302. }
  2303. $arrayinfo = array(
  2304. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2305. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2306. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2307. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2308. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2309. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2310. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2311. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2312. '0'=>$timestamp
  2313. );
  2314. return $arrayinfo;
  2315. }
  2316. /**
  2317. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2318. * Replace function mktime not available under Windows if year < 1970
  2319. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2320. *
  2321. * @param int $hour Hour (can be -1 for undefined)
  2322. * @param int $minute Minute (can be -1 for undefined)
  2323. * @param int $second Second (can be -1 for undefined)
  2324. * @param int $month Month (1 to 12)
  2325. * @param int $day Day (1 to 31)
  2326. * @param int $year Year
  2327. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2328. * False or 0 or 'tzserver' = local to server TZ
  2329. * 'auto'
  2330. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2331. * '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.
  2332. * 'tz,TimeZone' = use specified timezone
  2333. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2334. * @return int|string Date as a timestamp, '' or false if error
  2335. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2336. */
  2337. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2338. {
  2339. global $conf;
  2340. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2341. //print 'gm:'.$gm.' gm==auto:'.($gm == 'auto').'<br>';
  2342. if ($gm === 'auto') {
  2343. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2344. }
  2345. // Clean parameters
  2346. if ($hour == -1 || empty($hour)) {
  2347. $hour = 0;
  2348. }
  2349. if ($minute == -1 || empty($minute)) {
  2350. $minute = 0;
  2351. }
  2352. if ($second == -1 || empty($second)) {
  2353. $second = 0;
  2354. }
  2355. // Check parameters
  2356. if ($check) {
  2357. if (!$month || !$day) {
  2358. return '';
  2359. }
  2360. if ($day > 31) {
  2361. return '';
  2362. }
  2363. if ($month > 12) {
  2364. return '';
  2365. }
  2366. if ($hour < 0 || $hour > 24) {
  2367. return '';
  2368. }
  2369. if ($minute < 0 || $minute > 60) {
  2370. return '';
  2371. }
  2372. if ($second < 0 || $second > 60) {
  2373. return '';
  2374. }
  2375. }
  2376. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2377. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2378. $localtz = new DateTimeZone($default_timezone);
  2379. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2380. // We use dol_tz_string first because it is more reliable.
  2381. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2382. try {
  2383. $localtz = new DateTimeZone($default_timezone);
  2384. } catch (Exception $e) {
  2385. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2386. $default_timezone = @date_default_timezone_get();
  2387. }
  2388. } elseif (strrpos($gm, "tz,") !== false) {
  2389. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2390. try {
  2391. $localtz = new DateTimeZone($timezone);
  2392. } catch (Exception $e) {
  2393. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2394. }
  2395. }
  2396. if (empty($localtz)) {
  2397. $localtz = new DateTimeZone('UTC');
  2398. }
  2399. //var_dump($localtz);
  2400. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2401. $dt = new DateTime(null, $localtz);
  2402. $dt->setDate((int) $year, (int) $month, (int) $day);
  2403. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2404. $date = $dt->getTimestamp(); // should include daylight saving time
  2405. //var_dump($date);
  2406. return $date;
  2407. }
  2408. /**
  2409. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2410. *
  2411. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2412. * 'gmt' => we return GMT timestamp,
  2413. * 'tzserver' => we add the PHP server timezone
  2414. * 'tzref' => we add the company timezone. Not implemented.
  2415. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2416. * @return int $date Timestamp
  2417. */
  2418. function dol_now($mode = 'auto')
  2419. {
  2420. $ret = 0;
  2421. if ($mode === 'auto') {
  2422. $mode = 'gmt';
  2423. }
  2424. if ($mode == 'gmt') {
  2425. $ret = time(); // Time for now at greenwich.
  2426. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2427. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2428. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2429. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2430. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2431. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2432. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2433. // $ret=dol_now('gmt')+($tzsecond*3600);
  2434. //}
  2435. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2436. // Time for now with user timezone added
  2437. //print 'time: '.time();
  2438. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2439. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2440. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2441. }
  2442. return $ret;
  2443. }
  2444. /**
  2445. * Return string with formated size
  2446. *
  2447. * @param int $size Size to print
  2448. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2449. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2450. * @return string Link
  2451. */
  2452. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2453. {
  2454. global $conf, $langs;
  2455. $level = 1024;
  2456. if (!empty($conf->dol_optimize_smallscreen)) {
  2457. $shortunit = 1;
  2458. }
  2459. // Set value text
  2460. if (empty($shortvalue) || $size < ($level * 10)) {
  2461. $ret = $size;
  2462. $textunitshort = $langs->trans("b");
  2463. $textunitlong = $langs->trans("Bytes");
  2464. } else {
  2465. $ret = round($size / $level, 0);
  2466. $textunitshort = $langs->trans("Kb");
  2467. $textunitlong = $langs->trans("KiloBytes");
  2468. }
  2469. // Use long or short text unit
  2470. if (empty($shortunit)) {
  2471. $ret .= ' '.$textunitlong;
  2472. } else {
  2473. $ret .= ' '.$textunitshort;
  2474. }
  2475. return $ret;
  2476. }
  2477. /**
  2478. * Show Url link
  2479. *
  2480. * @param string $url Url to show
  2481. * @param string $target Target for link
  2482. * @param int $max Max number of characters to show
  2483. * @param int $withpicto With picto
  2484. * @return string HTML Link
  2485. */
  2486. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2487. {
  2488. global $langs;
  2489. if (empty($url)) {
  2490. return '';
  2491. }
  2492. $link = '<a href="';
  2493. if (!preg_match('/^http/i', $url)) {
  2494. $link .= 'http://';
  2495. }
  2496. $link .= $url;
  2497. $link .= '"';
  2498. if ($target) {
  2499. $link .= ' target="'.$target.'"';
  2500. }
  2501. $link .= '>';
  2502. if (!preg_match('/^http/i', $url)) {
  2503. $link .= 'http://';
  2504. }
  2505. $link .= dol_trunc($url, $max);
  2506. $link .= '</a>';
  2507. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2508. }
  2509. /**
  2510. * Show EMail link formatted for HTML output.
  2511. *
  2512. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2513. * @param int $cid Id of contact if known
  2514. * @param int $socid Id of third party if known
  2515. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2516. * @param int $max Max number of characters to show
  2517. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2518. * @param int $withpicto Show picto
  2519. * @return string HTML Link
  2520. */
  2521. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2522. {
  2523. global $conf, $user, $langs, $hookmanager;
  2524. $newemail = dol_escape_htmltag($email);
  2525. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2526. $withpicto = 0;
  2527. }
  2528. if (empty($email)) {
  2529. return '&nbsp;';
  2530. }
  2531. if (!empty($addlink)) {
  2532. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2533. if (!preg_match('/^mailto:/i', $email)) {
  2534. $newemail .= 'mailto:';
  2535. }
  2536. $newemail .= $email;
  2537. $newemail .= '">';
  2538. $newemail .= dol_trunc($email, $max);
  2539. $newemail .= '</a>';
  2540. if ($showinvalid && !isValidEmail($email)) {
  2541. $langs->load("errors");
  2542. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2543. }
  2544. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2545. $type = 'AC_EMAIL';
  2546. $link = '';
  2547. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2548. $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>';
  2549. }
  2550. if ($link) {
  2551. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2552. }
  2553. }
  2554. } else {
  2555. if ($showinvalid && !isValidEmail($email)) {
  2556. $langs->load("errors");
  2557. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2558. }
  2559. }
  2560. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2561. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2562. //$rep .= '</div>';
  2563. if ($hookmanager) {
  2564. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2565. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2566. if ($reshook > 0) {
  2567. $rep = '';
  2568. }
  2569. $rep .= $hookmanager->resPrint;
  2570. }
  2571. return $rep;
  2572. }
  2573. /**
  2574. * Get array of social network dictionary
  2575. *
  2576. * @return array Array of Social Networks Dictionary
  2577. */
  2578. function getArrayOfSocialNetworks()
  2579. {
  2580. global $conf, $db;
  2581. $socialnetworks = array();
  2582. // Enable caching of array
  2583. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2584. $cachekey = 'socialnetworks_' . $conf->entity;
  2585. $dataretrieved = dol_getcache($cachekey);
  2586. if (!is_null($dataretrieved)) {
  2587. $socialnetworks = $dataretrieved;
  2588. } else {
  2589. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2590. $sql .= " WHERE entity=".$conf->entity;
  2591. $resql = $db->query($sql);
  2592. if ($resql) {
  2593. while ($obj = $db->fetch_object($resql)) {
  2594. $socialnetworks[$obj->code] = array(
  2595. 'rowid' => $obj->rowid,
  2596. 'label' => $obj->label,
  2597. 'url' => $obj->url,
  2598. 'icon' => $obj->icon,
  2599. 'active' => $obj->active,
  2600. );
  2601. }
  2602. }
  2603. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2604. }
  2605. return $socialnetworks;
  2606. }
  2607. /**
  2608. * Show social network link
  2609. *
  2610. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2611. * @param int $cid Id of contact if known
  2612. * @param int $socid Id of third party if known
  2613. * @param string $type 'skype','facebook',...
  2614. * @param array $dictsocialnetworks socialnetworks availables
  2615. * @return string HTML Link
  2616. */
  2617. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2618. {
  2619. global $conf, $user, $langs;
  2620. $htmllink = $value;
  2621. if (empty($value)) {
  2622. return '&nbsp;';
  2623. }
  2624. if (!empty($type)) {
  2625. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2626. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2627. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2628. if ($type == 'skype') {
  2629. $htmllink .= $value;
  2630. $htmllink .= '&nbsp;';
  2631. $htmllink .= '<a href="skype:';
  2632. $htmllink .= $value;
  2633. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2634. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2635. $htmllink .= '</a><a href="skype:';
  2636. $htmllink .= $value;
  2637. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2638. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2639. $htmllink .= '</a>';
  2640. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2641. $addlink = 'AC_SKYPE';
  2642. $link = '';
  2643. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2644. $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>';
  2645. }
  2646. $htmllink .= ($link ? ' '.$link : '');
  2647. }
  2648. } else {
  2649. if (!empty($dictsocialnetworks[$type]['url'])) {
  2650. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2651. $htmllink .= '&nbsp;<a href="'.$link.'" target="_blank" rel="noopener noreferrer">'.$value.'</a>';
  2652. } else {
  2653. $htmllink .= $value;
  2654. }
  2655. }
  2656. $htmllink .= '</div>';
  2657. } else {
  2658. $langs->load("errors");
  2659. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2660. }
  2661. return $htmllink;
  2662. }
  2663. /**
  2664. * Format phone numbers according to country
  2665. *
  2666. * @param string $phone Phone number to format
  2667. * @param string $countrycode Country code to use for formatting
  2668. * @param int $cid Id of contact if known
  2669. * @param int $socid Id of third party if known
  2670. * @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)
  2671. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2672. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2673. * @param string $titlealt Text to show on alt
  2674. * @param int $adddivfloat Add div float around phone.
  2675. * @return string Formated phone number
  2676. */
  2677. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2678. {
  2679. global $conf, $user, $langs, $mysoc, $hookmanager;
  2680. // Clean phone parameter
  2681. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2682. if (empty($phone)) {
  2683. return '';
  2684. }
  2685. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2686. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2687. }
  2688. if (empty($countrycode)) {
  2689. $countrycode = $mysoc->country_code;
  2690. }
  2691. // Short format for small screens
  2692. if ($conf->dol_optimize_smallscreen) {
  2693. $separ = '';
  2694. }
  2695. $newphone = $phone;
  2696. if (strtoupper($countrycode) == "FR") {
  2697. // France
  2698. if (dol_strlen($phone) == 10) {
  2699. $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);
  2700. } elseif (dol_strlen($phone) == 7) {
  2701. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2702. } elseif (dol_strlen($phone) == 9) {
  2703. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2704. } elseif (dol_strlen($phone) == 11) {
  2705. $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);
  2706. } elseif (dol_strlen($phone) == 12) {
  2707. $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);
  2708. }
  2709. } elseif (strtoupper($countrycode) == "CA") {
  2710. if (dol_strlen($phone) == 10) {
  2711. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2712. }
  2713. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2714. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2715. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2716. }
  2717. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2718. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2719. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2720. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2721. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2722. }
  2723. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2724. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2725. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2726. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2727. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2728. }
  2729. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2730. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2731. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2732. }
  2733. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2734. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2735. $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);
  2736. }
  2737. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2738. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2739. $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);
  2740. }
  2741. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2742. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2743. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2744. }
  2745. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2746. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2747. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2748. }
  2749. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2750. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2751. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2752. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2753. $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);
  2754. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2755. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2756. }
  2757. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2758. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2759. $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);
  2760. }
  2761. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2762. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2763. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2764. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2765. $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);
  2766. }
  2767. } elseif (strtoupper($countrycode) == "MU") {
  2768. //Maurice
  2769. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  2770. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2771. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  2772. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2773. }
  2774. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  2775. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  2776. $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);
  2777. }
  2778. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  2779. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  2780. $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);
  2781. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  2782. $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);
  2783. }
  2784. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  2785. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  2786. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2787. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  2788. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2789. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  2790. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2791. }
  2792. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  2793. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  2794. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2795. }
  2796. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  2797. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  2798. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2799. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  2800. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2801. }
  2802. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  2803. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  2804. $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);
  2805. }
  2806. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  2807. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  2808. $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);
  2809. }
  2810. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  2811. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  2812. $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);
  2813. }
  2814. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  2815. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  2816. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2817. }
  2818. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  2819. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
  2820. $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);
  2821. }
  2822. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  2823. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  2824. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2825. }
  2826. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  2827. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  2828. $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);
  2829. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  2830. $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);
  2831. }
  2832. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  2833. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  2834. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2835. }
  2836. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  2837. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2838. $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);
  2839. }
  2840. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  2841. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2842. $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);
  2843. }
  2844. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  2845. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2846. $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);
  2847. }
  2848. } elseif (strtoupper($countrycode) == "IT") {//Italie
  2849. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  2850. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2851. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  2852. $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);
  2853. }
  2854. } elseif (strtoupper($countrycode) == "AU") {
  2855. //Australie
  2856. if (dol_strlen($phone) == 12) {
  2857. //ex: +61_A_BCDE_FGHI
  2858. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2859. }
  2860. }
  2861. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2862. 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
  2863. $newphoneform = $newphone;
  2864. $newphone = '<a href="tel:'.$phone.'"';
  2865. $newphone .= '>'.$newphoneform.'</a>';
  2866. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  2867. if (empty($user->clicktodial_loaded)) {
  2868. $user->fetch_clicktodial();
  2869. }
  2870. // Define urlmask
  2871. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2872. if (!empty($conf->global->CLICKTODIAL_URL)) {
  2873. $urlmask = $conf->global->CLICKTODIAL_URL;
  2874. }
  2875. if (!empty($user->clicktodial_url)) {
  2876. $urlmask = $user->clicktodial_url;
  2877. }
  2878. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2879. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2880. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2881. // This line is for backward compatibility
  2882. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2883. // Thoose lines are for substitution
  2884. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2885. '__PHONETO__'=>urlencode($phone),
  2886. '__LOGIN__'=>$clicktodial_login,
  2887. '__PASS__'=>$clicktodial_password);
  2888. $url = make_substitutions($url, $substitarray);
  2889. $newphonesav = $newphone;
  2890. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  2891. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  2892. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  2893. $newphone .= '>'.$newphonesav.'</a>';
  2894. } else {
  2895. // Old method
  2896. $newphone = '<a href="'.$url.'"';
  2897. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  2898. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  2899. }
  2900. $newphone .= '>'.$newphonesav.'</a>';
  2901. }
  2902. }
  2903. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2904. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2905. $type = 'AC_TEL';
  2906. $link = '';
  2907. if ($addlink == 'AC_FAX') {
  2908. $type = 'AC_FAX';
  2909. }
  2910. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  2911. $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>';
  2912. }
  2913. if ($link) {
  2914. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2915. }
  2916. }
  2917. }
  2918. if (empty($titlealt)) {
  2919. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2920. }
  2921. $rep = '';
  2922. if ($hookmanager) {
  2923. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2924. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2925. $rep .= $hookmanager->resPrint;
  2926. }
  2927. if (empty($reshook)) {
  2928. $picto = '';
  2929. if ($withpicto) {
  2930. if ($withpicto == 'fax') {
  2931. $picto = 'phoning_fax';
  2932. } elseif ($withpicto == 'phone') {
  2933. $picto = 'phoning';
  2934. } elseif ($withpicto == 'mobile') {
  2935. $picto = 'phoning_mobile';
  2936. } else {
  2937. $picto = '';
  2938. }
  2939. }
  2940. if ($adddivfloat) {
  2941. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2942. } else {
  2943. $rep .= '<span style="margin-right: 10px;">';
  2944. }
  2945. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2946. if ($adddivfloat) {
  2947. $rep .= '</div>';
  2948. } else {
  2949. $rep .= '</span>';
  2950. }
  2951. }
  2952. return $rep;
  2953. }
  2954. /**
  2955. * Return an IP formated to be shown on screen
  2956. *
  2957. * @param string $ip IP
  2958. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2959. * @return string Formated IP, with country if GeoIP module is enabled
  2960. */
  2961. function dol_print_ip($ip, $mode = 0)
  2962. {
  2963. global $conf, $langs;
  2964. $ret = '';
  2965. if (empty($mode)) {
  2966. $ret .= $ip;
  2967. }
  2968. if ($mode != 2) {
  2969. $countrycode = dolGetCountryCodeFromIp($ip);
  2970. if ($countrycode) { // If success, countrycode is us, fr, ...
  2971. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  2972. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2973. } else {
  2974. $ret .= ' ('.$countrycode.')';
  2975. }
  2976. } else {
  2977. // Nothing
  2978. }
  2979. }
  2980. return $ret;
  2981. }
  2982. /**
  2983. * Return the IP of remote user.
  2984. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2985. * Then HTTP_CLIENT_IP if defined (rare)
  2986. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2987. *
  2988. * @return string Ip of remote user.
  2989. */
  2990. function getUserRemoteIP()
  2991. {
  2992. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  2993. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  2994. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  2995. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  2996. } else {
  2997. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  2998. }
  2999. } else {
  3000. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3001. }
  3002. } else {
  3003. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3004. }
  3005. return $ip;
  3006. }
  3007. /**
  3008. * Return if we are using a HTTPS connexion
  3009. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3010. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3011. * Then HTTP_X_FORWARDED_SSL
  3012. *
  3013. * @return boolean True if user is using HTTPS
  3014. */
  3015. function isHTTPS()
  3016. {
  3017. $isSecure = false;
  3018. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3019. $isSecure = true;
  3020. } 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') {
  3021. $isSecure = true;
  3022. }
  3023. return $isSecure;
  3024. }
  3025. /**
  3026. * Return a country code from IP. Empty string if not found.
  3027. *
  3028. * @param string $ip IP
  3029. * @return string Country code ('us', 'fr', ...)
  3030. */
  3031. function dolGetCountryCodeFromIp($ip)
  3032. {
  3033. global $conf;
  3034. $countrycode = '';
  3035. if (!empty($conf->geoipmaxmind->enabled)) {
  3036. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3037. //$ip='24.24.24.24';
  3038. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3039. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3040. $geoip = new DolGeoIP('country', $datafile);
  3041. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3042. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3043. }
  3044. return $countrycode;
  3045. }
  3046. /**
  3047. * Return country code for current user.
  3048. * If software is used inside a local network, detection may fails (we need a public ip)
  3049. *
  3050. * @return string Country code (fr, es, it, us, ...)
  3051. */
  3052. function dol_user_country()
  3053. {
  3054. global $conf, $langs, $user;
  3055. //$ret=$user->xxx;
  3056. $ret = '';
  3057. if (!empty($conf->geoipmaxmind->enabled)) {
  3058. $ip = getUserRemoteIP();
  3059. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  3060. //$ip='24.24.24.24';
  3061. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3062. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3063. $geoip = new DolGeoIP('country', $datafile);
  3064. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3065. $ret = $countrycode;
  3066. }
  3067. return $ret;
  3068. }
  3069. /**
  3070. * Format address string
  3071. *
  3072. * @param string $address Address string, already formatted with dol_format_address()
  3073. * @param int $htmlid Html ID (for example 'gmap')
  3074. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3075. * @param int $id Id of object
  3076. * @param int $noprint No output. Result is the function return
  3077. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3078. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3079. * @see dol_format_address()
  3080. */
  3081. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3082. {
  3083. global $conf, $user, $langs, $hookmanager;
  3084. $out = '';
  3085. if ($address) {
  3086. if ($hookmanager) {
  3087. $parameters = array('element' => $element, 'id' => $id);
  3088. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3089. $out .= $hookmanager->resPrint;
  3090. }
  3091. if (empty($reshook)) {
  3092. if (empty($charfornl)) {
  3093. $out .= nl2br($address);
  3094. } else {
  3095. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3096. }
  3097. // TODO Remove this block, we can add this using the hook now
  3098. $showgmap = $showomap = 0;
  3099. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3100. $showgmap = 1;
  3101. }
  3102. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3103. $showgmap = 1;
  3104. }
  3105. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3106. $showgmap = 1;
  3107. }
  3108. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3109. $showomap = 1;
  3110. }
  3111. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3112. $showomap = 1;
  3113. }
  3114. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3115. $showomap = 1;
  3116. }
  3117. if ($showgmap) {
  3118. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3119. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3120. }
  3121. if ($showomap) {
  3122. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3123. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3124. }
  3125. }
  3126. }
  3127. if ($noprint) {
  3128. return $out;
  3129. } else {
  3130. print $out;
  3131. }
  3132. }
  3133. /**
  3134. * Return true if email syntax is ok.
  3135. *
  3136. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3137. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3138. * @return boolean true if email syntax is OK, false if KO or empty string
  3139. * @see isValidMXRecord()
  3140. */
  3141. function isValidEmail($address, $acceptsupervisorkey = 0)
  3142. {
  3143. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3144. return true;
  3145. }
  3146. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3147. return true;
  3148. }
  3149. return false;
  3150. }
  3151. /**
  3152. * Return if the domain name has a valid MX record.
  3153. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3154. *
  3155. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3156. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3157. * @see isValidEmail()
  3158. */
  3159. function isValidMXRecord($domain)
  3160. {
  3161. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3162. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3163. return 0;
  3164. }
  3165. if (function_exists('getmxrr')) {
  3166. $mxhosts = array();
  3167. $weight = array();
  3168. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3169. if (count($mxhosts) > 1) {
  3170. return 1;
  3171. }
  3172. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3173. return 1;
  3174. }
  3175. return 0;
  3176. }
  3177. }
  3178. return -1;
  3179. }
  3180. /**
  3181. * Return true if phone number syntax is ok
  3182. * TODO Decide what to do with this
  3183. *
  3184. * @param string $phone phone (Ex: "0601010101")
  3185. * @return boolean true if phone syntax is OK, false if KO or empty string
  3186. */
  3187. function isValidPhone($phone)
  3188. {
  3189. return true;
  3190. }
  3191. /**
  3192. * Make a strlen call. Works even if mbstring module not enabled
  3193. *
  3194. * @param string $string String to calculate length
  3195. * @param string $stringencoding Encoding of string
  3196. * @return int Length of string
  3197. */
  3198. function dol_strlen($string, $stringencoding = 'UTF-8')
  3199. {
  3200. if (function_exists('mb_strlen')) {
  3201. return mb_strlen($string, $stringencoding);
  3202. } else {
  3203. return strlen($string);
  3204. }
  3205. }
  3206. /**
  3207. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3208. *
  3209. * @param string $string String to scan
  3210. * @param string $start Start position
  3211. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3212. * @param string $stringencoding Page code used for input string encoding
  3213. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3214. * @return string substring
  3215. */
  3216. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3217. {
  3218. global $langs;
  3219. if (empty($stringencoding)) {
  3220. $stringencoding = $langs->charset_output;
  3221. }
  3222. $ret = '';
  3223. if (empty($trunconbytes)) {
  3224. if (function_exists('mb_substr')) {
  3225. $ret = mb_substr($string, $start, $length, $stringencoding);
  3226. } else {
  3227. $ret = substr($string, $start, $length);
  3228. }
  3229. } else {
  3230. if (function_exists('mb_strcut')) {
  3231. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3232. } else {
  3233. $ret = substr($string, $start, $length);
  3234. }
  3235. }
  3236. return $ret;
  3237. }
  3238. /**
  3239. * Truncate a string to a particular length adding '…' if string larger than length.
  3240. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3241. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3242. *
  3243. * @param string $string String to truncate
  3244. * @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 ...)
  3245. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3246. * @param string $stringencoding Tell what is source string encoding
  3247. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3248. * @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)
  3249. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3250. */
  3251. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3252. {
  3253. global $conf;
  3254. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3255. return $string;
  3256. }
  3257. if (empty($stringencoding)) {
  3258. $stringencoding = 'UTF-8';
  3259. }
  3260. // reduce for small screen
  3261. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3262. $size = round($size / 3);
  3263. }
  3264. // We go always here
  3265. if ($trunc == 'right') {
  3266. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3267. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3268. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3269. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3270. } else {
  3271. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3272. return $string;
  3273. }
  3274. } elseif ($trunc == 'middle') {
  3275. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3276. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3277. $size1 = round($size / 2);
  3278. $size2 = round($size / 2);
  3279. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3280. } else {
  3281. return $string;
  3282. }
  3283. } elseif ($trunc == 'left') {
  3284. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3285. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3286. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3287. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3288. } else {
  3289. return $string;
  3290. }
  3291. } elseif ($trunc == 'wrap') {
  3292. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3293. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3294. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3295. } else {
  3296. return $string;
  3297. }
  3298. } else {
  3299. return 'BadParam3CallingDolTrunc';
  3300. }
  3301. }
  3302. /**
  3303. * Show picto whatever it's its name (generic function)
  3304. *
  3305. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3306. * @param string $picto Name of image file to show ('filenew', ...)
  3307. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3308. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3309. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3310. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3311. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3312. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3313. * @param int $srconly Return only content of the src attribute of img.
  3314. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3315. * @param string $alt Force alt for bind people
  3316. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3317. * @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.
  3318. * @return string Return img tag
  3319. * @see img_object(), img_picto_common()
  3320. */
  3321. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3322. {
  3323. global $conf, $langs;
  3324. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3325. $url = DOL_URL_ROOT;
  3326. $theme = isset($conf->theme) ? $conf->theme : null;
  3327. $path = 'theme/'.$theme;
  3328. // Define fullpathpicto to use into src
  3329. if ($pictoisfullpath) {
  3330. // Clean parameters
  3331. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3332. $picto .= '.png';
  3333. }
  3334. $fullpathpicto = $picto;
  3335. $reg = array();
  3336. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3337. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3338. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3339. }
  3340. } else {
  3341. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3342. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3343. if (empty($srconly) && in_array($pictowithouttext, array(
  3344. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3345. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3346. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'bug', 'building',
  3347. 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3348. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3349. 'multicurrency',
  3350. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3351. 'edit', 'ellipsis-h', 'email', 'entity', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3352. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3353. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3354. 'help', 'holiday',
  3355. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3356. 'label', 'language', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3357. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3358. 'off', 'on', 'order',
  3359. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'stock', 'resize', 'service', 'stats', 'trip',
  3360. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  3361. 'github', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3362. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3363. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3364. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3365. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3366. 'technic', 'ticket',
  3367. 'error', 'warning',
  3368. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource', 'recurring',
  3369. 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3370. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3371. 'uncheck', 'user-cog', 'vat', 'website', 'workstation',
  3372. 'conferenceorbooth', 'eventorganization'
  3373. ))) {
  3374. $fakey = $pictowithouttext;
  3375. $facolor = '';
  3376. $fasize = '';
  3377. $fa = 'fas';
  3378. if (in_array($pictowithouttext, array('bell', 'clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3379. $fa = 'far';
  3380. }
  3381. if (in_array($pictowithouttext, array('black-tie', 'github', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3382. $fa = 'fab';
  3383. }
  3384. $arrayconvpictotofa = array(
  3385. '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',
  3386. 'bank_account'=>'university',
  3387. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3388. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3389. 'bom'=>'shapes',
  3390. 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3391. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3392. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3393. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3394. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3395. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3396. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3397. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3398. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3399. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'loan'=>'money-bill-alt',
  3400. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3401. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3402. 'sign-out'=>'sign-out-alt',
  3403. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3404. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3405. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3406. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3407. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3408. 'other'=>'square',
  3409. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3410. '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',
  3411. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3412. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3413. 'refresh'=>'redo', 'region'=>'map-marked', 'resource'=>'laptop-house', 'recurring'=>'history',
  3414. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3415. 'supplier'=>'building', 'technic'=>'cogs',
  3416. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3417. 'title_agenda'=>'calendar-alt',
  3418. 'uncheck'=>'times', 'uparrow'=>'share', 'vat'=>'money-check-alt', 'vcard'=>'address-card',
  3419. 'jabber'=>'comment-o',
  3420. 'website'=>'globe-americas', 'workstation'=>'pallet',
  3421. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3422. );
  3423. if ($pictowithouttext == 'off') {
  3424. $fakey = 'fa-square';
  3425. $fasize = '1.3em';
  3426. } elseif ($pictowithouttext == 'on') {
  3427. $fakey = 'fa-check-square';
  3428. $fasize = '1.3em';
  3429. } elseif ($pictowithouttext == 'listlight') {
  3430. $fakey = 'fa-download';
  3431. $marginleftonlyshort = 1;
  3432. } elseif ($pictowithouttext == 'printer') {
  3433. $fakey = 'fa-print';
  3434. $fasize = '1.2em';
  3435. } elseif ($pictowithouttext == 'note') {
  3436. $fakey = 'fa-sticky-note';
  3437. $marginleftonlyshort = 1;
  3438. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3439. $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');
  3440. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3441. if (preg_match('/selected/', $pictowithouttext)) {
  3442. $facolor = '#888';
  3443. }
  3444. $marginleftonlyshort = 1;
  3445. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3446. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3447. } else {
  3448. $fakey = 'fa-'.$pictowithouttext;
  3449. }
  3450. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3451. $morecss .= ' em092';
  3452. }
  3453. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3454. $morecss .= ' em088';
  3455. }
  3456. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3457. $morecss .= ' em080';
  3458. }
  3459. // Define $marginleftonlyshort
  3460. $arrayconvpictotomarginleftonly = array(
  3461. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3462. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3463. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3464. );
  3465. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3466. $marginleftonlyshort = 0;
  3467. }
  3468. // Add CSS
  3469. $arrayconvpictotomorcess = array(
  3470. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3471. 'bank_account'=>'bg-infobox-bank_account',
  3472. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3473. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3474. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3475. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3476. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3477. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3478. 'incoterm'=>'infobox-supplier_proposal',
  3479. 'multicurrency'=>'infobox-bank_account',
  3480. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3481. 'order'=>'infobox-commande',
  3482. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3483. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_red'=>'font-status8',
  3484. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3485. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3486. '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',
  3487. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3488. 'resource'=>'infobox-action',
  3489. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3490. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3491. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3492. 'vat'=>'infobox-bank_account',
  3493. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3494. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3495. );
  3496. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3497. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3498. }
  3499. // Define $color
  3500. $arrayconvpictotocolor = array(
  3501. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3502. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3503. 'dynamicprice'=>'#a69944',
  3504. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3505. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3506. 'lot'=>'#a69944',
  3507. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3508. 'other'=>'#ddd',
  3509. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3510. //'shipment'=>'#a69944',
  3511. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3512. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3513. 'website'=>'#304', 'workstation'=>'#a69944'
  3514. );
  3515. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3516. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3517. }
  3518. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3519. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3520. $morestyle = '';
  3521. $reg = array();
  3522. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3523. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3524. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3525. }
  3526. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3527. $morestyle = $reg[1];
  3528. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3529. }
  3530. $moreatt = trim($moreatt);
  3531. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3532. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3533. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3534. $enabledisablehtml .= $titlealt;
  3535. }*/
  3536. $enabledisablehtml .= '</span>';
  3537. return $enabledisablehtml;
  3538. }
  3539. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3540. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3541. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3542. $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
  3543. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3544. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3545. }
  3546. // If we ask an image into $url/$mymodule/img (instead of default path)
  3547. $regs = array();
  3548. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3549. $picto = $regs[1];
  3550. $path = $regs[2]; // $path is $mymodule
  3551. }
  3552. // Clean parameters
  3553. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3554. $picto .= '.png';
  3555. }
  3556. // If alt path are defined, define url where img file is, according to physical path
  3557. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3558. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3559. if ($type == 'main') {
  3560. continue;
  3561. }
  3562. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3563. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3564. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3565. break;
  3566. }
  3567. }
  3568. // $url is '' or '/custom', $path is current theme or
  3569. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3570. }
  3571. if ($srconly) {
  3572. return $fullpathpicto;
  3573. }
  3574. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3575. 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
  3576. }
  3577. /**
  3578. * Show a picto called object_picto (generic function)
  3579. *
  3580. * @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.
  3581. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3582. * For external modules use imagename@mymodule to search into directory "img" of module.
  3583. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3584. * @param int $pictoisfullpath If 1, image path is a full path
  3585. * @param int $srconly Return only content of the src attribute of img.
  3586. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3587. * @return string Return img tag
  3588. * @see img_picto(), img_picto_common()
  3589. */
  3590. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3591. {
  3592. if (strpos($picto, '^') === 0) {
  3593. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3594. } else {
  3595. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3596. }
  3597. }
  3598. /**
  3599. * Show weather picto
  3600. *
  3601. * @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.
  3602. * @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).
  3603. * @param string $moreatt Add more attribute on img tag
  3604. * @param int $pictoisfullpath If 1, image path is a full path
  3605. * @param string $morecss More CSS
  3606. * @return string Return img tag
  3607. * @see img_object(), img_picto()
  3608. */
  3609. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3610. {
  3611. global $conf;
  3612. if (is_numeric($picto)) {
  3613. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3614. //$picto = $leveltopicto[$picto];
  3615. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3616. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3617. $picto .= '.png';
  3618. }
  3619. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3620. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3621. }
  3622. /**
  3623. * Show picto (generic function)
  3624. *
  3625. * @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.
  3626. * @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.
  3627. * @param string $moreatt Add more attribute on img tag
  3628. * @param int $pictoisfullpath If 1, image path is a full path
  3629. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3630. * @return string Return img tag
  3631. * @see img_object(), img_picto()
  3632. */
  3633. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  3634. {
  3635. global $conf;
  3636. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3637. $picto .= '.png';
  3638. }
  3639. if ($pictoisfullpath) {
  3640. $path = $picto;
  3641. } else {
  3642. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3643. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3644. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3645. if (file_exists($themepath)) {
  3646. $path = $themepath;
  3647. }
  3648. }
  3649. }
  3650. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  3651. }
  3652. /**
  3653. * Show logo action
  3654. *
  3655. * @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.
  3656. * @param string $numaction Action id or code to show
  3657. * @param string $picto Name of image file to show ('filenew', ...)
  3658. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3659. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3660. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3661. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3662. * @return string Return an img tag
  3663. */
  3664. function img_action($titlealt, $numaction, $picto = '')
  3665. {
  3666. global $langs;
  3667. if (empty($titlealt) || $titlealt == 'default') {
  3668. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3669. $numaction = -1;
  3670. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3671. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3672. $numaction = 0;
  3673. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3674. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3675. $numaction = 1;
  3676. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3677. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3678. $numaction = 2;
  3679. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3680. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3681. $numaction = 3;
  3682. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3683. } else {
  3684. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3685. $numaction = 0;
  3686. }
  3687. }
  3688. if (!is_numeric($numaction)) {
  3689. $numaction = 0;
  3690. }
  3691. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3692. }
  3693. /**
  3694. * Show pdf logo
  3695. *
  3696. * @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.
  3697. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3698. * @return string Retourne tag img
  3699. */
  3700. function img_pdf($titlealt = 'default', $size = 3)
  3701. {
  3702. global $langs;
  3703. if ($titlealt == 'default') {
  3704. $titlealt = $langs->trans('Show');
  3705. }
  3706. return img_picto($titlealt, 'pdf'.$size.'.png');
  3707. }
  3708. /**
  3709. * Show logo +
  3710. *
  3711. * @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.
  3712. * @param string $other Add more attributes on img
  3713. * @return string Return tag img
  3714. */
  3715. function img_edit_add($titlealt = 'default', $other = '')
  3716. {
  3717. global $langs;
  3718. if ($titlealt == 'default') {
  3719. $titlealt = $langs->trans('Add');
  3720. }
  3721. return img_picto($titlealt, 'edit_add.png', $other);
  3722. }
  3723. /**
  3724. * Show logo -
  3725. *
  3726. * @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.
  3727. * @param string $other Add more attributes on img
  3728. * @return string Return tag img
  3729. */
  3730. function img_edit_remove($titlealt = 'default', $other = '')
  3731. {
  3732. global $langs;
  3733. if ($titlealt == 'default') {
  3734. $titlealt = $langs->trans('Remove');
  3735. }
  3736. return img_picto($titlealt, 'edit_remove.png', $other);
  3737. }
  3738. /**
  3739. * Show logo editer/modifier fiche
  3740. *
  3741. * @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.
  3742. * @param integer $float If you have to put the style "float: right"
  3743. * @param string $other Add more attributes on img
  3744. * @return string Return tag img
  3745. */
  3746. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3747. {
  3748. global $langs;
  3749. if ($titlealt == 'default') {
  3750. $titlealt = $langs->trans('Modify');
  3751. }
  3752. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3753. }
  3754. /**
  3755. * Show logo view card
  3756. *
  3757. * @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.
  3758. * @param integer $float If you have to put the style "float: right"
  3759. * @param string $other Add more attributes on img
  3760. * @return string Return tag img
  3761. */
  3762. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  3763. {
  3764. global $langs;
  3765. if ($titlealt == 'default') {
  3766. $titlealt = $langs->trans('View');
  3767. }
  3768. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3769. return img_picto($titlealt, 'view.png', $moreatt);
  3770. }
  3771. /**
  3772. * Show delete logo
  3773. *
  3774. * @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.
  3775. * @param string $other Add more attributes on img
  3776. * @param string $morecss More CSS
  3777. * @return string Retourne tag img
  3778. */
  3779. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3780. {
  3781. global $langs;
  3782. if ($titlealt == 'default') {
  3783. $titlealt = $langs->trans('Delete');
  3784. }
  3785. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3786. }
  3787. /**
  3788. * Show printer logo
  3789. *
  3790. * @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.
  3791. * @param string $other Add more attributes on img
  3792. * @return string Retourne tag img
  3793. */
  3794. function img_printer($titlealt = "default", $other = '')
  3795. {
  3796. global $langs;
  3797. if ($titlealt == "default") {
  3798. $titlealt = $langs->trans("Print");
  3799. }
  3800. return img_picto($titlealt, 'printer.png', $other);
  3801. }
  3802. /**
  3803. * Show split logo
  3804. *
  3805. * @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.
  3806. * @param string $other Add more attributes on img
  3807. * @return string Retourne tag img
  3808. */
  3809. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3810. {
  3811. global $langs;
  3812. if ($titlealt == 'default') {
  3813. $titlealt = $langs->trans('Split');
  3814. }
  3815. return img_picto($titlealt, 'split.png', $other);
  3816. }
  3817. /**
  3818. * Show help logo with cursor "?"
  3819. *
  3820. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3821. * @param int|string $usealttitle Text to use as alt title
  3822. * @return string Return tag img
  3823. */
  3824. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3825. {
  3826. global $langs;
  3827. if ($usealttitle) {
  3828. if (is_string($usealttitle)) {
  3829. $usealttitle = dol_escape_htmltag($usealttitle);
  3830. } else {
  3831. $usealttitle = $langs->trans('Info');
  3832. }
  3833. }
  3834. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3835. }
  3836. /**
  3837. * Show info logo
  3838. *
  3839. * @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.
  3840. * @return string Return img tag
  3841. */
  3842. function img_info($titlealt = 'default')
  3843. {
  3844. global $langs;
  3845. if ($titlealt == 'default') {
  3846. $titlealt = $langs->trans('Informations');
  3847. }
  3848. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3849. }
  3850. /**
  3851. * Show warning logo
  3852. *
  3853. * @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.
  3854. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3855. * @param string $morecss Add more CSS
  3856. * @return string Return img tag
  3857. */
  3858. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3859. {
  3860. global $langs;
  3861. if ($titlealt == 'default') {
  3862. $titlealt = $langs->trans('Warning');
  3863. }
  3864. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3865. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3866. }
  3867. /**
  3868. * Show error logo
  3869. *
  3870. * @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.
  3871. * @return string Return img tag
  3872. */
  3873. function img_error($titlealt = 'default')
  3874. {
  3875. global $langs;
  3876. if ($titlealt == 'default') {
  3877. $titlealt = $langs->trans('Error');
  3878. }
  3879. return img_picto($titlealt, 'error.png');
  3880. }
  3881. /**
  3882. * Show next logo
  3883. *
  3884. * @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.
  3885. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3886. * @return string Return img tag
  3887. */
  3888. function img_next($titlealt = 'default', $moreatt = '')
  3889. {
  3890. global $langs;
  3891. if ($titlealt == 'default') {
  3892. $titlealt = $langs->trans('Next');
  3893. }
  3894. //return img_picto($titlealt, 'next.png', $moreatt);
  3895. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3896. }
  3897. /**
  3898. * Show previous logo
  3899. *
  3900. * @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.
  3901. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3902. * @return string Return img tag
  3903. */
  3904. function img_previous($titlealt = 'default', $moreatt = '')
  3905. {
  3906. global $langs;
  3907. if ($titlealt == 'default') {
  3908. $titlealt = $langs->trans('Previous');
  3909. }
  3910. //return img_picto($titlealt, 'previous.png', $moreatt);
  3911. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3912. }
  3913. /**
  3914. * Show down arrow logo
  3915. *
  3916. * @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.
  3917. * @param int $selected Selected
  3918. * @param string $moreclass Add more CSS classes
  3919. * @return string Return img tag
  3920. */
  3921. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3922. {
  3923. global $langs;
  3924. if ($titlealt == 'default') {
  3925. $titlealt = $langs->trans('Down');
  3926. }
  3927. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3928. }
  3929. /**
  3930. * Show top arrow logo
  3931. *
  3932. * @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.
  3933. * @param int $selected Selected
  3934. * @param string $moreclass Add more CSS classes
  3935. * @return string Return img tag
  3936. */
  3937. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3938. {
  3939. global $langs;
  3940. if ($titlealt == 'default') {
  3941. $titlealt = $langs->trans('Up');
  3942. }
  3943. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3944. }
  3945. /**
  3946. * Show left arrow logo
  3947. *
  3948. * @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.
  3949. * @param int $selected Selected
  3950. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3951. * @return string Return img tag
  3952. */
  3953. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3954. {
  3955. global $langs;
  3956. if ($titlealt == 'default') {
  3957. $titlealt = $langs->trans('Left');
  3958. }
  3959. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3960. }
  3961. /**
  3962. * Show right arrow logo
  3963. *
  3964. * @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.
  3965. * @param int $selected Selected
  3966. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3967. * @return string Return img tag
  3968. */
  3969. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3970. {
  3971. global $langs;
  3972. if ($titlealt == 'default') {
  3973. $titlealt = $langs->trans('Right');
  3974. }
  3975. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3976. }
  3977. /**
  3978. * Show tick logo if allowed
  3979. *
  3980. * @param string $allow Allow
  3981. * @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.
  3982. * @return string Return img tag
  3983. */
  3984. function img_allow($allow, $titlealt = 'default')
  3985. {
  3986. global $langs;
  3987. if ($titlealt == 'default') {
  3988. $titlealt = $langs->trans('Active');
  3989. }
  3990. if ($allow == 1) {
  3991. return img_picto($titlealt, 'tick.png');
  3992. }
  3993. return '-';
  3994. }
  3995. /**
  3996. * Return image of a credit card according to its brand name
  3997. *
  3998. * @param string $brand Brand name of credit card
  3999. * @param string $morecss More CSS
  4000. * @return string Return img tag
  4001. */
  4002. function img_credit_card($brand, $morecss = null)
  4003. {
  4004. if (is_null($morecss)) {
  4005. $morecss = 'fa-2x';
  4006. }
  4007. if ($brand == 'visa' || $brand == 'Visa') {
  4008. $brand = 'cc-visa';
  4009. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4010. $brand = 'cc-mastercard';
  4011. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4012. $brand = 'cc-amex';
  4013. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4014. $brand = 'cc-discover';
  4015. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4016. $brand = 'cc-jcb';
  4017. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4018. $brand = 'cc-diners-club';
  4019. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4020. $brand = 'credit-card';
  4021. }
  4022. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4023. }
  4024. /**
  4025. * Show MIME img of a file
  4026. *
  4027. * @param string $file Filename
  4028. * @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.
  4029. * @param string $morecss More css
  4030. * @return string Return img tag
  4031. */
  4032. function img_mime($file, $titlealt = '', $morecss = '')
  4033. {
  4034. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4035. $mimetype = dol_mimetype($file, '', 1);
  4036. $mimeimg = dol_mimetype($file, '', 2);
  4037. $mimefa = dol_mimetype($file, '', 4);
  4038. if (empty($titlealt)) {
  4039. $titlealt = 'Mime type: '.$mimetype;
  4040. }
  4041. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4042. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4043. }
  4044. /**
  4045. * Show search logo
  4046. *
  4047. * @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.
  4048. * @param string $other Add more attributes on img
  4049. * @return string Retourne tag img
  4050. */
  4051. function img_search($titlealt = 'default', $other = '')
  4052. {
  4053. global $conf, $langs;
  4054. if ($titlealt == 'default') {
  4055. $titlealt = $langs->trans('Search');
  4056. }
  4057. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4058. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4059. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4060. return $input;
  4061. }
  4062. /**
  4063. * Show search logo
  4064. *
  4065. * @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.
  4066. * @param string $other Add more attributes on img
  4067. * @return string Retourne tag img
  4068. */
  4069. function img_searchclear($titlealt = 'default', $other = '')
  4070. {
  4071. global $conf, $langs;
  4072. if ($titlealt == 'default') {
  4073. $titlealt = $langs->trans('Search');
  4074. }
  4075. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4076. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4077. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4078. return $input;
  4079. }
  4080. /**
  4081. * Show information for admin users or standard users
  4082. *
  4083. * @param string $text Text info
  4084. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4085. * @param int $nodiv No div
  4086. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4087. * @param string $morecss More CSS ('', 'warning', 'error')
  4088. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4089. * @return string String with info text
  4090. */
  4091. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  4092. {
  4093. global $conf, $langs;
  4094. if ($infoonimgalt) {
  4095. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  4096. } else {
  4097. if (empty($conf->use_javascript_ajax)) {
  4098. $textfordropdown = '';
  4099. }
  4100. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4101. $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>');
  4102. if ($textfordropdown) {
  4103. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4104. $tmpresult .= '<script type="text/javascript">
  4105. jQuery(document).ready(function() {
  4106. jQuery(".'.$class.'text").click(function() {
  4107. console.log("toggle text");
  4108. jQuery(".'.$class.'").toggle();
  4109. });
  4110. });
  4111. </script>';
  4112. $result = $tmpresult.$result;
  4113. }
  4114. }
  4115. return $result;
  4116. }
  4117. /**
  4118. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4119. * This function must be called when a blocking technical error is encountered.
  4120. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4121. *
  4122. * @param DoliDB|string $db Database handler
  4123. * @param string|string[] $error String or array of errors strings to show
  4124. * @param array $errors Array of errors
  4125. * @return void
  4126. * @see dol_htmloutput_errors()
  4127. */
  4128. function dol_print_error($db = '', $error = '', $errors = null)
  4129. {
  4130. global $conf, $langs, $argv;
  4131. global $dolibarr_main_prod;
  4132. $out = '';
  4133. $syslog = '';
  4134. // If error occurs before the $lang object was loaded
  4135. if (!$langs) {
  4136. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4137. $langs = new Translate('', $conf);
  4138. $langs->load("main");
  4139. }
  4140. // Load translation files required by the error messages
  4141. $langs->loadLangs(array('main', 'errors'));
  4142. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4143. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4144. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4145. $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";
  4146. }
  4147. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4148. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4149. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4150. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4151. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4152. }
  4153. if (function_exists("phpversion")) {
  4154. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4155. }
  4156. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4157. if (function_exists("php_uname")) {
  4158. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4159. }
  4160. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4161. $out .= "<br>\n";
  4162. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4163. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4164. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4165. $out .= "<br>\n";
  4166. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4167. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4168. } else // Mode CLI
  4169. {
  4170. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4171. $syslog .= "pid=".dol_getmypid();
  4172. }
  4173. if (!empty($conf->modules)) {
  4174. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4175. }
  4176. if (is_object($db)) {
  4177. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4178. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4179. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4180. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4181. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4182. $out .= "<br>\n";
  4183. } else // Mode CLI
  4184. {
  4185. // No dol_escape_htmltag for output, we are in CLI mode
  4186. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4187. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4188. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4189. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4190. }
  4191. $syslog .= ", sql=".$db->lastquery();
  4192. $syslog .= ", db_error=".$db->lasterror();
  4193. }
  4194. if ($error || $errors) {
  4195. $langs->load("errors");
  4196. // Merge all into $errors array
  4197. if (is_array($error) && is_array($errors)) {
  4198. $errors = array_merge($error, $errors);
  4199. } elseif (is_array($error)) {
  4200. $errors = $error;
  4201. } elseif (is_array($errors)) {
  4202. $errors = array_merge(array($error), $errors);
  4203. } else {
  4204. $errors = array_merge(array($error));
  4205. }
  4206. foreach ($errors as $msg) {
  4207. if (empty($msg)) {
  4208. continue;
  4209. }
  4210. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4211. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4212. } else // Mode CLI
  4213. {
  4214. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4215. }
  4216. $syslog .= ", msg=".$msg;
  4217. }
  4218. }
  4219. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4220. xdebug_print_function_stack();
  4221. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4222. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4223. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4224. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4225. $out .= "<br>\n";
  4226. }
  4227. // Return a http error code if possible
  4228. if (!headers_sent()) {
  4229. http_response_code(500);
  4230. }
  4231. if (empty($dolibarr_main_prod)) {
  4232. print $out;
  4233. } else {
  4234. if (empty($langs->defaultlang)) {
  4235. $langs->setDefaultLang();
  4236. }
  4237. $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.
  4238. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4239. 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";
  4240. print $langs->trans("DolibarrHasDetectedError").'. ';
  4241. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4242. define("MAIN_CORE_ERROR", 1);
  4243. }
  4244. dol_syslog("Error ".$syslog, LOG_ERR);
  4245. }
  4246. /**
  4247. * Show a public email and error code to contact if technical error
  4248. *
  4249. * @param string $prefixcode Prefix of public error code
  4250. * @param string $errormessage Complete error message
  4251. * @param array $errormessages Array of error messages
  4252. * @param string $morecss More css
  4253. * @param string $email Email
  4254. * @return void
  4255. */
  4256. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4257. {
  4258. global $langs, $conf;
  4259. if (empty($email)) {
  4260. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4261. }
  4262. $langs->load("errors");
  4263. $now = dol_now();
  4264. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4265. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4266. if ($errormessage) {
  4267. print '<br><br>'.$errormessage;
  4268. }
  4269. if (is_array($errormessages) && count($errormessages)) {
  4270. foreach ($errormessages as $mesgtoshow) {
  4271. print '<br><br>'.$mesgtoshow;
  4272. }
  4273. }
  4274. print '</div></div>';
  4275. }
  4276. /**
  4277. * Show title line of an array
  4278. *
  4279. * @param string $name Label of field
  4280. * @param string $file Url used when we click on sort picto
  4281. * @param string $field Field to use for new sorting
  4282. * @param string $begin ("" by defaut)
  4283. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4284. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  4285. * @param string $sortfield Current field used to sort
  4286. * @param string $sortorder Current sort order
  4287. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4288. * @param string $tooltip Tooltip
  4289. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4290. * @return void
  4291. */
  4292. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4293. {
  4294. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4295. }
  4296. /**
  4297. * Get title line of an array
  4298. *
  4299. * @param string $name Translation key of field to show or complete HTML string to show
  4300. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4301. * @param string $file Url used when we click on sort picto
  4302. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4303. * @param string $begin ("" by defaut)
  4304. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4305. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  4306. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4307. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4308. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4309. * @param string $disablesortlink 1=Disable sort link
  4310. * @param string $tooltip Tooltip
  4311. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4312. * @return string
  4313. */
  4314. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4315. {
  4316. global $conf, $langs, $form;
  4317. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4318. if ($moreattrib == 'class="right"') {
  4319. $prefix .= 'right '; // For backward compatibility
  4320. }
  4321. $sortorder = strtoupper($sortorder);
  4322. $out = '';
  4323. $sortimg = '';
  4324. $tag = 'th';
  4325. if ($thead == 2) {
  4326. $tag = 'div';
  4327. }
  4328. $tmpsortfield = explode(',', $sortfield);
  4329. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4330. $tmpfield = explode(',', $field);
  4331. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4332. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4333. $prefix = 'wrapcolumntitle '.$prefix;
  4334. }
  4335. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4336. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4337. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4338. $liste_titre = 'liste_titre';
  4339. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4340. $liste_titre = 'liste_titre_sel';
  4341. }
  4342. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4343. //$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)).'"' : '');
  4344. $out .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4345. $out .= '>';
  4346. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4347. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4348. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4349. $options = preg_replace('/&+/i', '&', $options);
  4350. if (!preg_match('/^&/', $options)) {
  4351. $options = '&'.$options;
  4352. }
  4353. $sortordertouseinlink = '';
  4354. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4355. if (preg_match('/^DESC/i', $sortorder)) {
  4356. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4357. } else // We reverse the var $sortordertouseinlink
  4358. {
  4359. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4360. }
  4361. } else // We are on field that is the first current sorting criteria
  4362. {
  4363. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4364. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4365. } else {
  4366. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4367. }
  4368. }
  4369. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4370. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4371. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4372. $out .= '>';
  4373. }
  4374. if ($tooltip) {
  4375. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4376. $tmptooltip = explode(':', $tooltip);
  4377. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4378. } else {
  4379. $out .= $langs->trans($name);
  4380. }
  4381. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4382. $out .= '</a>';
  4383. }
  4384. if (empty($thead) && $field) { // If this is a sort field
  4385. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4386. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4387. $options = preg_replace('/&+/i', '&', $options);
  4388. if (!preg_match('/^&/', $options)) {
  4389. $options = '&'.$options;
  4390. }
  4391. if (!$sortorder || $field1 != $sortfield1) {
  4392. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4393. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4394. } else {
  4395. if (preg_match('/^DESC/', $sortorder)) {
  4396. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4397. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4398. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  4399. }
  4400. if (preg_match('/^ASC/', $sortorder)) {
  4401. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4402. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4403. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  4404. }
  4405. }
  4406. }
  4407. $out .= $sortimg;
  4408. $out .= '</'.$tag.'>';
  4409. return $out;
  4410. }
  4411. /**
  4412. * Show a title.
  4413. *
  4414. * @param string $title Title to show
  4415. * @return void
  4416. * @deprecated Use load_fiche_titre instead
  4417. * @see load_fiche_titre()
  4418. */
  4419. function print_titre($title)
  4420. {
  4421. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4422. print '<div class="titre">'.$title.'</div>';
  4423. }
  4424. /**
  4425. * Show a title with picto
  4426. *
  4427. * @param string $title Title to show
  4428. * @param string $mesg Added message to show on right
  4429. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4430. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4431. * @param int $id To force an id on html objects
  4432. * @return void
  4433. * @deprecated Use print load_fiche_titre instead
  4434. */
  4435. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4436. {
  4437. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4438. }
  4439. /**
  4440. * Load a title with picto
  4441. *
  4442. * @param string $titre Title to show
  4443. * @param string $morehtmlright Added message to show on right
  4444. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4445. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4446. * @param string $id To force an id on html objects
  4447. * @param string $morecssontable More css on table
  4448. * @param string $morehtmlcenter Added message to show on center
  4449. * @return string
  4450. * @see print_barre_liste()
  4451. */
  4452. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4453. {
  4454. global $conf;
  4455. $return = '';
  4456. if ($picto == 'setup') {
  4457. $picto = 'generic';
  4458. }
  4459. $return .= "\n";
  4460. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4461. $return .= '<tr class="titre">';
  4462. if ($picto) {
  4463. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4464. }
  4465. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4466. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4467. $return .= '</td>';
  4468. if (dol_strlen($morehtmlcenter)) {
  4469. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4470. }
  4471. if (dol_strlen($morehtmlright)) {
  4472. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4473. }
  4474. $return .= '</tr></table>'."\n";
  4475. return $return;
  4476. }
  4477. /**
  4478. * Print a title with navigation controls for pagination
  4479. *
  4480. * @param string $titre Title to show (required)
  4481. * @param int $page Numero of page to show in navigation links (required)
  4482. * @param string $file Url of page (required)
  4483. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4484. * @param string $sortfield Field to sort on ('' by default)
  4485. * @param string $sortorder Order to sort ('' by default)
  4486. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4487. * @param int $num Number of records found by select with limit+1
  4488. * @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.
  4489. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4490. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4491. * @param string $morehtmlright More html to show (after arrows)
  4492. * @param string $morecss More css to the table
  4493. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4494. * @param int $hideselectlimit Force to hide select limit
  4495. * @param int $hidenavigation Force to hide all navigation tools
  4496. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4497. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4498. * @return void
  4499. */
  4500. 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 = '')
  4501. {
  4502. global $conf, $langs;
  4503. $savlimit = $limit;
  4504. $savtotalnboflines = $totalnboflines;
  4505. $totalnboflines = abs((int) $totalnboflines);
  4506. if ($picto == 'setup') {
  4507. $picto = 'title_setup.png';
  4508. }
  4509. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4510. $picto = 'title.gif';
  4511. }
  4512. if ($limit < 0) {
  4513. $limit = $conf->liste_limit;
  4514. }
  4515. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4516. $nextpage = 1;
  4517. } else {
  4518. $nextpage = 0;
  4519. }
  4520. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4521. print "\n";
  4522. print "<!-- Begin title -->\n";
  4523. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4524. // Left
  4525. if ($picto && $titre) {
  4526. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4527. }
  4528. print '<td class="nobordernopadding valignmiddle col-title">';
  4529. print '<div class="titre inline-block">'.$titre;
  4530. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4531. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4532. }
  4533. print '</div></td>';
  4534. // Center
  4535. if ($morehtmlcenter) {
  4536. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4537. }
  4538. // Right
  4539. print '<td class="nobordernopadding valignmiddle right">';
  4540. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4541. if ($sortfield) {
  4542. $options .= "&sortfield=".urlencode($sortfield);
  4543. }
  4544. if ($sortorder) {
  4545. $options .= "&sortorder=".urlencode($sortorder);
  4546. }
  4547. // Show navigation bar
  4548. $pagelist = '';
  4549. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4550. if ($totalnboflines) { // If we know total nb of lines
  4551. // Define nb of extra page links before and after selected page + ... + first or last
  4552. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4553. if ($limit > 0) {
  4554. $nbpages = ceil($totalnboflines / $limit);
  4555. } else {
  4556. $nbpages = 1;
  4557. }
  4558. $cpt = ($page - $maxnbofpage);
  4559. if ($cpt < 0) {
  4560. $cpt = 0;
  4561. }
  4562. if ($cpt >= 1) {
  4563. if (empty($pagenavastextinput)) {
  4564. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4565. if ($cpt > 2) {
  4566. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4567. } elseif ($cpt == 2) {
  4568. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4569. }
  4570. }
  4571. }
  4572. do {
  4573. if ($pagenavastextinput) {
  4574. if ($cpt == $page) {
  4575. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4576. $pagelist .= '/';
  4577. }
  4578. } else {
  4579. if ($cpt == $page) {
  4580. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4581. } else {
  4582. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4583. }
  4584. }
  4585. $cpt++;
  4586. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4587. if (empty($pagenavastextinput)) {
  4588. if ($cpt < $nbpages) {
  4589. if ($cpt < $nbpages - 2) {
  4590. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4591. } elseif ($cpt == $nbpages - 2) {
  4592. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4593. }
  4594. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4595. }
  4596. } else {
  4597. //var_dump($page.' '.$cpt.' '.$nbpages);
  4598. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4599. }
  4600. } else {
  4601. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4602. }
  4603. }
  4604. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4605. 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
  4606. }
  4607. // js to autoselect page field on focus
  4608. if ($pagenavastextinput) {
  4609. print ajax_autoselect('.pageplusone');
  4610. }
  4611. print '</td>';
  4612. print '</tr></table>'."\n";
  4613. print "<!-- End title -->\n\n";
  4614. }
  4615. /**
  4616. * Function to show navigation arrows into lists
  4617. *
  4618. * @param int $page Number of page
  4619. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4620. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4621. * @param integer $nextpage Do we show a next page button
  4622. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4623. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4624. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4625. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4626. * @param int $hideselectlimit Force to hide select limit
  4627. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4628. * @return void
  4629. */
  4630. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4631. {
  4632. global $conf, $langs;
  4633. print '<div class="pagination"><ul>';
  4634. if ($beforearrows) {
  4635. print '<li class="paginationbeforearrows">';
  4636. print $beforearrows;
  4637. print '</li>';
  4638. }
  4639. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4640. $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';
  4641. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4642. //$pagesizechoices.=',2:2';
  4643. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4644. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4645. }
  4646. print '<li class="pagination">';
  4647. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4648. $tmpchoice = explode(',', $pagesizechoices);
  4649. $tmpkey = $limit.':'.$limit;
  4650. if (!in_array($tmpkey, $tmpchoice)) {
  4651. $tmpchoice[] = $tmpkey;
  4652. }
  4653. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4654. if (!in_array($tmpkey, $tmpchoice)) {
  4655. $tmpchoice[] = $tmpkey;
  4656. }
  4657. asort($tmpchoice, SORT_NUMERIC);
  4658. foreach ($tmpchoice as $val) {
  4659. $selected = '';
  4660. $tmp = explode(':', $val);
  4661. $key = $tmp[0];
  4662. $val = $tmp[1];
  4663. if ($key != '' && $val != '') {
  4664. if ((int) $key == (int) $limit) {
  4665. $selected = ' selected="selected"';
  4666. }
  4667. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4668. }
  4669. }
  4670. print '</select>';
  4671. if ($conf->use_javascript_ajax) {
  4672. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4673. <script>
  4674. jQuery(document).ready(function () {
  4675. jQuery(".selectlimit").change(function() {
  4676. console.log("Change limit. Send submit");
  4677. $(this).parents(\'form:first\').submit();
  4678. });
  4679. });
  4680. </script>
  4681. ';
  4682. }
  4683. print '</li>';
  4684. }
  4685. if ($page > 0) {
  4686. 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>';
  4687. }
  4688. if ($betweenarrows) {
  4689. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4690. print $betweenarrows;
  4691. print '<!--</div>-->';
  4692. }
  4693. if ($nextpage > 0) {
  4694. 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>';
  4695. }
  4696. if ($afterarrows) {
  4697. print '<li class="paginationafterarrows">';
  4698. print $afterarrows;
  4699. print '</li>';
  4700. }
  4701. print '</ul></div>'."\n";
  4702. }
  4703. /**
  4704. * Return a string with VAT rate label formated for view output
  4705. * Used into pdf and HTML pages
  4706. *
  4707. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4708. * @param boolean $addpercent Add a percent % sign in output
  4709. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4710. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4711. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4712. */
  4713. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4714. {
  4715. $morelabel = '';
  4716. if (preg_match('/%/', $rate)) {
  4717. $rate = str_replace('%', '', $rate);
  4718. $addpercent = true;
  4719. }
  4720. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  4721. $morelabel = ' ('.$reg[1].')';
  4722. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4723. }
  4724. if (preg_match('/\*/', $rate)) {
  4725. $rate = str_replace('*', '', $rate);
  4726. $info_bits |= 1;
  4727. }
  4728. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4729. if (!preg_match('/\//', $rate)) {
  4730. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4731. } else {
  4732. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4733. $ret = $rate.($addpercent ? '%' : '');
  4734. }
  4735. if (($info_bits & 1) && $usestarfornpr >= 0) {
  4736. $ret .= ' *';
  4737. }
  4738. $ret .= $morelabel;
  4739. return $ret;
  4740. }
  4741. /**
  4742. * Function to format a value into an amount for visual output
  4743. * Function used into PDF and HTML pages
  4744. *
  4745. * @param float $amount Amount to format
  4746. * @param integer $form Type of format, HTML or not (not by default)
  4747. * @param Translate|string $outlangs Object langs for output
  4748. * @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.
  4749. * @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)
  4750. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4751. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4752. * @return string String with formated amount
  4753. *
  4754. * @see price2num() Revert function of price
  4755. */
  4756. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4757. {
  4758. global $langs, $conf;
  4759. // Clean parameters
  4760. if (empty($amount)) {
  4761. $amount = 0; // To have a numeric value if amount not defined or = ''
  4762. }
  4763. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4764. if ($rounding < 0) {
  4765. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4766. }
  4767. $nbdecimal = $rounding;
  4768. // Output separators by default (french)
  4769. $dec = ',';
  4770. $thousand = ' ';
  4771. // If $outlangs not forced, we use use language
  4772. if (!is_object($outlangs)) {
  4773. $outlangs = $langs;
  4774. }
  4775. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4776. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4777. }
  4778. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4779. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4780. }
  4781. if ($thousand == 'None') {
  4782. $thousand = '';
  4783. } elseif ($thousand == 'Space') {
  4784. $thousand = ' ';
  4785. }
  4786. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4787. //print "amount=".$amount."-";
  4788. $amount = str_replace(',', '.', $amount); // should be useless
  4789. //print $amount."-";
  4790. $datas = explode('.', $amount);
  4791. $decpart = isset($datas[1]) ? $datas[1] : '';
  4792. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4793. //print "decpart=".$decpart."<br>";
  4794. $end = '';
  4795. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4796. if (dol_strlen($decpart) > $nbdecimal) {
  4797. $nbdecimal = dol_strlen($decpart);
  4798. }
  4799. // Si on depasse max
  4800. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  4801. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4802. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  4803. // Si un affichage est tronque, on montre des ...
  4804. $end = '...';
  4805. }
  4806. }
  4807. // If force rounding
  4808. if ($forcerounding >= 0) {
  4809. $nbdecimal = $forcerounding;
  4810. }
  4811. // Format number
  4812. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4813. if ($form) {
  4814. $output = preg_replace('/\s/', '&nbsp;', $output);
  4815. $output = preg_replace('/\'/', '&#039;', $output);
  4816. }
  4817. // Add symbol of currency if requested
  4818. $cursymbolbefore = $cursymbolafter = '';
  4819. if ($currency_code) {
  4820. if ($currency_code == 'auto') {
  4821. $currency_code = $conf->currency;
  4822. }
  4823. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4824. $listoflanguagesbefore = array('nl_NL');
  4825. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  4826. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4827. } else {
  4828. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4829. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4830. }
  4831. }
  4832. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4833. return $output;
  4834. }
  4835. /**
  4836. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4837. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4838. * should be roundtext2num().
  4839. *
  4840. * @param string|float $amount Amount to convert/clean or round
  4841. * @param string|int $rounding ''=No rounding
  4842. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4843. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4844. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4845. * 'CU'=Round to Max unit price of foreign currency accuracy
  4846. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  4847. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  4848. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4849. * Put 2 if you know that number is a user input (so we know we don't have to fix decimal separator).
  4850. * @return string Amount with universal numeric format (Example: '99.99999').
  4851. * If conversion fails to return a numeric, it returns:
  4852. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  4853. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  4854. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  4855. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  4856. *
  4857. * @see price() Opposite function of price2num
  4858. */
  4859. function price2num($amount, $rounding = '', $option = 0)
  4860. {
  4861. global $langs, $conf;
  4862. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4863. // Numbers must be '1234.56'
  4864. // Decimal delimiter for PHP and database SQL requests must be '.'
  4865. $dec = ',';
  4866. $thousand = ' ';
  4867. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  4868. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4869. }
  4870. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  4871. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4872. }
  4873. if ($thousand == 'None') {
  4874. $thousand = '';
  4875. } elseif ($thousand == 'Space') {
  4876. $thousand = ' ';
  4877. }
  4878. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4879. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4880. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4881. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4882. if (!is_numeric($amount)) {
  4883. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  4884. }
  4885. 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
  4886. $amount = str_replace($thousand, '', $amount);
  4887. }
  4888. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4889. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4890. // So if number was already a good number, it is converted into local Dolibarr setup.
  4891. if (is_numeric($amount)) {
  4892. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4893. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4894. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4895. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4896. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4897. }
  4898. //print "QQ".$amount."<br>\n";
  4899. // Now make replace (the main goal of function)
  4900. if ($thousand != ',' && $thousand != '.') {
  4901. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4902. }
  4903. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4904. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4905. $amount = str_replace($dec, '.', $amount);
  4906. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  4907. }
  4908. //print ' XX'.$amount.' '.$rounding;
  4909. // Now, $amount is a real PHP float number. We make a rounding if required.
  4910. if ($rounding) {
  4911. $nbofdectoround = '';
  4912. if ($rounding == 'MU') {
  4913. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4914. } elseif ($rounding == 'MT') {
  4915. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4916. } elseif ($rounding == 'MS') {
  4917. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  4918. } elseif ($rounding == 'CU') {
  4919. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  4920. } elseif ($rounding == 'CT') {
  4921. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  4922. } elseif (is_numeric($rounding)) {
  4923. $nbofdectoround = (int) $rounding;
  4924. }
  4925. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  4926. if (dol_strlen($nbofdectoround)) {
  4927. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  4928. } else {
  4929. return 'ErrorBadParameterProvidedToFunction';
  4930. }
  4931. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4932. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4933. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4934. if (is_numeric($amount)) {
  4935. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4936. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4937. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4938. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4939. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4940. }
  4941. //print "TT".$amount.'<br>';
  4942. // Always make replace because each math function (like round) replace
  4943. // with local values and we want a number that has a SQL string format x.y
  4944. if ($thousand != ',' && $thousand != '.') {
  4945. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4946. }
  4947. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4948. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4949. $amount = str_replace($dec, '.', $amount);
  4950. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  4951. }
  4952. return $amount;
  4953. }
  4954. /**
  4955. * Output a dimension with best unit
  4956. *
  4957. * @param float $dimension Dimension
  4958. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4959. * @param string $type 'weight', 'volume', ...
  4960. * @param Translate $outputlangs Translate language object
  4961. * @param int $round -1 = non rounding, x = number of decimal
  4962. * @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)
  4963. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  4964. * @return string String to show dimensions
  4965. */
  4966. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  4967. {
  4968. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4969. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  4970. $dimension = $dimension * 1000000;
  4971. $unit = $unit - 6;
  4972. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  4973. $dimension = $dimension * 1000;
  4974. $unit = $unit - 3;
  4975. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  4976. $dimension = $dimension / 1000000;
  4977. $unit = $unit + 6;
  4978. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  4979. $dimension = $dimension / 1000;
  4980. $unit = $unit + 3;
  4981. }
  4982. // Special case when we want output unit into pound or ounce
  4983. /* TODO
  4984. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4985. {
  4986. $dimension = // convert dimension from standard unit into ounce or pound
  4987. $unit = $forceunitoutput;
  4988. }
  4989. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4990. {
  4991. $dimension = // convert dimension from standard unit into ounce or pound
  4992. $unit = $forceunitoutput;
  4993. }*/
  4994. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  4995. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  4996. return $ret;
  4997. }
  4998. /**
  4999. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5000. * Note: This function applies same rules than get_default_tva
  5001. *
  5002. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5003. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5004. * @param Societe $thirdparty_buyer Object of buying third party
  5005. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5006. * @param int $vatnpr If vat rate is NPR or not
  5007. * @return mixed 0 if not found, localtax rate if found
  5008. * @see get_default_tva()
  5009. */
  5010. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5011. {
  5012. global $db, $conf, $mysoc;
  5013. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5014. $thirdparty_seller = $mysoc;
  5015. }
  5016. 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);
  5017. $vatratecleaned = $vatrate;
  5018. $reg = array();
  5019. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5020. $vatratecleaned = trim($reg[1]);
  5021. $vatratecode = $reg[2];
  5022. }
  5023. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5024. {
  5025. return 0;
  5026. }*/
  5027. // Some test to guess with no need to make database access
  5028. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5029. if ($local == 1) {
  5030. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5031. return 0;
  5032. }
  5033. if ($thirdparty_seller->id == $mysoc->id) {
  5034. if (!$thirdparty_buyer->localtax1_assuj) {
  5035. return 0;
  5036. }
  5037. } else {
  5038. if (!$thirdparty_seller->localtax1_assuj) {
  5039. return 0;
  5040. }
  5041. }
  5042. }
  5043. if ($local == 2) {
  5044. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5045. if (!$mysoc->localtax2_assuj) {
  5046. return 0; // If main vat is 0, IRPF may be different than 0.
  5047. }
  5048. if ($thirdparty_seller->id == $mysoc->id) {
  5049. if (!$thirdparty_buyer->localtax2_assuj) {
  5050. return 0;
  5051. }
  5052. } else {
  5053. if (!$thirdparty_seller->localtax2_assuj) {
  5054. return 0;
  5055. }
  5056. }
  5057. }
  5058. } else {
  5059. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5060. return 0;
  5061. }
  5062. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5063. return 0;
  5064. }
  5065. }
  5066. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5067. if (in_array($mysoc->country_code, array('ES'))) {
  5068. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5069. }
  5070. // Search local taxes
  5071. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5072. if ($local == 1) {
  5073. if ($thirdparty_seller != $mysoc) {
  5074. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5075. return $thirdparty_seller->localtax1_value;
  5076. }
  5077. } else { // i am the seller
  5078. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5079. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5080. }
  5081. }
  5082. }
  5083. if ($local == 2) {
  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. // TODO We should also return value defined on thirdparty only if defined
  5087. return $thirdparty_seller->localtax2_value;
  5088. }
  5089. } else { // i am the seller
  5090. if (in_array($mysoc->country_code, array('ES'))) {
  5091. return $thirdparty_buyer->localtax2_value;
  5092. } else {
  5093. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5094. }
  5095. }
  5096. }
  5097. }
  5098. // By default, search value of local tax on line of common tax
  5099. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5100. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5101. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5102. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5103. if (!empty($vatratecode)) {
  5104. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5105. } else {
  5106. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5107. }
  5108. $resql = $db->query($sql);
  5109. if ($resql) {
  5110. $obj = $db->fetch_object($resql);
  5111. if ($obj) {
  5112. if ($local == 1) {
  5113. return $obj->localtax1;
  5114. } elseif ($local == 2) {
  5115. return $obj->localtax2;
  5116. }
  5117. }
  5118. }
  5119. return 0;
  5120. }
  5121. /**
  5122. * Return true if LocalTax (1 or 2) is unique.
  5123. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5124. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5125. *
  5126. * @param int $local Local tax to test (1 or 2)
  5127. * @return boolean True if LocalTax have multiple values, False if not
  5128. */
  5129. function isOnlyOneLocalTax($local)
  5130. {
  5131. $tax = get_localtax_by_third($local);
  5132. $valors = explode(":", $tax);
  5133. if (count($valors) > 1) {
  5134. return false;
  5135. } else {
  5136. return true;
  5137. }
  5138. }
  5139. /**
  5140. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5141. *
  5142. * @param int $local LocalTax to get
  5143. * @return number Values of localtax
  5144. */
  5145. function get_localtax_by_third($local)
  5146. {
  5147. global $db, $mysoc;
  5148. $sql = "SELECT t.localtax1, t.localtax2 ";
  5149. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5150. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5151. $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";
  5152. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5153. $sql .= " )";
  5154. $resql = $db->query($sql);
  5155. if ($resql) {
  5156. $obj = $db->fetch_object($resql);
  5157. if ($local == 1) {
  5158. return $obj->localtax1;
  5159. } elseif ($local == 2) {
  5160. return $obj->localtax2;
  5161. }
  5162. }
  5163. return 0;
  5164. }
  5165. /**
  5166. * Get tax (VAT) main information from Id.
  5167. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5168. *
  5169. * @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.
  5170. * @param Societe $buyer Company object
  5171. * @param Societe $seller Company object
  5172. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5173. * @return array array('rowid'=> , 'code'=> ...)
  5174. * @see getLocalTaxesFromRate()
  5175. */
  5176. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5177. {
  5178. global $db, $mysoc;
  5179. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5180. // Search local taxes
  5181. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5182. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5183. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5184. if ($firstparamisid) {
  5185. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5186. } else {
  5187. $vatratecleaned = $vatrate;
  5188. $vatratecode = '';
  5189. $reg = array();
  5190. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5191. $vatratecleaned = $reg[1];
  5192. $vatratecode = $reg[2];
  5193. }
  5194. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5195. /*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 ??
  5196. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5197. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5198. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5199. if ($vatratecode) {
  5200. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5201. }
  5202. }
  5203. $resql = $db->query($sql);
  5204. if ($resql) {
  5205. $obj = $db->fetch_object($resql);
  5206. if ($obj) {
  5207. return array(
  5208. 'rowid'=>$obj->rowid,
  5209. 'code'=>$obj->code,
  5210. 'rate'=>$obj->rate,
  5211. 'localtax1'=>$obj->localtax1,
  5212. 'localtax1_type'=>$obj->localtax1_type,
  5213. 'localtax2'=>$obj->localtax2,
  5214. 'localtax2_type'=>$obj->localtax2_type,
  5215. 'npr'=>$obj->npr,
  5216. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5217. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5218. );
  5219. } else {
  5220. return array();
  5221. }
  5222. } else {
  5223. dol_print_error($db);
  5224. }
  5225. return array();
  5226. }
  5227. /**
  5228. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5229. * This does not take into account the seller setup if subject to vat or not, only country.
  5230. *
  5231. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5232. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5233. * provide the selected value to the function calcul_price_total.
  5234. *
  5235. * @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.
  5236. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5237. * @param Societe $buyer Company object
  5238. * @param Societe $seller Company object
  5239. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5240. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5241. * @see getTaxesFromId()
  5242. */
  5243. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5244. {
  5245. global $db, $mysoc;
  5246. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5247. // Search local taxes
  5248. $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";
  5249. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5250. if ($firstparamisid) {
  5251. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5252. } else {
  5253. $vatratecleaned = $vatrate;
  5254. $vatratecode = '';
  5255. $reg = array();
  5256. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5257. $vatratecleaned = $reg[1];
  5258. $vatratecode = $reg[2];
  5259. }
  5260. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5261. if ($mysoc->country_code == 'ES') {
  5262. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5263. } else {
  5264. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5265. }
  5266. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5267. if ($vatratecode) {
  5268. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5269. }
  5270. }
  5271. $resql = $db->query($sql);
  5272. if ($resql) {
  5273. $obj = $db->fetch_object($resql);
  5274. if ($obj) {
  5275. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5276. if ($local == 1) {
  5277. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5278. } elseif ($local == 2) {
  5279. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5280. } else {
  5281. 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);
  5282. }
  5283. }
  5284. }
  5285. return array();
  5286. }
  5287. /**
  5288. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5289. * Function called by get_default_tva().
  5290. *
  5291. * @param int $idprod Id of product or 0 if not a predefined product
  5292. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5293. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5294. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5295. * @see get_product_localtax_for_country()
  5296. */
  5297. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5298. {
  5299. global $db, $conf, $mysoc;
  5300. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5301. $ret = 0;
  5302. $found = 0;
  5303. if ($idprod > 0) {
  5304. // Load product
  5305. $product = new Product($db);
  5306. $result = $product->fetch($idprod);
  5307. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5308. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5309. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5310. $ret = $product->vatrate_supplier;
  5311. if ($product->default_vat_code) {
  5312. $ret .= ' ('.$product->default_vat_code.')';
  5313. }
  5314. } else {
  5315. $ret = $product->tva_tx; // Default vat of product we defined
  5316. if ($product->default_vat_code) {
  5317. $ret .= ' ('.$product->default_vat_code.')';
  5318. }
  5319. }
  5320. $found = 1;
  5321. } else {
  5322. // TODO Read default product vat according to product and another countrycode.
  5323. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5324. }
  5325. }
  5326. if (!$found) {
  5327. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5328. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5329. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5330. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5331. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5332. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5333. $sql .= $db->plimit(1);
  5334. $resql = $db->query($sql);
  5335. if ($resql) {
  5336. $obj = $db->fetch_object($resql);
  5337. if ($obj) {
  5338. $ret = $obj->vat_rate;
  5339. if ($obj->default_vat_code) {
  5340. $ret .= ' ('.$obj->default_vat_code.')';
  5341. }
  5342. }
  5343. $db->free($resql);
  5344. } else {
  5345. dol_print_error($db);
  5346. }
  5347. } else {
  5348. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5349. }
  5350. }
  5351. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5352. return $ret;
  5353. }
  5354. /**
  5355. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5356. *
  5357. * @param int $idprod Id of product
  5358. * @param int $local 1 for localtax1, 2 for localtax 2
  5359. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5360. * @return int <0 if KO, Vat rate if OK
  5361. * @see get_product_vat_for_country()
  5362. */
  5363. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5364. {
  5365. global $db, $mysoc;
  5366. if (!class_exists('Product')) {
  5367. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5368. }
  5369. $ret = 0;
  5370. $found = 0;
  5371. if ($idprod > 0) {
  5372. // Load product
  5373. $product = new Product($db);
  5374. $result = $product->fetch($idprod);
  5375. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5376. /* Not defined yet, so we don't use this
  5377. if ($local==1) $ret=$product->localtax1_tx;
  5378. elseif ($local==2) $ret=$product->localtax2_tx;
  5379. $found=1;
  5380. */
  5381. } else {
  5382. // TODO Read default product vat according to product and another countrycode.
  5383. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5384. }
  5385. }
  5386. if (!$found) {
  5387. // If vat of product for the country not found or not defined, we return higher vat of country.
  5388. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5389. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5390. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5391. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5392. $sql .= $db->plimit(1);
  5393. $resql = $db->query($sql);
  5394. if ($resql) {
  5395. $obj = $db->fetch_object($resql);
  5396. if ($obj) {
  5397. if ($local == 1) {
  5398. $ret = $obj->localtax1;
  5399. } elseif ($local == 2) {
  5400. $ret = $obj->localtax2;
  5401. }
  5402. }
  5403. } else {
  5404. dol_print_error($db);
  5405. }
  5406. }
  5407. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5408. return $ret;
  5409. }
  5410. /**
  5411. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5412. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5413. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5414. * 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.
  5415. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5416. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5417. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5418. *
  5419. * @param Societe $thirdparty_seller Objet societe vendeuse
  5420. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5421. * @param int $idprod Id product
  5422. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5423. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5424. * @see get_default_npr(), get_default_localtax()
  5425. */
  5426. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5427. {
  5428. global $conf;
  5429. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5430. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5431. $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;
  5432. $seller_country_code = $thirdparty_seller->country_code;
  5433. $seller_in_cee = isInEEC($thirdparty_seller);
  5434. $buyer_country_code = $thirdparty_buyer->country_code;
  5435. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5436. 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 : ''));
  5437. // 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)
  5438. // we use the buyer VAT.
  5439. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5440. if ($seller_in_cee && $buyer_in_cee) {
  5441. $isacompany = $thirdparty_buyer->isACompany();
  5442. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5443. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5444. if (!isValidVATID($thirdparty_buyer)) {
  5445. $isacompany = 0;
  5446. }
  5447. }
  5448. if (!$isacompany) {
  5449. //print 'VATRULE 0';
  5450. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5451. }
  5452. }
  5453. }
  5454. // If seller does not use VAT
  5455. if (!$seller_use_vat) {
  5456. //print 'VATRULE 1';
  5457. return 0;
  5458. }
  5459. // 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.
  5460. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5461. if (($seller_country_code == $buyer_country_code)
  5462. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5463. //print 'VATRULE 2';
  5464. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5465. }
  5466. // 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.
  5467. // 'VATRULE 3' - Not supported
  5468. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5469. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5470. if (($seller_in_cee && $buyer_in_cee)) {
  5471. $isacompany = $thirdparty_buyer->isACompany();
  5472. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5473. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5474. if (!isValidVATID($thirdparty_buyer)) {
  5475. $isacompany = 0;
  5476. }
  5477. }
  5478. if (!$isacompany) {
  5479. //print 'VATRULE 4';
  5480. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5481. } else {
  5482. //print 'VATRULE 5';
  5483. return 0;
  5484. }
  5485. }
  5486. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5487. // I don't see any use case that need this rule.
  5488. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5489. $isacompany = $thirdparty_buyer->isACompany();
  5490. if (!$isacompany) {
  5491. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5492. //print 'VATRULE extra';
  5493. }
  5494. }
  5495. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5496. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5497. //print 'VATRULE 6';
  5498. return 0;
  5499. }
  5500. /**
  5501. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5502. *
  5503. * @param Societe $thirdparty_seller Thirdparty seller
  5504. * @param Societe $thirdparty_buyer Thirdparty buyer
  5505. * @param int $idprod Id product
  5506. * @param int $idprodfournprice Id supplier price for product
  5507. * @return float 0 or 1
  5508. * @see get_default_tva(), get_default_localtax()
  5509. */
  5510. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5511. {
  5512. global $db;
  5513. if ($idprodfournprice > 0) {
  5514. if (!class_exists('ProductFournisseur')) {
  5515. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5516. }
  5517. $prodprice = new ProductFournisseur($db);
  5518. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5519. return $prodprice->fourn_tva_npr;
  5520. } elseif ($idprod > 0) {
  5521. if (!class_exists('Product')) {
  5522. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5523. }
  5524. $prod = new Product($db);
  5525. $prod->fetch($idprod);
  5526. return $prod->tva_npr;
  5527. }
  5528. return 0;
  5529. }
  5530. /**
  5531. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5532. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5533. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5534. * Sinon TVA proposee par defaut=0. Fin de regle.
  5535. *
  5536. * @param Societe $thirdparty_seller Thirdparty seller
  5537. * @param Societe $thirdparty_buyer Thirdparty buyer
  5538. * @param int $local Localtax to process (1 or 2)
  5539. * @param int $idprod Id product
  5540. * @return integer localtax, -1 si ne peut etre determine
  5541. * @see get_default_tva(), get_default_npr()
  5542. */
  5543. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5544. {
  5545. global $mysoc;
  5546. if (!is_object($thirdparty_seller)) {
  5547. return -1;
  5548. }
  5549. if (!is_object($thirdparty_buyer)) {
  5550. return -1;
  5551. }
  5552. if ($local == 1) { // Localtax 1
  5553. if ($mysoc->country_code == 'ES') {
  5554. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5555. return 0;
  5556. }
  5557. } else {
  5558. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5559. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5560. return 0;
  5561. }
  5562. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5563. return 0;
  5564. }
  5565. }
  5566. } elseif ($local == 2) { //I Localtax 2
  5567. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5568. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5569. return 0;
  5570. }
  5571. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5572. return 0;
  5573. }
  5574. }
  5575. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5576. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5577. }
  5578. return 0;
  5579. }
  5580. /**
  5581. * Return yes or no in current language
  5582. *
  5583. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5584. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5585. * @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.
  5586. * @return string HTML string
  5587. */
  5588. function yn($yesno, $case = 1, $color = 0)
  5589. {
  5590. global $langs;
  5591. $result = 'unknown';
  5592. $classname = '';
  5593. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5594. $result = $langs->trans('yes');
  5595. if ($case == 1 || $case == 3) {
  5596. $result = $langs->trans("Yes");
  5597. }
  5598. if ($case == 2) {
  5599. $result = '<input type="checkbox" value="1" checked disabled>';
  5600. }
  5601. if ($case == 3) {
  5602. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5603. }
  5604. $classname = 'ok';
  5605. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5606. $result = $langs->trans("no");
  5607. if ($case == 1 || $case == 3) {
  5608. $result = $langs->trans("No");
  5609. }
  5610. if ($case == 2) {
  5611. $result = '<input type="checkbox" value="0" disabled>';
  5612. }
  5613. if ($case == 3) {
  5614. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5615. }
  5616. if ($color == 2) {
  5617. $classname = 'ok';
  5618. } else {
  5619. $classname = 'error';
  5620. }
  5621. }
  5622. if ($color) {
  5623. return '<span class="'.$classname.'">'.$result.'</span>';
  5624. }
  5625. return $result;
  5626. }
  5627. /**
  5628. * Return a path to have a the directory according to object where files are stored.
  5629. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5630. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5631. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5632. * 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/"
  5633. *
  5634. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5635. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5636. * @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)
  5637. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5638. * @param Object $object Object to use to get ref to forge the path.
  5639. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5640. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5641. */
  5642. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5643. {
  5644. global $conf;
  5645. if (empty($modulepart) && !empty($object->module)) {
  5646. $modulepart = $object->module;
  5647. }
  5648. $path = '';
  5649. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5650. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5651. $arrayforoldpath[] = 'product';
  5652. }
  5653. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5654. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5655. if (empty($alpha)) {
  5656. $num = preg_replace('/([^0-9])/i', '', $num);
  5657. } else {
  5658. $num = preg_replace('/^.*\-/i', '', $num);
  5659. }
  5660. $num = substr("000".$num, -$level);
  5661. if ($level == 1) {
  5662. $path = substr($num, 0, 1);
  5663. }
  5664. if ($level == 2) {
  5665. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5666. }
  5667. if ($level == 3) {
  5668. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5669. }
  5670. } else {
  5671. // We will enhance here a common way of forging path for document storage.
  5672. // In a future, we may distribute directories on several levels depending on setup and object.
  5673. // Here, $object->id, $object->ref and $modulepart are required.
  5674. //var_dump($modulepart);
  5675. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5676. }
  5677. if (empty($withoutslash) && !empty($path)) {
  5678. $path .= '/';
  5679. }
  5680. return $path;
  5681. }
  5682. /**
  5683. * Creation of a directory (this can create recursive subdir)
  5684. *
  5685. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5686. * @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)
  5687. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5688. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5689. */
  5690. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5691. {
  5692. global $conf;
  5693. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5694. $dir_osencoded = dol_osencode($dir);
  5695. if (@is_dir($dir_osencoded)) {
  5696. return 0;
  5697. }
  5698. $nberr = 0;
  5699. $nbcreated = 0;
  5700. $ccdir = '';
  5701. if (!empty($dataroot)) {
  5702. // Remove data root from loop
  5703. $dir = str_replace($dataroot.'/', '', $dir);
  5704. $ccdir = $dataroot.'/';
  5705. }
  5706. $cdir = explode("/", $dir);
  5707. $num = count($cdir);
  5708. for ($i = 0; $i < $num; $i++) {
  5709. if ($i > 0) {
  5710. $ccdir .= '/'.$cdir[$i];
  5711. } else {
  5712. $ccdir .= $cdir[$i];
  5713. }
  5714. if (preg_match("/^.:$/", $ccdir, $regs)) {
  5715. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5716. }
  5717. // Attention, le is_dir() peut echouer bien que le rep existe.
  5718. // (ex selon config de open_basedir)
  5719. if ($ccdir) {
  5720. $ccdir_osencoded = dol_osencode($ccdir);
  5721. if (!@is_dir($ccdir_osencoded)) {
  5722. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5723. umask(0);
  5724. $dirmaskdec = octdec($newmask);
  5725. if (empty($newmask)) {
  5726. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5727. }
  5728. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5729. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  5730. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5731. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5732. $nberr++;
  5733. } else {
  5734. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5735. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5736. $nbcreated++;
  5737. }
  5738. } else {
  5739. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5740. }
  5741. }
  5742. }
  5743. return ($nberr ? -$nberr : $nbcreated);
  5744. }
  5745. /**
  5746. * Return picto saying a field is required
  5747. *
  5748. * @return string Chaine avec picto obligatoire
  5749. */
  5750. function picto_required()
  5751. {
  5752. return '<span class="fieldrequired">*</span>';
  5753. }
  5754. /**
  5755. * Clean a string from all HTML tags and entities.
  5756. * This function differs from strip_tags because:
  5757. * - <br> are replaced with \n if removelinefeed=0 or 1
  5758. * - if entities are found, they are decoded BEFORE the strip
  5759. * - you can decide to convert line feed into a space
  5760. *
  5761. * @param string $stringtoclean String to clean
  5762. * @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..."
  5763. * @param string $pagecodeto Encoding of input/output string
  5764. * @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')
  5765. * @param integer $removedoublespaces Replace double space into one space
  5766. * @return string String cleaned
  5767. *
  5768. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5769. */
  5770. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5771. {
  5772. if ($removelinefeed == 2) {
  5773. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5774. }
  5775. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5776. // 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)
  5777. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5778. $temp = str_replace('< ', '__ltspace__', $temp);
  5779. if ($strip_tags) {
  5780. $temp = strip_tags($temp);
  5781. } else {
  5782. $temp = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  5783. $pattern = "/<[^<>]+>/";
  5784. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5785. $temp = preg_replace($pattern, "", $temp); // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5786. $temp = preg_replace($pattern, "", $temp); // pass 2 - $temp after pass 2: 0000-021
  5787. // 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).
  5788. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  5789. }
  5790. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5791. // Remove also carriage returns
  5792. if ($removelinefeed == 1) {
  5793. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5794. }
  5795. // And double quotes
  5796. if ($removedoublespaces) {
  5797. while (strpos($temp, " ")) {
  5798. $temp = str_replace(" ", " ", $temp);
  5799. }
  5800. }
  5801. $temp = str_replace('__ltspace__', '< ', $temp);
  5802. return trim($temp);
  5803. }
  5804. /**
  5805. * Clean a string to keep only desirable HTML tags.
  5806. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  5807. *
  5808. * @param string $stringtoclean String to clean
  5809. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5810. * @param int $removeclassattribute 1=Remove the class attribute from tags
  5811. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  5812. * @param int $allowiframe Allow iframe tags.
  5813. * @return string String cleaned
  5814. *
  5815. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5816. */
  5817. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  5818. {
  5819. $allowed_tags = array(
  5820. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5821. "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"
  5822. );
  5823. if ($allowiframe) {
  5824. $allowed_tags[] = "iframe";
  5825. }
  5826. $allowed_tags_string = join("><", $allowed_tags);
  5827. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5828. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  5829. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5830. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  5831. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5832. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  5833. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  5834. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </> changing string obfuscated with </> that pass injection detection into harmfull string
  5835. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5836. $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
  5837. }
  5838. if ($removeclassattribute) { // Clean for remaining html tags
  5839. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5840. }
  5841. // Remove 'javascript:' that we should not find into a text with
  5842. // 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)).
  5843. if ($cleanalsojavascript) {
  5844. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5845. }
  5846. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  5847. return $temp;
  5848. }
  5849. /**
  5850. * Clean a string from some undesirable HTML tags.
  5851. * Note: Complementary to dol_string_onlythesehtmltags().
  5852. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  5853. *
  5854. * @param string $stringtoclean String to clean
  5855. * @param array $allowed_attributes Array of tags not allowed
  5856. * @return string String cleaned
  5857. *
  5858. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  5859. */
  5860. 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"))
  5861. {
  5862. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  5863. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  5864. $dom = new DOMDocument(null, 'UTF-8');
  5865. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  5866. if (is_object($dom)) {
  5867. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  5868. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  5869. //var_dump($attrs->item($ii));
  5870. if (! empty($attrs->item($ii)->name)) {
  5871. // Delete attribute if not into allowed_attributes
  5872. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  5873. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  5874. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  5875. $valuetoclean = $attrs->item($ii)->value;
  5876. do {
  5877. $oldvaluetoclean = $valuetoclean;
  5878. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  5879. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  5880. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  5881. $valuetoclean = preg_replace('/display\s*://m', '', $valuetoclean);
  5882. $valuetoclean = preg_replace('/z-index\s*://m', '', $valuetoclean);
  5883. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*://m', '', $valuetoclean);
  5884. }
  5885. } while ($oldvaluetoclean != $valuetoclean);
  5886. $attrs->item($ii)->value = $valuetoclean;
  5887. }
  5888. }
  5889. }
  5890. }
  5891. }
  5892. $return = $dom->saveHTML();
  5893. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  5894. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  5895. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  5896. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  5897. return trim($return);
  5898. } else {
  5899. return $stringtoclean;
  5900. }
  5901. }
  5902. /**
  5903. * Clean a string from some undesirable HTML tags.
  5904. * Note. Not as secured as dol_string_onlythesehtmltags().
  5905. *
  5906. * @param string $stringtoclean String to clean
  5907. * @param array $disallowed_tags Array of tags not allowed
  5908. * @param string $cleanalsosomestyles Clean also some tags
  5909. * @return string String cleaned
  5910. *
  5911. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  5912. */
  5913. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5914. {
  5915. $temp = $stringtoclean;
  5916. foreach ($disallowed_tags as $tagtoremove) {
  5917. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5918. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5919. }
  5920. if ($cleanalsosomestyles) {
  5921. $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
  5922. }
  5923. return $temp;
  5924. }
  5925. /**
  5926. * Return first line of text. Cut will depends if content is HTML or not.
  5927. *
  5928. * @param string $text Input text
  5929. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5930. * @param string $charset Charset of $text string (UTF-8 by default)
  5931. * @return string Output text
  5932. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5933. */
  5934. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5935. {
  5936. if ($nboflines == 1) {
  5937. if (dol_textishtml($text)) {
  5938. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5939. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5940. } else {
  5941. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5942. }
  5943. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5944. } else {
  5945. $ishtml = 0;
  5946. if (dol_textishtml($text)) {
  5947. $text = preg_replace('/\n/', '', $text);
  5948. $ishtml = 1;
  5949. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5950. } else {
  5951. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5952. }
  5953. $text = strtr($text, $repTable);
  5954. if ($charset == 'UTF-8') {
  5955. $pattern = '/(<br[^>]*>)/Uu';
  5956. } else {
  5957. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5958. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5959. }
  5960. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5961. $firstline = '';
  5962. $i = 0;
  5963. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5964. while (($i < $nba) && ($i < ($nboflines * 2))) {
  5965. if ($i % 2 == 0) {
  5966. $firstline .= $a[$i];
  5967. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  5968. $firstline .= ($ishtml ? "<br>\n" : "\n");
  5969. }
  5970. $i++;
  5971. }
  5972. unset($a);
  5973. return $firstline.(($i < $nba) ? '...' : '');
  5974. }
  5975. }
  5976. /**
  5977. * Replace CRLF in string with a HTML BR tag.
  5978. * 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.
  5979. *
  5980. * @param string $stringtoencode String to encode
  5981. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5982. * @param bool $forxml false=Use <br>, true=Use <br />
  5983. * @return string String encoded
  5984. * @see dol_nboflines(), dolGetFirstLineOfText()
  5985. */
  5986. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5987. {
  5988. if (!$nl2brmode) {
  5989. return nl2br($stringtoencode, $forxml);
  5990. } else {
  5991. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  5992. return $ret;
  5993. }
  5994. }
  5995. /**
  5996. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5997. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5998. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5999. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6000. * For PDF usage, you can show text by 2 ways:
  6001. * - writeHTMLCell -> param must be encoded into HTML.
  6002. * - MultiCell -> param must not be encoded into HTML.
  6003. * Because writeHTMLCell convert also \n into <br>, if function
  6004. * is used to build PDF, nl2brmode must be 1.
  6005. *
  6006. * @param string $stringtoencode String to encode
  6007. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6008. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6009. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6010. * @return string String encoded
  6011. */
  6012. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6013. {
  6014. $newstring = $stringtoencode;
  6015. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6016. $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.
  6017. if ($removelasteolbr) {
  6018. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6019. }
  6020. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6021. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6022. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6023. } else {
  6024. if ($removelasteolbr) {
  6025. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6026. }
  6027. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6028. }
  6029. // Other substitutions that htmlentities does not do
  6030. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6031. return $newstring;
  6032. }
  6033. /**
  6034. * This function is called to decode a HTML string (it decodes entities and br tags)
  6035. *
  6036. * @param string $stringtodecode String to decode
  6037. * @param string $pagecodeto Page code for result
  6038. * @return string String decoded
  6039. */
  6040. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6041. {
  6042. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6043. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6044. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6045. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6046. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6047. return $ret;
  6048. }
  6049. /**
  6050. * This function remove all ending \n and br at end
  6051. *
  6052. * @param string $stringtodecode String to decode
  6053. * @return string String decoded
  6054. */
  6055. function dol_htmlcleanlastbr($stringtodecode)
  6056. {
  6057. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6058. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6059. return $ret;
  6060. }
  6061. /**
  6062. * Replace html_entity_decode functions to manage errors
  6063. *
  6064. * @param string $a Operand a
  6065. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6066. * @param string $c Operand c
  6067. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6068. * @return string String decoded
  6069. */
  6070. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6071. {
  6072. $newstring = $a;
  6073. if ($keepsomeentities) {
  6074. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6075. }
  6076. $newstring = html_entity_decode($newstring, $b, $c);
  6077. if ($keepsomeentities) {
  6078. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6079. }
  6080. return $newstring;
  6081. }
  6082. /**
  6083. * Replace htmlentities functions.
  6084. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6085. *
  6086. * @param string $string The input string to encode
  6087. * @param int $flags Flags (see PHP doc above)
  6088. * @param string $encoding Encoding page code
  6089. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6090. * @return string $ret Encoded string
  6091. */
  6092. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6093. {
  6094. return htmlentities($string, $flags, $encoding, $double_encode);
  6095. }
  6096. /**
  6097. * Check if a string is a correct iso string
  6098. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6099. * Example, if string contains euro symbol that has ascii code 128
  6100. *
  6101. * @param string $s String to check
  6102. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6103. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6104. */
  6105. function dol_string_is_good_iso($s, $clean = 0)
  6106. {
  6107. $len = dol_strlen($s);
  6108. $out = '';
  6109. $ok = 1;
  6110. for ($scursor = 0; $scursor < $len; $scursor++) {
  6111. $ordchar = ord($s[$scursor]);
  6112. //print $scursor.'-'.$ordchar.'<br>';
  6113. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6114. $ok = 0;
  6115. break;
  6116. } elseif ($ordchar > 126 && $ordchar < 160) {
  6117. $ok = 0;
  6118. break;
  6119. } elseif ($clean) {
  6120. $out .= $s[$scursor];
  6121. }
  6122. }
  6123. if ($clean) {
  6124. return $out;
  6125. }
  6126. return $ok;
  6127. }
  6128. /**
  6129. * Return nb of lines of a clear text
  6130. *
  6131. * @param string $s String to check
  6132. * @param int $maxchar Not yet used
  6133. * @return int Number of lines
  6134. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6135. */
  6136. function dol_nboflines($s, $maxchar = 0)
  6137. {
  6138. if ($s == '') {
  6139. return 0;
  6140. }
  6141. $arraystring = explode("\n", $s);
  6142. $nb = count($arraystring);
  6143. return $nb;
  6144. }
  6145. /**
  6146. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6147. *
  6148. * @param string $text Text
  6149. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6150. * @param string $charset Give the charset used to encode the $text variable in memory.
  6151. * @return int Number of lines
  6152. * @see dol_nboflines(), dolGetFirstLineOfText()
  6153. */
  6154. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6155. {
  6156. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6157. if (dol_textishtml($text)) {
  6158. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6159. }
  6160. $text = strtr($text, $repTable);
  6161. if ($charset == 'UTF-8') {
  6162. $pattern = '/(<br[^>]*>)/Uu';
  6163. } else {
  6164. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6165. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6166. }
  6167. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6168. $nblines = (int) floor((count($a) + 1) / 2);
  6169. // count possible auto line breaks
  6170. if ($maxlinesize) {
  6171. foreach ($a as $line) {
  6172. if (dol_strlen($line) > $maxlinesize) {
  6173. //$line_dec = html_entity_decode(strip_tags($line));
  6174. $line_dec = html_entity_decode($line);
  6175. if (dol_strlen($line_dec) > $maxlinesize) {
  6176. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6177. $nblines += substr_count($line_dec, '\n');
  6178. }
  6179. }
  6180. }
  6181. }
  6182. unset($a);
  6183. return $nblines;
  6184. }
  6185. /**
  6186. * Return if a text is a html content
  6187. *
  6188. * @param string $msg Content to check
  6189. * @param int $option 0=Full detection, 1=Fast check
  6190. * @return boolean true/false
  6191. * @see dol_concatdesc()
  6192. */
  6193. function dol_textishtml($msg, $option = 0)
  6194. {
  6195. if ($option == 1) {
  6196. if (preg_match('/<html/i', $msg)) {
  6197. return true;
  6198. } elseif (preg_match('/<body/i', $msg)) {
  6199. return true;
  6200. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6201. return true;
  6202. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6203. return true;
  6204. } elseif (preg_match('/<br/i', $msg)) {
  6205. return true;
  6206. }
  6207. return false;
  6208. } else {
  6209. if (preg_match('/<html/i', $msg)) {
  6210. return true;
  6211. } elseif (preg_match('/<body/i', $msg)) {
  6212. return true;
  6213. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6214. return true;
  6215. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6216. return true;
  6217. } elseif (preg_match('/<br\/>/i', $msg)) {
  6218. return true;
  6219. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6220. return true;
  6221. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6222. return true;
  6223. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6224. return true; // must accept <img src="http://example.com/aaa.png" />
  6225. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6226. return true; // must accept <a href="http://example.com/aaa.png" />
  6227. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6228. return true;
  6229. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6230. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6231. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6232. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6233. }
  6234. return false;
  6235. }
  6236. }
  6237. /**
  6238. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6239. * text1 html + text2 html => text1 + '<br>' + text2
  6240. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6241. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6242. * text1 txt + text2 txt => text1 + '\n' + text2
  6243. *
  6244. * @param string $text1 Text 1
  6245. * @param string $text2 Text 2
  6246. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6247. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6248. * @return string Text 1 + new line + Text2
  6249. * @see dol_textishtml()
  6250. */
  6251. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6252. {
  6253. if (!empty($invert)) {
  6254. $tmp = $text1;
  6255. $text1 = $text2;
  6256. $text2 = $tmp;
  6257. }
  6258. $ret = '';
  6259. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6260. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6261. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6262. return $ret;
  6263. }
  6264. /**
  6265. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6266. *
  6267. * @param Translate $outputlangs Output language
  6268. * @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)
  6269. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6270. * @param Object $object Object for keys on object
  6271. * @return array Array of substitutions
  6272. * @see setSubstitFromObject()
  6273. */
  6274. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6275. {
  6276. global $db, $conf, $mysoc, $user, $extrafields;
  6277. $substitutionarray = array();
  6278. if (empty($exclude) || !in_array('user', $exclude)) {
  6279. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6280. // this will include signature content first and then replace var found into content of signature
  6281. $signature = $user->signature;
  6282. $substitutionarray = array_merge($substitutionarray, array(
  6283. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6284. ));
  6285. if (is_object($user)) {
  6286. $substitutionarray = array_merge($substitutionarray, array(
  6287. '__USER_ID__' => (string) $user->id,
  6288. '__USER_LOGIN__' => (string) $user->login,
  6289. '__USER_EMAIL__' => (string) $user->email,
  6290. '__USER_LASTNAME__' => (string) $user->lastname,
  6291. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6292. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6293. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6294. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6295. ));
  6296. }
  6297. }
  6298. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6299. $substitutionarray = array_merge($substitutionarray, array(
  6300. '__MYCOMPANY_NAME__' => $mysoc->name,
  6301. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6302. '__MYCOMPANY_PHONE__' => $mysoc->phone,
  6303. '__MYCOMPANY_FAX__' => $mysoc->fax,
  6304. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6305. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6306. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6307. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6308. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6309. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6310. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6311. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6312. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6313. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6314. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6315. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6316. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6317. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6318. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6319. ));
  6320. }
  6321. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6322. if ($onlykey) {
  6323. $substitutionarray['__ID__'] = '__ID__';
  6324. $substitutionarray['__REF__'] = '__REF__';
  6325. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6326. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6327. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6328. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6329. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6330. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6331. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6332. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6333. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6334. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6335. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6336. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6337. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6338. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6339. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6340. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6341. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6342. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6343. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6344. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6345. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6346. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6347. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6348. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6349. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6350. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6351. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6352. }
  6353. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6354. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6355. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6356. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6357. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6358. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6359. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6360. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6361. }
  6362. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature')) {
  6363. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6364. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6365. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6366. }
  6367. if (!empty($conf->projet->enabled)) { // Most objects
  6368. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6369. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6370. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6371. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6372. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6373. }
  6374. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6375. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6376. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6377. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6378. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6379. }
  6380. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6381. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6382. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6383. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6384. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6385. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6386. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  6387. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6388. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6389. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6390. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6391. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6392. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6393. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6394. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6395. }
  6396. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6397. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6398. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6399. }
  6400. } else {
  6401. $substitutionarray['__ID__'] = $object->id;
  6402. $substitutionarray['__REF__'] = $object->ref;
  6403. $substitutionarray['__NEWREF__'] = $object->newref;
  6404. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6405. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6406. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6407. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6408. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6409. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6410. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6411. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6412. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6413. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6414. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6415. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6416. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6417. // For backward compatibility
  6418. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6419. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6420. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6421. $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 : '')) : '');
  6422. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6423. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6424. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6425. if (method_exists($object, 'getCivilityLabel')) {
  6426. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6427. }
  6428. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6429. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6430. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6431. if (method_exists($object, 'getFullName')) {
  6432. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6433. }
  6434. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6435. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6436. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6437. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6438. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6439. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6440. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6441. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6442. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6443. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6444. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  6445. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  6446. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  6447. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6448. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6449. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  6450. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  6451. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6452. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6453. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6454. }
  6455. if (is_object($object) && $object->element == 'societe') {
  6456. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6457. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6458. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6459. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6460. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6461. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6462. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  6463. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  6464. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6465. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6466. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6467. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6468. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6469. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6470. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6471. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6472. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6473. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6474. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6475. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6476. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6477. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6478. } elseif (is_object($object->thirdparty)) {
  6479. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6480. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6481. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6482. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6483. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6484. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6485. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  6486. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  6487. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6488. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6489. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6490. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6491. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6492. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6493. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6494. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6495. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6496. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6497. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6498. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6499. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6500. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6501. }
  6502. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6503. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6504. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  6505. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  6506. }
  6507. if (is_object($object->project)) {
  6508. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6509. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6510. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6511. }
  6512. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6513. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6514. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6515. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6516. }
  6517. if (is_object($object) && $object->element == 'shipping') {
  6518. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6519. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6520. }
  6521. if (is_object($object) && $object->element == 'reception') {
  6522. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6523. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6524. }
  6525. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6526. $dateplannedstart = '';
  6527. $datenextexpiration = '';
  6528. foreach ($object->lines as $line) {
  6529. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6530. $dateplannedstart = $line->date_ouverture_prevue;
  6531. }
  6532. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6533. $datenextexpiration = $line->date_fin_prevue;
  6534. }
  6535. }
  6536. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6537. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6538. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6539. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6540. }
  6541. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6542. if ($object->table_element && $object->id > 0) {
  6543. if (!is_object($extrafields)) {
  6544. $extrafields = new ExtraFields($db);
  6545. }
  6546. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6547. if ($object->fetch_optionals() > 0) {
  6548. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6549. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6550. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6551. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6552. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6553. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6554. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6555. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6556. $datetime = $object->array_options['options_'.$key];
  6557. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6558. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6559. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6560. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6561. }
  6562. }
  6563. }
  6564. }
  6565. }
  6566. // Complete substitution array with the url to make online payment
  6567. $paymenturl = '';
  6568. if (empty($substitutionarray['__REF__'])) {
  6569. $paymenturl = '';
  6570. } else {
  6571. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6572. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6573. $outputlangs->loadLangs(array('paypal', 'other'));
  6574. $typeforonlinepayment = 'free';
  6575. if (is_object($object) && $object->element == 'commande') {
  6576. $typeforonlinepayment = 'order';
  6577. }
  6578. if (is_object($object) && $object->element == 'facture') {
  6579. $typeforonlinepayment = 'invoice';
  6580. }
  6581. if (is_object($object) && $object->element == 'member') {
  6582. $typeforonlinepayment = 'member';
  6583. }
  6584. if (is_object($object) && $object->element == 'contrat') {
  6585. $typeforonlinepayment = 'contract';
  6586. }
  6587. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6588. $paymenturl = $url;
  6589. }
  6590. if ($object->id > 0) {
  6591. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6592. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6593. if (is_object($object) && $object->element == 'propal') {
  6594. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  6595. }
  6596. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6597. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6598. } else {
  6599. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6600. }
  6601. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6602. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6603. } else {
  6604. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6605. }
  6606. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6607. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6608. } else {
  6609. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6610. }
  6611. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6612. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6613. } else {
  6614. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6615. }
  6616. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6617. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6618. } else {
  6619. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6620. }
  6621. if (is_object($object) && $object->element == 'propal') {
  6622. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6623. }
  6624. if (is_object($object) && $object->element == 'commande') {
  6625. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6626. }
  6627. if (is_object($object) && $object->element == 'facture') {
  6628. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6629. }
  6630. if (is_object($object) && $object->element == 'contrat') {
  6631. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6632. }
  6633. if (is_object($object) && $object->element == 'supplier_proposal') {
  6634. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6635. }
  6636. if (is_object($object) && $object->element == 'shipping') {
  6637. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  6638. }
  6639. }
  6640. if (is_object($object) && $object->element == 'action') {
  6641. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6642. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  6643. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  6644. }
  6645. }
  6646. }
  6647. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  6648. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  6649. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  6650. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  6651. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  6652. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  6653. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  6654. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  6655. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6656. $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)) : '';
  6657. $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)) : '';
  6658. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6659. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  6660. }
  6661. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6662. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  6663. }
  6664. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6665. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6666. $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)) : '';
  6667. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  6668. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6669. }
  6670. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  6671. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  6672. }
  6673. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  6674. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  6675. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  6676. // TODO Add other keys for foreign multicurrency
  6677. // For backward compatibility
  6678. if ($onlykey != 2) {
  6679. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  6680. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  6681. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  6682. }
  6683. }
  6684. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  6685. if (empty($exclude) || !in_array('date', $exclude)) {
  6686. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  6687. $tmp = dol_getdate(dol_now(), true);
  6688. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6689. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  6690. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  6691. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  6692. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  6693. $substitutionarray = array_merge($substitutionarray, array(
  6694. '__DAY__' => (string) $tmp['mday'],
  6695. '__DAY_TEXT__' => $daytext, // Monday
  6696. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  6697. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  6698. '__MONTH__' => (string) $tmp['mon'],
  6699. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  6700. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  6701. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  6702. '__YEAR__' => (string) $tmp['year'],
  6703. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  6704. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  6705. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  6706. '__NEXT_DAY__' => (string) $tmp4['day'],
  6707. '__NEXT_MONTH__' => (string) $tmp5['month'],
  6708. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  6709. ));
  6710. }
  6711. if (!empty($conf->multicompany->enabled)) {
  6712. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  6713. }
  6714. if (empty($exclude) || !in_array('system', $exclude)) {
  6715. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  6716. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  6717. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  6718. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  6719. }
  6720. return $substitutionarray;
  6721. }
  6722. /**
  6723. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  6724. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  6725. * Example of usage:
  6726. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  6727. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  6728. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  6729. *
  6730. * @param string $text Source string in which we must do substitution
  6731. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  6732. * @param Translate $outputlangs Output language
  6733. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  6734. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  6735. * @return string Output string after substitutions
  6736. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  6737. */
  6738. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  6739. {
  6740. global $conf, $langs;
  6741. if (!is_array($substitutionarray)) {
  6742. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  6743. }
  6744. if (empty($outputlangs)) {
  6745. $outputlangs = $langs;
  6746. }
  6747. // Is initial text HTML or simple text ?
  6748. $msgishtml = 0;
  6749. if (dol_textishtml($text, 1)) {
  6750. $msgishtml = 1;
  6751. }
  6752. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  6753. if (is_object($outputlangs)) {
  6754. $reg = array();
  6755. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  6756. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  6757. $tmp = explode('|', $reg[1]);
  6758. if (!empty($tmp[1])) {
  6759. $outputlangs->load($tmp[1]);
  6760. }
  6761. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  6762. if (empty($converttextinhtmlifnecessary)) {
  6763. // convert $newval into HTML is necessary
  6764. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6765. } else {
  6766. if (! $msgishtml) {
  6767. $valueishtml = dol_textishtml($value, 1);
  6768. if ($valueishtml) {
  6769. $text = dol_htmlentitiesbr($text);
  6770. $msgishtml = 1;
  6771. }
  6772. } else {
  6773. $value = dol_nl2br("$value");
  6774. }
  6775. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  6776. }
  6777. }
  6778. }
  6779. // Make substitution for constant keys.
  6780. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  6781. $reg = array();
  6782. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  6783. $keyfound = $reg[1];
  6784. if (isASecretKey($keyfound)) {
  6785. $value = '*****forbidden*****';
  6786. } else {
  6787. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  6788. }
  6789. if (empty($converttextinhtmlifnecessary)) {
  6790. // convert $newval into HTML is necessary
  6791. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  6792. } else {
  6793. if (! $msgishtml) {
  6794. $valueishtml = dol_textishtml($value, 1);
  6795. if ($valueishtml) {
  6796. $text = dol_htmlentitiesbr($text);
  6797. $msgishtml = 1;
  6798. }
  6799. } else {
  6800. $value = dol_nl2br("$value");
  6801. }
  6802. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  6803. }
  6804. }
  6805. // Make substitition for array $substitutionarray
  6806. foreach ($substitutionarray as $key => $value) {
  6807. if (!isset($value)) {
  6808. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  6809. }
  6810. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  6811. $value = ''; // Protection
  6812. }
  6813. if (empty($converttextinhtmlifnecessary)) {
  6814. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6815. } else {
  6816. if (! $msgishtml) {
  6817. $valueishtml = dol_textishtml($value, 1);
  6818. if ($valueishtml) {
  6819. $text = dol_htmlentitiesbr($text);
  6820. $msgishtml = 1;
  6821. }
  6822. } else {
  6823. $value = dol_nl2br("$value");
  6824. }
  6825. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6826. }
  6827. }
  6828. return $text;
  6829. }
  6830. /**
  6831. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6832. * In this case, method completesubstitutionarray provided by module is called.
  6833. *
  6834. * @param array $substitutionarray Array substitution old value => new value value
  6835. * @param Translate $outputlangs Output language
  6836. * @param Object $object Source object
  6837. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6838. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6839. * @return void
  6840. * @see make_substitutions()
  6841. */
  6842. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6843. {
  6844. global $conf, $user;
  6845. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6846. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  6847. // Check if there is external substitution to do, requested by plugins
  6848. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  6849. foreach ($dirsubstitutions as $reldir) {
  6850. $dir = dol_buildpath($reldir, 0);
  6851. // Check if directory exists
  6852. if (!dol_is_dir($dir)) {
  6853. continue;
  6854. }
  6855. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  6856. foreach ($substitfiles as $substitfile) {
  6857. $reg = array();
  6858. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  6859. $module = $reg[1];
  6860. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  6861. // Include the user's functions file
  6862. require_once $dir.$substitfile['name'];
  6863. // Call the user's function, and only if it is defined
  6864. $function_name = $module."_".$callfunc;
  6865. if (function_exists($function_name)) {
  6866. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  6867. }
  6868. }
  6869. }
  6870. }
  6871. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  6872. // to list all tags in odt template
  6873. $tags = '';
  6874. foreach ($substitutionarray as $key => $value) {
  6875. $tags .= '{'.$key.'} => '.$value."\n";
  6876. }
  6877. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  6878. }
  6879. }
  6880. /**
  6881. * Format output for start and end date
  6882. *
  6883. * @param int $date_start Start date
  6884. * @param int $date_end End date
  6885. * @param string $format Output format
  6886. * @param Translate $outputlangs Output language
  6887. * @return void
  6888. */
  6889. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  6890. {
  6891. print get_date_range($date_start, $date_end, $format, $outputlangs);
  6892. }
  6893. /**
  6894. * Format output for start and end date
  6895. *
  6896. * @param int $date_start Start date
  6897. * @param int $date_end End date
  6898. * @param string $format Output format
  6899. * @param Translate $outputlangs Output language
  6900. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  6901. * @return string String
  6902. */
  6903. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  6904. {
  6905. global $langs;
  6906. $out = '';
  6907. if (!is_object($outputlangs)) {
  6908. $outputlangs = $langs;
  6909. }
  6910. if ($date_start && $date_end) {
  6911. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6912. }
  6913. if ($date_start && !$date_end) {
  6914. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6915. }
  6916. if (!$date_start && $date_end) {
  6917. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6918. }
  6919. return $out;
  6920. }
  6921. /**
  6922. * Return firstname and lastname in correct order
  6923. *
  6924. * @param string $firstname Firstname
  6925. * @param string $lastname Lastname
  6926. * @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
  6927. * @return string Firstname + lastname or Lastname + firstname
  6928. */
  6929. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  6930. {
  6931. global $conf;
  6932. $ret = '';
  6933. // If order not defined, we use the setup
  6934. if ($nameorder < 0) {
  6935. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  6936. }
  6937. if ($nameorder == 1) {
  6938. $ret .= $firstname;
  6939. if ($firstname && $lastname) {
  6940. $ret .= ' ';
  6941. }
  6942. $ret .= $lastname;
  6943. } elseif ($nameorder == 2 || $nameorder == 3) {
  6944. $ret .= $firstname;
  6945. if (empty($ret) && $nameorder == 3) {
  6946. $ret .= $lastname;
  6947. }
  6948. } else { // 0, 4 or 5
  6949. $ret .= $lastname;
  6950. if (empty($ret) && $nameorder == 5) {
  6951. $ret .= $firstname;
  6952. }
  6953. if ($nameorder == 0) {
  6954. if ($firstname && $lastname) {
  6955. $ret .= ' ';
  6956. }
  6957. $ret .= $firstname;
  6958. }
  6959. }
  6960. return $ret;
  6961. }
  6962. /**
  6963. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  6964. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6965. * Note: Prefer to use setEventMessages instead.
  6966. *
  6967. * @param string|string[] $mesgs Message string or array
  6968. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6969. * @return void
  6970. * @see dol_htmloutput_events()
  6971. */
  6972. function setEventMessage($mesgs, $style = 'mesgs')
  6973. {
  6974. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  6975. if (!is_array($mesgs)) {
  6976. // If mesgs is a string
  6977. if ($mesgs) {
  6978. $_SESSION['dol_events'][$style][] = $mesgs;
  6979. }
  6980. } else {
  6981. // If mesgs is an array
  6982. foreach ($mesgs as $mesg) {
  6983. if ($mesg) {
  6984. $_SESSION['dol_events'][$style][] = $mesg;
  6985. }
  6986. }
  6987. }
  6988. }
  6989. /**
  6990. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  6991. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6992. *
  6993. * @param string $mesg Message string
  6994. * @param array $mesgs Message array
  6995. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6996. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  6997. * @return void
  6998. * @see dol_htmloutput_events()
  6999. */
  7000. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  7001. {
  7002. if (empty($mesg) && empty($mesgs)) {
  7003. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  7004. } else {
  7005. if ($messagekey) {
  7006. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7007. // TODO
  7008. $mesg .= '';
  7009. }
  7010. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7011. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7012. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7013. }
  7014. if (empty($mesgs)) {
  7015. setEventMessage($mesg, $style);
  7016. } else {
  7017. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7018. setEventMessage($mesg, $style); // Add message string if not already into array
  7019. }
  7020. setEventMessage($mesgs, $style);
  7021. }
  7022. }
  7023. }
  7024. }
  7025. /**
  7026. * Print formated messages to output (Used to show messages on html output).
  7027. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7028. * no need to call it explicitely.
  7029. *
  7030. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7031. * @return void
  7032. * @see dol_htmloutput_mesg()
  7033. */
  7034. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7035. {
  7036. // Show mesgs
  7037. if (isset($_SESSION['dol_events']['mesgs'])) {
  7038. if (empty($disabledoutputofmessages)) {
  7039. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7040. }
  7041. unset($_SESSION['dol_events']['mesgs']);
  7042. }
  7043. // Show errors
  7044. if (isset($_SESSION['dol_events']['errors'])) {
  7045. if (empty($disabledoutputofmessages)) {
  7046. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7047. }
  7048. unset($_SESSION['dol_events']['errors']);
  7049. }
  7050. // Show warnings
  7051. if (isset($_SESSION['dol_events']['warnings'])) {
  7052. if (empty($disabledoutputofmessages)) {
  7053. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7054. }
  7055. unset($_SESSION['dol_events']['warnings']);
  7056. }
  7057. }
  7058. /**
  7059. * Get formated messages to output (Used to show messages on html output).
  7060. * This include also the translation of the message key.
  7061. *
  7062. * @param string $mesgstring Message string or message key
  7063. * @param string[] $mesgarray Array of message strings or message keys
  7064. * @param string $style Style of message output ('ok' or 'error')
  7065. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7066. * @return string Return html output
  7067. *
  7068. * @see dol_print_error()
  7069. * @see dol_htmloutput_errors()
  7070. * @see setEventMessages()
  7071. */
  7072. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7073. {
  7074. global $conf, $langs;
  7075. $ret = 0;
  7076. $return = '';
  7077. $out = '';
  7078. $divstart = $divend = '';
  7079. // If inline message with no format, we add it.
  7080. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7081. $divstart = '<div class="'.$style.' clearboth">';
  7082. $divend = '</div>';
  7083. }
  7084. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7085. $langs->load("errors");
  7086. $out .= $divstart;
  7087. if (is_array($mesgarray) && count($mesgarray)) {
  7088. foreach ($mesgarray as $message) {
  7089. $ret++;
  7090. $out .= $langs->trans($message);
  7091. if ($ret < count($mesgarray)) {
  7092. $out .= "<br>\n";
  7093. }
  7094. }
  7095. }
  7096. if ($mesgstring) {
  7097. $langs->load("errors");
  7098. $ret++;
  7099. $out .= $langs->trans($mesgstring);
  7100. }
  7101. $out .= $divend;
  7102. }
  7103. if ($out) {
  7104. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7105. $return = '<script>
  7106. $(document).ready(function() {
  7107. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7108. if (block) {
  7109. $.dolEventValid("","'.dol_escape_js($out).'");
  7110. } else {
  7111. /* jnotify(message, preset of message type, keepmessage) */
  7112. $.jnotify("'.dol_escape_js($out).'",
  7113. "'.($style == "ok" ? 3000 : $style).'",
  7114. '.($style == "ok" ? "false" : "true").',
  7115. { remove: function (){} } );
  7116. }
  7117. });
  7118. </script>';
  7119. } else {
  7120. $return = $out;
  7121. }
  7122. }
  7123. return $return;
  7124. }
  7125. /**
  7126. * Get formated error messages to output (Used to show messages on html output).
  7127. *
  7128. * @param string $mesgstring Error message
  7129. * @param array $mesgarray Error messages array
  7130. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7131. * @return string Return html output
  7132. *
  7133. * @see dol_print_error()
  7134. * @see dol_htmloutput_mesg()
  7135. */
  7136. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7137. {
  7138. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7139. }
  7140. /**
  7141. * Print formated messages to output (Used to show messages on html output).
  7142. *
  7143. * @param string $mesgstring Message string or message key
  7144. * @param string[] $mesgarray Array of message strings or message keys
  7145. * @param string $style Which style to use ('ok', 'warning', 'error')
  7146. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7147. * @return void
  7148. *
  7149. * @see dol_print_error()
  7150. * @see dol_htmloutput_errors()
  7151. * @see setEventMessages()
  7152. */
  7153. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7154. {
  7155. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7156. return;
  7157. }
  7158. $iserror = 0;
  7159. $iswarning = 0;
  7160. if (is_array($mesgarray)) {
  7161. foreach ($mesgarray as $val) {
  7162. if ($val && preg_match('/class="error"/i', $val)) {
  7163. $iserror++;
  7164. break;
  7165. }
  7166. if ($val && preg_match('/class="warning"/i', $val)) {
  7167. $iswarning++;
  7168. break;
  7169. }
  7170. }
  7171. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7172. $iserror++;
  7173. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7174. $iswarning++;
  7175. }
  7176. if ($style == 'error') {
  7177. $iserror++;
  7178. }
  7179. if ($style == 'warning') {
  7180. $iswarning++;
  7181. }
  7182. if ($iserror || $iswarning) {
  7183. // Remove div from texts
  7184. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7185. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7186. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7187. // Remove div from texts array
  7188. if (is_array($mesgarray)) {
  7189. $newmesgarray = array();
  7190. foreach ($mesgarray as $val) {
  7191. if (is_string($val)) {
  7192. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7193. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7194. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7195. $newmesgarray[] = $tmpmesgstring;
  7196. } else {
  7197. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7198. }
  7199. }
  7200. $mesgarray = $newmesgarray;
  7201. }
  7202. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7203. } else {
  7204. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7205. }
  7206. }
  7207. /**
  7208. * Print formated error messages to output (Used to show messages on html output).
  7209. *
  7210. * @param string $mesgstring Error message
  7211. * @param array $mesgarray Error messages array
  7212. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7213. * @return void
  7214. *
  7215. * @see dol_print_error()
  7216. * @see dol_htmloutput_mesg()
  7217. */
  7218. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7219. {
  7220. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7221. }
  7222. /**
  7223. * Advanced sort array by second index function, which produces ascending (default)
  7224. * or descending output and uses optionally natural case insensitive sorting (which
  7225. * can be optionally case sensitive as well).
  7226. *
  7227. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7228. * @param string $index Key in array to use for sorting criteria
  7229. * @param int $order Sort order ('asc' or 'desc')
  7230. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7231. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7232. * @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.
  7233. * @return array Sorted array
  7234. */
  7235. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7236. {
  7237. // Clean parameters
  7238. $order = strtolower($order);
  7239. if (is_array($array)) {
  7240. $sizearray = count($array);
  7241. if ($sizearray > 0) {
  7242. $temp = array();
  7243. foreach (array_keys($array) as $key) {
  7244. if (is_object($array[$key])) {
  7245. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7246. } else {
  7247. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7248. }
  7249. }
  7250. if (!$natsort) {
  7251. if ($order == 'asc') {
  7252. asort($temp);
  7253. } else {
  7254. arsort($temp);
  7255. }
  7256. } else {
  7257. if ($case_sensitive) {
  7258. natsort($temp);
  7259. } else {
  7260. natcasesort($temp); // natecasesort is not sensible to case
  7261. }
  7262. if ($order != 'asc') {
  7263. $temp = array_reverse($temp, true);
  7264. }
  7265. }
  7266. $sorted = array();
  7267. foreach (array_keys($temp) as $key) {
  7268. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7269. }
  7270. return $sorted;
  7271. }
  7272. }
  7273. return $array;
  7274. }
  7275. /**
  7276. * Check if a string is in UTF8
  7277. *
  7278. * @param string $str String to check
  7279. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7280. */
  7281. function utf8_check($str)
  7282. {
  7283. $str = (string) $str; // Sometimes string is an int.
  7284. // We must use here a binary strlen function (so not dol_strlen)
  7285. $strLength = dol_strlen($str);
  7286. for ($i = 0; $i < $strLength; $i++) {
  7287. if (ord($str[$i]) < 0x80) {
  7288. continue; // 0bbbbbbb
  7289. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7290. $n = 1; // 110bbbbb
  7291. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7292. $n = 2; // 1110bbbb
  7293. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7294. $n = 3; // 11110bbb
  7295. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7296. $n = 4; // 111110bb
  7297. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7298. $n = 5; // 1111110b
  7299. } else {
  7300. return false; // Does not match any model
  7301. }
  7302. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7303. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7304. return false;
  7305. }
  7306. }
  7307. }
  7308. return true;
  7309. }
  7310. /**
  7311. * Check if a string is in ASCII
  7312. *
  7313. * @param string $str String to check
  7314. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7315. */
  7316. function ascii_check($str)
  7317. {
  7318. if (function_exists('mb_check_encoding')) {
  7319. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7320. if (!mb_check_encoding($str, 'ASCII')) {
  7321. return false;
  7322. }
  7323. } else {
  7324. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7325. return false; // Contains a byte > 7f
  7326. }
  7327. }
  7328. return true;
  7329. }
  7330. /**
  7331. * Return a string encoded into OS filesystem encoding. This function is used to define
  7332. * value to pass to filesystem PHP functions.
  7333. *
  7334. * @param string $str String to encode (UTF-8)
  7335. * @return string Encoded string (UTF-8, ISO-8859-1)
  7336. */
  7337. function dol_osencode($str)
  7338. {
  7339. global $conf;
  7340. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7341. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7342. $tmp = 'iso-8859-1'; // By default for windows
  7343. }
  7344. if (empty($tmp)) {
  7345. $tmp = 'utf-8'; // By default for other
  7346. }
  7347. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7348. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7349. }
  7350. if ($tmp == 'iso-8859-1') {
  7351. return utf8_decode($str);
  7352. }
  7353. return $str;
  7354. }
  7355. /**
  7356. * Return an id or code from a code or id.
  7357. * Store also Code-Id into a cache to speed up next request on same key.
  7358. *
  7359. * @param DoliDB $db Database handler
  7360. * @param string $key Code or Id to get Id or Code
  7361. * @param string $tablename Table name without prefix
  7362. * @param string $fieldkey Field to search the key into
  7363. * @param string $fieldid Field to get
  7364. * @param int $entityfilter Filter by entity
  7365. * @return int <0 if KO, Id of code if OK
  7366. * @see $langs->getLabelFromKey
  7367. */
  7368. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  7369. {
  7370. global $cache_codes;
  7371. // If key empty
  7372. if ($key == '') {
  7373. return '';
  7374. }
  7375. // Check in cache
  7376. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7377. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7378. }
  7379. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7380. $sql = "SELECT ".$fieldid." as valuetoget";
  7381. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7382. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7383. if (!empty($entityfilter)) {
  7384. $sql .= " AND entity IN (".getEntity($tablename).")";
  7385. }
  7386. $resql = $db->query($sql);
  7387. if ($resql) {
  7388. $obj = $db->fetch_object($resql);
  7389. if ($obj) {
  7390. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7391. } else {
  7392. $cache_codes[$tablename][$key][$fieldid] = '';
  7393. }
  7394. $db->free($resql);
  7395. return $cache_codes[$tablename][$key][$fieldid];
  7396. } else {
  7397. return -1;
  7398. }
  7399. }
  7400. /**
  7401. * Verify if condition in string is ok or not
  7402. *
  7403. * @param string $strToEvaluate String with condition to check
  7404. * @return boolean True or False. Note: It returns True if $strToEvaluate is ''
  7405. */
  7406. function verifCond($strToEvaluate)
  7407. {
  7408. global $user, $conf, $langs;
  7409. global $leftmenu;
  7410. global $rights; // To export to dol_eval function
  7411. //print $strToEvaluate."<br>\n";
  7412. $rights = true;
  7413. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  7414. $str = 'if(!('.$strToEvaluate.')) { $rights = false; }';
  7415. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  7416. }
  7417. return $rights;
  7418. }
  7419. /**
  7420. * Replace eval function to add more security.
  7421. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7422. *
  7423. * @param string $s String to evaluate
  7424. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7425. * @param int $hideerrors 1=Hide errors
  7426. * @return mixed Nothing or return result of eval
  7427. */
  7428. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  7429. {
  7430. // Only global variables can be changed by eval function and returned to caller
  7431. global $db, $langs, $user, $conf, $website, $websitepage;
  7432. global $action, $mainmenu, $leftmenu;
  7433. global $rights;
  7434. global $object;
  7435. global $mysoc;
  7436. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7437. global $soc; // For backward compatibility
  7438. // Replace dangerous char (used for RCE), we allow only PHP variable testing.
  7439. if (strpos($s, '`') !== false) {
  7440. return 'Bad string syntax to evaluate: '.$s;
  7441. }
  7442. // We block use of php exec or php file functions
  7443. $forbiddenphpstrings = array('$$');
  7444. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7445. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI");
  7446. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask"));
  7447. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  7448. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  7449. do {
  7450. $oldstringtoclean = $s;
  7451. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7452. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  7453. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7454. } while ($oldstringtoclean != $s);
  7455. if (strpos($s, '__forbiddenstring__') !== false) {
  7456. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7457. return 'Bad string syntax to evaluate: '.$s;
  7458. }
  7459. //print $s."<br>\n";
  7460. if ($returnvalue) {
  7461. if ($hideerrors) {
  7462. return @eval('return '.$s.';');
  7463. } else {
  7464. return eval('return '.$s.';');
  7465. }
  7466. } else {
  7467. if ($hideerrors) {
  7468. @eval($s);
  7469. } else {
  7470. eval($s);
  7471. }
  7472. }
  7473. }
  7474. /**
  7475. * Return if var element is ok
  7476. *
  7477. * @param string $element Variable to check
  7478. * @return boolean Return true of variable is not empty
  7479. */
  7480. function dol_validElement($element)
  7481. {
  7482. return (trim($element) != '');
  7483. }
  7484. /**
  7485. * Return img flag of country for a language code or country code.
  7486. *
  7487. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7488. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7489. * @param int $notitlealt No title alt
  7490. * @return string HTML img string with flag.
  7491. */
  7492. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  7493. {
  7494. if (empty($codelang)) {
  7495. return '';
  7496. }
  7497. if ($codelang == 'auto') {
  7498. return '<span class="fa fa-language"></span>';
  7499. }
  7500. $langtocountryflag = array(
  7501. 'ar_AR' => '',
  7502. 'ca_ES' => 'catalonia',
  7503. 'da_DA' => 'dk',
  7504. 'fr_CA' => 'mq',
  7505. 'sv_SV' => 'se',
  7506. 'sw_SW' => 'unknown',
  7507. 'AQ' => 'unknown',
  7508. 'CW' => 'unknown',
  7509. 'IM' => 'unknown',
  7510. 'JE' => 'unknown',
  7511. 'MF' => 'unknown',
  7512. 'BL' => 'unknown',
  7513. 'SX' => 'unknown'
  7514. );
  7515. if (isset($langtocountryflag[$codelang])) {
  7516. $flagImage = $langtocountryflag[$codelang];
  7517. } else {
  7518. $tmparray = explode('_', $codelang);
  7519. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7520. }
  7521. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  7522. }
  7523. /**
  7524. * Return default language from country code.
  7525. * Return null if not found.
  7526. *
  7527. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  7528. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  7529. */
  7530. function getLanguageCodeFromCountryCode($countrycode)
  7531. {
  7532. global $mysoc;
  7533. if (empty($countrycode)) {
  7534. return null;
  7535. }
  7536. if (strtoupper($countrycode) == 'MQ') {
  7537. return 'fr_CA';
  7538. }
  7539. if (strtoupper($countrycode) == 'SE') {
  7540. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7541. }
  7542. if (strtoupper($countrycode) == 'CH') {
  7543. if ($mysoc->country_code == 'FR') {
  7544. return 'fr_CH';
  7545. }
  7546. if ($mysoc->country_code == 'DE') {
  7547. return 'de_CH';
  7548. }
  7549. if ($mysoc->country_code == 'IT') {
  7550. return 'it_CH';
  7551. }
  7552. }
  7553. // Locale list taken from:
  7554. // http://stackoverflow.com/questions/3191664/
  7555. // list-of-all-locales-and-their-short-codes
  7556. $locales = array(
  7557. 'af-ZA',
  7558. 'am-ET',
  7559. 'ar-AE',
  7560. 'ar-BH',
  7561. 'ar-DZ',
  7562. 'ar-EG',
  7563. 'ar-IQ',
  7564. 'ar-JO',
  7565. 'ar-KW',
  7566. 'ar-LB',
  7567. 'ar-LY',
  7568. 'ar-MA',
  7569. 'ar-OM',
  7570. 'ar-QA',
  7571. 'ar-SA',
  7572. 'ar-SY',
  7573. 'ar-TN',
  7574. 'ar-YE',
  7575. //'as-IN', // Moved after en-IN
  7576. 'ba-RU',
  7577. 'be-BY',
  7578. 'bg-BG',
  7579. 'bn-BD',
  7580. //'bn-IN', // Moved after en-IN
  7581. 'bo-CN',
  7582. 'br-FR',
  7583. 'ca-ES',
  7584. 'co-FR',
  7585. 'cs-CZ',
  7586. 'cy-GB',
  7587. 'da-DK',
  7588. 'de-AT',
  7589. 'de-CH',
  7590. 'de-DE',
  7591. 'de-LI',
  7592. 'de-LU',
  7593. 'dv-MV',
  7594. 'el-GR',
  7595. 'en-AU',
  7596. 'en-BZ',
  7597. 'en-CA',
  7598. 'en-GB',
  7599. 'en-IE',
  7600. 'en-IN',
  7601. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  7602. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  7603. 'en-JM',
  7604. 'en-MY',
  7605. 'en-NZ',
  7606. 'en-PH',
  7607. 'en-SG',
  7608. 'en-TT',
  7609. 'en-US',
  7610. 'en-ZA',
  7611. 'en-ZW',
  7612. 'es-AR',
  7613. 'es-BO',
  7614. 'es-CL',
  7615. 'es-CO',
  7616. 'es-CR',
  7617. 'es-DO',
  7618. 'es-EC',
  7619. 'es-ES',
  7620. 'es-GT',
  7621. 'es-HN',
  7622. 'es-MX',
  7623. 'es-NI',
  7624. 'es-PA',
  7625. 'es-PE',
  7626. 'es-PR',
  7627. 'es-PY',
  7628. 'es-SV',
  7629. 'es-US',
  7630. 'es-UY',
  7631. 'es-VE',
  7632. 'et-EE',
  7633. 'eu-ES',
  7634. 'fa-IR',
  7635. 'fi-FI',
  7636. 'fo-FO',
  7637. 'fr-BE',
  7638. 'fr-CA',
  7639. 'fr-CH',
  7640. 'fr-FR',
  7641. 'fr-LU',
  7642. 'fr-MC',
  7643. 'fy-NL',
  7644. 'ga-IE',
  7645. 'gd-GB',
  7646. 'gl-ES',
  7647. 'gu-IN',
  7648. 'he-IL',
  7649. 'hi-IN',
  7650. 'hr-BA',
  7651. 'hr-HR',
  7652. 'hu-HU',
  7653. 'hy-AM',
  7654. 'id-ID',
  7655. 'ig-NG',
  7656. 'ii-CN',
  7657. 'is-IS',
  7658. 'it-CH',
  7659. 'it-IT',
  7660. 'ja-JP',
  7661. 'ka-GE',
  7662. 'kk-KZ',
  7663. 'kl-GL',
  7664. 'km-KH',
  7665. 'kn-IN',
  7666. 'ko-KR',
  7667. 'ky-KG',
  7668. 'lb-LU',
  7669. 'lo-LA',
  7670. 'lt-LT',
  7671. 'lv-LV',
  7672. 'mi-NZ',
  7673. 'mk-MK',
  7674. 'ml-IN',
  7675. 'mn-MN',
  7676. 'mr-IN',
  7677. 'ms-BN',
  7678. 'ms-MY',
  7679. 'mt-MT',
  7680. 'nb-NO',
  7681. 'ne-NP',
  7682. 'nl-BE',
  7683. 'nl-NL',
  7684. 'nn-NO',
  7685. 'oc-FR',
  7686. 'or-IN',
  7687. 'pa-IN',
  7688. 'pl-PL',
  7689. 'ps-AF',
  7690. 'pt-BR',
  7691. 'pt-PT',
  7692. 'rm-CH',
  7693. 'ro-MD',
  7694. 'ro-RO',
  7695. 'ru-RU',
  7696. 'rw-RW',
  7697. 'sa-IN',
  7698. 'se-FI',
  7699. 'se-NO',
  7700. 'se-SE',
  7701. 'si-LK',
  7702. 'sk-SK',
  7703. 'sl-SI',
  7704. 'sq-AL',
  7705. 'sv-FI',
  7706. 'sv-SE',
  7707. 'sw-KE',
  7708. 'ta-IN',
  7709. 'te-IN',
  7710. 'th-TH',
  7711. 'tk-TM',
  7712. 'tn-ZA',
  7713. 'tr-TR',
  7714. 'tt-RU',
  7715. 'ug-CN',
  7716. 'uk-UA',
  7717. 'ur-PK',
  7718. 'vi-VN',
  7719. 'wo-SN',
  7720. 'xh-ZA',
  7721. 'yo-NG',
  7722. 'zh-CN',
  7723. 'zh-HK',
  7724. 'zh-MO',
  7725. 'zh-SG',
  7726. 'zh-TW',
  7727. 'zu-ZA',
  7728. );
  7729. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  7730. if (in_array($buildprimarykeytotest, $locales)) {
  7731. return strtolower($countrycode).'_'.strtoupper($countrycode);
  7732. }
  7733. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  7734. foreach ($locales as $locale) {
  7735. $locale_language = locale_get_primary_language($locale);
  7736. $locale_region = locale_get_region($locale);
  7737. if (strtoupper($countrycode) == $locale_region) {
  7738. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  7739. return strtolower($locale_language).'_'.strtoupper($locale_region);
  7740. }
  7741. }
  7742. } else {
  7743. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  7744. }
  7745. return null;
  7746. }
  7747. /**
  7748. * Complete or removed entries into a head array (used to build tabs).
  7749. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  7750. * Or by change using hook completeTabsHead
  7751. *
  7752. * @param Conf $conf Object conf
  7753. * @param Translate $langs Object langs
  7754. * @param object|null $object Object object
  7755. * @param array $head Object head
  7756. * @param int $h New position to fill
  7757. * @param string $type Value for object where objectvalue can be
  7758. * 'thirdparty' to add a tab in third party view
  7759. * 'intervention' to add a tab in intervention view
  7760. * 'supplier_order' to add a tab in supplier order view
  7761. * 'supplier_invoice' to add a tab in supplier invoice view
  7762. * 'invoice' to add a tab in customer invoice view
  7763. * 'order' to add a tab in customer order view
  7764. * 'contract' to add a tabl in contract view
  7765. * 'product' to add a tab in product view
  7766. * 'propal' to add a tab in propal view
  7767. * 'user' to add a tab in user view
  7768. * 'group' to add a tab in group view
  7769. * 'member' to add a tab in fundation member view
  7770. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  7771. * 'ecm' to add a tab for another ecm view
  7772. * 'stock' to add a tab for warehouse view
  7773. * @param string $mode 'add' to complete head, 'remove' to remove entries
  7774. * @return void
  7775. */
  7776. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  7777. {
  7778. global $hookmanager;
  7779. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  7780. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  7781. $values = explode(':', $value);
  7782. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  7783. if (count($values) == 6) { // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  7784. if ($values[0] != $type) {
  7785. continue;
  7786. }
  7787. if (verifCond($values[4])) {
  7788. if ($values[3]) {
  7789. $langs->load($values[3]);
  7790. }
  7791. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7792. $substitutionarray = array();
  7793. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7794. $label = make_substitutions($reg[1], $substitutionarray);
  7795. } else {
  7796. $label = $langs->trans($values[2]);
  7797. }
  7798. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  7799. $head[$h][1] = $label;
  7800. $head[$h][2] = str_replace('+', '', $values[1]);
  7801. $h++;
  7802. }
  7803. } elseif (count($values) == 5) { // deprecated
  7804. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  7805. if ($values[0] != $type) {
  7806. continue;
  7807. }
  7808. if ($values[3]) {
  7809. $langs->load($values[3]);
  7810. }
  7811. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  7812. $substitutionarray = array();
  7813. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  7814. $label = make_substitutions($reg[1], $substitutionarray);
  7815. } else {
  7816. $label = $langs->trans($values[2]);
  7817. }
  7818. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  7819. $head[$h][1] = $label;
  7820. $head[$h][2] = str_replace('+', '', $values[1]);
  7821. $h++;
  7822. }
  7823. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  7824. if ($values[0] != $type) {
  7825. continue;
  7826. }
  7827. $tabname = str_replace('-', '', $values[1]);
  7828. foreach ($head as $key => $val) {
  7829. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  7830. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  7831. if ($head[$key][2] == $tabname && $condition) {
  7832. unset($head[$key]);
  7833. break;
  7834. }
  7835. }
  7836. }
  7837. }
  7838. }
  7839. // No need to make a return $head. Var is modified as a reference
  7840. if (!empty($hookmanager)) {
  7841. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  7842. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  7843. if ($reshook > 0) { // Hook ask to replace completely the array
  7844. $head = $hookmanager->resArray;
  7845. } else { // Hook
  7846. $head = array_merge($head, $hookmanager->resArray);
  7847. }
  7848. $h = count($head);
  7849. }
  7850. }
  7851. /**
  7852. * Print common footer :
  7853. * conf->global->MAIN_HTML_FOOTER
  7854. * js for switch of menu hider
  7855. * js for conf->global->MAIN_GOOGLE_AN_ID
  7856. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  7857. * js for conf->logbuffer
  7858. *
  7859. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  7860. * @return void
  7861. */
  7862. function printCommonFooter($zone = 'private')
  7863. {
  7864. global $conf, $hookmanager, $user, $debugbar;
  7865. global $action;
  7866. global $micro_start_time;
  7867. if ($zone == 'private') {
  7868. print "\n".'<!-- Common footer for private page -->'."\n";
  7869. } else {
  7870. print "\n".'<!-- Common footer for public page -->'."\n";
  7871. }
  7872. // A div to store page_y POST parameter so we can read it using javascript
  7873. print "\n<!-- A div to store page_y POST parameter -->\n";
  7874. print '<div id="page_y" style="display: none;">'.(empty($_POST['page_y']) ? '' : $_POST['page_y']).'</div>'."\n";
  7875. $parameters = array();
  7876. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  7877. if (empty($reshook)) {
  7878. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  7879. print $conf->global->MAIN_HTML_FOOTER."\n";
  7880. }
  7881. print "\n";
  7882. if (!empty($conf->use_javascript_ajax)) {
  7883. print '<script>'."\n";
  7884. print 'jQuery(document).ready(function() {'."\n";
  7885. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  7886. print "\n";
  7887. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  7888. print 'jQuery("li.menuhider").click(function(event) {';
  7889. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  7890. print ' console.log("We click on .menuhider");'."\n";
  7891. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  7892. print '});'."\n";
  7893. }
  7894. // Management of focus and mandatory for fields
  7895. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  7896. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  7897. $relativepathstring = $_SERVER["PHP_SELF"];
  7898. // Clean $relativepathstring
  7899. if (constant('DOL_URL_ROOT')) {
  7900. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  7901. }
  7902. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  7903. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  7904. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  7905. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  7906. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  7907. $qualified = 0;
  7908. if ($defkey != '_noquery_') {
  7909. $tmpqueryarraytohave = explode('&', $defkey);
  7910. $foundintru = 0;
  7911. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7912. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7913. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7914. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7915. $foundintru = 1;
  7916. }
  7917. }
  7918. if (!$foundintru) {
  7919. $qualified = 1;
  7920. }
  7921. //var_dump($defkey.'-'.$qualified);
  7922. } else {
  7923. $qualified = 1;
  7924. }
  7925. if ($qualified) {
  7926. foreach ($defval as $paramkey => $paramval) {
  7927. // Set focus on field
  7928. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  7929. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  7930. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  7931. }
  7932. }
  7933. }
  7934. }
  7935. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  7936. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  7937. $qualified = 0;
  7938. if ($defkey != '_noquery_') {
  7939. $tmpqueryarraytohave = explode('&', $defkey);
  7940. $foundintru = 0;
  7941. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  7942. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7943. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7944. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  7945. $foundintru = 1;
  7946. }
  7947. }
  7948. if (!$foundintru) {
  7949. $qualified = 1;
  7950. }
  7951. //var_dump($defkey.'-'.$qualified);
  7952. } else {
  7953. $qualified = 1;
  7954. }
  7955. if ($qualified) {
  7956. foreach ($defval as $paramkey => $paramval) {
  7957. // Add property 'required' on input
  7958. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7959. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7960. 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";
  7961. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7962. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  7963. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  7964. }
  7965. }
  7966. }
  7967. }
  7968. }
  7969. print '});'."\n";
  7970. // End of tuning
  7971. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  7972. print "\n";
  7973. print "/* JS CODE TO ENABLE to add memory info */\n";
  7974. print 'window.console && console.log("';
  7975. if (!empty($conf->global->MEMCACHED_SERVER)) {
  7976. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  7977. }
  7978. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  7979. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  7980. $micro_end_time = microtime(true);
  7981. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  7982. }
  7983. if (function_exists("memory_get_usage")) {
  7984. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  7985. }
  7986. if (function_exists("memory_get_peak_usage")) {
  7987. print ' - Real mem peak: '.memory_get_peak_usage(true);
  7988. }
  7989. if (function_exists("zend_loader_file_encoded")) {
  7990. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  7991. }
  7992. print '");'."\n";
  7993. }
  7994. print "\n".'</script>'."\n";
  7995. // Google Analytics
  7996. // TODO Add a hook here
  7997. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  7998. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  7999. foreach ($tmptagarray as $tmptag) {
  8000. print "\n";
  8001. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8002. print "
  8003. <!-- Global site tag (gtag.js) - Google Analytics -->
  8004. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  8005. <script>
  8006. window.dataLayer = window.dataLayer || [];
  8007. function gtag(){dataLayer.push(arguments);}
  8008. gtag('js', new Date());
  8009. gtag('config', '".trim($tmptag)."');
  8010. </script>";
  8011. print "\n";
  8012. }
  8013. }
  8014. }
  8015. // Add Xdebug coverage of code
  8016. if (defined('XDEBUGCOVERAGE')) {
  8017. print_r(xdebug_get_code_coverage());
  8018. }
  8019. // Add DebugBar data
  8020. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8021. $debugbar['time']->stopMeasure('pageaftermaster');
  8022. print '<!-- Output debugbar data -->'."\n";
  8023. $renderer = $debugbar->getRenderer();
  8024. print $debugbar->getRenderer()->render();
  8025. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8026. print "\n";
  8027. print "<!-- Start of log output\n";
  8028. //print '<div class="hidden">'."\n";
  8029. foreach ($conf->logbuffer as $logline) {
  8030. print $logline."<br>\n";
  8031. }
  8032. //print '</div>'."\n";
  8033. print "End of log output -->\n";
  8034. }
  8035. }
  8036. }
  8037. /**
  8038. * Split a string with 2 keys into key array.
  8039. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8040. *
  8041. * @param string $string String to explode
  8042. * @param string $delimiter Delimiter between each couple of data
  8043. * @param string $kv Delimiter between key and value
  8044. * @return array Array of data exploded
  8045. */
  8046. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8047. {
  8048. if ($a = explode($delimiter, $string)) {
  8049. $ka = array();
  8050. foreach ($a as $s) { // each part
  8051. if ($s) {
  8052. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8053. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8054. } else { // key delimiter not found
  8055. $ka[] = trim($s);
  8056. }
  8057. }
  8058. }
  8059. return $ka;
  8060. }
  8061. return array();
  8062. }
  8063. /**
  8064. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  8065. *
  8066. * @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.
  8067. * @return void
  8068. */
  8069. function dol_set_focus($selector)
  8070. {
  8071. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8072. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8073. }
  8074. /**
  8075. * Return getmypid() or random PID when function is disabled
  8076. * Some web hosts disable this php function for security reasons
  8077. * and sometimes we can't redeclare function
  8078. *
  8079. * @return int
  8080. */
  8081. function dol_getmypid()
  8082. {
  8083. if (!function_exists('getmypid')) {
  8084. return mt_rand(1, 32768);
  8085. } else {
  8086. return getmypid();
  8087. }
  8088. }
  8089. /**
  8090. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8091. *
  8092. * @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")
  8093. * @param string $value The value to look for.
  8094. * If param $mode is 0, can contains several keywords separated with a space or |
  8095. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8096. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8097. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8098. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8099. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8100. * @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')
  8101. * 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'
  8102. * @param integer $nofirstand 1=Do not output the first 'AND'
  8103. * @return string $res The statement to append to the SQL query
  8104. */
  8105. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8106. {
  8107. global $db, $langs;
  8108. $value = trim($value);
  8109. if ($mode == 0) {
  8110. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8111. }
  8112. if ($mode == 1) {
  8113. $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
  8114. }
  8115. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8116. $crits = explode(' ', $value);
  8117. $res = '';
  8118. if (!is_array($fields)) {
  8119. $fields = array($fields);
  8120. }
  8121. $j = 0;
  8122. foreach ($crits as $crit) {
  8123. $crit = trim($crit);
  8124. $i = 0;
  8125. $i2 = 0;
  8126. $newres = '';
  8127. foreach ($fields as $field) {
  8128. if ($mode == 1) {
  8129. $operator = '=';
  8130. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8131. $reg = array();
  8132. preg_match('/([<>=]+)/', $crit, $reg);
  8133. if ($reg[1]) {
  8134. $operator = $reg[1];
  8135. }
  8136. if ($newcrit != '') {
  8137. $numnewcrit = price2num($newcrit);
  8138. if (is_numeric($numnewcrit)) {
  8139. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  8140. } else {
  8141. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8142. }
  8143. $i2++; // a criteria was added to string
  8144. }
  8145. } elseif ($mode == 2 || $mode == -2) {
  8146. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8147. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8148. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8149. if ($mode == -2) {
  8150. $newres .= ' OR '.$field.' IS NULL';
  8151. }
  8152. $i2++; // a criteria was added to string
  8153. } elseif ($mode == 3 || $mode == -3) {
  8154. $tmparray = explode(',', $crit);
  8155. if (count($tmparray)) {
  8156. $listofcodes = '';
  8157. foreach ($tmparray as $val) {
  8158. $val = trim($val);
  8159. if ($val) {
  8160. $listofcodes .= ($listofcodes ? ',' : '');
  8161. $listofcodes .= "'".$db->escape($val)."'";
  8162. }
  8163. }
  8164. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8165. $i2++; // a criteria was added to string
  8166. }
  8167. if ($mode == -3) {
  8168. $newres .= ' OR '.$field.' IS NULL';
  8169. }
  8170. } elseif ($mode == 4) {
  8171. $tmparray = explode(',', $crit);
  8172. if (count($tmparray)) {
  8173. $listofcodes = '';
  8174. foreach ($tmparray as $val) {
  8175. $val = trim($val);
  8176. if ($val) {
  8177. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8178. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8179. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8180. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8181. $newres .= ')';
  8182. $i2++;
  8183. }
  8184. }
  8185. }
  8186. } else // $mode=0
  8187. {
  8188. $tmpcrits = explode('|', $crit);
  8189. $i3 = 0;
  8190. foreach ($tmpcrits as $tmpcrit) {
  8191. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8192. continue;
  8193. }
  8194. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8195. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8196. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? ((float) trim($tmpcrit)) : '0');
  8197. } else {
  8198. $newres .= $field." LIKE '";
  8199. $tmpcrit = trim($tmpcrit);
  8200. $tmpcrit2 = $tmpcrit;
  8201. $tmpbefore = '%';
  8202. $tmpafter = '%';
  8203. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8204. $tmpbefore = '';
  8205. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8206. }
  8207. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8208. $tmpafter = '';
  8209. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8210. }
  8211. $newres .= $tmpbefore;
  8212. $newres .= $db->escape($tmpcrit2);
  8213. $newres .= $tmpafter;
  8214. $newres .= "'";
  8215. if ($tmpcrit2 == '') {
  8216. $newres .= " OR ".$field." IS NULL";
  8217. }
  8218. }
  8219. $i3++;
  8220. }
  8221. $i2++; // a criteria was added to string
  8222. }
  8223. $i++;
  8224. }
  8225. if ($newres) {
  8226. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8227. }
  8228. $j++;
  8229. }
  8230. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8231. //print 'xx'.$res.'yy';
  8232. return $res;
  8233. }
  8234. /**
  8235. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8236. *
  8237. * @param Object $object Object
  8238. * @return string Url string
  8239. */
  8240. function showDirectDownloadLink($object)
  8241. {
  8242. global $conf, $langs;
  8243. $out = '';
  8244. $url = $object->getLastMainDocLink($object->element);
  8245. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8246. if ($url) {
  8247. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8248. $out .= ajax_autoselect("directdownloadlink", 0);
  8249. } else {
  8250. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8251. }
  8252. return $out;
  8253. }
  8254. /**
  8255. * Return the filename of file to get the thumbs
  8256. *
  8257. * @param string $file Original filename (full or relative path)
  8258. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8259. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8260. * @return string New file name (full or relative path, including the thumbs/)
  8261. */
  8262. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8263. {
  8264. $dirName = dirname($file);
  8265. if ($dirName == '.') {
  8266. $dirName = '';
  8267. }
  8268. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8269. $fileName = basename($fileName);
  8270. if (empty($extImgTarget)) {
  8271. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8272. }
  8273. if (empty($extImgTarget)) {
  8274. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8275. }
  8276. if (empty($extImgTarget)) {
  8277. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8278. }
  8279. if (empty($extImgTarget)) {
  8280. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8281. }
  8282. if (empty($extImgTarget)) {
  8283. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8284. }
  8285. if (empty($extImgTarget)) {
  8286. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8287. }
  8288. if (!$extImgTarget) {
  8289. return $file;
  8290. }
  8291. $subdir = '';
  8292. if ($extName) {
  8293. $subdir = 'thumbs/';
  8294. }
  8295. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8296. }
  8297. /**
  8298. * Return URL we can use for advanced preview links
  8299. *
  8300. * @param string $modulepart propal, facture, facture_fourn, ...
  8301. * @param string $relativepath Relative path of docs.
  8302. * @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)
  8303. * @param string $param More param on http links
  8304. * @return string|array Output string with href link or array with all components of link
  8305. */
  8306. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8307. {
  8308. global $conf, $langs;
  8309. if (empty($conf->use_javascript_ajax)) {
  8310. return '';
  8311. }
  8312. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8313. if ($alldata == 1) {
  8314. if ($isAllowedForPreview) {
  8315. 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));
  8316. } else {
  8317. return array();
  8318. }
  8319. }
  8320. // old behavior, return a string
  8321. if ($isAllowedForPreview) {
  8322. 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')).'\')';
  8323. } else {
  8324. return '';
  8325. }
  8326. }
  8327. /**
  8328. * Make content of an input box selected when we click into input field.
  8329. *
  8330. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8331. * @param string $addlink Add a 'link to' after
  8332. * @param string $textonlink Text to show on link or 'image'
  8333. * @return string
  8334. */
  8335. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  8336. {
  8337. global $langs;
  8338. $out = '<script>
  8339. jQuery(document).ready(function () {
  8340. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8341. });
  8342. </script>';
  8343. if ($addlink) {
  8344. if ($textonlink === 'image') {
  8345. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  8346. } else {
  8347. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  8348. }
  8349. }
  8350. return $out;
  8351. }
  8352. /**
  8353. * Return if a file is qualified for preview
  8354. *
  8355. * @param string $file Filename we looking for information
  8356. * @return int 1 If allowed, 0 otherwise
  8357. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8358. */
  8359. function dolIsAllowedForPreview($file)
  8360. {
  8361. global $conf;
  8362. // Check .noexe extension in filename
  8363. if (preg_match('/\.noexe$/i', $file)) {
  8364. return 0;
  8365. }
  8366. // Check mime types
  8367. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8368. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8369. $mime_preview[] = 'svg+xml';
  8370. }
  8371. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8372. //$mime_preview[]='archive';
  8373. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8374. if ($num_mime !== false) {
  8375. return 1;
  8376. }
  8377. // By default, not allowed for preview
  8378. return 0;
  8379. }
  8380. /**
  8381. * Return mime type of a file
  8382. *
  8383. * @param string $file Filename we looking for MIME type
  8384. * @param string $default Default mime type if extension not found in known list
  8385. * @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
  8386. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8387. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8388. */
  8389. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8390. {
  8391. $mime = $default;
  8392. $imgmime = 'other.png';
  8393. $famime = 'file-o';
  8394. $srclang = '';
  8395. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8396. // Plain text files
  8397. if (preg_match('/\.txt$/i', $tmpfile)) {
  8398. $mime = 'text/plain';
  8399. $imgmime = 'text.png';
  8400. $famime = 'file-text-o';
  8401. }
  8402. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8403. $mime = 'text/richtext';
  8404. $imgmime = 'text.png';
  8405. $famime = 'file-text-o';
  8406. }
  8407. if (preg_match('/\.csv$/i', $tmpfile)) {
  8408. $mime = 'text/csv';
  8409. $imgmime = 'text.png';
  8410. $famime = 'file-text-o';
  8411. }
  8412. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8413. $mime = 'text/tab-separated-values';
  8414. $imgmime = 'text.png';
  8415. $famime = 'file-text-o';
  8416. }
  8417. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8418. $mime = 'text/plain';
  8419. $imgmime = 'text.png';
  8420. $famime = 'file-text-o';
  8421. }
  8422. if (preg_match('/\.ini$/i', $tmpfile)) {
  8423. $mime = 'text/plain';
  8424. $imgmime = 'text.png';
  8425. $srclang = 'ini';
  8426. $famime = 'file-text-o';
  8427. }
  8428. if (preg_match('/\.md$/i', $tmpfile)) {
  8429. $mime = 'text/plain';
  8430. $imgmime = 'text.png';
  8431. $srclang = 'md';
  8432. $famime = 'file-text-o';
  8433. }
  8434. if (preg_match('/\.css$/i', $tmpfile)) {
  8435. $mime = 'text/css';
  8436. $imgmime = 'css.png';
  8437. $srclang = 'css';
  8438. $famime = 'file-text-o';
  8439. }
  8440. if (preg_match('/\.lang$/i', $tmpfile)) {
  8441. $mime = 'text/plain';
  8442. $imgmime = 'text.png';
  8443. $srclang = 'lang';
  8444. $famime = 'file-text-o';
  8445. }
  8446. // Certificate files
  8447. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8448. $mime = 'text/plain';
  8449. $imgmime = 'text.png';
  8450. $famime = 'file-text-o';
  8451. }
  8452. // XML based (HTML/XML/XAML)
  8453. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8454. $mime = 'text/html';
  8455. $imgmime = 'html.png';
  8456. $srclang = 'html';
  8457. $famime = 'file-text-o';
  8458. }
  8459. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8460. $mime = 'text/xml';
  8461. $imgmime = 'other.png';
  8462. $srclang = 'xml';
  8463. $famime = 'file-text-o';
  8464. }
  8465. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8466. $mime = 'text/xml';
  8467. $imgmime = 'other.png';
  8468. $srclang = 'xaml';
  8469. $famime = 'file-text-o';
  8470. }
  8471. // Languages
  8472. if (preg_match('/\.bas$/i', $tmpfile)) {
  8473. $mime = 'text/plain';
  8474. $imgmime = 'text.png';
  8475. $srclang = 'bas';
  8476. $famime = 'file-code-o';
  8477. }
  8478. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8479. $mime = 'text/plain';
  8480. $imgmime = 'text.png';
  8481. $srclang = 'c';
  8482. $famime = 'file-code-o';
  8483. }
  8484. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8485. $mime = 'text/plain';
  8486. $imgmime = 'text.png';
  8487. $srclang = 'cpp';
  8488. $famime = 'file-code-o';
  8489. }
  8490. if (preg_match('/\.cs$/i', $tmpfile)) {
  8491. $mime = 'text/plain';
  8492. $imgmime = 'text.png';
  8493. $srclang = 'cs';
  8494. $famime = 'file-code-o';
  8495. }
  8496. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8497. $mime = 'text/plain';
  8498. $imgmime = 'text.png';
  8499. $srclang = 'h';
  8500. $famime = 'file-code-o';
  8501. }
  8502. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8503. $mime = 'text/plain';
  8504. $imgmime = 'text.png';
  8505. $srclang = 'java';
  8506. $famime = 'file-code-o';
  8507. }
  8508. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8509. $mime = 'text/plain';
  8510. $imgmime = 'php.png';
  8511. $srclang = 'php';
  8512. $famime = 'file-code-o';
  8513. }
  8514. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8515. $mime = 'text/plain';
  8516. $imgmime = 'php.png';
  8517. $srclang = 'php';
  8518. $famime = 'file-code-o';
  8519. }
  8520. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8521. $mime = 'text/plain';
  8522. $imgmime = 'pl.png';
  8523. $srclang = 'perl';
  8524. $famime = 'file-code-o';
  8525. }
  8526. if (preg_match('/\.sql$/i', $tmpfile)) {
  8527. $mime = 'text/plain';
  8528. $imgmime = 'text.png';
  8529. $srclang = 'sql';
  8530. $famime = 'file-code-o';
  8531. }
  8532. if (preg_match('/\.js$/i', $tmpfile)) {
  8533. $mime = 'text/x-javascript';
  8534. $imgmime = 'jscript.png';
  8535. $srclang = 'js';
  8536. $famime = 'file-code-o';
  8537. }
  8538. // Open office
  8539. if (preg_match('/\.odp$/i', $tmpfile)) {
  8540. $mime = 'application/vnd.oasis.opendocument.presentation';
  8541. $imgmime = 'ooffice.png';
  8542. $famime = 'file-powerpoint-o';
  8543. }
  8544. if (preg_match('/\.ods$/i', $tmpfile)) {
  8545. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8546. $imgmime = 'ooffice.png';
  8547. $famime = 'file-excel-o';
  8548. }
  8549. if (preg_match('/\.odt$/i', $tmpfile)) {
  8550. $mime = 'application/vnd.oasis.opendocument.text';
  8551. $imgmime = 'ooffice.png';
  8552. $famime = 'file-word-o';
  8553. }
  8554. // MS Office
  8555. if (preg_match('/\.mdb$/i', $tmpfile)) {
  8556. $mime = 'application/msaccess';
  8557. $imgmime = 'mdb.png';
  8558. $famime = 'file-o';
  8559. }
  8560. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  8561. $mime = 'application/msword';
  8562. $imgmime = 'doc.png';
  8563. $famime = 'file-word-o';
  8564. }
  8565. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  8566. $mime = 'application/msword';
  8567. $imgmime = 'doc.png';
  8568. $famime = 'file-word-o';
  8569. }
  8570. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  8571. $mime = 'application/vnd.ms-excel';
  8572. $imgmime = 'xls.png';
  8573. $famime = 'file-excel-o';
  8574. }
  8575. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  8576. $mime = 'application/vnd.ms-excel';
  8577. $imgmime = 'xls.png';
  8578. $famime = 'file-excel-o';
  8579. }
  8580. if (preg_match('/\.xls$/i', $tmpfile)) {
  8581. $mime = 'application/vnd.ms-excel';
  8582. $imgmime = 'xls.png';
  8583. $famime = 'file-excel-o';
  8584. }
  8585. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  8586. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  8587. $imgmime = 'xls.png';
  8588. $famime = 'file-excel-o';
  8589. }
  8590. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  8591. $mime = 'application/vnd.ms-powerpoint';
  8592. $imgmime = 'ppt.png';
  8593. $famime = 'file-powerpoint-o';
  8594. }
  8595. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  8596. $mime = 'application/x-mspowerpoint';
  8597. $imgmime = 'ppt.png';
  8598. $famime = 'file-powerpoint-o';
  8599. }
  8600. // Other
  8601. if (preg_match('/\.pdf$/i', $tmpfile)) {
  8602. $mime = 'application/pdf';
  8603. $imgmime = 'pdf.png';
  8604. $famime = 'file-pdf-o';
  8605. }
  8606. // Scripts
  8607. if (preg_match('/\.bat$/i', $tmpfile)) {
  8608. $mime = 'text/x-bat';
  8609. $imgmime = 'script.png';
  8610. $srclang = 'dos';
  8611. $famime = 'file-code-o';
  8612. }
  8613. if (preg_match('/\.sh$/i', $tmpfile)) {
  8614. $mime = 'text/x-sh';
  8615. $imgmime = 'script.png';
  8616. $srclang = 'bash';
  8617. $famime = 'file-code-o';
  8618. }
  8619. if (preg_match('/\.ksh$/i', $tmpfile)) {
  8620. $mime = 'text/x-ksh';
  8621. $imgmime = 'script.png';
  8622. $srclang = 'bash';
  8623. $famime = 'file-code-o';
  8624. }
  8625. if (preg_match('/\.bash$/i', $tmpfile)) {
  8626. $mime = 'text/x-bash';
  8627. $imgmime = 'script.png';
  8628. $srclang = 'bash';
  8629. $famime = 'file-code-o';
  8630. }
  8631. // Images
  8632. if (preg_match('/\.ico$/i', $tmpfile)) {
  8633. $mime = 'image/x-icon';
  8634. $imgmime = 'image.png';
  8635. $famime = 'file-image-o';
  8636. }
  8637. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  8638. $mime = 'image/jpeg';
  8639. $imgmime = 'image.png';
  8640. $famime = 'file-image-o';
  8641. }
  8642. if (preg_match('/\.png$/i', $tmpfile)) {
  8643. $mime = 'image/png';
  8644. $imgmime = 'image.png';
  8645. $famime = 'file-image-o';
  8646. }
  8647. if (preg_match('/\.gif$/i', $tmpfile)) {
  8648. $mime = 'image/gif';
  8649. $imgmime = 'image.png';
  8650. $famime = 'file-image-o';
  8651. }
  8652. if (preg_match('/\.bmp$/i', $tmpfile)) {
  8653. $mime = 'image/bmp';
  8654. $imgmime = 'image.png';
  8655. $famime = 'file-image-o';
  8656. }
  8657. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  8658. $mime = 'image/tiff';
  8659. $imgmime = 'image.png';
  8660. $famime = 'file-image-o';
  8661. }
  8662. if (preg_match('/\.svg$/i', $tmpfile)) {
  8663. $mime = 'image/svg+xml';
  8664. $imgmime = 'image.png';
  8665. $famime = 'file-image-o';
  8666. }
  8667. if (preg_match('/\.webp$/i', $tmpfile)) {
  8668. $mime = 'image/webp';
  8669. $imgmime = 'image.png';
  8670. $famime = 'file-image-o';
  8671. }
  8672. // Calendar
  8673. if (preg_match('/\.vcs$/i', $tmpfile)) {
  8674. $mime = 'text/calendar';
  8675. $imgmime = 'other.png';
  8676. $famime = 'file-text-o';
  8677. }
  8678. if (preg_match('/\.ics$/i', $tmpfile)) {
  8679. $mime = 'text/calendar';
  8680. $imgmime = 'other.png';
  8681. $famime = 'file-text-o';
  8682. }
  8683. // Other
  8684. if (preg_match('/\.torrent$/i', $tmpfile)) {
  8685. $mime = 'application/x-bittorrent';
  8686. $imgmime = 'other.png';
  8687. $famime = 'file-o';
  8688. }
  8689. // Audio
  8690. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  8691. $mime = 'audio';
  8692. $imgmime = 'audio.png';
  8693. $famime = 'file-audio-o';
  8694. }
  8695. // Video
  8696. if (preg_match('/\.mp4$/i', $tmpfile)) {
  8697. $mime = 'video/mp4';
  8698. $imgmime = 'video.png';
  8699. $famime = 'file-video-o';
  8700. }
  8701. if (preg_match('/\.ogv$/i', $tmpfile)) {
  8702. $mime = 'video/ogg';
  8703. $imgmime = 'video.png';
  8704. $famime = 'file-video-o';
  8705. }
  8706. if (preg_match('/\.webm$/i', $tmpfile)) {
  8707. $mime = 'video/webm';
  8708. $imgmime = 'video.png';
  8709. $famime = 'file-video-o';
  8710. }
  8711. if (preg_match('/\.avi$/i', $tmpfile)) {
  8712. $mime = 'video/x-msvideo';
  8713. $imgmime = 'video.png';
  8714. $famime = 'file-video-o';
  8715. }
  8716. if (preg_match('/\.divx$/i', $tmpfile)) {
  8717. $mime = 'video/divx';
  8718. $imgmime = 'video.png';
  8719. $famime = 'file-video-o';
  8720. }
  8721. if (preg_match('/\.xvid$/i', $tmpfile)) {
  8722. $mime = 'video/xvid';
  8723. $imgmime = 'video.png';
  8724. $famime = 'file-video-o';
  8725. }
  8726. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  8727. $mime = 'video';
  8728. $imgmime = 'video.png';
  8729. $famime = 'file-video-o';
  8730. }
  8731. // Archive
  8732. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  8733. $mime = 'archive';
  8734. $imgmime = 'archive.png';
  8735. $famime = 'file-archive-o';
  8736. } // application/xxx where zzz is zip, ...
  8737. // Exe
  8738. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  8739. $mime = 'application/octet-stream';
  8740. $imgmime = 'other.png';
  8741. $famime = 'file-o';
  8742. }
  8743. // Lib
  8744. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  8745. $mime = 'library';
  8746. $imgmime = 'library.png';
  8747. $famime = 'file-o';
  8748. }
  8749. // Err
  8750. if (preg_match('/\.err$/i', $tmpfile)) {
  8751. $mime = 'error';
  8752. $imgmime = 'error.png';
  8753. $famime = 'file-text-o';
  8754. }
  8755. // Return string
  8756. if ($mode == 1) {
  8757. $tmp = explode('/', $mime);
  8758. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  8759. }
  8760. if ($mode == 2) {
  8761. return $imgmime;
  8762. }
  8763. if ($mode == 3) {
  8764. return $srclang;
  8765. }
  8766. if ($mode == 4) {
  8767. return $famime;
  8768. }
  8769. return $mime;
  8770. }
  8771. /**
  8772. * Return the value of a filed into a dictionary for the record $id.
  8773. * This also set all the values into a cache for a next search.
  8774. *
  8775. * @param string $tablename Name of dictionary
  8776. * @param string $field The name of field where to find the value to return
  8777. * @param int $id Id of line record
  8778. * @param bool $checkentity Add filter on entity
  8779. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  8780. * @return string The value of field $field. This also set $dictvalues cache.
  8781. */
  8782. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  8783. {
  8784. global $conf, $db;
  8785. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  8786. if (is_null($dictvalues)) {
  8787. $dictvalues = array();
  8788. $sql = "SELECT * FROM ".$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  8789. if ($checkentity) {
  8790. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  8791. }
  8792. $resql = $db->query($sql);
  8793. if ($resql) {
  8794. while ($obj = $db->fetch_object($resql)) {
  8795. $dictvalues[$obj->{$rowidfield}] = $obj;
  8796. }
  8797. } else {
  8798. dol_print_error($db);
  8799. }
  8800. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  8801. }
  8802. if (!empty($dictvalues[$id])) {
  8803. // Found
  8804. return $dictvalues[$id]->{$field};
  8805. } else {
  8806. // Not found
  8807. return '';
  8808. }
  8809. }
  8810. /**
  8811. * Return true if the color is light
  8812. *
  8813. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  8814. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  8815. */
  8816. function colorIsLight($stringcolor)
  8817. {
  8818. $stringcolor = str_replace('#', '', $stringcolor);
  8819. $res = -1;
  8820. if (!empty($stringcolor)) {
  8821. $res = 0;
  8822. $tmp = explode(',', $stringcolor);
  8823. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  8824. $r = $tmp[0];
  8825. $g = $tmp[1];
  8826. $b = $tmp[2];
  8827. } else {
  8828. $hexr = $stringcolor[0].$stringcolor[1];
  8829. $hexg = $stringcolor[2].$stringcolor[3];
  8830. $hexb = $stringcolor[4].$stringcolor[5];
  8831. $r = hexdec($hexr);
  8832. $g = hexdec($hexg);
  8833. $b = hexdec($hexb);
  8834. }
  8835. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  8836. if ($bright > 0.6) {
  8837. $res = 1;
  8838. }
  8839. }
  8840. return $res;
  8841. }
  8842. /**
  8843. * Function to test if an entry is enabled or not
  8844. *
  8845. * @param string $type_user 0=We test for internal user, 1=We test for external user
  8846. * @param array $menuentry Array for feature entry to test
  8847. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  8848. * @return int 0=Hide, 1=Show, 2=Show gray
  8849. */
  8850. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  8851. {
  8852. global $conf;
  8853. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  8854. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  8855. if (empty($menuentry['enabled'])) {
  8856. return 0; // Entry disabled by condition
  8857. }
  8858. if ($type_user && $menuentry['module']) {
  8859. $tmploops = explode('|', $menuentry['module']);
  8860. $found = 0;
  8861. foreach ($tmploops as $tmploop) {
  8862. if (in_array($tmploop, $listofmodulesforexternal)) {
  8863. $found++;
  8864. break;
  8865. }
  8866. }
  8867. if (!$found) {
  8868. return 0; // Entry is for menus all excluded to external users
  8869. }
  8870. }
  8871. if (!$menuentry['perms'] && $type_user) {
  8872. return 0; // No permissions and user is external
  8873. }
  8874. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  8875. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  8876. }
  8877. if (!$menuentry['perms']) {
  8878. return 2; // No permissions and user is external
  8879. }
  8880. return 1;
  8881. }
  8882. /**
  8883. * Round to next multiple.
  8884. *
  8885. * @param double $n Number to round up
  8886. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  8887. * @return integer Value rounded.
  8888. */
  8889. function roundUpToNextMultiple($n, $x = 5)
  8890. {
  8891. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  8892. }
  8893. /**
  8894. * Function dolGetBadge
  8895. *
  8896. * @param string $label label of badge no html : use in alt attribute for accessibility
  8897. * @param string $html optional : label of badge with html
  8898. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  8899. * @param string $mode default '' , 'pill', 'dot'
  8900. * @param string $url the url for link
  8901. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  8902. * @return string Html badge
  8903. */
  8904. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  8905. {
  8906. $attr = array(
  8907. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  8908. );
  8909. if (empty($html)) {
  8910. $html = $label;
  8911. }
  8912. if (!empty($url)) {
  8913. $attr['href'] = $url;
  8914. }
  8915. if ($mode === 'dot') {
  8916. $attr['class'] .= ' classfortooltip';
  8917. $attr['title'] = $html;
  8918. $attr['aria-label'] = $label;
  8919. $html = '';
  8920. }
  8921. // Override attr
  8922. if (!empty($params['attr']) && is_array($params['attr'])) {
  8923. foreach ($params['attr'] as $key => $value) {
  8924. if ($key == 'class') {
  8925. $attr['class'] .= ' '.$value;
  8926. } elseif ($key == 'classOverride') {
  8927. $attr['class'] = $value;
  8928. } else {
  8929. $attr[$key] = $value;
  8930. }
  8931. }
  8932. }
  8933. // TODO: add hook
  8934. // escape all attribute
  8935. $attr = array_map('dol_escape_htmltag', $attr);
  8936. $TCompiledAttr = array();
  8937. foreach ($attr as $key => $value) {
  8938. $TCompiledAttr[] = $key.'="'.$value.'"';
  8939. }
  8940. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  8941. $tag = !empty($url) ? 'a' : 'span';
  8942. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  8943. }
  8944. /**
  8945. * Output the badge of a status.
  8946. *
  8947. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  8948. * @param string $statusLabelShort Short label of badge no html
  8949. * @param string $html Optional : label of badge with html
  8950. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  8951. * @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
  8952. * @param string $url The url for link
  8953. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  8954. * @return string Html status string
  8955. */
  8956. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  8957. {
  8958. global $conf;
  8959. $return = '';
  8960. $dolGetBadgeParams = array();
  8961. if (!empty($params['badgeParams'])) {
  8962. $dolGetBadgeParams = $params['badgeParams'];
  8963. }
  8964. // TODO : add a hook
  8965. if ($displayMode == 0) {
  8966. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  8967. } elseif ($displayMode == 1) {
  8968. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  8969. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  8970. // Use status with images (for backward compatibility)
  8971. $return = '';
  8972. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  8973. $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>' : '');
  8974. // For small screen, we always use the short label instead of long label.
  8975. if (!empty($conf->dol_optimize_smallscreen)) {
  8976. if ($displayMode == 0) {
  8977. $displayMode = 1;
  8978. } elseif ($displayMode == 4) {
  8979. $displayMode = 2;
  8980. } elseif ($displayMode == 6) {
  8981. $displayMode = 5;
  8982. }
  8983. }
  8984. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  8985. $statusImg = array(
  8986. 'status0' => 'statut0',
  8987. 'status1' => 'statut1',
  8988. 'status2' => 'statut2',
  8989. 'status3' => 'statut3',
  8990. 'status4' => 'statut4',
  8991. 'status5' => 'statut5',
  8992. 'status6' => 'statut6',
  8993. 'status7' => 'statut7',
  8994. 'status8' => 'statut8',
  8995. 'status9' => 'statut9'
  8996. );
  8997. if (!empty($statusImg[$statusType])) {
  8998. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  8999. } else {
  9000. $htmlImg = img_picto($statusLabel, $statusType);
  9001. }
  9002. if ($displayMode === 2) {
  9003. $return = $htmlImg.' '.$htmlLabelShort;
  9004. } elseif ($displayMode === 3) {
  9005. $return = $htmlImg;
  9006. } elseif ($displayMode === 4) {
  9007. $return = $htmlImg.' '.$htmlLabel;
  9008. } elseif ($displayMode === 5) {
  9009. $return = $htmlLabelShort.' '.$htmlImg;
  9010. } else { // $displayMode >= 6
  9011. $return = $htmlLabel.' '.$htmlImg;
  9012. }
  9013. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9014. // Use new badge
  9015. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9016. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9017. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9018. if ($displayMode == 3) {
  9019. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9020. } elseif ($displayMode === 5) {
  9021. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9022. } else {
  9023. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9024. }
  9025. }
  9026. return $return;
  9027. }
  9028. /**
  9029. * Function dolGetButtonAction
  9030. *
  9031. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  9032. * @param string $html optional : content with html
  9033. * @param string $actionType default, delete, danger
  9034. * @param string $url the url for link
  9035. * @param string $id attribute id of button
  9036. * @param int $userRight user action right
  9037. * // phpcs:disable
  9038. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  9039. * 'attr' => [ // to add or override button attributes
  9040. * 'xxxxx' => '', // your xxxxx attribute you want
  9041. * 'class' => '', // to add more css class to the button class attribute
  9042. * 'classOverride' => '' // to replace class attribute of the button
  9043. * ],
  9044. * 'confirm' => [
  9045. * '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.
  9046. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  9047. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  9048. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  9049. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  9050. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  9051. * ],
  9052. * ]
  9053. * // phpcs:enable
  9054. * @return string html button
  9055. */
  9056. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  9057. {
  9058. global $hookmanager, $action, $object, $langs;
  9059. $class = 'butAction';
  9060. if ($actionType == 'danger' || $actionType == 'delete') {
  9061. $class = 'butActionDelete';
  9062. if (strpos($url, 'token=') === false) $url .= '&token='.newToken();
  9063. }
  9064. $attr = array(
  9065. 'class' => $class,
  9066. 'href' => empty($url) ? '' : $url,
  9067. 'title' => $label
  9068. );
  9069. if (empty($html)) {
  9070. $html = $label;
  9071. } else {
  9072. $attr['aria-label'] = $label;
  9073. }
  9074. if (empty($userRight)) {
  9075. $attr['class'] = 'butActionRefused';
  9076. $attr['href'] = '';
  9077. }
  9078. if (!empty($id)) {
  9079. $attr['id'] = $id;
  9080. }
  9081. // Override attr
  9082. if (!empty($params['attr']) && is_array($params['attr'])) {
  9083. foreach ($params['attr'] as $key => $value) {
  9084. if ($key == 'class') {
  9085. $attr['class'] .= ' '.$value;
  9086. } elseif ($key == 'classOverride') {
  9087. $attr['class'] = $value;
  9088. } else {
  9089. $attr[$key] = $value;
  9090. }
  9091. }
  9092. }
  9093. // Js Confirm button
  9094. if ($userRight && !empty($params['confirm'])) {
  9095. if (!is_array($params['confirm'])) {
  9096. $params['confirm'] = array(
  9097. 'url' => $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes'
  9098. );
  9099. }
  9100. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9101. $attr['data-confirm-url'] = $params['confirm']['url'];
  9102. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9103. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9104. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9105. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9106. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9107. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9108. $attr['class'].= ' butActionConfirm';
  9109. }
  9110. if (isset($attr['href']) && empty($attr['href'])) {
  9111. unset($attr['href']);
  9112. }
  9113. // escape all attribute
  9114. $attr = array_map('dol_escape_htmltag', $attr);
  9115. $TCompiledAttr = array();
  9116. foreach ($attr as $key => $value) {
  9117. $TCompiledAttr[] = $key.'="'.$value.'"';
  9118. }
  9119. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9120. $tag = !empty($attr['href']) ? 'a' : 'span';
  9121. $parameters = array(
  9122. 'TCompiledAttr' => $TCompiledAttr,
  9123. 'compiledAttributes' => $compiledAttributes,
  9124. 'attr' => $attr,
  9125. 'tag' => $tag,
  9126. 'label' => $label,
  9127. 'html' => $html,
  9128. 'actionType' => $actionType,
  9129. 'url' => $url,
  9130. 'id' => $id,
  9131. 'userRight' => $userRight,
  9132. 'params' => $params
  9133. );
  9134. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9135. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9136. if (empty($reshook)) {
  9137. return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
  9138. } else {
  9139. return $hookmanager->resPrint;
  9140. }
  9141. }
  9142. /**
  9143. * Add space between dolGetButtonTitle
  9144. *
  9145. * @param string $moreClass more css class label
  9146. * @return string html of title separator
  9147. */
  9148. function dolGetButtonTitleSeparator($moreClass = "")
  9149. {
  9150. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9151. }
  9152. /**
  9153. * get field error icon
  9154. *
  9155. * @param string $fieldValidationErrorMsg message to add in tooltip
  9156. * @return string html output
  9157. */
  9158. function getFieldErrorIcon($fieldValidationErrorMsg)
  9159. {
  9160. $out = '';
  9161. if (!empty($fieldValidationErrorMsg)) {
  9162. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9163. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9164. $out.= '</span>';
  9165. }
  9166. return $out;
  9167. }
  9168. /**
  9169. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9170. *
  9171. * @param string $label label of button
  9172. * @param string $helpText optional : content for help tooltip
  9173. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9174. * @param string $url the url for link
  9175. * @param string $id attribute id of button
  9176. * @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
  9177. * @param array $params various params for future : recommended rather than adding more function arguments
  9178. * @return string html button
  9179. */
  9180. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9181. {
  9182. global $langs, $conf, $user;
  9183. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9184. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9185. return '';
  9186. }
  9187. $class = 'btnTitle';
  9188. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots'))) {
  9189. $class .= ' btnTitlePlus';
  9190. }
  9191. $useclassfortooltip = 1;
  9192. if (!empty($params['morecss'])) {
  9193. $class .= ' '.$params['morecss'];
  9194. }
  9195. $attr = array(
  9196. 'class' => $class,
  9197. 'href' => empty($url) ? '' : $url
  9198. );
  9199. if (!empty($helpText)) {
  9200. $attr['title'] = dol_escape_htmltag($helpText);
  9201. } elseif (empty($attr['title']) && $label) {
  9202. $attr['title'] = $label;
  9203. $useclassfortooltip = 0;
  9204. }
  9205. if ($status == 2) {
  9206. $attr['class'] .= ' btnTitleSelected';
  9207. } elseif ($status <= 0) {
  9208. $attr['class'] .= ' refused';
  9209. $attr['href'] = '';
  9210. if ($status == -1) { // disable
  9211. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9212. } elseif ($status == 0) { // Not enough permissions
  9213. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9214. }
  9215. }
  9216. if (!empty($attr['title']) && $useclassfortooltip) {
  9217. $attr['class'] .= ' classfortooltip';
  9218. }
  9219. if (!empty($id)) {
  9220. $attr['id'] = $id;
  9221. }
  9222. // Override attr
  9223. if (!empty($params['attr']) && is_array($params['attr'])) {
  9224. foreach ($params['attr'] as $key => $value) {
  9225. if ($key == 'class') {
  9226. $attr['class'] .= ' '.$value;
  9227. } elseif ($key == 'classOverride') {
  9228. $attr['class'] = $value;
  9229. } else {
  9230. $attr[$key] = $value;
  9231. }
  9232. }
  9233. }
  9234. if (isset($attr['href']) && empty($attr['href'])) {
  9235. unset($attr['href']);
  9236. }
  9237. // TODO : add a hook
  9238. // escape all attribute
  9239. $attr = array_map('dol_escape_htmltag', $attr);
  9240. $TCompiledAttr = array();
  9241. foreach ($attr as $key => $value) {
  9242. $TCompiledAttr[] = $key.'="'.$value.'"';
  9243. }
  9244. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9245. $tag = (empty($attr['href']) ? 'span' : 'a');
  9246. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9247. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9248. if (!empty($params['forcenohideoftext'])) {
  9249. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9250. }
  9251. $button .= '</'.$tag.'>';
  9252. return $button;
  9253. }
  9254. /**
  9255. * Get an array with properties of an element.
  9256. * Called by fetchObjectByElement.
  9257. *
  9258. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9259. * @return array (module, classpath, element, subelement, classfile, classname)
  9260. */
  9261. function getElementProperties($element_type)
  9262. {
  9263. $regs = array();
  9264. $classfile = $classname = $classpath = '';
  9265. // Parse element/subelement (ex: project_task)
  9266. $module = $element_type;
  9267. $element = $element_type;
  9268. $subelement = $element_type;
  9269. // If we ask an resource form external module (instead of default path)
  9270. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9271. $element = $subelement = $regs[1];
  9272. $module = $regs[2];
  9273. }
  9274. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9275. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9276. $module = $element = $regs[1];
  9277. $subelement = $regs[2];
  9278. }
  9279. // For compat
  9280. if ($element_type == "action") {
  9281. $classpath = 'comm/action/class';
  9282. $subelement = 'Actioncomm';
  9283. $module = 'agenda';
  9284. }
  9285. // To work with non standard path
  9286. if ($element_type == 'facture' || $element_type == 'invoice') {
  9287. $classpath = 'compta/facture/class';
  9288. $module = 'facture';
  9289. $subelement = 'facture';
  9290. }
  9291. if ($element_type == 'commande' || $element_type == 'order') {
  9292. $classpath = 'commande/class';
  9293. $module = 'commande';
  9294. $subelement = 'commande';
  9295. }
  9296. if ($element_type == 'propal') {
  9297. $classpath = 'comm/propal/class';
  9298. }
  9299. if ($element_type == 'supplier_proposal') {
  9300. $classpath = 'supplier_proposal/class';
  9301. }
  9302. if ($element_type == 'shipping') {
  9303. $classpath = 'expedition/class';
  9304. $subelement = 'expedition';
  9305. $module = 'expedition_bon';
  9306. }
  9307. if ($element_type == 'delivery') {
  9308. $classpath = 'delivery/class';
  9309. $subelement = 'delivery';
  9310. $module = 'delivery_note';
  9311. }
  9312. if ($element_type == 'contract') {
  9313. $classpath = 'contrat/class';
  9314. $module = 'contrat';
  9315. $subelement = 'contrat';
  9316. }
  9317. if ($element_type == 'member') {
  9318. $classpath = 'adherents/class';
  9319. $module = 'adherent';
  9320. $subelement = 'adherent';
  9321. }
  9322. if ($element_type == 'cabinetmed_cons') {
  9323. $classpath = 'cabinetmed/class';
  9324. $module = 'cabinetmed';
  9325. $subelement = 'cabinetmedcons';
  9326. }
  9327. if ($element_type == 'fichinter') {
  9328. $classpath = 'fichinter/class';
  9329. $module = 'ficheinter';
  9330. $subelement = 'fichinter';
  9331. }
  9332. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9333. $classpath = 'resource/class';
  9334. $module = 'resource';
  9335. $subelement = 'dolresource';
  9336. }
  9337. if ($element_type == 'propaldet') {
  9338. $classpath = 'comm/propal/class';
  9339. $module = 'propal';
  9340. $subelement = 'propaleligne';
  9341. }
  9342. if ($element_type == 'order_supplier') {
  9343. $classpath = 'fourn/class';
  9344. $module = 'fournisseur';
  9345. $subelement = 'commandefournisseur';
  9346. $classfile = 'fournisseur.commande';
  9347. }
  9348. if ($element_type == 'invoice_supplier') {
  9349. $classpath = 'fourn/class';
  9350. $module = 'fournisseur';
  9351. $subelement = 'facturefournisseur';
  9352. $classfile = 'fournisseur.facture';
  9353. }
  9354. if ($element_type == "service") {
  9355. $classpath = 'product/class';
  9356. $subelement = 'product';
  9357. }
  9358. if (empty($classfile)) {
  9359. $classfile = strtolower($subelement);
  9360. }
  9361. if (empty($classname)) {
  9362. $classname = ucfirst($subelement);
  9363. }
  9364. if (empty($classpath)) {
  9365. $classpath = $module.'/class';
  9366. }
  9367. $element_properties = array(
  9368. 'module' => $module,
  9369. 'classpath' => $classpath,
  9370. 'element' => $element,
  9371. 'subelement' => $subelement,
  9372. 'classfile' => $classfile,
  9373. 'classname' => $classname
  9374. );
  9375. return $element_properties;
  9376. }
  9377. /**
  9378. * Fetch an object from its id and element_type
  9379. * Inclusion of classes is automatic
  9380. *
  9381. * @param int $element_id Element id
  9382. * @param string $element_type Element type
  9383. * @param string $element_ref Element ref (Use this or element_id but not both)
  9384. * @return int|object object || 0 || -1 if error
  9385. */
  9386. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9387. {
  9388. global $conf, $db;
  9389. $element_prop = getElementProperties($element_type);
  9390. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9391. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9392. $objecttmp = new $element_prop['classname']($db);
  9393. $ret = $objecttmp->fetch($element_id, $element_ref);
  9394. if ($ret >= 0) {
  9395. return $objecttmp;
  9396. }
  9397. }
  9398. return 0;
  9399. }
  9400. /**
  9401. * Return if a file can contains executable content
  9402. *
  9403. * @param string $filename File name to test
  9404. * @return boolean True if yes, False if no
  9405. */
  9406. function isAFileWithExecutableContent($filename)
  9407. {
  9408. 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)) {
  9409. return true;
  9410. }
  9411. return false;
  9412. }
  9413. /**
  9414. * Return the value of token currently saved into session with name 'newtoken'.
  9415. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9416. *
  9417. * @return string
  9418. */
  9419. function newToken()
  9420. {
  9421. return $_SESSION['newtoken'];
  9422. }
  9423. /**
  9424. * Return the value of token currently saved into session with name 'token'.
  9425. *
  9426. * @return string
  9427. */
  9428. function currentToken()
  9429. {
  9430. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  9431. }
  9432. /**
  9433. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9434. *
  9435. * @param string $header The first left header of the table (automatic translated)
  9436. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9437. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9438. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9439. * @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"
  9440. * @return void
  9441. *
  9442. * @see finishSimpleTable()
  9443. */
  9444. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9445. {
  9446. global $langs;
  9447. print '<div class="div-table-responsive-no-min">';
  9448. print '<table class="noborder centpercent">';
  9449. print '<tr class="liste_titre">';
  9450. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9451. print $langs->trans($header);
  9452. // extra space between the first header and the number
  9453. if ($number > -1) {
  9454. print ' ';
  9455. }
  9456. if (!empty($link)) {
  9457. if (!empty($arguments)) {
  9458. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9459. } else {
  9460. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9461. }
  9462. }
  9463. if ($number > -1) {
  9464. print '<span class="badge">'.$number.'</span>';
  9465. }
  9466. if (!empty($link)) {
  9467. print '</a>';
  9468. }
  9469. print '</th>';
  9470. if ($number < 0 && !empty($link)) {
  9471. print '<th class="right">';
  9472. if (!empty($arguments)) {
  9473. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9474. } else {
  9475. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9476. }
  9477. print $langs->trans("FullList");
  9478. print '</a>';
  9479. print '</th>';
  9480. }
  9481. print '</tr>';
  9482. }
  9483. /**
  9484. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9485. *
  9486. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9487. * @return void
  9488. *
  9489. * @see startSimpleTable()
  9490. */
  9491. function finishSimpleTable($addLineBreak = false)
  9492. {
  9493. print '</table>';
  9494. print '</div>';
  9495. if ($addLineBreak) {
  9496. print '<br>';
  9497. }
  9498. }
  9499. /**
  9500. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9501. *
  9502. * @param integer $tableColumnCount The complete count columns of the table
  9503. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9504. * @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)
  9505. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9506. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9507. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9508. * @return void
  9509. */
  9510. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9511. {
  9512. global $langs;
  9513. if ($num === 0) {
  9514. print '<tr class="oddeven">';
  9515. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9516. print '</tr>';
  9517. return;
  9518. }
  9519. if ($nbofloop === 0) {
  9520. // don't show a summary line
  9521. return;
  9522. }
  9523. if ($num === 0) {
  9524. $colspan = $tableColumnCount;
  9525. } elseif ($num > $nbofloop) {
  9526. $colspan = $tableColumnCount;
  9527. } else {
  9528. $colspan = $tableColumnCount - 1;
  9529. }
  9530. if ($extraRightColumn) {
  9531. $colspan--;
  9532. }
  9533. print '<tr class="liste_total">';
  9534. if ($nbofloop > 0 && $num > $nbofloop) {
  9535. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9536. } else {
  9537. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  9538. print '<td class="right" width="100">'.price($total).'</td>';
  9539. }
  9540. if ($extraRightColumn) {
  9541. print '<td></td>';
  9542. }
  9543. print '</tr>';
  9544. }
  9545. /**
  9546. * Return a file on output using a low memory. It can return very large files with no need of memory.
  9547. * WARNING: This close output buffers.
  9548. *
  9549. * @param string $fullpath_original_file_osencoded Full path of file to return.
  9550. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  9551. * @return void
  9552. */
  9553. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  9554. {
  9555. global $conf;
  9556. if ($method == -1) {
  9557. $method = 0;
  9558. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  9559. $method = 1;
  9560. }
  9561. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  9562. $method = 2;
  9563. }
  9564. }
  9565. // Be sure we don't have output buffering enabled to have readfile working correctly
  9566. while (ob_get_level()) {
  9567. ob_end_flush();
  9568. }
  9569. // Solution 0
  9570. if ($method == 0) {
  9571. readfile($fullpath_original_file_osencoded);
  9572. } elseif ($method == 1) {
  9573. // Solution 1
  9574. $handle = fopen($fullpath_original_file_osencoded, "rb");
  9575. while (!feof($handle)) {
  9576. print fread($handle, 8192);
  9577. }
  9578. fclose($handle);
  9579. } elseif ($method == 2) {
  9580. // Solution 2
  9581. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  9582. $handle2 = fopen("php://output", "wb");
  9583. stream_copy_to_stream($handle1, $handle2);
  9584. fclose($handle1);
  9585. fclose($handle2);
  9586. }
  9587. }
  9588. /**
  9589. * Create a button to copy $valuetocopy in the clipboard.
  9590. * Code that handle the click is inside lib_foot.jsp.php.
  9591. *
  9592. * @param string $valuetocopy The value to print
  9593. * @param int $showonlyonhover Show the copy-paste button only on hover
  9594. * @param string $texttoshow Replace the value to show with this text
  9595. * @return string The string to print for the button
  9596. */
  9597. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  9598. {
  9599. /*
  9600. global $conf;
  9601. if (!empty($conf->dol_no_mouse_hover)) {
  9602. $showonlyonhover = 0;
  9603. }*/
  9604. $tag = 'span'; // Using div does not work when using the js copy code.
  9605. if ($texttoshow) {
  9606. $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>';
  9607. } else {
  9608. $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>';
  9609. }
  9610. return $result;
  9611. }
  9612. /**
  9613. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  9614. *
  9615. * @param string $stringtodecode String to decode (json or serialize coded)
  9616. * @return mixed The decoded object.
  9617. */
  9618. function jsonOrUnserialize($stringtodecode)
  9619. {
  9620. $result = json_decode($stringtodecode);
  9621. if ($result === null) {
  9622. $result = unserialize($stringtodecode);
  9623. }
  9624. return $result;
  9625. }
  9626. /**
  9627. * Return if a $sqlfilters parameter is valid and will pass the preg_replace_callback() to replace Generic filter string with SQL filter string
  9628. * Example of usage:
  9629. * if ($sqlfilters) {
  9630. * $errormessage = '';
  9631. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9632. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9633. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9634. * }
  9635. * }
  9636. *
  9637. * @param string $sqlfilters sqlfilter string
  9638. * @param string $error Error message
  9639. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  9640. */
  9641. function dolCheckFilters($sqlfilters, &$error = '')
  9642. {
  9643. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  9644. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  9645. $tmp = $sqlfilters;
  9646. $i = 0; $nb = strlen($tmp);
  9647. $counter = 0;
  9648. while ($i < $nb) {
  9649. if ($tmp[$i] == '(') {
  9650. $counter++;
  9651. }
  9652. if ($tmp[$i] == ')') {
  9653. $counter--;
  9654. }
  9655. if ($counter < 0) {
  9656. $error = "Bad sqlfilters=".$sqlfilters;
  9657. dol_syslog($error, LOG_WARNING);
  9658. return false;
  9659. }
  9660. $i++;
  9661. }
  9662. return true;
  9663. }
  9664. /**
  9665. * Function to forge a SQL criteria from a Generic filter string.
  9666. * Example of usage:
  9667. * if ($sqlfilters) {
  9668. * $errormessage = '';
  9669. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  9670. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  9671. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  9672. * }
  9673. * }
  9674. *
  9675. * @param array $matches Array of found string by regex search.
  9676. * 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"
  9677. * @return string Forged criteria. Example: "t.field like 'abc%'"
  9678. */
  9679. function dolForgeCriteriaCallback($matches)
  9680. {
  9681. global $db;
  9682. //dol_syslog("Convert matches ".$matches[1]);
  9683. if (empty($matches[1])) {
  9684. return '';
  9685. }
  9686. $tmp = explode(':', $matches[1], 3);
  9687. if (count($tmp) < 3) {
  9688. return '';
  9689. }
  9690. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  9691. $operator = strtoupper(preg_replace('/[^a-z<>=]/i', '', trim($tmp[1])));
  9692. $tmpescaped = trim($tmp[2]);
  9693. $regbis = array();
  9694. if ($operator == 'IN') {
  9695. $tmpescaped = "(".$db->sanitize($tmpescaped, 1).")";
  9696. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  9697. $tmpescaped = "'".$db->escape($regbis[1])."'";
  9698. } else {
  9699. $tmpescaped = $db->sanitize($db->escape($tmpescaped));
  9700. }
  9701. return $db->escape($operand).' '.$db->escape($operator)." ".$tmpescaped;
  9702. }