functions.lib.php 452 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199
  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-2022 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. * Copyright (C) 2022 Anthony Berton <anthony.berton@bb2a.fr>
  21. * Copyright (C) 2022 Ferran Marcet <fmarcet@2byte.es>
  22. *
  23. * This program is free software; you can redistribute it and/or modify
  24. * it under the terms of the GNU General Public License as published by
  25. * the Free Software Foundation; either version 3 of the License, or
  26. * (at your option) any later version.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU General Public License
  34. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  35. * or see https://www.gnu.org/
  36. */
  37. /**
  38. * \file htdocs/core/lib/functions.lib.php
  39. * \brief A set of functions for Dolibarr
  40. * This file contains all frequently used functions.
  41. */
  42. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  43. if (!function_exists('utf8_encode')) {
  44. /**
  45. * Implement utf8_encode for PHP that does not support it.
  46. *
  47. * @param mixed $elements PHP Object to json encode
  48. * @return string Json encoded string
  49. */
  50. function utf8_encode($elements)
  51. {
  52. return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
  53. }
  54. }
  55. if (!function_exists('utf8_decode')) {
  56. /**
  57. * Implement utf8_decode for PHP that does not support it.
  58. *
  59. * @param mixed $elements PHP Object to json encode
  60. * @return string Json encoded string
  61. */
  62. function utf8_decode($elements)
  63. {
  64. return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
  65. }
  66. }
  67. /**
  68. * Return dolibarr global constant string value
  69. * @param string $key key to return value, return '' if not set
  70. * @param string $default value to return
  71. * @return string
  72. */
  73. function getDolGlobalString($key, $default = '')
  74. {
  75. global $conf;
  76. // return $conf->global->$key ?? $default;
  77. return (string) (empty($conf->global->$key) ? $default : $conf->global->$key);
  78. }
  79. /**
  80. * Return dolibarr global constant int value
  81. * @param string $key key to return value, return 0 if not set
  82. * @param int $default value to return
  83. * @return int
  84. */
  85. function getDolGlobalInt($key, $default = 0)
  86. {
  87. global $conf;
  88. // return $conf->global->$key ?? $default;
  89. return (int) (empty($conf->global->$key) ? $default : $conf->global->$key);
  90. }
  91. /**
  92. * Is Dolibarr module enabled
  93. * @param string $module module name to check
  94. * @return int
  95. */
  96. function isModEnabled($module)
  97. {
  98. global $conf;
  99. return !empty($conf->$module->enabled);
  100. }
  101. /**
  102. * Return a DoliDB instance (database handler).
  103. *
  104. * @param string $type Type of database (mysql, pgsql...)
  105. * @param string $host Address of database server
  106. * @param string $user Authorized username
  107. * @param string $pass Password
  108. * @param string $name Name of database
  109. * @param int $port Port of database server
  110. * @return DoliDB A DoliDB instance
  111. */
  112. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  113. {
  114. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  115. $class = 'DoliDB'.ucfirst($type);
  116. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  117. return $dolidb;
  118. }
  119. /**
  120. * Get list of entity id to use.
  121. *
  122. * @param string $element Current element
  123. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  124. * 'product', 'productprice', 'stock', 'bom', 'mo',
  125. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  126. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  127. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  128. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  129. * 'email_template', 'event', 'donation'
  130. * 'c_paiement', 'c_payment_term', ...
  131. * @param int $shared 0=Return id of current entity only,
  132. * 1=Return id of current entity + shared entities (default)
  133. * @param object $currentobject Current object if needed
  134. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  135. */
  136. function getEntity($element, $shared = 1, $currentobject = null)
  137. {
  138. global $conf, $mc, $hookmanager, $object, $action, $db;
  139. if (! is_object($hookmanager)) {
  140. $hookmanager = new HookManager($db);
  141. }
  142. // fix different element names (France to English)
  143. switch ($element) {
  144. case 'contrat':
  145. $element = 'contract';
  146. break; // "/contrat/class/contrat.class.php"
  147. case 'order_supplier':
  148. $element = 'supplier_order';
  149. break; // "/fourn/class/fournisseur.commande.class.php"
  150. case 'invoice_supplier':
  151. $element = 'supplier_invoice';
  152. break; // "/fourn/class/fournisseur.facture.class.php"
  153. }
  154. if (is_object($mc)) {
  155. $out = $mc->getEntity($element, $shared, $currentobject);
  156. } else {
  157. $out = '';
  158. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  159. if (in_array($element, $addzero)) {
  160. $out .= '0,';
  161. }
  162. $out .= ((int) $conf->entity);
  163. }
  164. // Manipulate entities to query on the fly
  165. $parameters = array(
  166. 'element' => $element,
  167. 'shared' => $shared,
  168. 'object' => $object,
  169. 'currentobject' => $currentobject,
  170. 'out' => $out
  171. );
  172. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  173. if (is_numeric($reshook)) {
  174. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  175. $out .= ','.$hookmanager->resPrint; // add
  176. } elseif ($reshook == 1) {
  177. $out = $hookmanager->resPrint; // replace
  178. }
  179. }
  180. return $out;
  181. }
  182. /**
  183. * Set entity id to use when to create an object
  184. *
  185. * @param object $currentobject Current object
  186. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  187. */
  188. function setEntity($currentobject)
  189. {
  190. global $conf, $mc;
  191. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  192. return $mc->setEntity($currentobject);
  193. } else {
  194. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  195. }
  196. }
  197. /**
  198. * Return if string has a name dedicated to store a secret
  199. *
  200. * @param string $keyname Name of key to test
  201. * @return boolean True if key is used to store a secret
  202. */
  203. function isASecretKey($keyname)
  204. {
  205. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  206. }
  207. /**
  208. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  209. *
  210. * @param int|string $n Numeric value
  211. * @return string Column in Excel format
  212. */
  213. function num2Alpha($n)
  214. {
  215. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
  216. $r = chr($n % 26 + 0x41) . $r;
  217. return $r;
  218. }
  219. /**
  220. * Return information about user browser
  221. *
  222. * Returns array with the following format:
  223. * array(
  224. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  225. * 'browserversion' => Browser version. Empty if unknown
  226. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  227. * 'layout' => (tablet|phone|classic)
  228. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  229. * 'tablet' => true/false
  230. * )
  231. *
  232. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  233. * @return array Check function documentation
  234. */
  235. function getBrowserInfo($user_agent)
  236. {
  237. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  238. $name = 'unknown';
  239. $version = '';
  240. $os = 'unknown';
  241. $phone = '';
  242. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  243. $detectmobile = new Mobile_Detect(null, $user_agent);
  244. $tablet = $detectmobile->isTablet();
  245. if ($detectmobile->isMobile()) {
  246. $phone = 'unknown';
  247. // If phone/smartphone, we set phone os name.
  248. if ($detectmobile->is('AndroidOS')) {
  249. $os = $phone = 'android';
  250. } elseif ($detectmobile->is('BlackBerryOS')) {
  251. $os = $phone = 'blackberry';
  252. } elseif ($detectmobile->is('iOS')) {
  253. $os = 'ios';
  254. $phone = 'iphone';
  255. } elseif ($detectmobile->is('PalmOS')) {
  256. $os = $phone = 'palm';
  257. } elseif ($detectmobile->is('SymbianOS')) {
  258. $os = 'symbian';
  259. } elseif ($detectmobile->is('webOS')) {
  260. $os = 'webos';
  261. } elseif ($detectmobile->is('MaemoOS')) {
  262. $os = 'maemo';
  263. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  264. $os = 'windows';
  265. }
  266. }
  267. // OS
  268. if (preg_match('/linux/i', $user_agent)) {
  269. $os = 'linux';
  270. } elseif (preg_match('/macintosh/i', $user_agent)) {
  271. $os = 'macintosh';
  272. } elseif (preg_match('/windows/i', $user_agent)) {
  273. $os = 'windows';
  274. }
  275. // Name
  276. $reg = array();
  277. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  278. $name = 'firefox';
  279. $version = $reg[2];
  280. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  281. $name = 'edge';
  282. $version = $reg[2];
  283. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  284. $name = 'chrome';
  285. $version = $reg[2];
  286. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  287. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  288. $name = 'chrome';
  289. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  290. $name = 'iceweasel';
  291. } elseif (preg_match('/epiphany/i', $user_agent)) {
  292. $name = 'epiphany';
  293. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  294. $name = 'safari';
  295. $version = $reg[2];
  296. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  297. // Safari is often present in string for mobile but its not.
  298. $name = 'opera';
  299. $version = $reg[2];
  300. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  301. $name = 'ie';
  302. $version = end($reg);
  303. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  304. // MS products at end
  305. $name = 'ie';
  306. $version = end($reg);
  307. } elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  308. // MS products at end
  309. $name = 'lynxlinks';
  310. $version = $reg[4];
  311. }
  312. if ($tablet) {
  313. $layout = 'tablet';
  314. } elseif ($phone) {
  315. $layout = 'phone';
  316. } else {
  317. $layout = 'classic';
  318. }
  319. return array(
  320. 'browsername' => $name,
  321. 'browserversion' => $version,
  322. 'browseros' => $os,
  323. 'layout' => $layout,
  324. 'phone' => $phone,
  325. 'tablet' => $tablet
  326. );
  327. }
  328. /**
  329. * Function called at end of web php process
  330. *
  331. * @return void
  332. */
  333. function dol_shutdown()
  334. {
  335. global $conf, $user, $langs, $db;
  336. $disconnectdone = false;
  337. $depth = 0;
  338. if (is_object($db) && !empty($db->connected)) {
  339. $depth = $db->transaction_opened;
  340. $disconnectdone = $db->close();
  341. }
  342. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
  343. }
  344. /**
  345. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  346. *
  347. * @param string $paramname Name or parameter to test
  348. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  349. */
  350. function GETPOSTISSET($paramname)
  351. {
  352. $isset = false;
  353. $relativepathstring = $_SERVER["PHP_SELF"];
  354. // Clean $relativepathstring
  355. if (constant('DOL_URL_ROOT')) {
  356. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  357. }
  358. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  359. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  360. //var_dump($relativepathstring);
  361. //var_dump($user->default_values);
  362. // Code for search criteria persistence.
  363. // Retrieve values if restore_lastsearch_values
  364. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  365. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  366. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  367. if (is_array($tmp)) {
  368. foreach ($tmp as $key => $val) {
  369. if ($key == $paramname) { // We are on the requested parameter
  370. $isset = true;
  371. break;
  372. }
  373. }
  374. }
  375. }
  376. // If there is saved contextpage, limit, page or mode
  377. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  378. $isset = true;
  379. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  380. $isset = true;
  381. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  382. $isset = true;
  383. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  384. $isset = true;
  385. }
  386. } else {
  387. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  388. }
  389. return $isset;
  390. }
  391. /**
  392. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  393. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  394. *
  395. * @param string $paramname Name or parameter to test
  396. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  397. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  398. */
  399. function GETPOSTISARRAY($paramname, $method = 0)
  400. {
  401. // for $method test need return the same $val as GETPOST
  402. if (empty($method)) {
  403. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  404. } elseif ($method == 1) {
  405. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  406. } elseif ($method == 2) {
  407. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  408. } elseif ($method == 3) {
  409. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  410. } else {
  411. $val = 'BadFirstParameterForGETPOST';
  412. }
  413. return is_array($val);
  414. }
  415. /**
  416. * Return value of a param into GET or POST supervariable.
  417. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  418. * Note: The property $user->default_values is loaded by main.php when loading the user.
  419. *
  420. * @param string $paramname Name of parameter to found
  421. * @param string $check Type of check
  422. * ''=no check (deprecated)
  423. * 'none'=no check (only for param that should have very rich content like passwords)
  424. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  425. * 'int'=check it's numeric (integer or float)
  426. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  427. * 'alpha'=Same than alphanohtml since v13
  428. * 'alphawithlgt'=alpha with lgt
  429. * 'alphanohtml'=check there is no html content and no " and no ../
  430. * 'aZ'=check it's a-z only
  431. * 'aZ09'=check it's simple alpha string (recommended for keys)
  432. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  433. * 'nohtml'=check there is no html content and no " and no ../
  434. * 'restricthtml'=check html content is restricted to some tags only
  435. * 'custom'= custom filter specify $filter and $options)
  436. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  437. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  438. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  439. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  440. * @return string|array Value found (string or array), or '' if check fails
  441. */
  442. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  443. {
  444. global $mysoc, $user, $conf;
  445. if (empty($paramname)) {
  446. return 'BadFirstParameterForGETPOST';
  447. }
  448. if (empty($check)) {
  449. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  450. // Enable this line to know who call the GETPOST with '' $check parameter.
  451. //var_dump(debug_backtrace()[0]);
  452. }
  453. if (empty($method)) {
  454. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  455. } elseif ($method == 1) {
  456. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  457. } elseif ($method == 2) {
  458. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  459. } elseif ($method == 3) {
  460. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  461. } else {
  462. return 'BadThirdParameterForGETPOST';
  463. }
  464. if (empty($method) || $method == 3 || $method == 4) {
  465. $relativepathstring = $_SERVER["PHP_SELF"];
  466. // Clean $relativepathstring
  467. if (constant('DOL_URL_ROOT')) {
  468. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  469. }
  470. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  471. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  472. //var_dump($relativepathstring);
  473. //var_dump($user->default_values);
  474. // Code for search criteria persistence.
  475. // Retrieve values if restore_lastsearch_values
  476. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  477. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  478. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  479. if (is_array($tmp)) {
  480. foreach ($tmp as $key => $val) {
  481. if ($key == $paramname) { // We are on the requested parameter
  482. $out = $val;
  483. break;
  484. }
  485. }
  486. }
  487. }
  488. // If there is saved contextpage, page or limit
  489. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  490. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  491. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  492. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  493. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  494. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  495. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  496. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  497. }
  498. } elseif (!isset($_GET['sortfield'])) {
  499. // Else, retrieve default values if we are not doing a sort
  500. // 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
  501. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  502. // Search default value from $object->field
  503. global $object;
  504. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  505. $out = $object->fields[$paramname]['default'];
  506. }
  507. }
  508. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  509. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  510. // Now search in setup to overwrite default values
  511. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  512. if (isset($user->default_values[$relativepathstring]['createform'])) {
  513. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  514. $qualified = 0;
  515. if ($defkey != '_noquery_') {
  516. $tmpqueryarraytohave = explode('&', $defkey);
  517. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  518. $foundintru = 0;
  519. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  520. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  521. $foundintru = 1;
  522. }
  523. }
  524. if (!$foundintru) {
  525. $qualified = 1;
  526. }
  527. //var_dump($defkey.'-'.$qualified);
  528. } else {
  529. $qualified = 1;
  530. }
  531. if ($qualified) {
  532. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  533. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  534. break;
  535. }
  536. }
  537. }
  538. }
  539. }
  540. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  541. // Management of default search_filters and sort order
  542. if (!empty($user->default_values)) {
  543. // $user->default_values defined from menu 'Setup - Default values'
  544. //var_dump($user->default_values[$relativepathstring]);
  545. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  546. // Sorted on which fields ? ASC or DESC ?
  547. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  548. // Even if paramname is sortfield, data are stored into ['sortorder...']
  549. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  550. $qualified = 0;
  551. if ($defkey != '_noquery_') {
  552. $tmpqueryarraytohave = explode('&', $defkey);
  553. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  554. $foundintru = 0;
  555. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  556. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  557. $foundintru = 1;
  558. }
  559. }
  560. if (!$foundintru) {
  561. $qualified = 1;
  562. }
  563. //var_dump($defkey.'-'.$qualified);
  564. } else {
  565. $qualified = 1;
  566. }
  567. if ($qualified) {
  568. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  569. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  570. if ($out) {
  571. $out .= ', ';
  572. }
  573. if ($paramname == 'sortfield') {
  574. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  575. }
  576. if ($paramname == 'sortorder') {
  577. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  578. }
  579. }
  580. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  581. }
  582. }
  583. }
  584. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  585. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  586. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  587. continue;
  588. }
  589. $qualified = 0;
  590. if ($defkey != '_noquery_') {
  591. $tmpqueryarraytohave = explode('&', $defkey);
  592. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  593. $foundintru = 0;
  594. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  595. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  596. $foundintru = 1;
  597. }
  598. }
  599. if (!$foundintru) {
  600. $qualified = 1;
  601. }
  602. //var_dump($defkey.'-'.$qualified);
  603. } else {
  604. $qualified = 1;
  605. }
  606. if ($qualified) {
  607. // We must keep $_POST and $_GET here
  608. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  609. // We made a search from quick search menu, do we still use default filter ?
  610. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  611. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  612. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  613. }
  614. } else {
  615. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  616. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  617. }
  618. break;
  619. }
  620. }
  621. }
  622. }
  623. }
  624. }
  625. }
  626. }
  627. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  628. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  629. // 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.
  630. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  631. $reg = array();
  632. $maxloop = 20;
  633. $loopnb = 0; // Protection against infinite loop
  634. 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.
  635. $loopnb++;
  636. $newout = '';
  637. if ($reg[1] == 'DAY') {
  638. $tmp = dol_getdate(dol_now(), true);
  639. $newout = $tmp['mday'];
  640. } elseif ($reg[1] == 'MONTH') {
  641. $tmp = dol_getdate(dol_now(), true);
  642. $newout = $tmp['mon'];
  643. } elseif ($reg[1] == 'YEAR') {
  644. $tmp = dol_getdate(dol_now(), true);
  645. $newout = $tmp['year'];
  646. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  647. $tmp = dol_getdate(dol_now(), true);
  648. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  649. $newout = $tmp2['day'];
  650. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  651. $tmp = dol_getdate(dol_now(), true);
  652. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  653. $newout = $tmp2['month'];
  654. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  655. $tmp = dol_getdate(dol_now(), true);
  656. $newout = ($tmp['year'] - 1);
  657. } elseif ($reg[1] == 'NEXT_DAY') {
  658. $tmp = dol_getdate(dol_now(), true);
  659. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  660. $newout = $tmp2['day'];
  661. } elseif ($reg[1] == 'NEXT_MONTH') {
  662. $tmp = dol_getdate(dol_now(), true);
  663. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  664. $newout = $tmp2['month'];
  665. } elseif ($reg[1] == 'NEXT_YEAR') {
  666. $tmp = dol_getdate(dol_now(), true);
  667. $newout = ($tmp['year'] + 1);
  668. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  669. $newout = $mysoc->country_id;
  670. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  671. $newout = $user->id;
  672. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  673. $newout = $user->fk_user;
  674. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  675. $newout = $conf->entity;
  676. } else {
  677. $newout = ''; // Key not found, we replace with empty string
  678. }
  679. //var_dump('__'.$reg[1].'__ -> '.$newout);
  680. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  681. }
  682. }
  683. // Check rule
  684. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  685. if (!is_array($out) || empty($out)) {
  686. $out = array();
  687. } else {
  688. $tmparray = explode(':', $check);
  689. if (!empty($tmparray[1])) {
  690. $tmpcheck = $tmparray[1];
  691. } else {
  692. $tmpcheck = 'alphanohtml';
  693. }
  694. foreach ($out as $outkey => $outval) {
  695. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  696. }
  697. }
  698. } else {
  699. $out = sanitizeVal($out, $check, $filter, $options);
  700. }
  701. // Sanitizing for special parameters.
  702. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  703. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  704. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  705. $out = str_replace(array(':', ';', '@', "\t", ' '), '', $out); // Can be before the loop because only 1 char is replaced. No risk to retreive it after other replacements.
  706. do {
  707. $oldstringtoclean = $out;
  708. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  709. $out = preg_replace(array('/^[^\?]*%/'), '', $out); // We remove any % chars before the ?. Example in url: '/product/stock/card.php?action=create&backtopage=%2Fdolibarr_dev%2Fhtdocs%2Fpro%25duct%2Fcard.php%3Fid%3Dabc'
  710. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  711. } while ($oldstringtoclean != $out);
  712. }
  713. // Code for search criteria persistence.
  714. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  715. if (empty($method) || $method == 3 || $method == 4) {
  716. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  717. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  718. // We save search key only if $out not empty that means:
  719. // - posted value not empty, or
  720. // - 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).
  721. if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
  722. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  723. }
  724. }
  725. }
  726. return $out;
  727. }
  728. /**
  729. * Return value of a param into GET or POST supervariable.
  730. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  731. * Note: The property $user->default_values is loaded by main.php when loading the user.
  732. *
  733. * @param string $paramname Name of parameter to found
  734. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  735. * @return int Value found (int)
  736. */
  737. function GETPOSTINT($paramname, $method = 0)
  738. {
  739. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  740. }
  741. /**
  742. * Return a sanitized or empty value after checking value against a rule.
  743. *
  744. * @deprecated
  745. * @param string|array $out Value to check/clear.
  746. * @param string $check Type of check/sanitizing
  747. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  748. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  749. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  750. */
  751. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  752. {
  753. return sanitizeVal($out, $check, $filter, $options);
  754. }
  755. /**
  756. * Return a sanitized or empty value after checking value against a rule.
  757. *
  758. * @param string|array $out Value to check/clear.
  759. * @param string $check Type of check/sanitizing
  760. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  761. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  762. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  763. */
  764. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  765. {
  766. global $conf;
  767. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  768. // Check is done after replacement
  769. switch ($check) {
  770. case 'none':
  771. break;
  772. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  773. if (!is_numeric($out)) {
  774. $out = '';
  775. }
  776. break;
  777. case 'intcomma':
  778. if (preg_match('/[^0-9,-]+/i', $out)) {
  779. $out = '';
  780. }
  781. break;
  782. case 'san_alpha':
  783. $out = filter_var($out, FILTER_SANITIZE_STRING);
  784. break;
  785. case 'email':
  786. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  787. break;
  788. case 'aZ':
  789. if (!is_array($out)) {
  790. $out = trim($out);
  791. if (preg_match('/[^a-z]+/i', $out)) {
  792. $out = '';
  793. }
  794. }
  795. break;
  796. case 'aZ09':
  797. if (!is_array($out)) {
  798. $out = trim($out);
  799. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  800. $out = '';
  801. }
  802. }
  803. break;
  804. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  805. if (!is_array($out)) {
  806. $out = trim($out);
  807. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  808. $out = '';
  809. }
  810. }
  811. break;
  812. case 'nohtml': // No html
  813. $out = dol_string_nohtmltag($out, 0);
  814. break;
  815. case 'alpha': // No html and no ../ and "
  816. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  817. if (!is_array($out)) {
  818. $out = trim($out);
  819. do {
  820. $oldstringtoclean = $out;
  821. // Remove html tags
  822. $out = dol_string_nohtmltag($out, 0);
  823. // Remove also other dangerous string sequences
  824. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  825. // '../' or '..\' is dangerous because it allows dir transversals
  826. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  827. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  828. } while ($oldstringtoclean != $out);
  829. // keep lines feed
  830. }
  831. break;
  832. case 'alphawithlgt': // No " and no ../ but we keep balanced < > tags with no special chars inside. Can be used for email string like "Name <email>". Less secured than 'alphanohtml'
  833. if (!is_array($out)) {
  834. $out = trim($out);
  835. do {
  836. $oldstringtoclean = $out;
  837. // Remove html tags
  838. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  839. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  840. // '../' or '..\' is dangerous because it allows dir transversals
  841. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  842. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  843. } while ($oldstringtoclean != $out);
  844. }
  845. break;
  846. case 'restricthtml': // Recommended for most html textarea
  847. case 'restricthtmlallowunvalid':
  848. do {
  849. $oldstringtoclean = $out;
  850. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  851. try {
  852. $dom = new DOMDocument;
  853. // Add a trick to solve pb with text without parent tag
  854. // like '<h1>Foo</h1><p>bar</p>' that ends up with '<h1>Foo<p>bar</p></h1>'
  855. // like 'abc' that ends up with '<p>abc</p>'
  856. $out = '<div class="tricktoremove">'.$out.'</div>';
  857. $dom->loadHTML($out, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  858. $out = trim($dom->saveHTML());
  859. // Remove the trick added to solve pb with text without parent tag
  860. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  861. $out = preg_replace('/<\/div>$/', '', $out);
  862. } catch (Exception $e) {
  863. //print $e->getMessage();
  864. return 'InvalidHTMLString';
  865. }
  866. }
  867. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  868. // encoded using text entities) so we can then exclude all numeric entities.
  869. $out = preg_replace('/&#39;/i', '&apos;', $out);
  870. // 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).
  871. // 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
  872. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  873. //$out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', 'realCharForNumericEntities', $out);
  874. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  875. return realCharForNumericEntities($m); }, $out);
  876. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  877. $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'.
  878. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  879. // We should also exclude non expected HTML attributes and clean content of some attributes.
  880. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  881. // 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.
  882. $out = dol_string_onlythesehtmlattributes($out);
  883. }
  884. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  885. $out = preg_replace('/&apos;/i', "&#39;", $out);
  886. } while ($oldstringtoclean != $out);
  887. break;
  888. case 'custom':
  889. if (empty($filter)) {
  890. return 'BadFourthParameterForGETPOST';
  891. }
  892. $out = filter_var($out, $filter, $options);
  893. break;
  894. }
  895. return $out;
  896. }
  897. if (!function_exists('dol_getprefix')) {
  898. /**
  899. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  900. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  901. * or two instances in same virtual servers.
  902. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  903. *
  904. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  905. * @return string A calculated prefix
  906. */
  907. function dol_getprefix($mode = '')
  908. {
  909. // If prefix is for email (we need to have $conf already loaded for this case)
  910. if ($mode == 'email') {
  911. global $conf;
  912. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  913. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  914. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  915. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  916. return $_SERVER["SERVER_NAME"];
  917. }
  918. }
  919. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  920. if (!empty($conf->file->instance_unique_id)) {
  921. return sha1('dolibarr'.$conf->file->instance_unique_id);
  922. }
  923. // For backward compatibility when instance_unique_id is not set
  924. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  925. }
  926. // If prefix is for session (no need to have $conf loaded)
  927. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  928. $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
  929. // The recommended value (may be not defined for old versions)
  930. if (!empty($tmp_instance_unique_id)) {
  931. return sha1('dolibarr'.$tmp_instance_unique_id);
  932. }
  933. // For backward compatibility when instance_unique_id is not set
  934. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  935. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  936. } else {
  937. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  938. }
  939. }
  940. }
  941. /**
  942. * Make an include_once using default root and alternate root if it fails.
  943. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  944. * To link to a module file from a module file, use include './mymodulefile';
  945. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  946. *
  947. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  948. * @param string $classname Class name (deprecated)
  949. * @return bool True if load is a success, False if it fails
  950. */
  951. function dol_include_once($relpath, $classname = '')
  952. {
  953. 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']
  954. $fullpath = dol_buildpath($relpath);
  955. if (!file_exists($fullpath)) {
  956. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  957. return false;
  958. }
  959. if (!empty($classname) && !class_exists($classname)) {
  960. return include $fullpath;
  961. } else {
  962. return include_once $fullpath;
  963. }
  964. }
  965. /**
  966. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  967. *
  968. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  969. * @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)
  970. * @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)
  971. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  972. * 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
  973. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  974. */
  975. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  976. {
  977. global $conf;
  978. $path = preg_replace('/^\//', '', $path);
  979. if (empty($type)) { // For a filesystem path
  980. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  981. if (is_array($conf->file->dol_document_root)) {
  982. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  983. if ($key == 'main') {
  984. continue;
  985. }
  986. if (file_exists($dirroot.'/'.$path)) {
  987. $res = $dirroot.'/'.$path;
  988. return $res;
  989. }
  990. }
  991. }
  992. if ($returnemptyifnotfound) {
  993. // Not found into alternate dir
  994. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  995. return '';
  996. }
  997. }
  998. } else {
  999. // For an url path
  1000. // We try to get local path of file on filesystem from url
  1001. // Note that trying to know if a file on disk exist by forging path on disk from url
  1002. // works only for some web server and some setup. This is bugged when
  1003. // using proxy, rewriting, virtual path, etc...
  1004. $res = '';
  1005. if ($type == 1) {
  1006. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  1007. }
  1008. if ($type == 2) {
  1009. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  1010. }
  1011. if ($type == 3) {
  1012. $res = DOL_URL_ROOT.'/'.$path;
  1013. }
  1014. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  1015. if ($key == 'main') {
  1016. if ($type == 3) {
  1017. global $dolibarr_main_url_root;
  1018. // Define $urlwithroot
  1019. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1020. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1021. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1022. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  1023. }
  1024. continue;
  1025. }
  1026. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  1027. if (!empty($regs[1])) {
  1028. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1029. if (file_exists($dirroot.'/'.$regs[1])) {
  1030. if ($type == 1) {
  1031. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1032. }
  1033. if ($type == 2) {
  1034. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1035. }
  1036. if ($type == 3) {
  1037. global $dolibarr_main_url_root;
  1038. // Define $urlwithroot
  1039. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1040. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1041. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1042. $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
  1043. }
  1044. break;
  1045. }
  1046. }
  1047. }
  1048. }
  1049. return $res;
  1050. }
  1051. /**
  1052. * Create a clone of instance of object (new instance with same value for properties)
  1053. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  1054. * 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.
  1055. *
  1056. * @param object $object Object to clone
  1057. * @param int $native 0=Full isolation method, 1=Native PHP method
  1058. * @return object Clone object
  1059. * @see https://php.net/manual/language.oop5.cloning.php
  1060. */
  1061. function dol_clone($object, $native = 0)
  1062. {
  1063. if (empty($native)) {
  1064. $tmpsavdb = null;
  1065. if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
  1066. $tmpsavdb = $object->db;
  1067. unset($object->db); // Such property can not be serialized when PgSql/Connection
  1068. }
  1069. $myclone = unserialize(serialize($object)); // serialize then unserialize is hack to be sure to have a new object for all fields
  1070. if ($tmpsavdb) {
  1071. $object->db = $tmpsavdb;
  1072. }
  1073. } else {
  1074. $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)
  1075. }
  1076. return $myclone;
  1077. }
  1078. /**
  1079. * Optimize a size for some browsers (phone, smarphone, ...)
  1080. *
  1081. * @param int $size Size we want
  1082. * @param string $type Type of optimizing:
  1083. * '' = function used to define a size for truncation
  1084. * 'width' = function is used to define a width
  1085. * @return int New size after optimizing
  1086. */
  1087. function dol_size($size, $type = '')
  1088. {
  1089. global $conf;
  1090. if (empty($conf->dol_optimize_smallscreen)) {
  1091. return $size;
  1092. }
  1093. if ($type == 'width' && $size > 250) {
  1094. return 250;
  1095. } else {
  1096. return 10;
  1097. }
  1098. }
  1099. /**
  1100. * Clean a string to use it as a file name.
  1101. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1102. *
  1103. * @param string $str String to clean
  1104. * @param string $newstr String to replace bad chars with.
  1105. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1106. * @return string String cleaned (a-zA-Z_)
  1107. *
  1108. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1109. */
  1110. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1111. {
  1112. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1113. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1114. // Char '/' and '\' are file delimiters.
  1115. // 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
  1116. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1117. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1118. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1119. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1120. $tmp = str_replace('..', '', $tmp);
  1121. return $tmp;
  1122. }
  1123. /**
  1124. * Clean a string to use it as a path name.
  1125. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1126. *
  1127. * @param string $str String to clean
  1128. * @param string $newstr String to replace bad chars with
  1129. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1130. * @return string String cleaned (a-zA-Z_)
  1131. *
  1132. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1133. */
  1134. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1135. {
  1136. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1137. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1138. // 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
  1139. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1140. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1141. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1142. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1143. $tmp = str_replace('..', '', $tmp);
  1144. return $tmp;
  1145. }
  1146. /**
  1147. * Clean a string to use it as an URL (into a href or src attribute)
  1148. *
  1149. * @param string $stringtoclean String to clean
  1150. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1151. * @return string Escaped string.
  1152. */
  1153. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1154. {
  1155. // 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)
  1156. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1157. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1158. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1159. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1160. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1161. if ($type == 1) {
  1162. // removing : should disable links to external url like http:aaa)
  1163. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1164. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1165. }
  1166. do {
  1167. $oldstringtoclean = $stringtoclean;
  1168. // removing '&colon' should disable links to external url like http:aaa)
  1169. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1170. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1171. } while ($oldstringtoclean != $stringtoclean);
  1172. if ($type == 1) {
  1173. // removing '//' should disable links to external url like //aaa or http//)
  1174. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1175. }
  1176. return $stringtoclean;
  1177. }
  1178. /**
  1179. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1180. *
  1181. * @param string $str String to clean
  1182. * @return string Cleaned string
  1183. *
  1184. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1185. */
  1186. function dol_string_unaccent($str)
  1187. {
  1188. global $conf;
  1189. if (utf8_check($str)) {
  1190. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1191. $transliterator = \Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', \Transliterator::FORWARD);
  1192. return $transliterator->transliterate($str);
  1193. }
  1194. // See http://www.utf8-chartable.de/
  1195. $string = rawurlencode($str);
  1196. $replacements = array(
  1197. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1198. '%C3%87' => 'C',
  1199. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1200. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1201. '%C3%91' => 'N',
  1202. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1203. '%C5%A0' => 'S',
  1204. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1205. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1206. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1207. '%C3%A7' => 'c',
  1208. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1209. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1210. '%C3%B1' => 'n',
  1211. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1212. '%C5%A1' => 's',
  1213. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1214. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1215. );
  1216. $string = strtr($string, $replacements);
  1217. return rawurldecode($string);
  1218. } else {
  1219. // See http://www.ascii-code.com/
  1220. $string = strtr(
  1221. $str,
  1222. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1223. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1224. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1225. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1226. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1227. \xF9\xFA\xFB\xFC\xFD\xFF",
  1228. "AAAAAAC
  1229. EEEEIIIIDN
  1230. OOOOOUUUY
  1231. aaaaaaceeee
  1232. iiiidnooooo
  1233. uuuuyy"
  1234. );
  1235. $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"));
  1236. return $string;
  1237. }
  1238. }
  1239. /**
  1240. * Clean a string from all punctuation characters to use it as a ref or login.
  1241. * This is a more complete function than dol_sanitizeFileName.
  1242. *
  1243. * @param string $str String to clean
  1244. * @param string $newstr String to replace forbidden chars with
  1245. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1246. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1247. * @return string Cleaned string
  1248. *
  1249. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1250. */
  1251. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1252. {
  1253. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1254. $forbidden_chars_to_remove = array();
  1255. //$forbidden_chars_to_remove=array("(",")");
  1256. if (is_array($badcharstoreplace)) {
  1257. $forbidden_chars_to_replace = $badcharstoreplace;
  1258. }
  1259. if (is_array($badcharstoremove)) {
  1260. $forbidden_chars_to_remove = $badcharstoremove;
  1261. }
  1262. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1263. }
  1264. /**
  1265. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1266. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1267. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1268. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1269. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1270. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1271. * @param string $str String to clean
  1272. * @param int $removetabcrlf Remove also CR-LF
  1273. * @return string Cleaned string
  1274. *
  1275. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1276. */
  1277. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1278. {
  1279. if ($removetabcrlf) {
  1280. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1281. } else {
  1282. 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
  1283. }
  1284. }
  1285. /**
  1286. * Returns text escaped for inclusion into javascript code
  1287. *
  1288. * @param string $stringtoescape String to escape
  1289. * @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 \
  1290. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1291. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1292. */
  1293. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1294. {
  1295. // escape quotes and backslashes, newlines, etc.
  1296. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1297. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1298. if (empty($noescapebackslashn)) {
  1299. $substitjs["\n"] = '\\n';
  1300. $substitjs['\\'] = '\\\\';
  1301. }
  1302. if (empty($mode)) {
  1303. $substitjs["'"] = "\\'";
  1304. $substitjs['"'] = "\\'";
  1305. } elseif ($mode == 1) {
  1306. $substitjs["'"] = "\\'";
  1307. } elseif ($mode == 2) {
  1308. $substitjs['"'] = '\\"';
  1309. } elseif ($mode == 3) {
  1310. $substitjs["'"] = "\\'";
  1311. $substitjs['"'] = "\\\"";
  1312. }
  1313. return strtr($stringtoescape, $substitjs);
  1314. }
  1315. /**
  1316. * Returns text escaped for inclusion into javascript code
  1317. *
  1318. * @param string $stringtoescape String to escape
  1319. * @return string Escaped string for json content.
  1320. */
  1321. function dol_escape_json($stringtoescape)
  1322. {
  1323. return str_replace('"', '\"', $stringtoescape);
  1324. }
  1325. /**
  1326. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1327. *
  1328. * @param string $stringtoescape String to escape
  1329. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1330. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1331. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes to tag.
  1332. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1333. * @return string Escaped string
  1334. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1335. */
  1336. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1337. {
  1338. if ($noescapetags == 'common') {
  1339. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1340. }
  1341. // escape quotes and backslashes, newlines, etc.
  1342. if ($escapeonlyhtmltags) {
  1343. $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
  1344. } else {
  1345. $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
  1346. }
  1347. if (!$keepb) {
  1348. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1349. }
  1350. if (!$keepn) {
  1351. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1352. }
  1353. if ($escapeonlyhtmltags) {
  1354. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1355. } else {
  1356. // Escape tags to keep
  1357. // TODO Does not works yet when there is attributes to tag
  1358. $tmparrayoftags = array();
  1359. if ($noescapetags) {
  1360. $tmparrayoftags = explode(',', $noescapetags);
  1361. }
  1362. if (count($tmparrayoftags)) {
  1363. foreach ($tmparrayoftags as $tagtoreplace) {
  1364. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1365. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1366. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1367. }
  1368. }
  1369. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1370. if (count($tmparrayoftags)) {
  1371. foreach ($tmparrayoftags as $tagtoreplace) {
  1372. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1373. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1374. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1375. }
  1376. }
  1377. return $result;
  1378. }
  1379. }
  1380. /**
  1381. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1382. *
  1383. * @param string $string String to encode
  1384. * @param string $encoding Character set encoding
  1385. * @return string String converted
  1386. */
  1387. function dol_strtolower($string, $encoding = "UTF-8")
  1388. {
  1389. if (function_exists('mb_strtolower')) {
  1390. return mb_strtolower($string, $encoding);
  1391. } else {
  1392. return strtolower($string);
  1393. }
  1394. }
  1395. /**
  1396. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1397. *
  1398. * @param string $string String to encode
  1399. * @param string $encoding Character set encoding
  1400. * @return string String converted
  1401. */
  1402. function dol_strtoupper($string, $encoding = "UTF-8")
  1403. {
  1404. if (function_exists('mb_strtoupper')) {
  1405. return mb_strtoupper($string, $encoding);
  1406. } else {
  1407. return strtoupper($string);
  1408. }
  1409. }
  1410. /**
  1411. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1412. *
  1413. * @param string $string String to encode
  1414. * @param string $encoding Character set encodign
  1415. * @return string String converted
  1416. */
  1417. function dol_ucfirst($string, $encoding = "UTF-8")
  1418. {
  1419. if (function_exists('mb_substr')) {
  1420. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1421. } else {
  1422. return ucfirst($string);
  1423. }
  1424. }
  1425. /**
  1426. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1427. *
  1428. * @param string $string String to encode
  1429. * @param string $encoding Character set encodign
  1430. * @return string String converted
  1431. */
  1432. function dol_ucwords($string, $encoding = "UTF-8")
  1433. {
  1434. if (function_exists('mb_convert_case')) {
  1435. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1436. } else {
  1437. return ucwords($string);
  1438. }
  1439. }
  1440. /**
  1441. * Write log message into outputs. Possible outputs can be:
  1442. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1443. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1444. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1445. * this, use logging to files instead of syslog (see setup of module).
  1446. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1447. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1448. * This function works only if syslog module is enabled.
  1449. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1450. *
  1451. * @param string $message Line to log. ''=Show nothing
  1452. * @param int $level Log level
  1453. * 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
  1454. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1455. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1456. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1457. * @param string $restricttologhandler Force output of log only to this log handler
  1458. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1459. * @return void
  1460. */
  1461. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1462. {
  1463. global $conf, $user, $debugbar;
  1464. // If syslog module enabled
  1465. if (empty($conf->syslog->enabled)) {
  1466. return;
  1467. }
  1468. // Check if we are into execution of code of a website
  1469. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1470. global $website, $websitekey;
  1471. if (is_object($website) && !empty($website->ref)) {
  1472. $suffixinfilename .= '_website_'.$website->ref;
  1473. } elseif (!empty($websitekey)) {
  1474. $suffixinfilename .= '_website_'.$websitekey;
  1475. }
  1476. }
  1477. // Check if we have a forced suffix
  1478. if (defined('USESUFFIXINLOG')) {
  1479. $suffixinfilename .= constant('USESUFFIXINLOG');
  1480. }
  1481. if ($ident < 0) {
  1482. foreach ($conf->loghandlers as $loghandlerinstance) {
  1483. $loghandlerinstance->setIdent($ident);
  1484. }
  1485. }
  1486. if (!empty($message)) {
  1487. // Test log level
  1488. $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');
  1489. if (!array_key_exists($level, $logLevels)) {
  1490. throw new Exception('Incorrect log level');
  1491. }
  1492. if ($level > $conf->global->SYSLOG_LEVEL) {
  1493. return;
  1494. }
  1495. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1496. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1497. }
  1498. // If adding log inside HTML page is required
  1499. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1500. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1501. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1502. }
  1503. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1504. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1505. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1506. print "\n\n<!-- Log start\n";
  1507. print dol_escape_htmltag($message)."\n";
  1508. print "Log end -->\n";
  1509. }
  1510. $data = array(
  1511. 'message' => $message,
  1512. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1513. 'level' => $level,
  1514. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1515. 'ip' => false
  1516. );
  1517. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1518. if (!empty($remoteip)) {
  1519. $data['ip'] = $remoteip;
  1520. // This is when server run behind a reverse proxy
  1521. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1522. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1523. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1524. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1525. }
  1526. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1527. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1528. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1529. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1530. // 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).
  1531. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1532. } elseif (!empty($_SERVER['LOGNAME'])) {
  1533. // 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).
  1534. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1535. }
  1536. // Loop on each log handler and send output
  1537. foreach ($conf->loghandlers as $loghandlerinstance) {
  1538. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1539. continue;
  1540. }
  1541. $loghandlerinstance->export($data, $suffixinfilename);
  1542. }
  1543. unset($data);
  1544. }
  1545. if ($ident > 0) {
  1546. foreach ($conf->loghandlers as $loghandlerinstance) {
  1547. $loghandlerinstance->setIdent($ident);
  1548. }
  1549. }
  1550. }
  1551. /**
  1552. * Return HTML code to output a button to open a dialog popup box.
  1553. * Such buttons must be included inside a HTML form.
  1554. *
  1555. * @param string $name A name for the html component
  1556. * @param string $label Label shown in Popup title top bar
  1557. * @param string $buttonstring button string
  1558. * @param string $url Url to open
  1559. * @param string $disabled Disabled text
  1560. * @param string $morecss More CSS
  1561. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1562. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1563. * @return string HTML component with button
  1564. */
  1565. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'button bordertransp', $backtopagejsfields = '')
  1566. {
  1567. if (strpos($url, '?') > 0) {
  1568. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1569. } else {
  1570. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1571. }
  1572. $out = '';
  1573. $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
  1574. if ($backtopagejsfields) {
  1575. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1576. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1577. $backtopagejsfields = $name.":".$backtopagejsfields;
  1578. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1579. } else {
  1580. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1581. }
  1582. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1583. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1584. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1585. }
  1586. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1587. $out .= '<!-- a link for button to open url into a dialog popup backtopagejsfields = '.$backtopagejsfields.' -->'."\n";
  1588. $out .= '<a class="cursorpointer button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1589. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1590. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1591. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1592. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1593. $out .= '<script type="text/javascript">
  1594. jQuery(document).ready(function () {
  1595. jQuery(".button_'.$name.'").click(function () {
  1596. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1597. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1598. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1599. $tmpdialog.dialog({
  1600. autoOpen: false,
  1601. modal: true,
  1602. height: (window.innerHeight - 150),
  1603. width: \'80%\',
  1604. title: \''.dol_escape_js($label).'\',
  1605. open: function (event, ui) {
  1606. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1607. },
  1608. close: function (event, ui) {
  1609. returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1610. returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1611. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1612. if (returnedid != "" && returnedid != "div for returned id") {
  1613. jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
  1614. }
  1615. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1616. jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
  1617. }
  1618. }
  1619. });
  1620. $tmpdialog.dialog(\'open\');
  1621. });
  1622. });
  1623. </script>';
  1624. return $out;
  1625. }
  1626. /**
  1627. * Show tab header of a card
  1628. *
  1629. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1630. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1631. * @param string $title Title
  1632. * @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)
  1633. * @param string $picto Add a picto on tab title
  1634. * @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.
  1635. * @param string $morehtmlright Add more html content on right of tabs title
  1636. * @param string $morecss More Css
  1637. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1638. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1639. * @return void
  1640. * @deprecated Use print dol_get_fiche_head() instead
  1641. */
  1642. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1643. {
  1644. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1645. }
  1646. /**
  1647. * Show tabs of a record
  1648. *
  1649. * @param array $links Array of tabs. Note that label into $links[$i][1] must be already HTML escaped.
  1650. * @param string $active Active tab name
  1651. * @param string $title Title
  1652. * @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)
  1653. * @param string $picto Add a picto on tab title
  1654. * @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.
  1655. * @param string $morehtmlright Add more html content on right of tabs title
  1656. * @param string $morecss More CSS on the link <a>
  1657. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1658. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1659. * @return string
  1660. */
  1661. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1662. {
  1663. global $conf, $langs, $hookmanager;
  1664. // Show title
  1665. $showtitle = 1;
  1666. if (!empty($conf->dol_optimize_smallscreen)) {
  1667. $showtitle = 0;
  1668. }
  1669. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1670. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1671. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1672. }
  1673. // Show right part
  1674. if ($morehtmlright) {
  1675. $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.
  1676. }
  1677. // Show title
  1678. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1679. $limittitle = 30;
  1680. $out .= '<a class="tabTitle">';
  1681. if ($picto) {
  1682. $noprefix = $pictoisfullpath;
  1683. if (strpos($picto, 'fontawesome_') !== false) {
  1684. $noprefix = 1;
  1685. }
  1686. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1687. }
  1688. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1689. $out .= '</a>';
  1690. }
  1691. // Show tabs
  1692. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1693. $maxkey = -1;
  1694. if (is_array($links) && !empty($links)) {
  1695. $keys = array_keys($links);
  1696. if (count($keys)) {
  1697. $maxkey = max($keys);
  1698. }
  1699. }
  1700. // Show tabs
  1701. // if =0 we don't use the feature
  1702. if (empty($limittoshow)) {
  1703. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1704. }
  1705. if (!empty($conf->dol_optimize_smallscreen)) {
  1706. $limittoshow = 2;
  1707. }
  1708. $displaytab = 0;
  1709. $nbintab = 0;
  1710. $popuptab = 0;
  1711. $outmore = '';
  1712. for ($i = 0; $i <= $maxkey; $i++) {
  1713. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1714. // If active tab is already present
  1715. if ($i >= $limittoshow) {
  1716. $limittoshow--;
  1717. }
  1718. }
  1719. }
  1720. for ($i = 0; $i <= $maxkey; $i++) {
  1721. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1722. $isactive = true;
  1723. } else {
  1724. $isactive = false;
  1725. }
  1726. if ($i < $limittoshow || $isactive) {
  1727. // Output entry with a visible tab
  1728. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : dol_escape_htmltag($links[$i][2])).' -->';
  1729. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1730. if (!empty($links[$i][0])) {
  1731. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1732. } else {
  1733. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1734. }
  1735. } elseif (!empty($links[$i][1])) {
  1736. //print "x $i $active ".$links[$i][2]." z";
  1737. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1738. if (!empty($links[$i][0])) {
  1739. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1740. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  1741. }
  1742. $out .= $links[$i][1];
  1743. if (!empty($links[$i][0])) {
  1744. $out .= '</a>'."\n";
  1745. }
  1746. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1747. $out .= '</div>';
  1748. }
  1749. $out .= '</div>';
  1750. } else {
  1751. // Add entry into the combo popup with the other tabs
  1752. if (!$popuptab) {
  1753. $popuptab = 1;
  1754. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1755. }
  1756. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1757. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1758. if (!empty($links[$i][0])) {
  1759. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1760. } else {
  1761. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1762. }
  1763. } elseif (!empty($links[$i][1])) {
  1764. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1765. $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.
  1766. $outmore .= '</a>'."\n";
  1767. }
  1768. $outmore .= '</div>';
  1769. $nbintab++;
  1770. }
  1771. $displaytab = $i;
  1772. }
  1773. if ($popuptab) {
  1774. $outmore .= '</div>';
  1775. }
  1776. if ($popuptab) { // If there is some tabs not shown
  1777. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1778. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1779. $widthofpopup = 200;
  1780. $tabsname = $moretabssuffix;
  1781. if (empty($tabsname)) {
  1782. $tabsname = str_replace("@", "", $picto);
  1783. }
  1784. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  1785. $out .= '<div class="tab"><a href="#" class="tab moretab inline-block tabunactive"><span class="hideonsmartphone">'.$langs->trans("More").'</span>... ('.$nbintab.')</a></div>'; // Do not use "reposition" class in the "More".
  1786. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1787. $out .= $outmore;
  1788. $out .= '</div>';
  1789. $out .= '<div></div>';
  1790. $out .= "</div>\n";
  1791. $out .= "<script>";
  1792. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1793. var x = this.offsetLeft, y = this.offsetTop;
  1794. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1795. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1796. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1797. }
  1798. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1799. });
  1800. ";
  1801. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1802. $out .= "</script>";
  1803. }
  1804. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1805. $out .= "</div>\n";
  1806. }
  1807. if (!$notab || $notab == -1 || $notab == -2) {
  1808. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1809. }
  1810. $parameters = array('tabname' => $active, 'out' => $out);
  1811. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1812. if ($reshook > 0) {
  1813. $out = $hookmanager->resPrint;
  1814. }
  1815. return $out;
  1816. }
  1817. /**
  1818. * Show tab footer of a card
  1819. *
  1820. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1821. * @return void
  1822. * @deprecated Use print dol_get_fiche_end() instead
  1823. */
  1824. function dol_fiche_end($notab = 0)
  1825. {
  1826. print dol_get_fiche_end($notab);
  1827. }
  1828. /**
  1829. * Return tab footer of a card
  1830. *
  1831. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1832. * @return string
  1833. */
  1834. function dol_get_fiche_end($notab = 0)
  1835. {
  1836. if (!$notab || $notab == -1) {
  1837. return "\n</div>\n";
  1838. } else {
  1839. return '';
  1840. }
  1841. }
  1842. /**
  1843. * Show tab footer of a card.
  1844. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1845. *
  1846. * @param Object $object Object to show
  1847. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1848. * @param string $morehtml More html content to output just before the nav bar
  1849. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1850. * @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.
  1851. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1852. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1853. * @param string $moreparam More param to add in nav link url.
  1854. * @param int $nodbprefix Do not include DB prefix to forge table name
  1855. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1856. * @param string $morehtmlstatus More html code to show under navigation arrows
  1857. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1858. * @param string $morehtmlright More html code to show before navigation arrows
  1859. * @return void
  1860. */
  1861. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1862. {
  1863. global $conf, $form, $user, $langs, $hookmanager, $action;
  1864. $error = 0;
  1865. $maxvisiblephotos = 1;
  1866. $showimage = 1;
  1867. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1868. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1869. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1870. $showbarcode = 0;
  1871. }
  1872. $modulepart = 'unknown';
  1873. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1874. $modulepart = $object->element;
  1875. } elseif ($object->element == 'member') {
  1876. $modulepart = 'memberphoto';
  1877. } elseif ($object->element == 'user') {
  1878. $modulepart = 'userphoto';
  1879. }
  1880. if (class_exists("Imagick")) {
  1881. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1882. $modulepart = $object->element;
  1883. } elseif ($object->element == 'fichinter') {
  1884. $modulepart = 'ficheinter';
  1885. } elseif ($object->element == 'contrat') {
  1886. $modulepart = 'contract';
  1887. } elseif ($object->element == 'order_supplier') {
  1888. $modulepart = 'supplier_order';
  1889. } elseif ($object->element == 'invoice_supplier') {
  1890. $modulepart = 'supplier_invoice';
  1891. }
  1892. }
  1893. if ($object->element == 'product') {
  1894. $width = 80;
  1895. $cssclass = 'photowithmargin photoref';
  1896. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1897. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1898. if ($conf->browser->layout == 'phone') {
  1899. $maxvisiblephotos = 1;
  1900. }
  1901. if ($showimage) {
  1902. $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>';
  1903. } else {
  1904. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1905. $nophoto = '';
  1906. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1907. } else { // Show no photo link
  1908. $nophoto = '/public/theme/common/nophoto.png';
  1909. $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>';
  1910. }
  1911. }
  1912. } elseif ($object->element == 'ticket') {
  1913. $width = 80;
  1914. $cssclass = 'photoref';
  1915. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1916. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1917. if ($conf->browser->layout == 'phone') {
  1918. $maxvisiblephotos = 1;
  1919. }
  1920. if ($showimage) {
  1921. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1922. if ($object->nbphoto > 0) {
  1923. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1924. } else {
  1925. $showimage = 0;
  1926. }
  1927. }
  1928. if (!$showimage) {
  1929. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1930. $nophoto = '';
  1931. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1932. } else { // Show no photo link
  1933. $nophoto = img_picto('No photo', 'object_ticket');
  1934. $morehtmlleft .= '<!-- No photo to show -->';
  1935. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1936. $morehtmlleft .= $nophoto;
  1937. $morehtmlleft .= '</div></div>';
  1938. }
  1939. }
  1940. } else {
  1941. if ($showimage) {
  1942. if ($modulepart != 'unknown') {
  1943. $phototoshow = '';
  1944. // Check if a preview file is available
  1945. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1946. $objectref = dol_sanitizeFileName($object->ref);
  1947. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1948. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1949. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1950. $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
  1951. } else {
  1952. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1953. }
  1954. if (empty($subdir)) {
  1955. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1956. }
  1957. $filepath = $dir_output.$subdir."/";
  1958. $filepdf = $filepath.$objectref.".pdf";
  1959. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1960. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1961. $fileimage = $filepdf.'_preview.png';
  1962. $relativepathimage = $relativepath.'_preview.png';
  1963. $pdfexists = file_exists($filepdf);
  1964. // If PDF file exists
  1965. if ($pdfexists) {
  1966. // Conversion du PDF en image png si fichier png non existant
  1967. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  1968. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1969. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1970. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1971. if ($ret < 0) {
  1972. $error++;
  1973. }
  1974. }
  1975. }
  1976. }
  1977. if ($pdfexists && !$error) {
  1978. $heightforphotref = 80;
  1979. if (!empty($conf->dol_optimize_smallscreen)) {
  1980. $heightforphotref = 60;
  1981. }
  1982. // If the preview file is found
  1983. if (file_exists($fileimage)) {
  1984. $phototoshow = '<div class="photoref">';
  1985. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1986. $phototoshow .= '</div>';
  1987. }
  1988. }
  1989. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  1990. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  1991. }
  1992. if ($phototoshow) {
  1993. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1994. $morehtmlleft .= $phototoshow;
  1995. $morehtmlleft .= '</div>';
  1996. }
  1997. }
  1998. if (empty($phototoshow)) { // Show No photo link (picto of object)
  1999. if ($object->element == 'action') {
  2000. $width = 80;
  2001. $cssclass = 'photorefcenter';
  2002. $nophoto = img_picto('No photo', 'title_agenda');
  2003. } else {
  2004. $width = 14;
  2005. $cssclass = 'photorefcenter';
  2006. $picto = $object->picto;
  2007. $prefix = 'object_';
  2008. if ($object->element == 'project' && !$object->public) {
  2009. $picto = 'project'; // instead of projectpub
  2010. }
  2011. if (strpos($picto, 'fontawesome_') !== false) {
  2012. $prefix = '';
  2013. }
  2014. $nophoto = img_picto('No photo', $prefix.$picto);
  2015. }
  2016. $morehtmlleft .= '<!-- No photo to show -->';
  2017. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2018. $morehtmlleft .= $nophoto;
  2019. $morehtmlleft .= '</div></div>';
  2020. }
  2021. }
  2022. }
  2023. if ($showbarcode) {
  2024. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
  2025. }
  2026. if ($object->element == 'societe') {
  2027. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2028. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  2029. } else {
  2030. $morehtmlstatus .= $object->getLibStatut(6);
  2031. }
  2032. } elseif ($object->element == 'product') {
  2033. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  2034. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2035. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  2036. } else {
  2037. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  2038. }
  2039. $morehtmlstatus .= ' &nbsp; ';
  2040. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2041. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2042. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2043. } else {
  2044. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2045. }
  2046. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  2047. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2048. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2049. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2050. }
  2051. $morehtmlstatus .= $tmptxt;
  2052. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2053. if ($object->statut == 0) {
  2054. $morehtmlstatus .= $object->getLibStatut(5);
  2055. } else {
  2056. $morehtmlstatus .= $object->getLibStatut(4);
  2057. }
  2058. } elseif ($object->element == 'facturerec') {
  2059. if ($object->frequency == 0) {
  2060. $morehtmlstatus .= $object->getLibStatut(2);
  2061. } else {
  2062. $morehtmlstatus .= $object->getLibStatut(5);
  2063. }
  2064. } elseif ($object->element == 'project_task') {
  2065. $object->fk_statut = 1;
  2066. if ($object->progress > 0) {
  2067. $object->fk_statut = 2;
  2068. }
  2069. if ($object->progress >= 100) {
  2070. $object->fk_statut = 3;
  2071. }
  2072. $tmptxt = $object->getLibStatut(5);
  2073. $morehtmlstatus .= $tmptxt; // No status on task
  2074. } else { // Generic case
  2075. $tmptxt = $object->getLibStatut(6);
  2076. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2077. $tmptxt = $object->getLibStatut(5);
  2078. }
  2079. $morehtmlstatus .= $tmptxt;
  2080. }
  2081. // Add if object was dispatched "into accountancy"
  2082. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2083. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2084. if (method_exists($object, 'getVentilExportCompta')) {
  2085. $accounted = $object->getVentilExportCompta();
  2086. $langs->load("accountancy");
  2087. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2088. }
  2089. }
  2090. // Add alias for thirdparty
  2091. if (!empty($object->name_alias)) {
  2092. $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  2093. }
  2094. // Add label
  2095. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2096. if (!empty($object->label)) {
  2097. $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  2098. }
  2099. }
  2100. // Show address and email
  2101. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2102. $moreaddress = $object->getBannerAddress('refaddress', $object);
  2103. if ($moreaddress) {
  2104. $morehtmlref .= '<div class="refidno">';
  2105. $morehtmlref .= $moreaddress;
  2106. $morehtmlref .= '</div>';
  2107. }
  2108. }
  2109. 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)) {
  2110. $morehtmlref .= '<div style="clear: both;"></div>';
  2111. $morehtmlref .= '<div class="refidno">';
  2112. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  2113. $morehtmlref .= '</div>';
  2114. }
  2115. $parameters=array('morehtmlref'=>$morehtmlref);
  2116. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2117. if ($reshook < 0) {
  2118. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2119. } elseif (empty($reshook)) {
  2120. $morehtmlref .= $hookmanager->resPrint;
  2121. } elseif ($reshook > 0) {
  2122. $morehtmlref = $hookmanager->resPrint;
  2123. }
  2124. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2125. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2126. print '</div>';
  2127. print '<div class="underrefbanner clearboth"></div>';
  2128. }
  2129. /**
  2130. * Show a string with the label tag dedicated to the HTML edit field.
  2131. *
  2132. * @param string $langkey Translation key
  2133. * @param string $fieldkey Key of the html select field the text refers to
  2134. * @param int $fieldrequired 1=Field is mandatory
  2135. * @return string
  2136. * @deprecated Form::editfieldkey
  2137. */
  2138. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2139. {
  2140. global $langs;
  2141. $ret = '';
  2142. if ($fieldrequired) {
  2143. $ret .= '<span class="fieldrequired">';
  2144. }
  2145. $ret .= '<label for="'.$fieldkey.'">';
  2146. $ret .= $langs->trans($langkey);
  2147. $ret .= '</label>';
  2148. if ($fieldrequired) {
  2149. $ret .= '</span>';
  2150. }
  2151. return $ret;
  2152. }
  2153. /**
  2154. * Return string to add class property on html element with pair/impair.
  2155. *
  2156. * @param string $var 0 or 1
  2157. * @param string $moreclass More class to add
  2158. * @return string String to add class onto HTML element
  2159. */
  2160. function dol_bc($var, $moreclass = '')
  2161. {
  2162. global $bc;
  2163. $ret = ' '.$bc[$var];
  2164. if ($moreclass) {
  2165. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2166. }
  2167. return $ret;
  2168. }
  2169. /**
  2170. * Return a formated address (part address/zip/town/state) according to country rules.
  2171. * See https://en.wikipedia.org/wiki/Address
  2172. *
  2173. * @param Object $object A company or contact object
  2174. * @param int $withcountry 1=Add country into address string
  2175. * @param string $sep Separator to use to build string
  2176. * @param Translate $outputlangs Object lang that contains language for text translation.
  2177. * @param int $mode 0=Standard output, 1=Remove address
  2178. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2179. * @return string Formated string
  2180. * @see dol_print_address()
  2181. */
  2182. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2183. {
  2184. global $conf, $langs, $hookmanager;
  2185. $ret = '';
  2186. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2187. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2188. // Address
  2189. if (empty($mode)) {
  2190. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2191. }
  2192. // Zip/Town/State
  2193. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2194. // US: title firstname name \n address lines \n town, state, zip \n country
  2195. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2196. $ret .= (($ret && $town) ? $sep : '').$town;
  2197. if (!empty($object->state)) {
  2198. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2199. }
  2200. if (!empty($object->zip)) {
  2201. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2202. }
  2203. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2204. // UK: title firstname name \n address lines \n town state \n zip \n country
  2205. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2206. $ret .= ($ret ? $sep : '').$town;
  2207. if (!empty($object->state)) {
  2208. $ret .= ($ret ? ", " : '').$object->state;
  2209. }
  2210. if (!empty($object->zip)) {
  2211. $ret .= ($ret ? $sep : '').$object->zip;
  2212. }
  2213. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2214. // ES: title firstname name \n address lines \n zip town \n state \n country
  2215. $ret .= ($ret ? $sep : '').$object->zip;
  2216. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2217. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2218. if (!empty($object->state)) {
  2219. $ret .= "\n".$object->state;
  2220. }
  2221. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2222. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2223. // See https://www.sljfaq.org/afaq/addresses.html
  2224. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2225. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2226. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2227. // IT: title firstname name\n address lines \n zip town state_code \n country
  2228. $ret .= ($ret ? $sep : '').$object->zip;
  2229. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2230. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2231. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2232. } else {
  2233. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2234. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2235. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2236. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2237. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2238. $ret .= ($ret ? ", " : '').$object->state;
  2239. }
  2240. }
  2241. if (!is_object($outputlangs)) {
  2242. $outputlangs = $langs;
  2243. }
  2244. if ($withcountry) {
  2245. $langs->load("dict");
  2246. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2247. }
  2248. if ($hookmanager) {
  2249. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2250. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2251. if ($reshook > 0) {
  2252. $ret = '';
  2253. }
  2254. $ret .= $hookmanager->resPrint;
  2255. }
  2256. return $ret;
  2257. }
  2258. /**
  2259. * Format a string.
  2260. *
  2261. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2262. * @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)
  2263. * @param int $is_gmt See comment of timestamp parameter
  2264. * @return string A formatted string
  2265. */
  2266. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2267. {
  2268. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2269. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2270. } else {
  2271. return 'Error date into a not supported range';
  2272. }
  2273. }
  2274. /**
  2275. * Output date in a string format according to outputlangs (or langs if not defined).
  2276. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2277. *
  2278. * @param int $time GM Timestamps date
  2279. * @param string $format Output date format (tag of strftime function)
  2280. * "%d %b %Y",
  2281. * "%d/%m/%Y %H:%M",
  2282. * "%d/%m/%Y %H:%M:%S",
  2283. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2284. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2285. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2286. * false or 'tzserver' => output string is for local PHP server TZ usage
  2287. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2288. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2289. * @param Translate $outputlangs Object lang that contains language for text translation.
  2290. * @param boolean $encodetooutput false=no convert into output pagecode
  2291. * @return string Formated date or '' if time is null
  2292. *
  2293. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2294. */
  2295. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2296. {
  2297. global $conf, $langs;
  2298. // If date undefined or "", we return ""
  2299. if (dol_strlen($time) == 0) {
  2300. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2301. }
  2302. if ($tzoutput === 'auto') {
  2303. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2304. }
  2305. // Clean parameters
  2306. $to_gmt = false;
  2307. $offsettz = $offsetdst = 0;
  2308. if ($tzoutput) {
  2309. $to_gmt = true; // For backward compatibility
  2310. if (is_string($tzoutput)) {
  2311. if ($tzoutput == 'tzserver') {
  2312. $to_gmt = false;
  2313. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2314. $offsettz = 0; // Timezone offset with server timezone, so 0
  2315. $offsetdst = 0; // Dst offset with server timezone, so 0
  2316. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2317. $to_gmt = true;
  2318. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2319. if (class_exists('DateTimeZone')) {
  2320. $user_date_tz = new DateTimeZone($offsettzstring);
  2321. $user_dt = new DateTime();
  2322. $user_dt->setTimezone($user_date_tz);
  2323. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2324. $offsettz = $user_dt->getOffset();
  2325. } else { // old method (The 'tzuser' was processed like the 'tzuserrel')
  2326. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2327. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2328. }
  2329. }
  2330. }
  2331. }
  2332. if (!is_object($outputlangs)) {
  2333. $outputlangs = $langs;
  2334. }
  2335. if (!$format) {
  2336. $format = 'daytextshort';
  2337. }
  2338. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2339. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2340. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2341. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2342. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2343. if ($formatwithoutreduce != $format) {
  2344. $format = $formatwithoutreduce;
  2345. $reduceformat = 1;
  2346. } // so format 'dayreduceformat' is processed like day
  2347. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2348. // TODO Add format daysmallyear and dayhoursmallyear
  2349. if ($format == 'day') {
  2350. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2351. } elseif ($format == 'hour') {
  2352. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2353. } elseif ($format == 'hourduration') {
  2354. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2355. } elseif ($format == 'daytext') {
  2356. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2357. } elseif ($format == 'daytextshort') {
  2358. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2359. } elseif ($format == 'dayhour') {
  2360. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2361. } elseif ($format == 'dayhoursec') {
  2362. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2363. } elseif ($format == 'dayhourtext') {
  2364. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2365. } elseif ($format == 'dayhourtextshort') {
  2366. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2367. } elseif ($format == 'dayhourlog') {
  2368. // Format not sensitive to language
  2369. $format = '%Y%m%d%H%M%S';
  2370. } elseif ($format == 'dayhourlogsmall') {
  2371. // Format not sensitive to language
  2372. $format = '%Y%m%d%H%M';
  2373. } elseif ($format == 'dayhourldap') {
  2374. $format = '%Y%m%d%H%M%SZ';
  2375. } elseif ($format == 'dayhourxcard') {
  2376. $format = '%Y%m%dT%H%M%SZ';
  2377. } elseif ($format == 'dayxcard') {
  2378. $format = '%Y%m%d';
  2379. } elseif ($format == 'dayrfc') {
  2380. $format = '%Y-%m-%d'; // DATE_RFC3339
  2381. } elseif ($format == 'dayhourrfc') {
  2382. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2383. } elseif ($format == 'standard') {
  2384. $format = '%Y-%m-%d %H:%M:%S';
  2385. }
  2386. if ($reduceformat) {
  2387. $format = str_replace('%Y', '%y', $format);
  2388. $format = str_replace('yyyy', 'yy', $format);
  2389. }
  2390. // Clean format
  2391. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2392. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2393. $format = str_replace('%b', '__b__', $format);
  2394. $format = str_replace('%B', '__B__', $format);
  2395. }
  2396. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2397. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2398. $format = str_replace('%a', '__a__', $format);
  2399. $format = str_replace('%A', '__A__', $format);
  2400. }
  2401. // Analyze date
  2402. $reg = array();
  2403. 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
  2404. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2405. return '';
  2406. } 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
  2407. // This part of code should not be used anymore.
  2408. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2409. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2410. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2411. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2412. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2413. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2414. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2415. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2416. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2417. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2418. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  2419. } else {
  2420. // Date is a timestamps
  2421. if ($time < 100000000000) { // Protection against bad date values
  2422. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2423. $ret = adodb_strftime($format, $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2424. } else {
  2425. $ret = 'Bad value '.$time.' for date';
  2426. }
  2427. }
  2428. if (preg_match('/__b__/i', $format)) {
  2429. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2430. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  2431. $month = adodb_strftime('%m', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2432. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2433. if ($encodetooutput) {
  2434. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2435. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2436. } else {
  2437. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2438. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2439. }
  2440. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2441. $ret = str_replace('__b__', $monthtextshort, $ret);
  2442. $ret = str_replace('__B__', $monthtext, $ret);
  2443. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2444. //return $ret;
  2445. }
  2446. if (preg_match('/__a__/i', $format)) {
  2447. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2448. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2449. $w = adodb_strftime('%w', $timetouse, $to_gmt); // If to_gmt = false then adodb_strftime use TZ of server
  2450. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2451. $ret = str_replace('__A__', $dayweek, $ret);
  2452. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2453. }
  2454. return $ret;
  2455. }
  2456. /**
  2457. * Return an array with locale date info.
  2458. * WARNING: This function use PHP server timezone by default to return locale informations.
  2459. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2460. *
  2461. * @param int $timestamp Timestamp
  2462. * @param boolean $fast Fast mode. deprecated.
  2463. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2464. * @return array Array of informations
  2465. * 'seconds' => $secs,
  2466. * 'minutes' => $min,
  2467. * 'hours' => $hour,
  2468. * 'mday' => $day,
  2469. * 'wday' => $dow, 0=sunday, 6=saturday
  2470. * 'mon' => $month,
  2471. * 'year' => $year,
  2472. * 'yday' => floor($secsInYear/$_day_power)
  2473. * '0' => original timestamp
  2474. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2475. */
  2476. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2477. {
  2478. //$datetimeobj = new DateTime('@'.$timestamp);
  2479. $datetimeobj = new DateTime();
  2480. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2481. if ($forcetimezone) {
  2482. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2483. }
  2484. $arrayinfo = array(
  2485. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2486. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2487. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2488. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2489. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2490. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2491. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2492. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2493. '0'=>$timestamp
  2494. );
  2495. return $arrayinfo;
  2496. }
  2497. /**
  2498. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2499. * Replace function mktime not available under Windows if year < 1970
  2500. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2501. *
  2502. * @param int $hour Hour (can be -1 for undefined)
  2503. * @param int $minute Minute (can be -1 for undefined)
  2504. * @param int $second Second (can be -1 for undefined)
  2505. * @param int $month Month (1 to 12)
  2506. * @param int $day Day (1 to 31)
  2507. * @param int $year Year
  2508. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2509. * False or 0 or 'tzserver' = local to server TZ
  2510. * 'auto'
  2511. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2512. * '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.
  2513. * 'tz,TimeZone' = use specified timezone
  2514. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2515. * @return int|string Date as a timestamp, '' or false if error
  2516. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2517. */
  2518. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2519. {
  2520. global $conf;
  2521. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2522. if ($gm === 'auto') {
  2523. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2524. }
  2525. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2526. // Clean parameters
  2527. if ($hour == -1 || empty($hour)) {
  2528. $hour = 0;
  2529. }
  2530. if ($minute == -1 || empty($minute)) {
  2531. $minute = 0;
  2532. }
  2533. if ($second == -1 || empty($second)) {
  2534. $second = 0;
  2535. }
  2536. // Check parameters
  2537. if ($check) {
  2538. if (!$month || !$day) {
  2539. return '';
  2540. }
  2541. if ($day > 31) {
  2542. return '';
  2543. }
  2544. if ($month > 12) {
  2545. return '';
  2546. }
  2547. if ($hour < 0 || $hour > 24) {
  2548. return '';
  2549. }
  2550. if ($minute < 0 || $minute > 60) {
  2551. return '';
  2552. }
  2553. if ($second < 0 || $second > 60) {
  2554. return '';
  2555. }
  2556. }
  2557. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2558. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2559. $localtz = new DateTimeZone($default_timezone);
  2560. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2561. // We use dol_tz_string first because it is more reliable.
  2562. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2563. try {
  2564. $localtz = new DateTimeZone($default_timezone);
  2565. } catch (Exception $e) {
  2566. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2567. $default_timezone = @date_default_timezone_get();
  2568. }
  2569. } elseif (strrpos($gm, "tz,") !== false) {
  2570. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2571. try {
  2572. $localtz = new DateTimeZone($timezone);
  2573. } catch (Exception $e) {
  2574. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2575. }
  2576. }
  2577. if (empty($localtz)) {
  2578. $localtz = new DateTimeZone('UTC');
  2579. }
  2580. //var_dump($localtz);
  2581. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2582. $dt = new DateTime('now', $localtz);
  2583. $dt->setDate((int) $year, (int) $month, (int) $day);
  2584. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2585. $date = $dt->getTimestamp(); // should include daylight saving time
  2586. //var_dump($date);
  2587. return $date;
  2588. }
  2589. /**
  2590. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2591. *
  2592. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2593. * 'gmt' => we return GMT timestamp,
  2594. * 'tzserver' => we add the PHP server timezone
  2595. * 'tzref' => we add the company timezone. Not implemented.
  2596. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2597. * @return int $date Timestamp
  2598. */
  2599. function dol_now($mode = 'auto')
  2600. {
  2601. $ret = 0;
  2602. if ($mode === 'auto') {
  2603. $mode = 'gmt';
  2604. }
  2605. if ($mode == 'gmt') {
  2606. $ret = time(); // Time for now at greenwich.
  2607. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2608. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2609. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2610. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2611. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2612. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2613. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2614. // $ret=dol_now('gmt')+($tzsecond*3600);
  2615. //}
  2616. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2617. // Time for now with user timezone added
  2618. //print 'time: '.time();
  2619. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2620. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2621. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2622. }
  2623. return $ret;
  2624. }
  2625. /**
  2626. * Return string with formated size
  2627. *
  2628. * @param int $size Size to print
  2629. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2630. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2631. * @return string Link
  2632. */
  2633. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2634. {
  2635. global $conf, $langs;
  2636. $level = 1024;
  2637. if (!empty($conf->dol_optimize_smallscreen)) {
  2638. $shortunit = 1;
  2639. }
  2640. // Set value text
  2641. if (empty($shortvalue) || $size < ($level * 10)) {
  2642. $ret = $size;
  2643. $textunitshort = $langs->trans("b");
  2644. $textunitlong = $langs->trans("Bytes");
  2645. } else {
  2646. $ret = round($size / $level, 0);
  2647. $textunitshort = $langs->trans("Kb");
  2648. $textunitlong = $langs->trans("KiloBytes");
  2649. }
  2650. // Use long or short text unit
  2651. if (empty($shortunit)) {
  2652. $ret .= ' '.$textunitlong;
  2653. } else {
  2654. $ret .= ' '.$textunitshort;
  2655. }
  2656. return $ret;
  2657. }
  2658. /**
  2659. * Show Url link
  2660. *
  2661. * @param string $url Url to show
  2662. * @param string $target Target for link
  2663. * @param int $max Max number of characters to show
  2664. * @param int $withpicto With picto
  2665. * @return string HTML Link
  2666. */
  2667. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2668. {
  2669. global $langs;
  2670. if (empty($url)) {
  2671. return '';
  2672. }
  2673. $link = '<a href="';
  2674. if (!preg_match('/^http/i', $url)) {
  2675. $link .= 'http://';
  2676. }
  2677. $link .= $url;
  2678. $link .= '"';
  2679. if ($target) {
  2680. $link .= ' target="'.$target.'"';
  2681. }
  2682. $link .= '>';
  2683. if (!preg_match('/^http/i', $url)) {
  2684. $link .= 'http://';
  2685. }
  2686. $link .= dol_trunc($url, $max);
  2687. $link .= '</a>';
  2688. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2689. }
  2690. /**
  2691. * Show EMail link formatted for HTML output.
  2692. *
  2693. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2694. * @param int $cid Id of contact if known
  2695. * @param int $socid Id of third party if known
  2696. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2697. * @param int $max Max number of characters to show
  2698. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2699. * @param int|string $withpicto Show picto
  2700. * @return string HTML Link
  2701. */
  2702. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2703. {
  2704. global $conf, $user, $langs, $hookmanager;
  2705. $newemail = dol_escape_htmltag($email);
  2706. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2707. $withpicto = 0;
  2708. }
  2709. if (empty($email)) {
  2710. return '&nbsp;';
  2711. }
  2712. if (!empty($addlink)) {
  2713. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2714. if (!preg_match('/^mailto:/i', $email)) {
  2715. $newemail .= 'mailto:';
  2716. }
  2717. $newemail .= $email;
  2718. $newemail .= '">';
  2719. $newemail .= dol_trunc($email, $max);
  2720. $newemail .= '</a>';
  2721. if ($showinvalid && !isValidEmail($email)) {
  2722. $langs->load("errors");
  2723. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2724. }
  2725. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2726. $type = 'AC_EMAIL';
  2727. $link = '';
  2728. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2729. $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>';
  2730. }
  2731. if ($link) {
  2732. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2733. }
  2734. }
  2735. } else {
  2736. if ($showinvalid && !isValidEmail($email)) {
  2737. $langs->load("errors");
  2738. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2739. }
  2740. }
  2741. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2742. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  2743. //$rep .= '</div>';
  2744. if ($hookmanager) {
  2745. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2746. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2747. if ($reshook > 0) {
  2748. $rep = '';
  2749. }
  2750. $rep .= $hookmanager->resPrint;
  2751. }
  2752. return $rep;
  2753. }
  2754. /**
  2755. * Get array of social network dictionary
  2756. *
  2757. * @return array Array of Social Networks Dictionary
  2758. */
  2759. function getArrayOfSocialNetworks()
  2760. {
  2761. global $conf, $db;
  2762. $socialnetworks = array();
  2763. // Enable caching of array
  2764. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2765. $cachekey = 'socialnetworks_' . $conf->entity;
  2766. $dataretrieved = dol_getcache($cachekey);
  2767. if (!is_null($dataretrieved)) {
  2768. $socialnetworks = $dataretrieved;
  2769. } else {
  2770. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2771. $sql .= " WHERE entity=".$conf->entity;
  2772. $resql = $db->query($sql);
  2773. if ($resql) {
  2774. while ($obj = $db->fetch_object($resql)) {
  2775. $socialnetworks[$obj->code] = array(
  2776. 'rowid' => $obj->rowid,
  2777. 'label' => $obj->label,
  2778. 'url' => $obj->url,
  2779. 'icon' => $obj->icon,
  2780. 'active' => $obj->active,
  2781. );
  2782. }
  2783. }
  2784. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2785. }
  2786. return $socialnetworks;
  2787. }
  2788. /**
  2789. * Show social network link
  2790. *
  2791. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2792. * @param int $cid Id of contact if known
  2793. * @param int $socid Id of third party if known
  2794. * @param string $type 'skype','facebook',...
  2795. * @param array $dictsocialnetworks socialnetworks availables
  2796. * @return string HTML Link
  2797. */
  2798. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2799. {
  2800. global $conf, $user, $langs;
  2801. $htmllink = $value;
  2802. if (empty($value)) {
  2803. return '&nbsp;';
  2804. }
  2805. if (!empty($type)) {
  2806. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2807. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2808. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2809. if ($type == 'skype') {
  2810. $htmllink .= dol_escape_htmltag($value);
  2811. $htmllink .= '&nbsp;';
  2812. $htmllink .= '<a href="skype:';
  2813. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2814. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  2815. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2816. $htmllink .= '</a><a href="skype:';
  2817. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2818. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  2819. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2820. $htmllink .= '</a>';
  2821. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
  2822. $addlink = 'AC_SKYPE';
  2823. $link = '';
  2824. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2825. $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>';
  2826. }
  2827. $htmllink .= ($link ? ' '.$link : '');
  2828. }
  2829. } else {
  2830. if (!empty($dictsocialnetworks[$type]['url'])) {
  2831. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  2832. if ($tmpvirginurl) {
  2833. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  2834. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  2835. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  2836. if ($tmpvirginurl3) {
  2837. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  2838. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  2839. }
  2840. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  2841. if ($tmpvirginurl2) {
  2842. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  2843. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  2844. }
  2845. }
  2846. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2847. if (preg_match('/^https?:\/\//i', $link)) {
  2848. $htmllink .= '&nbsp;<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  2849. } else {
  2850. $htmllink .= '&nbsp;<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  2851. }
  2852. } else {
  2853. $htmllink .= dol_escape_htmltag($value);
  2854. }
  2855. }
  2856. $htmllink .= '</div>';
  2857. } else {
  2858. $langs->load("errors");
  2859. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2860. }
  2861. return $htmllink;
  2862. }
  2863. /**
  2864. * Format profIDs according to country
  2865. *
  2866. * @param string $profID Value of profID to format
  2867. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  2868. * @param string $countrycode Country code to use for formatting
  2869. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  2870. * @param string $separ Separation between numbers for a better visibility example : xxx xxx xxx xxxxx
  2871. * @return string Formated profID
  2872. */
  2873. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
  2874. {
  2875. global $mysoc;
  2876. if (empty($profID) || empty($profIDtype)) {
  2877. return '';
  2878. }
  2879. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2880. $newProfID = $profID;
  2881. $id = substr($profIDtype, -1);
  2882. $ret = '';
  2883. if (strtoupper($countrycode) == 'FR') {
  2884. // France
  2885. if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
  2886. if ($id == 2 && dol_strlen($newProfID) == 14) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3).$separ.substr($newProfID, 9, 5);
  2887. if ($profIDtype === 'VAT' && dol_strlen($newProfID) == 13) $newProfID = substr($newProfID, 0, 4).$separ.substr($newProfID, 4, 3).$separ.substr($newProfID, 7, 3).$separ.substr($newProfID, 10, 3);
  2888. }
  2889. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  2890. else $ret = $newProfID;
  2891. return $ret;
  2892. }
  2893. /**
  2894. * Format phone numbers according to country
  2895. *
  2896. * @param string $phone Phone number to format
  2897. * @param string $countrycode Country code to use for formatting
  2898. * @param int $cid Id of contact if known
  2899. * @param int $socid Id of third party if known
  2900. * @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)
  2901. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2902. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2903. * @param string $titlealt Text to show on alt
  2904. * @param int $adddivfloat Add div float around phone.
  2905. * @return string Formated phone number
  2906. */
  2907. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2908. {
  2909. global $conf, $user, $langs, $mysoc, $hookmanager;
  2910. // Clean phone parameter
  2911. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2912. if (empty($phone)) {
  2913. return '';
  2914. }
  2915. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  2916. $separ = $conf->global->MAIN_PHONE_SEPAR;
  2917. }
  2918. if (empty($countrycode) && is_object($mysoc)) {
  2919. $countrycode = $mysoc->country_code;
  2920. }
  2921. // Short format for small screens
  2922. if ($conf->dol_optimize_smallscreen) {
  2923. $separ = '';
  2924. }
  2925. $newphone = $phone;
  2926. if (strtoupper($countrycode) == "FR") {
  2927. // France
  2928. if (dol_strlen($phone) == 10) {
  2929. $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);
  2930. } elseif (dol_strlen($phone) == 7) {
  2931. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2932. } elseif (dol_strlen($phone) == 9) {
  2933. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2934. } elseif (dol_strlen($phone) == 11) {
  2935. $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);
  2936. } elseif (dol_strlen($phone) == 12) {
  2937. $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);
  2938. } elseif (dol_strlen($phone) == 13) {
  2939. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  2940. }
  2941. } elseif (strtoupper($countrycode) == "CA") {
  2942. if (dol_strlen($phone) == 10) {
  2943. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2944. }
  2945. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  2946. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  2947. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2948. }
  2949. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  2950. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  2951. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2952. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  2953. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2954. }
  2955. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  2956. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  2957. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2958. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  2959. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2960. }
  2961. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  2962. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  2963. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2964. }
  2965. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  2966. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  2967. $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);
  2968. }
  2969. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  2970. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  2971. $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);
  2972. }
  2973. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  2974. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  2975. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2976. }
  2977. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  2978. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  2979. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2980. }
  2981. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  2982. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  2983. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2984. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  2985. $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);
  2986. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  2987. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2988. }
  2989. } elseif (strtoupper($countrycode) == "ML") {//Mali
  2990. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  2991. $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);
  2992. }
  2993. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  2994. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  2995. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2996. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  2997. $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);
  2998. }
  2999. } elseif (strtoupper($countrycode) == "MU") {
  3000. //Maurice
  3001. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  3002. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  3003. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  3004. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  3005. }
  3006. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  3007. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  3008. $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);
  3009. }
  3010. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  3011. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  3012. $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);
  3013. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  3014. $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);
  3015. }
  3016. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  3017. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  3018. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3019. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  3020. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3021. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  3022. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  3023. }
  3024. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  3025. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  3026. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3027. }
  3028. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  3029. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  3030. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3031. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  3032. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3033. }
  3034. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  3035. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  3036. $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);
  3037. }
  3038. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  3039. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  3040. $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);
  3041. }
  3042. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3043. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3044. $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);
  3045. }
  3046. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3047. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3048. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3049. }
  3050. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3051. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
  3052. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 2);
  3053. }
  3054. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3055. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3056. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3057. }
  3058. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3059. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3060. $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);
  3061. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3062. $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);
  3063. }
  3064. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3065. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3066. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3067. }
  3068. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3069. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3070. $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);
  3071. }
  3072. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3073. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3074. $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);
  3075. }
  3076. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3077. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3078. $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);
  3079. }
  3080. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3081. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3082. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3083. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3084. $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);
  3085. }
  3086. } elseif (strtoupper($countrycode) == "AU") {
  3087. //Australie
  3088. if (dol_strlen($phone) == 12) {
  3089. //ex: +61_A_BCDE_FGHI
  3090. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3091. }
  3092. }
  3093. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3094. 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
  3095. $newphoneform = $newphone;
  3096. $newphone = '<a href="tel:'.$phone.'"';
  3097. $newphone .= '>'.$newphoneform.'</a>';
  3098. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3099. if (empty($user->clicktodial_loaded)) {
  3100. $user->fetch_clicktodial();
  3101. }
  3102. // Define urlmask
  3103. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  3104. if (!empty($conf->global->CLICKTODIAL_URL)) {
  3105. $urlmask = $conf->global->CLICKTODIAL_URL;
  3106. }
  3107. if (!empty($user->clicktodial_url)) {
  3108. $urlmask = $user->clicktodial_url;
  3109. }
  3110. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  3111. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  3112. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  3113. // This line is for backward compatibility
  3114. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3115. // Thoose lines are for substitution
  3116. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3117. '__PHONETO__'=>urlencode($phone),
  3118. '__LOGIN__'=>$clicktodial_login,
  3119. '__PASS__'=>$clicktodial_password);
  3120. $url = make_substitutions($url, $substitarray);
  3121. $newphonesav = $newphone;
  3122. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  3123. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3124. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3125. $newphone .= '>'.$newphonesav.'</a>';
  3126. } else {
  3127. // Old method
  3128. $newphone = '<a href="'.$url.'"';
  3129. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  3130. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  3131. }
  3132. $newphone .= '>'.$newphonesav.'</a>';
  3133. }
  3134. }
  3135. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  3136. if (isModEnabled('agenda') && $user->rights->agenda->myactions->create) {
  3137. $type = 'AC_TEL';
  3138. $link = '';
  3139. if ($addlink == 'AC_FAX') {
  3140. $type = 'AC_FAX';
  3141. }
  3142. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  3143. $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage='. urlencode($_SERVER['REQUEST_URI']) .'&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  3144. }
  3145. if ($link) {
  3146. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  3147. }
  3148. }
  3149. }
  3150. if (empty($titlealt)) {
  3151. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3152. }
  3153. $rep = '';
  3154. if ($hookmanager) {
  3155. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3156. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3157. $rep .= $hookmanager->resPrint;
  3158. }
  3159. if (empty($reshook)) {
  3160. $picto = '';
  3161. if ($withpicto) {
  3162. if ($withpicto == 'fax') {
  3163. $picto = 'phoning_fax';
  3164. } elseif ($withpicto == 'phone') {
  3165. $picto = 'phoning';
  3166. } elseif ($withpicto == 'mobile') {
  3167. $picto = 'phoning_mobile';
  3168. } else {
  3169. $picto = '';
  3170. }
  3171. }
  3172. if ($adddivfloat) {
  3173. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3174. } else {
  3175. $rep .= '<span style="margin-right: 10px;">';
  3176. }
  3177. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  3178. if ($adddivfloat) {
  3179. $rep .= '</div>';
  3180. } else {
  3181. $rep .= '</span>';
  3182. }
  3183. }
  3184. return $rep;
  3185. }
  3186. /**
  3187. * Return an IP formated to be shown on screen
  3188. *
  3189. * @param string $ip IP
  3190. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3191. * @return string Formated IP, with country if GeoIP module is enabled
  3192. */
  3193. function dol_print_ip($ip, $mode = 0)
  3194. {
  3195. global $conf, $langs;
  3196. $ret = '';
  3197. if (empty($mode)) {
  3198. $ret .= $ip;
  3199. }
  3200. if ($mode != 2) {
  3201. $countrycode = dolGetCountryCodeFromIp($ip);
  3202. if ($countrycode) { // If success, countrycode is us, fr, ...
  3203. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3204. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3205. } else {
  3206. $ret .= ' ('.$countrycode.')';
  3207. }
  3208. } else {
  3209. // Nothing
  3210. }
  3211. }
  3212. return $ret;
  3213. }
  3214. /**
  3215. * Return the IP of remote user.
  3216. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3217. * Then HTTP_CLIENT_IP if defined (rare)
  3218. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3219. *
  3220. * @return string Ip of remote user.
  3221. */
  3222. function getUserRemoteIP()
  3223. {
  3224. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3225. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3226. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3227. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3228. } else {
  3229. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3230. }
  3231. } else {
  3232. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3233. }
  3234. } else {
  3235. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3236. }
  3237. return $ip;
  3238. }
  3239. /**
  3240. * Return if we are using a HTTPS connexion
  3241. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3242. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3243. * Then HTTP_X_FORWARDED_SSL
  3244. *
  3245. * @return boolean True if user is using HTTPS
  3246. */
  3247. function isHTTPS()
  3248. {
  3249. $isSecure = false;
  3250. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3251. $isSecure = true;
  3252. } 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') {
  3253. $isSecure = true;
  3254. }
  3255. return $isSecure;
  3256. }
  3257. /**
  3258. * Return a country code from IP. Empty string if not found.
  3259. *
  3260. * @param string $ip IP
  3261. * @return string Country code ('us', 'fr', ...)
  3262. */
  3263. function dolGetCountryCodeFromIp($ip)
  3264. {
  3265. global $conf;
  3266. $countrycode = '';
  3267. if (!empty($conf->geoipmaxmind->enabled)) {
  3268. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3269. //$ip='24.24.24.24';
  3270. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3271. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3272. $geoip = new DolGeoIP('country', $datafile);
  3273. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3274. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3275. }
  3276. return $countrycode;
  3277. }
  3278. /**
  3279. * Return country code for current user.
  3280. * If software is used inside a local network, detection may fails (we need a public ip)
  3281. *
  3282. * @return string Country code (fr, es, it, us, ...)
  3283. */
  3284. function dol_user_country()
  3285. {
  3286. global $conf, $langs, $user;
  3287. //$ret=$user->xxx;
  3288. $ret = '';
  3289. if (!empty($conf->geoipmaxmind->enabled)) {
  3290. $ip = getUserRemoteIP();
  3291. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3292. //$ip='24.24.24.24';
  3293. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3294. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3295. $geoip = new DolGeoIP('country', $datafile);
  3296. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3297. $ret = $countrycode;
  3298. }
  3299. return $ret;
  3300. }
  3301. /**
  3302. * Format address string
  3303. *
  3304. * @param string $address Address string, already formatted with dol_format_address()
  3305. * @param int $htmlid Html ID (for example 'gmap')
  3306. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3307. * @param int $id Id of object
  3308. * @param int $noprint No output. Result is the function return
  3309. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3310. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3311. * @see dol_format_address()
  3312. */
  3313. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3314. {
  3315. global $conf, $user, $langs, $hookmanager;
  3316. $out = '';
  3317. if ($address) {
  3318. if ($hookmanager) {
  3319. $parameters = array('element' => $element, 'id' => $id);
  3320. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3321. $out .= $hookmanager->resPrint;
  3322. }
  3323. if (empty($reshook)) {
  3324. if (empty($charfornl)) {
  3325. $out .= nl2br($address);
  3326. } else {
  3327. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3328. }
  3329. // TODO Remove this block, we can add this using the hook now
  3330. $showgmap = $showomap = 0;
  3331. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3332. $showgmap = 1;
  3333. }
  3334. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3335. $showgmap = 1;
  3336. }
  3337. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3338. $showgmap = 1;
  3339. }
  3340. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3341. $showomap = 1;
  3342. }
  3343. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3344. $showomap = 1;
  3345. }
  3346. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3347. $showomap = 1;
  3348. }
  3349. if ($showgmap) {
  3350. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3351. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3352. }
  3353. if ($showomap) {
  3354. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3355. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3356. }
  3357. }
  3358. }
  3359. if ($noprint) {
  3360. return $out;
  3361. } else {
  3362. print $out;
  3363. }
  3364. }
  3365. /**
  3366. * Return true if email syntax is ok.
  3367. *
  3368. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3369. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3370. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3371. * @return boolean true if email syntax is OK, false if KO or empty string
  3372. * @see isValidMXRecord()
  3373. */
  3374. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3375. {
  3376. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3377. return true;
  3378. }
  3379. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3380. return true;
  3381. }
  3382. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3383. return true;
  3384. }
  3385. return false;
  3386. }
  3387. /**
  3388. * Return if the domain name has a valid MX record.
  3389. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3390. *
  3391. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3392. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3393. * @see isValidEmail()
  3394. */
  3395. function isValidMXRecord($domain)
  3396. {
  3397. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3398. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3399. return 0;
  3400. }
  3401. if (function_exists('getmxrr')) {
  3402. $mxhosts = array();
  3403. $weight = array();
  3404. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3405. if (count($mxhosts) > 1) {
  3406. return 1;
  3407. }
  3408. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3409. return 1;
  3410. }
  3411. return 0;
  3412. }
  3413. }
  3414. return -1;
  3415. }
  3416. /**
  3417. * Return true if phone number syntax is ok
  3418. * TODO Decide what to do with this
  3419. *
  3420. * @param string $phone phone (Ex: "0601010101")
  3421. * @return boolean true if phone syntax is OK, false if KO or empty string
  3422. */
  3423. function isValidPhone($phone)
  3424. {
  3425. return true;
  3426. }
  3427. /**
  3428. * Make a strlen call. Works even if mbstring module not enabled
  3429. *
  3430. * @param string $string String to calculate length
  3431. * @param string $stringencoding Encoding of string
  3432. * @return int Length of string
  3433. */
  3434. function dol_strlen($string, $stringencoding = 'UTF-8')
  3435. {
  3436. if (function_exists('mb_strlen')) {
  3437. return mb_strlen($string, $stringencoding);
  3438. } else {
  3439. return strlen($string);
  3440. }
  3441. }
  3442. /**
  3443. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3444. *
  3445. * @param string $string String to scan
  3446. * @param string $start Start position
  3447. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3448. * @param string $stringencoding Page code used for input string encoding
  3449. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3450. * @return string substring
  3451. */
  3452. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3453. {
  3454. global $langs;
  3455. if (empty($stringencoding)) {
  3456. $stringencoding = $langs->charset_output;
  3457. }
  3458. $ret = '';
  3459. if (empty($trunconbytes)) {
  3460. if (function_exists('mb_substr')) {
  3461. $ret = mb_substr($string, $start, $length, $stringencoding);
  3462. } else {
  3463. $ret = substr($string, $start, $length);
  3464. }
  3465. } else {
  3466. if (function_exists('mb_strcut')) {
  3467. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3468. } else {
  3469. $ret = substr($string, $start, $length);
  3470. }
  3471. }
  3472. return $ret;
  3473. }
  3474. /**
  3475. * Truncate a string to a particular length adding '…' if string larger than length.
  3476. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3477. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3478. *
  3479. * @param string $string String to truncate
  3480. * @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 ...)
  3481. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3482. * @param string $stringencoding Tell what is source string encoding
  3483. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3484. * @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)
  3485. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3486. */
  3487. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3488. {
  3489. global $conf;
  3490. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3491. return $string;
  3492. }
  3493. if (empty($stringencoding)) {
  3494. $stringencoding = 'UTF-8';
  3495. }
  3496. // reduce for small screen
  3497. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3498. $size = round($size / 3);
  3499. }
  3500. // We go always here
  3501. if ($trunc == 'right') {
  3502. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3503. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3504. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3505. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3506. } else {
  3507. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3508. return $string;
  3509. }
  3510. } elseif ($trunc == 'middle') {
  3511. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3512. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3513. $size1 = round($size / 2);
  3514. $size2 = round($size / 2);
  3515. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3516. } else {
  3517. return $string;
  3518. }
  3519. } elseif ($trunc == 'left') {
  3520. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3521. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3522. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3523. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3524. } else {
  3525. return $string;
  3526. }
  3527. } elseif ($trunc == 'wrap') {
  3528. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3529. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3530. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3531. } else {
  3532. return $string;
  3533. }
  3534. } else {
  3535. return 'BadParam3CallingDolTrunc';
  3536. }
  3537. }
  3538. /**
  3539. * Show picto whatever it's its name (generic function)
  3540. *
  3541. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3542. * @param string $picto Name of image file to show ('filenew', ...)
  3543. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3544. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3545. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3546. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3547. * Example: fontawesome_envelope-open-text_fas_red_1em if you want to use fontaweseome icons: fontawesome_<icon-name>_<style>_<color>_<size> (only icon-name is mandatory)
  3548. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3549. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3550. * @param int $srconly Return only content of the src attribute of img.
  3551. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3552. * @param string $alt Force alt for bind people
  3553. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3554. * @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.
  3555. * @return string Return img tag
  3556. * @see img_object(), img_picto_common()
  3557. */
  3558. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3559. {
  3560. global $conf, $langs;
  3561. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3562. $url = DOL_URL_ROOT;
  3563. $theme = isset($conf->theme) ? $conf->theme : null;
  3564. $path = 'theme/'.$theme;
  3565. // Define fullpathpicto to use into src
  3566. if ($pictoisfullpath) {
  3567. // Clean parameters
  3568. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3569. $picto .= '.png';
  3570. }
  3571. $fullpathpicto = $picto;
  3572. $reg = array();
  3573. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3574. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3575. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3576. }
  3577. } else {
  3578. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3579. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3580. if (strpos($pictowithouttext, 'fontawesome_') !== false || preg_match('/^fa-/', $pictowithouttext)) {
  3581. // This is a font awesome image 'fonwtawesome_xxx' or 'fa-xxx'
  3582. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  3583. $pictowithouttextarray = explode('_', $pictowithouttext);
  3584. $marginleftonlyshort = 0;
  3585. if (!empty($pictowithouttextarray[1])) {
  3586. $fakey = 'fa-'.$pictowithouttextarray[1];
  3587. $fa = empty($pictowithouttextarray[2]) ? 'fa' : $pictowithouttextarray[2];
  3588. $facolor = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  3589. $fasize = empty($pictowithouttextarray[4]) ? '' : $pictowithouttextarray[4];
  3590. } else {
  3591. $fakey = 'fa-'.$pictowithouttext;
  3592. $fa = 'fa';
  3593. $facolor = '';
  3594. $fasize = '';
  3595. }
  3596. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3597. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3598. $morestyle = '';
  3599. $reg = array();
  3600. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3601. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3602. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3603. }
  3604. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3605. $morestyle = $reg[1];
  3606. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3607. }
  3608. $moreatt = trim($moreatt);
  3609. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3610. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3611. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3612. $enabledisablehtml .= $titlealt;
  3613. }*/
  3614. $enabledisablehtml .= '</span>';
  3615. return $enabledisablehtml;
  3616. }
  3617. if (empty($srconly) && in_array($pictowithouttext, array(
  3618. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3619. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3620. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  3621. 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3622. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3623. 'currency', 'multicurrency',
  3624. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3625. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt',
  3626. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3627. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3628. 'help', 'holiday',
  3629. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3630. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lot', 'long-arrow-alt-right',
  3631. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3632. 'off', 'on', 'order',
  3633. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'puce',
  3634. 'stock', 'resize', 'service', 'stats', 'trip',
  3635. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
  3636. 'github', 'google', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3637. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3638. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3639. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3640. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3641. 'technic', 'ticket',
  3642. 'error', 'warning',
  3643. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'resource', 'recurring',
  3644. 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3645. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3646. 'uncheck', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
  3647. 'conferenceorbooth', 'eventorganization',
  3648. 'stamp', 'signature'
  3649. ))) {
  3650. $fakey = $pictowithouttext;
  3651. $facolor = '';
  3652. $fasize = '';
  3653. $fa = 'fas';
  3654. if (in_array($pictowithouttext, array('card', 'bell', 'clock', 'establishment', 'generic', 'minus-square', 'object_generic', 'pdf', 'plus-square', 'timespent', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  3655. $fa = 'far';
  3656. }
  3657. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3658. $fa = 'fab';
  3659. }
  3660. $arrayconvpictotofa = array(
  3661. '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',
  3662. 'bank_account'=>'university',
  3663. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3664. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3665. 'bom'=>'shapes',
  3666. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3667. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3668. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3669. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3670. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3671. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3672. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3673. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3674. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3675. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  3676. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3677. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3678. 'sign-out'=>'sign-out-alt',
  3679. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3680. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3681. 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3682. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'currency'=>'dollar-sign', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3683. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3684. 'other'=>'square',
  3685. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3686. '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', 'puce'=>'angle-right',
  3687. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3688. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3689. 'refresh'=>'redo', 'region'=>'map-marked', 'resource'=>'laptop-house', 'recurring'=>'history',
  3690. 'service'=>'concierge-bell',
  3691. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3692. 'supplier'=>'building', 'technic'=>'cogs',
  3693. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3694. 'title_agenda'=>'calendar-alt',
  3695. 'uncheck'=>'times', 'uparrow'=>'share', 'vat'=>'money-check-alt', 'vcard'=>'address-card',
  3696. 'jabber'=>'comment-o',
  3697. 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
  3698. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3699. );
  3700. if ($pictowithouttext == 'off') {
  3701. $fakey = 'fa-square';
  3702. $fasize = '1.3em';
  3703. } elseif ($pictowithouttext == 'on') {
  3704. $fakey = 'fa-check-square';
  3705. $fasize = '1.3em';
  3706. } elseif ($pictowithouttext == 'listlight') {
  3707. $fakey = 'fa-download';
  3708. $marginleftonlyshort = 1;
  3709. } elseif ($pictowithouttext == 'printer') {
  3710. $fakey = 'fa-print';
  3711. $fasize = '1.2em';
  3712. } elseif ($pictowithouttext == 'note') {
  3713. $fakey = 'fa-sticky-note';
  3714. $marginleftonlyshort = 1;
  3715. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3716. $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');
  3717. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3718. if (preg_match('/selected/', $pictowithouttext)) {
  3719. $facolor = '#888';
  3720. }
  3721. $marginleftonlyshort = 1;
  3722. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3723. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3724. } else {
  3725. $fakey = 'fa-'.$pictowithouttext;
  3726. }
  3727. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3728. $morecss .= ' em092';
  3729. }
  3730. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3731. $morecss .= ' em088';
  3732. }
  3733. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3734. $morecss .= ' em080';
  3735. }
  3736. // Define $marginleftonlyshort
  3737. $arrayconvpictotomarginleftonly = array(
  3738. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3739. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3740. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3741. );
  3742. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3743. $marginleftonlyshort = 0;
  3744. }
  3745. // Add CSS
  3746. $arrayconvpictotomorcess = array(
  3747. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3748. 'bank_account'=>'infobox-bank_account',
  3749. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3750. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3751. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3752. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3753. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3754. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3755. 'incoterm'=>'infobox-supplier_proposal',
  3756. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  3757. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3758. 'order'=>'infobox-commande',
  3759. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3760. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_red'=>'font-status8',
  3761. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3762. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3763. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  3764. 'propal'=>'infobox-propal', 'private'=>'infobox-project',
  3765. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3766. 'resource'=>'infobox-action',
  3767. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3768. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3769. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3770. 'vat'=>'infobox-bank_account',
  3771. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3772. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3773. );
  3774. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3775. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3776. }
  3777. // Define $color
  3778. $arrayconvpictotocolor = array(
  3779. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3780. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3781. 'dynamicprice'=>'#a69944',
  3782. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3783. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3784. 'lot'=>'#a69944',
  3785. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3786. 'other'=>'#ddd', 'world'=>'#986c6a',
  3787. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3788. //'shipment'=>'#a69944',
  3789. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3790. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3791. 'website'=>'#304', 'workstation'=>'#a69944'
  3792. );
  3793. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3794. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3795. }
  3796. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3797. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3798. $morestyle = '';
  3799. $reg = array();
  3800. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3801. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3802. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3803. }
  3804. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3805. $morestyle = $reg[1];
  3806. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3807. }
  3808. $moreatt = trim($moreatt);
  3809. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3810. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3811. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3812. $enabledisablehtml .= $titlealt;
  3813. }*/
  3814. $enabledisablehtml .= '</span>';
  3815. return $enabledisablehtml;
  3816. }
  3817. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3818. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3819. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3820. $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
  3821. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3822. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3823. }
  3824. // If we ask an image into $url/$mymodule/img (instead of default path)
  3825. $regs = array();
  3826. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3827. $picto = $regs[1];
  3828. $path = $regs[2]; // $path is $mymodule
  3829. }
  3830. // Clean parameters
  3831. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3832. $picto .= '.png';
  3833. }
  3834. // If alt path are defined, define url where img file is, according to physical path
  3835. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3836. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3837. if ($type == 'main') {
  3838. continue;
  3839. }
  3840. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3841. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3842. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3843. break;
  3844. }
  3845. }
  3846. // $url is '' or '/custom', $path is current theme or
  3847. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3848. }
  3849. if ($srconly) {
  3850. return $fullpathpicto;
  3851. }
  3852. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3853. 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
  3854. }
  3855. /**
  3856. * Show a picto called object_picto (generic function)
  3857. *
  3858. * @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.
  3859. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3860. * For external modules use imagename@mymodule to search into directory "img" of module.
  3861. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3862. * @param int $pictoisfullpath If 1, image path is a full path
  3863. * @param int $srconly Return only content of the src attribute of img.
  3864. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3865. * @return string Return img tag
  3866. * @see img_picto(), img_picto_common()
  3867. */
  3868. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3869. {
  3870. if (strpos($picto, '^') === 0) {
  3871. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3872. } else {
  3873. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3874. }
  3875. }
  3876. /**
  3877. * Show weather picto
  3878. *
  3879. * @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.
  3880. * @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).
  3881. * @param string $moreatt Add more attribute on img tag
  3882. * @param int $pictoisfullpath If 1, image path is a full path
  3883. * @param string $morecss More CSS
  3884. * @return string Return img tag
  3885. * @see img_object(), img_picto()
  3886. */
  3887. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3888. {
  3889. global $conf;
  3890. if (is_numeric($picto)) {
  3891. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3892. //$picto = $leveltopicto[$picto];
  3893. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3894. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3895. $picto .= '.png';
  3896. }
  3897. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3898. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3899. }
  3900. /**
  3901. * Show picto (generic function)
  3902. *
  3903. * @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.
  3904. * @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.
  3905. * @param string $moreatt Add more attribute on img tag
  3906. * @param int $pictoisfullpath If 1, image path is a full path
  3907. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3908. * @return string Return img tag
  3909. * @see img_object(), img_picto()
  3910. */
  3911. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  3912. {
  3913. global $conf;
  3914. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3915. $picto .= '.png';
  3916. }
  3917. if ($pictoisfullpath) {
  3918. $path = $picto;
  3919. } else {
  3920. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3921. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  3922. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3923. if (file_exists($themepath)) {
  3924. $path = $themepath;
  3925. }
  3926. }
  3927. }
  3928. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  3929. }
  3930. /**
  3931. * Show logo action
  3932. *
  3933. * @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.
  3934. * @param string $numaction Action id or code to show
  3935. * @param string $picto Name of image file to show ('filenew', ...)
  3936. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3937. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3938. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3939. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3940. * @return string Return an img tag
  3941. */
  3942. function img_action($titlealt, $numaction, $picto = '')
  3943. {
  3944. global $langs;
  3945. if (empty($titlealt) || $titlealt == 'default') {
  3946. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3947. $numaction = -1;
  3948. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3949. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3950. $numaction = 0;
  3951. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3952. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3953. $numaction = 1;
  3954. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3955. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3956. $numaction = 2;
  3957. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3958. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3959. $numaction = 3;
  3960. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3961. } else {
  3962. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3963. $numaction = 0;
  3964. }
  3965. }
  3966. if (!is_numeric($numaction)) {
  3967. $numaction = 0;
  3968. }
  3969. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3970. }
  3971. /**
  3972. * Show pdf logo
  3973. *
  3974. * @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.
  3975. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3976. * @return string Retourne tag img
  3977. */
  3978. function img_pdf($titlealt = 'default', $size = 3)
  3979. {
  3980. global $langs;
  3981. if ($titlealt == 'default') {
  3982. $titlealt = $langs->trans('Show');
  3983. }
  3984. return img_picto($titlealt, 'pdf'.$size.'.png');
  3985. }
  3986. /**
  3987. * Show logo +
  3988. *
  3989. * @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.
  3990. * @param string $other Add more attributes on img
  3991. * @return string Return tag img
  3992. */
  3993. function img_edit_add($titlealt = 'default', $other = '')
  3994. {
  3995. global $langs;
  3996. if ($titlealt == 'default') {
  3997. $titlealt = $langs->trans('Add');
  3998. }
  3999. return img_picto($titlealt, 'edit_add.png', $other);
  4000. }
  4001. /**
  4002. * Show logo -
  4003. *
  4004. * @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.
  4005. * @param string $other Add more attributes on img
  4006. * @return string Return tag img
  4007. */
  4008. function img_edit_remove($titlealt = 'default', $other = '')
  4009. {
  4010. global $langs;
  4011. if ($titlealt == 'default') {
  4012. $titlealt = $langs->trans('Remove');
  4013. }
  4014. return img_picto($titlealt, 'edit_remove.png', $other);
  4015. }
  4016. /**
  4017. * Show logo editer/modifier fiche
  4018. *
  4019. * @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.
  4020. * @param integer $float If you have to put the style "float: right"
  4021. * @param string $other Add more attributes on img
  4022. * @return string Return tag img
  4023. */
  4024. function img_edit($titlealt = 'default', $float = 0, $other = '')
  4025. {
  4026. global $langs;
  4027. if ($titlealt == 'default') {
  4028. $titlealt = $langs->trans('Modify');
  4029. }
  4030. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  4031. }
  4032. /**
  4033. * Show logo view card
  4034. *
  4035. * @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.
  4036. * @param integer $float If you have to put the style "float: right"
  4037. * @param string $other Add more attributes on img
  4038. * @return string Return tag img
  4039. */
  4040. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  4041. {
  4042. global $langs;
  4043. if ($titlealt == 'default') {
  4044. $titlealt = $langs->trans('View');
  4045. }
  4046. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4047. return img_picto($titlealt, 'view.png', $moreatt);
  4048. }
  4049. /**
  4050. * Show delete logo
  4051. *
  4052. * @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.
  4053. * @param string $other Add more attributes on img
  4054. * @param string $morecss More CSS
  4055. * @return string Retourne tag img
  4056. */
  4057. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4058. {
  4059. global $langs;
  4060. if ($titlealt == 'default') {
  4061. $titlealt = $langs->trans('Delete');
  4062. }
  4063. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4064. }
  4065. /**
  4066. * Show printer logo
  4067. *
  4068. * @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.
  4069. * @param string $other Add more attributes on img
  4070. * @return string Retourne tag img
  4071. */
  4072. function img_printer($titlealt = "default", $other = '')
  4073. {
  4074. global $langs;
  4075. if ($titlealt == "default") {
  4076. $titlealt = $langs->trans("Print");
  4077. }
  4078. return img_picto($titlealt, 'printer.png', $other);
  4079. }
  4080. /**
  4081. * Show split logo
  4082. *
  4083. * @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.
  4084. * @param string $other Add more attributes on img
  4085. * @return string Retourne tag img
  4086. */
  4087. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4088. {
  4089. global $langs;
  4090. if ($titlealt == 'default') {
  4091. $titlealt = $langs->trans('Split');
  4092. }
  4093. return img_picto($titlealt, 'split.png', $other);
  4094. }
  4095. /**
  4096. * Show help logo with cursor "?"
  4097. *
  4098. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4099. * @param int|string $usealttitle Text to use as alt title
  4100. * @return string Return tag img
  4101. */
  4102. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4103. {
  4104. global $langs;
  4105. if ($usealttitle) {
  4106. if (is_string($usealttitle)) {
  4107. $usealttitle = dol_escape_htmltag($usealttitle);
  4108. } else {
  4109. $usealttitle = $langs->trans('Info');
  4110. }
  4111. }
  4112. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4113. }
  4114. /**
  4115. * Show info logo
  4116. *
  4117. * @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.
  4118. * @return string Return img tag
  4119. */
  4120. function img_info($titlealt = 'default')
  4121. {
  4122. global $langs;
  4123. if ($titlealt == 'default') {
  4124. $titlealt = $langs->trans('Informations');
  4125. }
  4126. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4127. }
  4128. /**
  4129. * Show warning logo
  4130. *
  4131. * @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.
  4132. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4133. * @param string $morecss Add more CSS
  4134. * @return string Return img tag
  4135. */
  4136. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4137. {
  4138. global $langs;
  4139. if ($titlealt == 'default') {
  4140. $titlealt = $langs->trans('Warning');
  4141. }
  4142. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4143. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4144. }
  4145. /**
  4146. * Show error logo
  4147. *
  4148. * @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.
  4149. * @return string Return img tag
  4150. */
  4151. function img_error($titlealt = 'default')
  4152. {
  4153. global $langs;
  4154. if ($titlealt == 'default') {
  4155. $titlealt = $langs->trans('Error');
  4156. }
  4157. return img_picto($titlealt, 'error.png');
  4158. }
  4159. /**
  4160. * Show next logo
  4161. *
  4162. * @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.
  4163. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4164. * @return string Return img tag
  4165. */
  4166. function img_next($titlealt = 'default', $moreatt = '')
  4167. {
  4168. global $langs;
  4169. if ($titlealt == 'default') {
  4170. $titlealt = $langs->trans('Next');
  4171. }
  4172. //return img_picto($titlealt, 'next.png', $moreatt);
  4173. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4174. }
  4175. /**
  4176. * Show previous logo
  4177. *
  4178. * @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.
  4179. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4180. * @return string Return img tag
  4181. */
  4182. function img_previous($titlealt = 'default', $moreatt = '')
  4183. {
  4184. global $langs;
  4185. if ($titlealt == 'default') {
  4186. $titlealt = $langs->trans('Previous');
  4187. }
  4188. //return img_picto($titlealt, 'previous.png', $moreatt);
  4189. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4190. }
  4191. /**
  4192. * Show down arrow logo
  4193. *
  4194. * @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.
  4195. * @param int $selected Selected
  4196. * @param string $moreclass Add more CSS classes
  4197. * @return string Return img tag
  4198. */
  4199. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4200. {
  4201. global $langs;
  4202. if ($titlealt == 'default') {
  4203. $titlealt = $langs->trans('Down');
  4204. }
  4205. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4206. }
  4207. /**
  4208. * Show top arrow logo
  4209. *
  4210. * @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.
  4211. * @param int $selected Selected
  4212. * @param string $moreclass Add more CSS classes
  4213. * @return string Return img tag
  4214. */
  4215. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4216. {
  4217. global $langs;
  4218. if ($titlealt == 'default') {
  4219. $titlealt = $langs->trans('Up');
  4220. }
  4221. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4222. }
  4223. /**
  4224. * Show left arrow logo
  4225. *
  4226. * @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.
  4227. * @param int $selected Selected
  4228. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4229. * @return string Return img tag
  4230. */
  4231. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4232. {
  4233. global $langs;
  4234. if ($titlealt == 'default') {
  4235. $titlealt = $langs->trans('Left');
  4236. }
  4237. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4238. }
  4239. /**
  4240. * Show right arrow logo
  4241. *
  4242. * @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.
  4243. * @param int $selected Selected
  4244. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4245. * @return string Return img tag
  4246. */
  4247. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4248. {
  4249. global $langs;
  4250. if ($titlealt == 'default') {
  4251. $titlealt = $langs->trans('Right');
  4252. }
  4253. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4254. }
  4255. /**
  4256. * Show tick logo if allowed
  4257. *
  4258. * @param string $allow Allow
  4259. * @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.
  4260. * @return string Return img tag
  4261. */
  4262. function img_allow($allow, $titlealt = 'default')
  4263. {
  4264. global $langs;
  4265. if ($titlealt == 'default') {
  4266. $titlealt = $langs->trans('Active');
  4267. }
  4268. if ($allow == 1) {
  4269. return img_picto($titlealt, 'tick.png');
  4270. }
  4271. return '-';
  4272. }
  4273. /**
  4274. * Return image of a credit card according to its brand name
  4275. *
  4276. * @param string $brand Brand name of credit card
  4277. * @param string $morecss More CSS
  4278. * @return string Return img tag
  4279. */
  4280. function img_credit_card($brand, $morecss = null)
  4281. {
  4282. if (is_null($morecss)) {
  4283. $morecss = 'fa-2x';
  4284. }
  4285. if ($brand == 'visa' || $brand == 'Visa') {
  4286. $brand = 'cc-visa';
  4287. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4288. $brand = 'cc-mastercard';
  4289. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4290. $brand = 'cc-amex';
  4291. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4292. $brand = 'cc-discover';
  4293. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4294. $brand = 'cc-jcb';
  4295. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4296. $brand = 'cc-diners-club';
  4297. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4298. $brand = 'credit-card';
  4299. }
  4300. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4301. }
  4302. /**
  4303. * Show MIME img of a file
  4304. *
  4305. * @param string $file Filename
  4306. * @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.
  4307. * @param string $morecss More css
  4308. * @return string Return img tag
  4309. */
  4310. function img_mime($file, $titlealt = '', $morecss = '')
  4311. {
  4312. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4313. $mimetype = dol_mimetype($file, '', 1);
  4314. $mimeimg = dol_mimetype($file, '', 2);
  4315. $mimefa = dol_mimetype($file, '', 4);
  4316. if (empty($titlealt)) {
  4317. $titlealt = 'Mime type: '.$mimetype;
  4318. }
  4319. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4320. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4321. }
  4322. /**
  4323. * Show search logo
  4324. *
  4325. * @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.
  4326. * @param string $other Add more attributes on img
  4327. * @return string Retourne tag img
  4328. */
  4329. function img_search($titlealt = 'default', $other = '')
  4330. {
  4331. global $conf, $langs;
  4332. if ($titlealt == 'default') {
  4333. $titlealt = $langs->trans('Search');
  4334. }
  4335. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4336. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4337. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4338. return $input;
  4339. }
  4340. /**
  4341. * Show search logo
  4342. *
  4343. * @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.
  4344. * @param string $other Add more attributes on img
  4345. * @return string Retourne tag img
  4346. */
  4347. function img_searchclear($titlealt = 'default', $other = '')
  4348. {
  4349. global $conf, $langs;
  4350. if ($titlealt == 'default') {
  4351. $titlealt = $langs->trans('Search');
  4352. }
  4353. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4354. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4355. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4356. return $input;
  4357. }
  4358. /**
  4359. * Show information for admin users or standard users
  4360. *
  4361. * @param string $text Text info
  4362. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4363. * @param int $nodiv No div
  4364. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4365. * @param string $morecss More CSS ('', 'warning', 'error')
  4366. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4367. * @return string String with info text
  4368. */
  4369. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4370. {
  4371. global $conf, $langs;
  4372. if ($infoonimgalt) {
  4373. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4374. } else {
  4375. if (empty($conf->use_javascript_ajax)) {
  4376. $textfordropdown = '';
  4377. }
  4378. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4379. $result = ($nodiv ? '' : '<div class="'.$class.($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>');
  4380. if ($textfordropdown) {
  4381. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4382. $tmpresult .= '<script type="text/javascript">
  4383. jQuery(document).ready(function() {
  4384. jQuery(".'.$class.'text").click(function() {
  4385. console.log("toggle text");
  4386. jQuery(".'.$class.'").toggle();
  4387. });
  4388. });
  4389. </script>';
  4390. $result = $tmpresult.$result;
  4391. }
  4392. }
  4393. return $result;
  4394. }
  4395. /**
  4396. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4397. * This function must be called when a blocking technical error is encountered.
  4398. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4399. *
  4400. * @param DoliDB|string $db Database handler
  4401. * @param string|string[] $error String or array of errors strings to show
  4402. * @param array $errors Array of errors
  4403. * @return void
  4404. * @see dol_htmloutput_errors()
  4405. */
  4406. function dol_print_error($db = '', $error = '', $errors = null)
  4407. {
  4408. global $conf, $langs, $argv;
  4409. global $dolibarr_main_prod;
  4410. $out = '';
  4411. $syslog = '';
  4412. // If error occurs before the $lang object was loaded
  4413. if (!$langs) {
  4414. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4415. $langs = new Translate('', $conf);
  4416. $langs->load("main");
  4417. }
  4418. // Load translation files required by the error messages
  4419. $langs->loadLangs(array('main', 'errors'));
  4420. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4421. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4422. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4423. $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";
  4424. }
  4425. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4426. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4427. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4428. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4429. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4430. }
  4431. if (function_exists("phpversion")) {
  4432. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4433. }
  4434. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4435. if (function_exists("php_uname")) {
  4436. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4437. }
  4438. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4439. $out .= "<br>\n";
  4440. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4441. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4442. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4443. $out .= "<br>\n";
  4444. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4445. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4446. } else // Mode CLI
  4447. {
  4448. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4449. $syslog .= "pid=".dol_getmypid();
  4450. }
  4451. if (!empty($conf->modules)) {
  4452. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4453. }
  4454. if (is_object($db)) {
  4455. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4456. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4457. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4458. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4459. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4460. $out .= "<br>\n";
  4461. } else // Mode CLI
  4462. {
  4463. // No dol_escape_htmltag for output, we are in CLI mode
  4464. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4465. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4466. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4467. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4468. }
  4469. $syslog .= ", sql=".$db->lastquery();
  4470. $syslog .= ", db_error=".$db->lasterror();
  4471. }
  4472. if ($error || $errors) {
  4473. $langs->load("errors");
  4474. // Merge all into $errors array
  4475. if (is_array($error) && is_array($errors)) {
  4476. $errors = array_merge($error, $errors);
  4477. } elseif (is_array($error)) {
  4478. $errors = $error;
  4479. } elseif (is_array($errors)) {
  4480. $errors = array_merge(array($error), $errors);
  4481. } else {
  4482. $errors = array_merge(array($error));
  4483. }
  4484. foreach ($errors as $msg) {
  4485. if (empty($msg)) {
  4486. continue;
  4487. }
  4488. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4489. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4490. } else // Mode CLI
  4491. {
  4492. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4493. }
  4494. $syslog .= ", msg=".$msg;
  4495. }
  4496. }
  4497. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4498. xdebug_print_function_stack();
  4499. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4500. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4501. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4502. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4503. $out .= "<br>\n";
  4504. }
  4505. // Return a http error code if possible
  4506. if (!headers_sent()) {
  4507. http_response_code(500);
  4508. }
  4509. if (empty($dolibarr_main_prod)) {
  4510. print $out;
  4511. } else {
  4512. if (empty($langs->defaultlang)) {
  4513. $langs->setDefaultLang();
  4514. }
  4515. $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.
  4516. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4517. 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";
  4518. print $langs->trans("DolibarrHasDetectedError").'. ';
  4519. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4520. define("MAIN_CORE_ERROR", 1);
  4521. }
  4522. dol_syslog("Error ".$syslog, LOG_ERR);
  4523. }
  4524. /**
  4525. * Show a public email and error code to contact if technical error
  4526. *
  4527. * @param string $prefixcode Prefix of public error code
  4528. * @param string $errormessage Complete error message
  4529. * @param array $errormessages Array of error messages
  4530. * @param string $morecss More css
  4531. * @param string $email Email
  4532. * @return void
  4533. */
  4534. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4535. {
  4536. global $langs, $conf;
  4537. if (empty($email)) {
  4538. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4539. }
  4540. $langs->load("errors");
  4541. $now = dol_now();
  4542. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4543. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4544. if ($errormessage) {
  4545. print '<br><br>'.$errormessage;
  4546. }
  4547. if (is_array($errormessages) && count($errormessages)) {
  4548. foreach ($errormessages as $mesgtoshow) {
  4549. print '<br><br>'.$mesgtoshow;
  4550. }
  4551. }
  4552. print '</div></div>';
  4553. }
  4554. /**
  4555. * Show title line of an array
  4556. *
  4557. * @param string $name Label of field
  4558. * @param string $file Url used when we click on sort picto
  4559. * @param string $field Field to use for new sorting
  4560. * @param string $begin ("" by defaut)
  4561. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4562. * @param string $moreattrib Options of attribute td ("" by defaut)
  4563. * @param string $sortfield Current field used to sort
  4564. * @param string $sortorder Current sort order
  4565. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4566. * @param string $tooltip Tooltip
  4567. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4568. * @return void
  4569. */
  4570. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4571. {
  4572. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4573. }
  4574. /**
  4575. * Get title line of an array
  4576. *
  4577. * @param string $name Translation key of field to show or complete HTML string to show
  4578. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4579. * @param string $file Url used when we click on sort picto
  4580. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4581. * @param string $begin ("" by defaut)
  4582. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4583. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  4584. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4585. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4586. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4587. * @param string $disablesortlink 1=Disable sort link
  4588. * @param string $tooltip Tooltip
  4589. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4590. * @return string
  4591. */
  4592. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4593. {
  4594. global $conf, $langs, $form;
  4595. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4596. if ($moreattrib == 'class="right"') {
  4597. $prefix .= 'right '; // For backward compatibility
  4598. }
  4599. $sortorder = strtoupper($sortorder);
  4600. $out = '';
  4601. $sortimg = '';
  4602. $tag = 'th';
  4603. if ($thead == 2) {
  4604. $tag = 'div';
  4605. }
  4606. $tmpsortfield = explode(',', $sortfield);
  4607. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4608. $tmpfield = explode(',', $field);
  4609. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4610. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4611. $prefix = 'wrapcolumntitle '.$prefix;
  4612. }
  4613. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4614. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4615. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4616. $liste_titre = 'liste_titre';
  4617. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4618. $liste_titre = 'liste_titre_sel';
  4619. }
  4620. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4621. //$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)).'"' : '');
  4622. $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4623. $tagstart .= '>';
  4624. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4625. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4626. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4627. $options = preg_replace('/&+/i', '&', $options);
  4628. if (!preg_match('/^&/', $options)) {
  4629. $options = '&'.$options;
  4630. }
  4631. $sortordertouseinlink = '';
  4632. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4633. if (preg_match('/^DESC/i', $sortorder)) {
  4634. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4635. } else { // We reverse the var $sortordertouseinlink
  4636. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4637. }
  4638. } else { // We are on field that is the first current sorting criteria
  4639. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4640. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4641. } else {
  4642. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4643. }
  4644. }
  4645. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4646. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4647. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4648. $out .= '>';
  4649. }
  4650. if ($tooltip) {
  4651. // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  4652. $tmptooltip = explode(':', $tooltip);
  4653. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4654. } else {
  4655. $out .= $langs->trans($name);
  4656. }
  4657. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4658. $out .= '</a>';
  4659. }
  4660. if (empty($thead) && $field) { // If this is a sort field
  4661. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4662. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4663. $options = preg_replace('/&+/i', '&', $options);
  4664. if (!preg_match('/^&/', $options)) {
  4665. $options = '&'.$options;
  4666. }
  4667. if (!$sortorder || $field1 != $sortfield1) {
  4668. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4669. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4670. } else {
  4671. if (preg_match('/^DESC/', $sortorder)) {
  4672. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4673. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4674. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  4675. }
  4676. if (preg_match('/^ASC/', $sortorder)) {
  4677. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4678. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4679. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  4680. }
  4681. }
  4682. }
  4683. $tagend = '</'.$tag.'>';
  4684. $out = $tagstart.$sortimg.$out.$tagend;
  4685. return $out;
  4686. }
  4687. /**
  4688. * Show a title.
  4689. *
  4690. * @param string $title Title to show
  4691. * @return void
  4692. * @deprecated Use load_fiche_titre instead
  4693. * @see load_fiche_titre()
  4694. */
  4695. function print_titre($title)
  4696. {
  4697. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4698. print '<div class="titre">'.$title.'</div>';
  4699. }
  4700. /**
  4701. * Show a title with picto
  4702. *
  4703. * @param string $title Title to show
  4704. * @param string $mesg Added message to show on right
  4705. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4706. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4707. * @param int $id To force an id on html objects
  4708. * @return void
  4709. * @deprecated Use print load_fiche_titre instead
  4710. */
  4711. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4712. {
  4713. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4714. }
  4715. /**
  4716. * Load a title with picto
  4717. *
  4718. * @param string $titre Title to show
  4719. * @param string $morehtmlright Added message to show on right
  4720. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4721. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4722. * @param string $id To force an id on html objects
  4723. * @param string $morecssontable More css on table
  4724. * @param string $morehtmlcenter Added message to show on center
  4725. * @return string
  4726. * @see print_barre_liste()
  4727. */
  4728. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4729. {
  4730. global $conf;
  4731. $return = '';
  4732. if ($picto == 'setup') {
  4733. $picto = 'generic';
  4734. }
  4735. $return .= "\n";
  4736. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4737. $return .= '<tr class="titre">';
  4738. if ($picto) {
  4739. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4740. }
  4741. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4742. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4743. $return .= '</td>';
  4744. if (dol_strlen($morehtmlcenter)) {
  4745. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4746. }
  4747. if (dol_strlen($morehtmlright)) {
  4748. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4749. }
  4750. $return .= '</tr></table>'."\n";
  4751. return $return;
  4752. }
  4753. /**
  4754. * Print a title with navigation controls for pagination
  4755. *
  4756. * @param string $titre Title to show (required)
  4757. * @param int $page Numero of page to show in navigation links (required)
  4758. * @param string $file Url of page (required)
  4759. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4760. * @param string $sortfield Field to sort on ('' by default)
  4761. * @param string $sortorder Order to sort ('' by default)
  4762. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4763. * @param int $num Number of records found by select with limit+1
  4764. * @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.
  4765. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4766. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4767. * @param string $morehtmlright More html to show (after arrows)
  4768. * @param string $morecss More css to the table
  4769. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4770. * @param int $hideselectlimit Force to hide select limit
  4771. * @param int $hidenavigation Force to hide all navigation tools
  4772. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4773. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4774. * @return void
  4775. */
  4776. 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 = '')
  4777. {
  4778. global $conf, $langs;
  4779. $savlimit = $limit;
  4780. $savtotalnboflines = $totalnboflines;
  4781. $totalnboflines = abs((int) $totalnboflines);
  4782. if ($picto == 'setup') {
  4783. $picto = 'title_setup.png';
  4784. }
  4785. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4786. $picto = 'title.gif';
  4787. }
  4788. if ($limit < 0) {
  4789. $limit = $conf->liste_limit;
  4790. }
  4791. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4792. $nextpage = 1;
  4793. } else {
  4794. $nextpage = 0;
  4795. }
  4796. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4797. print "\n";
  4798. print "<!-- Begin title -->\n";
  4799. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4800. // Left
  4801. if ($picto && $titre) {
  4802. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4803. }
  4804. print '<td class="nobordernopadding valignmiddle col-title">';
  4805. print '<div class="titre inline-block">'.$titre;
  4806. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4807. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4808. }
  4809. print '</div></td>';
  4810. // Center
  4811. if ($morehtmlcenter) {
  4812. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4813. }
  4814. // Right
  4815. print '<td class="nobordernopadding valignmiddle right">';
  4816. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4817. if ($sortfield) {
  4818. $options .= "&sortfield=".urlencode($sortfield);
  4819. }
  4820. if ($sortorder) {
  4821. $options .= "&sortorder=".urlencode($sortorder);
  4822. }
  4823. // Show navigation bar
  4824. $pagelist = '';
  4825. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4826. if ($totalnboflines) { // If we know total nb of lines
  4827. // Define nb of extra page links before and after selected page + ... + first or last
  4828. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4829. if ($limit > 0) {
  4830. $nbpages = ceil($totalnboflines / $limit);
  4831. } else {
  4832. $nbpages = 1;
  4833. }
  4834. $cpt = ($page - $maxnbofpage);
  4835. if ($cpt < 0) {
  4836. $cpt = 0;
  4837. }
  4838. if ($cpt >= 1) {
  4839. if (empty($pagenavastextinput)) {
  4840. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4841. if ($cpt > 2) {
  4842. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4843. } elseif ($cpt == 2) {
  4844. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4845. }
  4846. }
  4847. }
  4848. do {
  4849. if ($pagenavastextinput) {
  4850. if ($cpt == $page) {
  4851. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4852. $pagelist .= '/';
  4853. }
  4854. } else {
  4855. if ($cpt == $page) {
  4856. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4857. } else {
  4858. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4859. }
  4860. }
  4861. $cpt++;
  4862. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4863. if (empty($pagenavastextinput)) {
  4864. if ($cpt < $nbpages) {
  4865. if ($cpt < $nbpages - 2) {
  4866. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4867. } elseif ($cpt == $nbpages - 2) {
  4868. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4869. }
  4870. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4871. }
  4872. } else {
  4873. //var_dump($page.' '.$cpt.' '.$nbpages);
  4874. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4875. }
  4876. } else {
  4877. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4878. }
  4879. }
  4880. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4881. 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
  4882. }
  4883. // js to autoselect page field on focus
  4884. if ($pagenavastextinput) {
  4885. print ajax_autoselect('.pageplusone');
  4886. }
  4887. print '</td>';
  4888. print '</tr></table>'."\n";
  4889. print "<!-- End title -->\n\n";
  4890. }
  4891. /**
  4892. * Function to show navigation arrows into lists
  4893. *
  4894. * @param int $page Number of page
  4895. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4896. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4897. * @param integer $nextpage Do we show a next page button
  4898. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4899. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4900. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4901. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4902. * @param int $hideselectlimit Force to hide select limit
  4903. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4904. * @return void
  4905. */
  4906. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4907. {
  4908. global $conf, $langs;
  4909. print '<div class="pagination"><ul>';
  4910. if ($beforearrows) {
  4911. print '<li class="paginationbeforearrows">';
  4912. print $beforearrows;
  4913. print '</li>';
  4914. }
  4915. if ((int) $limit > 0 && empty($hideselectlimit)) {
  4916. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
  4917. $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
  4918. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4919. //$pagesizechoices.=',2:2';
  4920. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  4921. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4922. }
  4923. print '<li class="pagination">';
  4924. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4925. $tmpchoice = explode(',', $pagesizechoices);
  4926. $tmpkey = $limit.':'.$limit;
  4927. if (!in_array($tmpkey, $tmpchoice)) {
  4928. $tmpchoice[] = $tmpkey;
  4929. }
  4930. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4931. if (!in_array($tmpkey, $tmpchoice)) {
  4932. $tmpchoice[] = $tmpkey;
  4933. }
  4934. asort($tmpchoice, SORT_NUMERIC);
  4935. foreach ($tmpchoice as $val) {
  4936. $selected = '';
  4937. $tmp = explode(':', $val);
  4938. $key = $tmp[0];
  4939. $val = $tmp[1];
  4940. if ($key != '' && $val != '') {
  4941. if ((int) $key == (int) $limit) {
  4942. $selected = ' selected="selected"';
  4943. }
  4944. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4945. }
  4946. }
  4947. print '</select>';
  4948. if ($conf->use_javascript_ajax) {
  4949. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4950. <script>
  4951. jQuery(document).ready(function () {
  4952. jQuery(".selectlimit").change(function() {
  4953. console.log("Change limit. Send submit");
  4954. $(this).parents(\'form:first\').submit();
  4955. });
  4956. });
  4957. </script>
  4958. ';
  4959. }
  4960. print '</li>';
  4961. }
  4962. if ($page > 0) {
  4963. 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>';
  4964. }
  4965. if ($betweenarrows) {
  4966. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4967. print $betweenarrows;
  4968. print '<!--</div>-->';
  4969. }
  4970. if ($nextpage > 0) {
  4971. 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>';
  4972. }
  4973. if ($afterarrows) {
  4974. print '<li class="paginationafterarrows">';
  4975. print $afterarrows;
  4976. print '</li>';
  4977. }
  4978. print '</ul></div>'."\n";
  4979. }
  4980. /**
  4981. * Return a string with VAT rate label formated for view output
  4982. * Used into pdf and HTML pages
  4983. *
  4984. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4985. * @param boolean $addpercent Add a percent % sign in output
  4986. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4987. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4988. * @param int $html Used for html output
  4989. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4990. */
  4991. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
  4992. {
  4993. $morelabel = '';
  4994. if (preg_match('/%/', $rate)) {
  4995. $rate = str_replace('%', '', $rate);
  4996. $addpercent = true;
  4997. }
  4998. $reg = array();
  4999. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  5000. $morelabel = ' ('.$reg[1].')';
  5001. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  5002. $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
  5003. }
  5004. if (preg_match('/\*/', $rate)) {
  5005. $rate = str_replace('*', '', $rate);
  5006. $info_bits |= 1;
  5007. }
  5008. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  5009. if (!preg_match('/\//', $rate)) {
  5010. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  5011. } else {
  5012. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  5013. $ret = $rate.($addpercent ? '%' : '');
  5014. }
  5015. if (($info_bits & 1) && $usestarfornpr >= 0) {
  5016. $ret .= ' *';
  5017. }
  5018. $ret .= $morelabel;
  5019. return $ret;
  5020. }
  5021. /**
  5022. * Function to format a value into an amount for visual output
  5023. * Function used into PDF and HTML pages
  5024. *
  5025. * @param float $amount Amount to format
  5026. * @param integer $form Type of format, HTML or not (not by default)
  5027. * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators.
  5028. * @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.
  5029. * @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)
  5030. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  5031. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  5032. * @return string String with formated amount
  5033. *
  5034. * @see price2num() Revert function of price
  5035. */
  5036. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  5037. {
  5038. global $langs, $conf;
  5039. // Clean parameters
  5040. if (empty($amount)) {
  5041. $amount = 0; // To have a numeric value if amount not defined or = ''
  5042. }
  5043. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  5044. if ($rounding < 0) {
  5045. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  5046. }
  5047. $nbdecimal = $rounding;
  5048. if ($outlangs === 'none') {
  5049. // Use international separators
  5050. $dec = '.';
  5051. $thousand = '';
  5052. } else {
  5053. // Output separators by default (french)
  5054. $dec = ',';
  5055. $thousand = ' ';
  5056. // If $outlangs not forced, we use use language
  5057. if (!is_object($outlangs)) {
  5058. $outlangs = $langs;
  5059. }
  5060. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5061. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5062. }
  5063. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5064. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5065. }
  5066. if ($thousand == 'None') {
  5067. $thousand = '';
  5068. } elseif ($thousand == 'Space') {
  5069. $thousand = ' ';
  5070. }
  5071. }
  5072. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5073. //print "amount=".$amount."-";
  5074. $amount = str_replace(',', '.', $amount); // should be useless
  5075. //print $amount."-";
  5076. $datas = explode('.', $amount);
  5077. $decpart = isset($datas[1]) ? $datas[1] : '';
  5078. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5079. //print "decpart=".$decpart."<br>";
  5080. $end = '';
  5081. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5082. if (dol_strlen($decpart) > $nbdecimal) {
  5083. $nbdecimal = dol_strlen($decpart);
  5084. }
  5085. // Si on depasse max
  5086. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5087. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5088. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5089. // Si un affichage est tronque, on montre des ...
  5090. $end = '...';
  5091. }
  5092. }
  5093. // If force rounding
  5094. if ($forcerounding >= 0) {
  5095. $nbdecimal = $forcerounding;
  5096. }
  5097. // Format number
  5098. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5099. if ($form) {
  5100. $output = preg_replace('/\s/', '&nbsp;', $output);
  5101. $output = preg_replace('/\'/', '&#039;', $output);
  5102. }
  5103. // Add symbol of currency if requested
  5104. $cursymbolbefore = $cursymbolafter = '';
  5105. if ($currency_code && is_object($outlangs)) {
  5106. if ($currency_code == 'auto') {
  5107. $currency_code = $conf->currency;
  5108. }
  5109. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  5110. $listoflanguagesbefore = array('nl_NL');
  5111. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5112. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5113. } else {
  5114. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5115. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5116. }
  5117. }
  5118. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5119. return $output;
  5120. }
  5121. /**
  5122. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5123. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5124. * should be roundtext2num().
  5125. *
  5126. * @param string|float $amount Amount to convert/clean or round
  5127. * @param string|int $rounding ''=No rounding
  5128. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5129. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5130. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5131. * 'CU'=Round to Max unit price of foreign currency accuracy
  5132. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5133. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5134. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5135. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5136. * @return string Amount with universal numeric format (Example: '99.99999').
  5137. * If conversion fails to return a numeric, it returns:
  5138. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5139. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5140. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5141. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  5142. *
  5143. * @see price() Opposite function of price2num
  5144. */
  5145. function price2num($amount, $rounding = '', $option = 0)
  5146. {
  5147. global $langs, $conf;
  5148. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5149. // Numbers must be '1234.56'
  5150. // Decimal delimiter for PHP and database SQL requests must be '.'
  5151. $dec = ',';
  5152. $thousand = ' ';
  5153. if (is_null($langs)) { // $langs is not defined, we use english values.
  5154. $dec = '.';
  5155. $thousand = ',';
  5156. } else {
  5157. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5158. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5159. }
  5160. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5161. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5162. }
  5163. }
  5164. if ($thousand == 'None') {
  5165. $thousand = '';
  5166. } elseif ($thousand == 'Space') {
  5167. $thousand = ' ';
  5168. }
  5169. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5170. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5171. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5172. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5173. if (!is_numeric($amount)) {
  5174. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5175. }
  5176. 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
  5177. $amount = str_replace($thousand, '', $amount);
  5178. }
  5179. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5180. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5181. // So if number was already a good number, it is converted into local Dolibarr setup.
  5182. if (is_numeric($amount)) {
  5183. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5184. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5185. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5186. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5187. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5188. }
  5189. //print "QQ".$amount."<br>\n";
  5190. // Now make replace (the main goal of function)
  5191. if ($thousand != ',' && $thousand != '.') {
  5192. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5193. }
  5194. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5195. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5196. $amount = str_replace($dec, '.', $amount);
  5197. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5198. }
  5199. //print ' XX'.$amount.' '.$rounding;
  5200. // Now, $amount is a real PHP float number. We make a rounding if required.
  5201. if ($rounding) {
  5202. $nbofdectoround = '';
  5203. if ($rounding == 'MU') {
  5204. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5205. } elseif ($rounding == 'MT') {
  5206. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5207. } elseif ($rounding == 'MS') {
  5208. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5209. } elseif ($rounding == 'CU') {
  5210. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5211. } elseif ($rounding == 'CT') {
  5212. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5213. } elseif (is_numeric($rounding)) {
  5214. $nbofdectoround = (int) $rounding;
  5215. }
  5216. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5217. if (dol_strlen($nbofdectoround)) {
  5218. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5219. } else {
  5220. return 'ErrorBadParameterProvidedToFunction';
  5221. }
  5222. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5223. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5224. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5225. if (is_numeric($amount)) {
  5226. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5227. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5228. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5229. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5230. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5231. }
  5232. //print "TT".$amount.'<br>';
  5233. // Always make replace because each math function (like round) replace
  5234. // with local values and we want a number that has a SQL string format x.y
  5235. if ($thousand != ',' && $thousand != '.') {
  5236. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5237. }
  5238. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5239. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5240. $amount = str_replace($dec, '.', $amount);
  5241. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5242. }
  5243. return $amount;
  5244. }
  5245. /**
  5246. * Output a dimension with best unit
  5247. *
  5248. * @param float $dimension Dimension
  5249. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5250. * @param string $type 'weight', 'volume', ...
  5251. * @param Translate $outputlangs Translate language object
  5252. * @param int $round -1 = non rounding, x = number of decimal
  5253. * @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)
  5254. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5255. * @return string String to show dimensions
  5256. */
  5257. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5258. {
  5259. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5260. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5261. $dimension = $dimension * 1000000;
  5262. $unit = $unit - 6;
  5263. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5264. $dimension = $dimension * 1000;
  5265. $unit = $unit - 3;
  5266. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5267. $dimension = $dimension / 1000000;
  5268. $unit = $unit + 6;
  5269. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5270. $dimension = $dimension / 1000;
  5271. $unit = $unit + 3;
  5272. }
  5273. // Special case when we want output unit into pound or ounce
  5274. /* TODO
  5275. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5276. {
  5277. $dimension = // convert dimension from standard unit into ounce or pound
  5278. $unit = $forceunitoutput;
  5279. }
  5280. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5281. {
  5282. $dimension = // convert dimension from standard unit into ounce or pound
  5283. $unit = $forceunitoutput;
  5284. }*/
  5285. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5286. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5287. return $ret;
  5288. }
  5289. /**
  5290. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5291. * Note: This function applies same rules than get_default_tva
  5292. *
  5293. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5294. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5295. * @param Societe $thirdparty_buyer Object of buying third party
  5296. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5297. * @param int $vatnpr If vat rate is NPR or not
  5298. * @return mixed 0 if not found, localtax rate if found
  5299. * @see get_default_tva()
  5300. */
  5301. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5302. {
  5303. global $db, $conf, $mysoc;
  5304. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5305. $thirdparty_seller = $mysoc;
  5306. }
  5307. 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);
  5308. $vatratecleaned = $vatrate;
  5309. $reg = array();
  5310. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5311. $vatratecleaned = trim($reg[1]);
  5312. $vatratecode = $reg[2];
  5313. }
  5314. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5315. {
  5316. return 0;
  5317. }*/
  5318. // Some test to guess with no need to make database access
  5319. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5320. if ($local == 1) {
  5321. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5322. return 0;
  5323. }
  5324. if ($thirdparty_seller->id == $mysoc->id) {
  5325. if (!$thirdparty_buyer->localtax1_assuj) {
  5326. return 0;
  5327. }
  5328. } else {
  5329. if (!$thirdparty_seller->localtax1_assuj) {
  5330. return 0;
  5331. }
  5332. }
  5333. }
  5334. if ($local == 2) {
  5335. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5336. if (!$mysoc->localtax2_assuj) {
  5337. return 0; // If main vat is 0, IRPF may be different than 0.
  5338. }
  5339. if ($thirdparty_seller->id == $mysoc->id) {
  5340. if (!$thirdparty_buyer->localtax2_assuj) {
  5341. return 0;
  5342. }
  5343. } else {
  5344. if (!$thirdparty_seller->localtax2_assuj) {
  5345. return 0;
  5346. }
  5347. }
  5348. }
  5349. } else {
  5350. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5351. return 0;
  5352. }
  5353. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5354. return 0;
  5355. }
  5356. }
  5357. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5358. if (in_array($mysoc->country_code, array('ES'))) {
  5359. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5360. }
  5361. // Search local taxes
  5362. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5363. if ($local == 1) {
  5364. if ($thirdparty_seller != $mysoc) {
  5365. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5366. return $thirdparty_seller->localtax1_value;
  5367. }
  5368. } else { // i am the seller
  5369. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5370. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5371. }
  5372. }
  5373. }
  5374. if ($local == 2) {
  5375. if ($thirdparty_seller != $mysoc) {
  5376. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5377. // TODO We should also return value defined on thirdparty only if defined
  5378. return $thirdparty_seller->localtax2_value;
  5379. }
  5380. } else { // i am the seller
  5381. if (in_array($mysoc->country_code, array('ES'))) {
  5382. return $thirdparty_buyer->localtax2_value;
  5383. } else {
  5384. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5385. }
  5386. }
  5387. }
  5388. }
  5389. // By default, search value of local tax on line of common tax
  5390. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5391. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5392. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5393. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5394. if (!empty($vatratecode)) {
  5395. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5396. } else {
  5397. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5398. }
  5399. $resql = $db->query($sql);
  5400. if ($resql) {
  5401. $obj = $db->fetch_object($resql);
  5402. if ($obj) {
  5403. if ($local == 1) {
  5404. return $obj->localtax1;
  5405. } elseif ($local == 2) {
  5406. return $obj->localtax2;
  5407. }
  5408. }
  5409. }
  5410. return 0;
  5411. }
  5412. /**
  5413. * Return true if LocalTax (1 or 2) is unique.
  5414. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5415. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5416. *
  5417. * @param int $local Local tax to test (1 or 2)
  5418. * @return boolean True if LocalTax have multiple values, False if not
  5419. */
  5420. function isOnlyOneLocalTax($local)
  5421. {
  5422. $tax = get_localtax_by_third($local);
  5423. $valors = explode(":", $tax);
  5424. if (count($valors) > 1) {
  5425. return false;
  5426. } else {
  5427. return true;
  5428. }
  5429. }
  5430. /**
  5431. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5432. *
  5433. * @param int $local LocalTax to get
  5434. * @return string Values of localtax (Can be '20', '-19:-15:-9')
  5435. */
  5436. function get_localtax_by_third($local)
  5437. {
  5438. global $db, $mysoc;
  5439. $sql = " SELECT t.localtax".$local." as localtax";
  5440. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
  5441. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux = (";
  5442. $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";
  5443. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1)";
  5444. $sql .= " AND t.localtax".$local."_type <> '0'";
  5445. $sql .= " ORDER BY t.rowid DESC";
  5446. $resql = $db->query($sql);
  5447. if ($resql) {
  5448. $obj = $db->fetch_object($resql);
  5449. return $obj->localtax;
  5450. } else {
  5451. return 'Error';
  5452. }
  5453. return '0';
  5454. }
  5455. /**
  5456. * Get tax (VAT) main information from Id.
  5457. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5458. *
  5459. * @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.
  5460. * @param Societe $buyer Company object
  5461. * @param Societe $seller Company object
  5462. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5463. * @return array array('rowid'=> , 'code'=> ...)
  5464. * @see getLocalTaxesFromRate()
  5465. */
  5466. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5467. {
  5468. global $db, $mysoc;
  5469. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5470. // Search local taxes
  5471. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5472. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5473. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5474. if ($firstparamisid) {
  5475. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5476. } else {
  5477. $vatratecleaned = $vatrate;
  5478. $vatratecode = '';
  5479. $reg = array();
  5480. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5481. $vatratecleaned = $reg[1];
  5482. $vatratecode = $reg[2];
  5483. }
  5484. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5485. /*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 ??
  5486. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5487. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5488. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5489. if ($vatratecode) {
  5490. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5491. }
  5492. }
  5493. $resql = $db->query($sql);
  5494. if ($resql) {
  5495. $obj = $db->fetch_object($resql);
  5496. if ($obj) {
  5497. return array(
  5498. 'rowid'=>$obj->rowid,
  5499. 'code'=>$obj->code,
  5500. 'rate'=>$obj->rate,
  5501. 'localtax1'=>$obj->localtax1,
  5502. 'localtax1_type'=>$obj->localtax1_type,
  5503. 'localtax2'=>$obj->localtax2,
  5504. 'localtax2_type'=>$obj->localtax2_type,
  5505. 'npr'=>$obj->npr,
  5506. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5507. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5508. );
  5509. } else {
  5510. return array();
  5511. }
  5512. } else {
  5513. dol_print_error($db);
  5514. }
  5515. return array();
  5516. }
  5517. /**
  5518. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5519. * This does not take into account the seller setup if subject to vat or not, only country.
  5520. *
  5521. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5522. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5523. * provide the selected value to the function calcul_price_total.
  5524. *
  5525. * @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.
  5526. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5527. * @param Societe $buyer Company object
  5528. * @param Societe $seller Company object
  5529. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5530. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5531. * @see getTaxesFromId()
  5532. */
  5533. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5534. {
  5535. global $db, $mysoc;
  5536. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5537. // Search local taxes
  5538. $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";
  5539. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5540. if ($firstparamisid) {
  5541. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5542. } else {
  5543. $vatratecleaned = $vatrate;
  5544. $vatratecode = '';
  5545. $reg = array();
  5546. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5547. $vatratecleaned = $reg[1];
  5548. $vatratecode = $reg[2];
  5549. }
  5550. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5551. if (!empty($mysoc) && $mysoc->country_code == 'ES') {
  5552. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5553. } else {
  5554. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5555. }
  5556. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5557. if ($vatratecode) {
  5558. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5559. }
  5560. }
  5561. $resql = $db->query($sql);
  5562. if ($resql) {
  5563. $obj = $db->fetch_object($resql);
  5564. if ($obj) {
  5565. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5566. if ($local == 1) {
  5567. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5568. } elseif ($local == 2) {
  5569. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5570. } else {
  5571. 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);
  5572. }
  5573. }
  5574. }
  5575. return array();
  5576. }
  5577. /**
  5578. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5579. * Function called by get_default_tva().
  5580. *
  5581. * @param int $idprod Id of product or 0 if not a predefined product
  5582. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5583. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5584. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5585. * @see get_product_localtax_for_country()
  5586. */
  5587. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5588. {
  5589. global $db, $conf, $mysoc;
  5590. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5591. $ret = 0;
  5592. $found = 0;
  5593. if ($idprod > 0) {
  5594. // Load product
  5595. $product = new Product($db);
  5596. $result = $product->fetch($idprod);
  5597. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If country to consider is ours
  5598. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5599. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5600. $ret = $product->vatrate_supplier;
  5601. if ($product->default_vat_code) {
  5602. $ret .= ' ('.$product->default_vat_code.')';
  5603. }
  5604. } else {
  5605. $ret = $product->tva_tx; // Default vat of product we defined
  5606. if ($product->default_vat_code) {
  5607. $ret .= ' ('.$product->default_vat_code.')';
  5608. }
  5609. }
  5610. $found = 1;
  5611. } else {
  5612. // TODO Read default product vat according to product and another countrycode.
  5613. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5614. }
  5615. }
  5616. if (!$found) {
  5617. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5618. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  5619. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5620. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5621. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5622. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5623. $sql .= $db->plimit(1);
  5624. $resql = $db->query($sql);
  5625. if ($resql) {
  5626. $obj = $db->fetch_object($resql);
  5627. if ($obj) {
  5628. $ret = $obj->vat_rate;
  5629. if ($obj->default_vat_code) {
  5630. $ret .= ' ('.$obj->default_vat_code.')';
  5631. }
  5632. }
  5633. $db->free($resql);
  5634. } else {
  5635. dol_print_error($db);
  5636. }
  5637. } else {
  5638. $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  5639. }
  5640. }
  5641. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5642. return $ret;
  5643. }
  5644. /**
  5645. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5646. *
  5647. * @param int $idprod Id of product
  5648. * @param int $local 1 for localtax1, 2 for localtax 2
  5649. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5650. * @return int <0 if KO, Vat rate if OK
  5651. * @see get_product_vat_for_country()
  5652. */
  5653. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5654. {
  5655. global $db, $mysoc;
  5656. if (!class_exists('Product')) {
  5657. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5658. }
  5659. $ret = 0;
  5660. $found = 0;
  5661. if ($idprod > 0) {
  5662. // Load product
  5663. $product = new Product($db);
  5664. $result = $product->fetch($idprod);
  5665. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5666. /* Not defined yet, so we don't use this
  5667. if ($local==1) $ret=$product->localtax1_tx;
  5668. elseif ($local==2) $ret=$product->localtax2_tx;
  5669. $found=1;
  5670. */
  5671. } else {
  5672. // TODO Read default product vat according to product and another countrycode.
  5673. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5674. }
  5675. }
  5676. if (!$found) {
  5677. // If vat of product for the country not found or not defined, we return higher vat of country.
  5678. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5679. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5680. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5681. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5682. $sql .= $db->plimit(1);
  5683. $resql = $db->query($sql);
  5684. if ($resql) {
  5685. $obj = $db->fetch_object($resql);
  5686. if ($obj) {
  5687. if ($local == 1) {
  5688. $ret = $obj->localtax1;
  5689. } elseif ($local == 2) {
  5690. $ret = $obj->localtax2;
  5691. }
  5692. }
  5693. } else {
  5694. dol_print_error($db);
  5695. }
  5696. }
  5697. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5698. return $ret;
  5699. }
  5700. /**
  5701. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5702. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5703. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5704. * 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.
  5705. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5706. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5707. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5708. *
  5709. * @param Societe $thirdparty_seller Objet societe vendeuse
  5710. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5711. * @param int $idprod Id product
  5712. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5713. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5714. * @see get_default_npr(), get_default_localtax()
  5715. */
  5716. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5717. {
  5718. global $conf;
  5719. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5720. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5721. $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;
  5722. $seller_country_code = $thirdparty_seller->country_code;
  5723. $seller_in_cee = isInEEC($thirdparty_seller);
  5724. $buyer_country_code = $thirdparty_buyer->country_code;
  5725. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5726. 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 : ''));
  5727. // 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)
  5728. // we use the buyer VAT.
  5729. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5730. if ($seller_in_cee && $buyer_in_cee) {
  5731. $isacompany = $thirdparty_buyer->isACompany();
  5732. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5733. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5734. if (!isValidVATID($thirdparty_buyer)) {
  5735. $isacompany = 0;
  5736. }
  5737. }
  5738. if (!$isacompany) {
  5739. //print 'VATRULE 0';
  5740. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5741. }
  5742. }
  5743. }
  5744. // If seller does not use VAT
  5745. if (!$seller_use_vat) {
  5746. //print 'VATRULE 1';
  5747. return 0;
  5748. }
  5749. // 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.
  5750. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5751. if (($seller_country_code == $buyer_country_code)
  5752. || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5753. //print 'VATRULE 2';
  5754. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5755. }
  5756. // 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.
  5757. // 'VATRULE 3' - Not supported
  5758. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5759. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5760. if (($seller_in_cee && $buyer_in_cee)) {
  5761. $isacompany = $thirdparty_buyer->isACompany();
  5762. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5763. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5764. if (!isValidVATID($thirdparty_buyer)) {
  5765. $isacompany = 0;
  5766. }
  5767. }
  5768. if (!$isacompany) {
  5769. //print 'VATRULE 4';
  5770. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5771. } else {
  5772. //print 'VATRULE 5';
  5773. return 0;
  5774. }
  5775. }
  5776. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5777. // I don't see any use case that need this rule.
  5778. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5779. $isacompany = $thirdparty_buyer->isACompany();
  5780. if (!$isacompany) {
  5781. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5782. //print 'VATRULE extra';
  5783. }
  5784. }
  5785. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5786. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5787. //print 'VATRULE 6';
  5788. return 0;
  5789. }
  5790. /**
  5791. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5792. *
  5793. * @param Societe $thirdparty_seller Thirdparty seller
  5794. * @param Societe $thirdparty_buyer Thirdparty buyer
  5795. * @param int $idprod Id product
  5796. * @param int $idprodfournprice Id supplier price for product
  5797. * @return float 0 or 1
  5798. * @see get_default_tva(), get_default_localtax()
  5799. */
  5800. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5801. {
  5802. global $db;
  5803. if ($idprodfournprice > 0) {
  5804. if (!class_exists('ProductFournisseur')) {
  5805. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5806. }
  5807. $prodprice = new ProductFournisseur($db);
  5808. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5809. return $prodprice->fourn_tva_npr;
  5810. } elseif ($idprod > 0) {
  5811. if (!class_exists('Product')) {
  5812. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5813. }
  5814. $prod = new Product($db);
  5815. $prod->fetch($idprod);
  5816. return $prod->tva_npr;
  5817. }
  5818. return 0;
  5819. }
  5820. /**
  5821. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5822. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5823. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5824. * Sinon TVA proposee par defaut=0. Fin de regle.
  5825. *
  5826. * @param Societe $thirdparty_seller Thirdparty seller
  5827. * @param Societe $thirdparty_buyer Thirdparty buyer
  5828. * @param int $local Localtax to process (1 or 2)
  5829. * @param int $idprod Id product
  5830. * @return integer localtax, -1 si ne peut etre determine
  5831. * @see get_default_tva(), get_default_npr()
  5832. */
  5833. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5834. {
  5835. global $mysoc;
  5836. if (!is_object($thirdparty_seller)) {
  5837. return -1;
  5838. }
  5839. if (!is_object($thirdparty_buyer)) {
  5840. return -1;
  5841. }
  5842. if ($local == 1) { // Localtax 1
  5843. if ($mysoc->country_code == 'ES') {
  5844. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  5845. return 0;
  5846. }
  5847. } else {
  5848. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  5849. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  5850. return 0;
  5851. }
  5852. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  5853. return 0;
  5854. }
  5855. }
  5856. } elseif ($local == 2) { //I Localtax 2
  5857. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  5858. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  5859. return 0;
  5860. }
  5861. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  5862. return 0;
  5863. }
  5864. }
  5865. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  5866. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  5867. }
  5868. return 0;
  5869. }
  5870. /**
  5871. * Return yes or no in current language
  5872. *
  5873. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5874. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5875. * @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.
  5876. * @return string HTML string
  5877. */
  5878. function yn($yesno, $case = 1, $color = 0)
  5879. {
  5880. global $langs;
  5881. $result = 'unknown';
  5882. $classname = '';
  5883. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  5884. $result = $langs->trans('yes');
  5885. if ($case == 1 || $case == 3) {
  5886. $result = $langs->trans("Yes");
  5887. }
  5888. if ($case == 2) {
  5889. $result = '<input type="checkbox" value="1" checked disabled>';
  5890. }
  5891. if ($case == 3) {
  5892. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5893. }
  5894. $classname = 'ok';
  5895. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  5896. $result = $langs->trans("no");
  5897. if ($case == 1 || $case == 3) {
  5898. $result = $langs->trans("No");
  5899. }
  5900. if ($case == 2) {
  5901. $result = '<input type="checkbox" value="0" disabled>';
  5902. }
  5903. if ($case == 3) {
  5904. $result = '<input type="checkbox" value="0" disabled> '.$result;
  5905. }
  5906. if ($color == 2) {
  5907. $classname = 'ok';
  5908. } else {
  5909. $classname = 'error';
  5910. }
  5911. }
  5912. if ($color) {
  5913. return '<span class="'.$classname.'">'.$result.'</span>';
  5914. }
  5915. return $result;
  5916. }
  5917. /**
  5918. * Return a path to have a the directory according to object where files are stored.
  5919. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  5920. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  5921. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  5922. * 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/"
  5923. *
  5924. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5925. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5926. * @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)
  5927. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5928. * @param Object $object Object to use to get ref to forge the path.
  5929. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5930. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5931. */
  5932. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5933. {
  5934. global $conf;
  5935. if (empty($modulepart) && !empty($object->module)) {
  5936. $modulepart = $object->module;
  5937. }
  5938. $path = '';
  5939. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5940. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  5941. $arrayforoldpath[] = 'product';
  5942. }
  5943. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  5944. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  5945. if (empty($alpha)) {
  5946. $num = preg_replace('/([^0-9])/i', '', $num);
  5947. } else {
  5948. $num = preg_replace('/^.*\-/i', '', $num);
  5949. }
  5950. $num = substr("000".$num, -$level);
  5951. if ($level == 1) {
  5952. $path = substr($num, 0, 1);
  5953. }
  5954. if ($level == 2) {
  5955. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5956. }
  5957. if ($level == 3) {
  5958. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5959. }
  5960. } else {
  5961. // We will enhance here a common way of forging path for document storage.
  5962. // In a future, we may distribute directories on several levels depending on setup and object.
  5963. // Here, $object->id, $object->ref and $modulepart are required.
  5964. //var_dump($modulepart);
  5965. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  5966. }
  5967. if (empty($withoutslash) && !empty($path)) {
  5968. $path .= '/';
  5969. }
  5970. return $path;
  5971. }
  5972. /**
  5973. * Creation of a directory (this can create recursive subdir)
  5974. *
  5975. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5976. * @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)
  5977. * @param string $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5978. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5979. */
  5980. function dol_mkdir($dir, $dataroot = '', $newmask = '')
  5981. {
  5982. global $conf;
  5983. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5984. $dir_osencoded = dol_osencode($dir);
  5985. if (@is_dir($dir_osencoded)) {
  5986. return 0;
  5987. }
  5988. $nberr = 0;
  5989. $nbcreated = 0;
  5990. $ccdir = '';
  5991. if (!empty($dataroot)) {
  5992. // Remove data root from loop
  5993. $dir = str_replace($dataroot.'/', '', $dir);
  5994. $ccdir = $dataroot.'/';
  5995. }
  5996. $cdir = explode("/", $dir);
  5997. $num = count($cdir);
  5998. for ($i = 0; $i < $num; $i++) {
  5999. if ($i > 0) {
  6000. $ccdir .= '/'.$cdir[$i];
  6001. } else {
  6002. $ccdir .= $cdir[$i];
  6003. }
  6004. if (preg_match("/^.:$/", $ccdir, $regs)) {
  6005. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  6006. }
  6007. // Attention, le is_dir() peut echouer bien que le rep existe.
  6008. // (ex selon config de open_basedir)
  6009. if ($ccdir) {
  6010. $ccdir_osencoded = dol_osencode($ccdir);
  6011. if (!@is_dir($ccdir_osencoded)) {
  6012. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  6013. umask(0);
  6014. $dirmaskdec = octdec((string) $newmask);
  6015. if (empty($newmask)) {
  6016. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  6017. }
  6018. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  6019. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  6020. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  6021. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  6022. $nberr++;
  6023. } else {
  6024. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  6025. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  6026. $nbcreated++;
  6027. }
  6028. } else {
  6029. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  6030. }
  6031. }
  6032. }
  6033. return ($nberr ? -$nberr : $nbcreated);
  6034. }
  6035. /**
  6036. * Return picto saying a field is required
  6037. *
  6038. * @return string Chaine avec picto obligatoire
  6039. */
  6040. function picto_required()
  6041. {
  6042. return '<span class="fieldrequired">*</span>';
  6043. }
  6044. /**
  6045. * Clean a string from all HTML tags and entities.
  6046. * This function differs from strip_tags because:
  6047. * - <br> are replaced with \n if removelinefeed=0 or 1
  6048. * - if entities are found, they are decoded BEFORE the strip
  6049. * - you can decide to convert line feed into a space
  6050. *
  6051. * @param string $stringtoclean String to clean
  6052. * @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..."
  6053. * @param string $pagecodeto Encoding of input/output string
  6054. * @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')
  6055. * @param integer $removedoublespaces Replace double space into one space
  6056. * @return string String cleaned
  6057. *
  6058. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6059. */
  6060. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6061. {
  6062. if ($removelinefeed == 2) {
  6063. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6064. }
  6065. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6066. // 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)
  6067. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6068. $temp = str_replace('< ', '__ltspace__', $temp);
  6069. if ($strip_tags) {
  6070. $temp = strip_tags($temp);
  6071. } else {
  6072. // 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).
  6073. $pattern = "/<[^<>]+>/";
  6074. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6075. // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6076. // pass 2 - $temp after pass 2: 0000-021
  6077. $tempbis = $temp;
  6078. do {
  6079. $temp = $tempbis;
  6080. $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6081. $tempbis = preg_replace($pattern, '', $tempbis);
  6082. //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
  6083. } while ($tempbis != $temp);
  6084. $temp = $tempbis;
  6085. // Remove '<' into remaining, 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).
  6086. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6087. }
  6088. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6089. // Remove also carriage returns
  6090. if ($removelinefeed == 1) {
  6091. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6092. }
  6093. // And double quotes
  6094. if ($removedoublespaces) {
  6095. while (strpos($temp, " ")) {
  6096. $temp = str_replace(" ", " ", $temp);
  6097. }
  6098. }
  6099. $temp = str_replace('__ltspace__', '< ', $temp);
  6100. return trim($temp);
  6101. }
  6102. /**
  6103. * Clean a string to keep only desirable HTML tags.
  6104. * WARNING: This also clean HTML comments (used to obfuscate tag name).
  6105. *
  6106. * @param string $stringtoclean String to clean
  6107. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6108. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6109. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6110. * @param int $allowiframe Allow iframe tags.
  6111. * @return string String cleaned
  6112. *
  6113. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6114. */
  6115. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0)
  6116. {
  6117. $allowed_tags = array(
  6118. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  6119. "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",
  6120. "comment" // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6121. );
  6122. if ($allowiframe) {
  6123. $allowed_tags[] = "iframe";
  6124. }
  6125. $allowed_tags_string = join("><", $allowed_tags);
  6126. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6127. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6128. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6129. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6130. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6131. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6132. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6133. $stringtoclean = preg_replace('/javascript\s*:/i', '', $stringtoclean);
  6134. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </> changing string obfuscated with </> that pass injection detection into harmfull string
  6135. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6136. $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
  6137. }
  6138. if ($removeclassattribute) { // Clean for remaining html tags
  6139. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6140. }
  6141. // Remove 'javascript:' that we should not find into a text with
  6142. // 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)).
  6143. if ($cleanalsojavascript) {
  6144. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  6145. }
  6146. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6147. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6148. return $temp;
  6149. }
  6150. /**
  6151. * Clean a string from some undesirable HTML tags.
  6152. * Note: Complementary to dol_string_onlythesehtmltags().
  6153. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6154. *
  6155. * @param string $stringtoclean String to clean
  6156. * @param array $allowed_attributes Array of tags not allowed
  6157. * @return string String cleaned
  6158. *
  6159. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6160. */
  6161. 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"))
  6162. {
  6163. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6164. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6165. $dom = new DOMDocument(null, 'UTF-8');
  6166. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6167. if (is_object($dom)) {
  6168. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6169. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6170. //var_dump($attrs->item($ii));
  6171. if (! empty($attrs->item($ii)->name)) {
  6172. // Delete attribute if not into allowed_attributes
  6173. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6174. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6175. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6176. $valuetoclean = $attrs->item($ii)->value;
  6177. if (isset($valuetoclean)) {
  6178. do {
  6179. $oldvaluetoclean = $valuetoclean;
  6180. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6181. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6182. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6183. $valuetoclean = preg_replace('/display\s*://m', '', $valuetoclean);
  6184. $valuetoclean = preg_replace('/z-index\s*://m', '', $valuetoclean);
  6185. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*://m', '', $valuetoclean);
  6186. }
  6187. } while ($oldvaluetoclean != $valuetoclean);
  6188. }
  6189. $attrs->item($ii)->value = $valuetoclean;
  6190. }
  6191. }
  6192. }
  6193. }
  6194. }
  6195. $return = $dom->saveHTML();
  6196. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6197. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6198. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6199. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6200. return trim($return);
  6201. } else {
  6202. return $stringtoclean;
  6203. }
  6204. }
  6205. /**
  6206. * Clean a string from some undesirable HTML tags.
  6207. * Note. Not as secured as dol_string_onlythesehtmltags().
  6208. *
  6209. * @param string $stringtoclean String to clean
  6210. * @param array $disallowed_tags Array of tags not allowed
  6211. * @param string $cleanalsosomestyles Clean also some tags
  6212. * @return string String cleaned
  6213. *
  6214. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6215. */
  6216. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6217. {
  6218. $temp = $stringtoclean;
  6219. foreach ($disallowed_tags as $tagtoremove) {
  6220. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6221. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6222. }
  6223. if ($cleanalsosomestyles) {
  6224. $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
  6225. }
  6226. return $temp;
  6227. }
  6228. /**
  6229. * Return first line of text. Cut will depends if content is HTML or not.
  6230. *
  6231. * @param string $text Input text
  6232. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6233. * @param string $charset Charset of $text string (UTF-8 by default)
  6234. * @return string Output text
  6235. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6236. */
  6237. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6238. {
  6239. if ($nboflines == 1) {
  6240. if (dol_textishtml($text)) {
  6241. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6242. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6243. } else {
  6244. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6245. }
  6246. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  6247. } else {
  6248. $ishtml = 0;
  6249. if (dol_textishtml($text)) {
  6250. $text = preg_replace('/\n/', '', $text);
  6251. $ishtml = 1;
  6252. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6253. } else {
  6254. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6255. }
  6256. $text = strtr($text, $repTable);
  6257. if ($charset == 'UTF-8') {
  6258. $pattern = '/(<br[^>]*>)/Uu';
  6259. } else {
  6260. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6261. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6262. }
  6263. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6264. $firstline = '';
  6265. $i = 0;
  6266. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  6267. while (($i < $nba) && ($i < ($nboflines * 2))) {
  6268. if ($i % 2 == 0) {
  6269. $firstline .= $a[$i];
  6270. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  6271. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6272. }
  6273. $i++;
  6274. }
  6275. unset($a);
  6276. return $firstline.(($i < $nba) ? '...' : '');
  6277. }
  6278. }
  6279. /**
  6280. * Replace CRLF in string with a HTML BR tag.
  6281. * 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.
  6282. *
  6283. * @param string $stringtoencode String to encode
  6284. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6285. * @param bool $forxml false=Use <br>, true=Use <br />
  6286. * @return string String encoded
  6287. * @see dol_nboflines(), dolGetFirstLineOfText()
  6288. */
  6289. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6290. {
  6291. if (!$nl2brmode) {
  6292. return nl2br($stringtoencode, $forxml);
  6293. } else {
  6294. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6295. return $ret;
  6296. }
  6297. }
  6298. /**
  6299. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6300. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6301. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6302. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6303. * For PDF usage, you can show text by 2 ways:
  6304. * - writeHTMLCell -> param must be encoded into HTML.
  6305. * - MultiCell -> param must not be encoded into HTML.
  6306. * Because writeHTMLCell convert also \n into <br>, if function
  6307. * is used to build PDF, nl2brmode must be 1.
  6308. *
  6309. * @param string $stringtoencode String to encode
  6310. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6311. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6312. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6313. * @return string String encoded
  6314. */
  6315. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6316. {
  6317. $newstring = $stringtoencode;
  6318. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6319. $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.
  6320. if ($removelasteolbr) {
  6321. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6322. }
  6323. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6324. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6325. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6326. } else {
  6327. if ($removelasteolbr) {
  6328. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6329. }
  6330. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6331. }
  6332. // Other substitutions that htmlentities does not do
  6333. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6334. return $newstring;
  6335. }
  6336. /**
  6337. * This function is called to decode a HTML string (it decodes entities and br tags)
  6338. *
  6339. * @param string $stringtodecode String to decode
  6340. * @param string $pagecodeto Page code for result
  6341. * @return string String decoded
  6342. */
  6343. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6344. {
  6345. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6346. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6347. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6348. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6349. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6350. return $ret;
  6351. }
  6352. /**
  6353. * This function remove all ending \n and br at end
  6354. *
  6355. * @param string $stringtodecode String to decode
  6356. * @return string String decoded
  6357. */
  6358. function dol_htmlcleanlastbr($stringtodecode)
  6359. {
  6360. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6361. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6362. return $ret;
  6363. }
  6364. /**
  6365. * Replace html_entity_decode functions to manage errors
  6366. *
  6367. * @param string $a Operand a
  6368. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6369. * @param string $c Operand c
  6370. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6371. * @return string String decoded
  6372. */
  6373. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6374. {
  6375. $newstring = $a;
  6376. if ($keepsomeentities) {
  6377. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6378. }
  6379. $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
  6380. if ($keepsomeentities) {
  6381. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6382. }
  6383. return $newstring;
  6384. }
  6385. /**
  6386. * Replace htmlentities functions.
  6387. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6388. *
  6389. * @param string $string The input string to encode
  6390. * @param int $flags Flags (see PHP doc above)
  6391. * @param string $encoding Encoding page code
  6392. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6393. * @return string $ret Encoded string
  6394. */
  6395. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6396. {
  6397. return htmlentities($string, $flags, $encoding, $double_encode);
  6398. }
  6399. /**
  6400. * Check if a string is a correct iso string
  6401. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6402. * Example, if string contains euro symbol that has ascii code 128
  6403. *
  6404. * @param string $s String to check
  6405. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6406. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6407. */
  6408. function dol_string_is_good_iso($s, $clean = 0)
  6409. {
  6410. $len = dol_strlen($s);
  6411. $out = '';
  6412. $ok = 1;
  6413. for ($scursor = 0; $scursor < $len; $scursor++) {
  6414. $ordchar = ord($s[$scursor]);
  6415. //print $scursor.'-'.$ordchar.'<br>';
  6416. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6417. $ok = 0;
  6418. break;
  6419. } elseif ($ordchar > 126 && $ordchar < 160) {
  6420. $ok = 0;
  6421. break;
  6422. } elseif ($clean) {
  6423. $out .= $s[$scursor];
  6424. }
  6425. }
  6426. if ($clean) {
  6427. return $out;
  6428. }
  6429. return $ok;
  6430. }
  6431. /**
  6432. * Return nb of lines of a clear text
  6433. *
  6434. * @param string $s String to check
  6435. * @param int $maxchar Not yet used
  6436. * @return int Number of lines
  6437. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6438. */
  6439. function dol_nboflines($s, $maxchar = 0)
  6440. {
  6441. if ($s == '') {
  6442. return 0;
  6443. }
  6444. $arraystring = explode("\n", $s);
  6445. $nb = count($arraystring);
  6446. return $nb;
  6447. }
  6448. /**
  6449. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6450. *
  6451. * @param string $text Text
  6452. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6453. * @param string $charset Give the charset used to encode the $text variable in memory.
  6454. * @return int Number of lines
  6455. * @see dol_nboflines(), dolGetFirstLineOfText()
  6456. */
  6457. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6458. {
  6459. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6460. if (dol_textishtml($text)) {
  6461. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6462. }
  6463. $text = strtr($text, $repTable);
  6464. if ($charset == 'UTF-8') {
  6465. $pattern = '/(<br[^>]*>)/Uu';
  6466. } else {
  6467. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6468. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6469. }
  6470. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6471. $nblines = (int) floor((count($a) + 1) / 2);
  6472. // count possible auto line breaks
  6473. if ($maxlinesize) {
  6474. foreach ($a as $line) {
  6475. if (dol_strlen($line) > $maxlinesize) {
  6476. //$line_dec = html_entity_decode(strip_tags($line));
  6477. $line_dec = html_entity_decode($line);
  6478. if (dol_strlen($line_dec) > $maxlinesize) {
  6479. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6480. $nblines += substr_count($line_dec, '\n');
  6481. }
  6482. }
  6483. }
  6484. }
  6485. unset($a);
  6486. return $nblines;
  6487. }
  6488. /**
  6489. * Return if a text is a html content
  6490. *
  6491. * @param string $msg Content to check
  6492. * @param int $option 0=Full detection, 1=Fast check
  6493. * @return boolean true/false
  6494. * @see dol_concatdesc()
  6495. */
  6496. function dol_textishtml($msg, $option = 0)
  6497. {
  6498. if ($option == 1) {
  6499. if (preg_match('/<html/i', $msg)) {
  6500. return true;
  6501. } elseif (preg_match('/<body/i', $msg)) {
  6502. return true;
  6503. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6504. return true;
  6505. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6506. return true;
  6507. } elseif (preg_match('/<br/i', $msg)) {
  6508. return true;
  6509. }
  6510. return false;
  6511. } else {
  6512. // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
  6513. $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
  6514. if (preg_match('/<html/i', $msg)) {
  6515. return true;
  6516. } elseif (preg_match('/<body/i', $msg)) {
  6517. return true;
  6518. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6519. return true;
  6520. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6521. return true;
  6522. } elseif (preg_match('/<br\/>/i', $msg)) {
  6523. return true;
  6524. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6525. return true;
  6526. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6527. return true;
  6528. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6529. return true; // must accept <img src="http://example.com/aaa.png" />
  6530. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6531. return true; // must accept <a href="http://example.com/aaa.png" />
  6532. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6533. return true;
  6534. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6535. // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
  6536. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6537. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6538. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6539. }
  6540. return false;
  6541. }
  6542. }
  6543. /**
  6544. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6545. * text1 html + text2 html => text1 + '<br>' + text2
  6546. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6547. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6548. * text1 txt + text2 txt => text1 + '\n' + text2
  6549. *
  6550. * @param string $text1 Text 1
  6551. * @param string $text2 Text 2
  6552. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6553. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6554. * @return string Text 1 + new line + Text2
  6555. * @see dol_textishtml()
  6556. */
  6557. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6558. {
  6559. if (!empty($invert)) {
  6560. $tmp = $text1;
  6561. $text1 = $text2;
  6562. $text2 = $tmp;
  6563. }
  6564. $ret = '';
  6565. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6566. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6567. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6568. return $ret;
  6569. }
  6570. /**
  6571. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6572. *
  6573. * @param Translate $outputlangs Output language
  6574. * @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)
  6575. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6576. * @param Object $object Object for keys on object
  6577. * @return array Array of substitutions
  6578. * @see setSubstitFromObject()
  6579. */
  6580. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6581. {
  6582. global $db, $conf, $mysoc, $user, $extrafields;
  6583. $substitutionarray = array();
  6584. if (empty($exclude) || !in_array('user', $exclude)) {
  6585. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6586. // this will include signature content first and then replace var found into content of signature
  6587. $signature = $user->signature;
  6588. $substitutionarray = array_merge($substitutionarray, array(
  6589. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  6590. ));
  6591. if (is_object($user)) {
  6592. $substitutionarray = array_merge($substitutionarray, array(
  6593. '__USER_ID__' => (string) $user->id,
  6594. '__USER_LOGIN__' => (string) $user->login,
  6595. '__USER_EMAIL__' => (string) $user->email,
  6596. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone),
  6597. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile),
  6598. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile),
  6599. '__USER_FAX__' => (string) $user->office_fax,
  6600. '__USER_LASTNAME__' => (string) $user->lastname,
  6601. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6602. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6603. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6604. '__USER_JOB__' => (string) $user->job,
  6605. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6606. ));
  6607. }
  6608. }
  6609. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6610. $substitutionarray = array_merge($substitutionarray, array(
  6611. '__MYCOMPANY_NAME__' => $mysoc->name,
  6612. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6613. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone),
  6614. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax),
  6615. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6616. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6617. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6618. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6619. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6620. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6621. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6622. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6623. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6624. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6625. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6626. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6627. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6628. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6629. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6630. ));
  6631. }
  6632. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6633. if ($onlykey) {
  6634. $substitutionarray['__ID__'] = '__ID__';
  6635. $substitutionarray['__REF__'] = '__REF__';
  6636. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6637. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6638. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6639. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6640. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6641. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6642. if (!empty($conf->societe->enabled)) { // Most objects are concerned
  6643. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6644. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6645. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6646. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6647. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6648. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6649. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6650. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6651. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6652. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6653. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6654. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6655. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6656. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6657. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6658. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6659. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6660. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6661. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6662. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6663. }
  6664. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent')) {
  6665. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6666. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6667. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6668. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6669. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6670. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6671. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6672. }
  6673. // add variables subtitutions ticket
  6674. if (!empty($conf->ticket->enabled) && (!is_object($object) || $object->element == 'ticket')) {
  6675. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  6676. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  6677. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  6678. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  6679. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  6680. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  6681. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  6682. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  6683. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  6684. }
  6685. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'recruitmentcandidature')) {
  6686. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6687. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6688. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6689. }
  6690. if (!empty($conf->project->enabled)) { // Most objects
  6691. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6692. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6693. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6694. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6695. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6696. }
  6697. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract')) {
  6698. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6699. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6700. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6701. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6702. }
  6703. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6704. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6705. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6706. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6707. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6708. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6709. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  6710. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6711. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6712. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6713. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6714. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6715. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping')) {
  6716. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6717. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6718. }
  6719. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception')) {
  6720. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6721. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6722. }
  6723. } else {
  6724. $substitutionarray['__ID__'] = $object->id;
  6725. $substitutionarray['__REF__'] = $object->ref;
  6726. $substitutionarray['__NEWREF__'] = $object->newref;
  6727. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6728. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6729. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6730. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6731. if ($object->element == "shipping") {
  6732. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, 'day', 0, $outputlangs) : '');
  6733. } else {
  6734. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6735. }
  6736. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6737. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6738. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6739. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6740. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6741. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6742. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6743. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6744. // For backward compatibility
  6745. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6746. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6747. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6748. $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 : '')) : '');
  6749. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6750. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  6751. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  6752. if (method_exists($object, 'getCivilityLabel')) {
  6753. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  6754. }
  6755. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  6756. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  6757. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  6758. if (method_exists($object, 'getFullName')) {
  6759. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  6760. }
  6761. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  6762. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  6763. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  6764. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  6765. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  6766. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  6767. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  6768. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  6769. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  6770. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  6771. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  6772. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  6773. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  6774. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  6775. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  6776. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
  6777. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
  6778. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  6779. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  6780. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  6781. }
  6782. if (is_object($object) && $object->element == 'societe') {
  6783. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  6784. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  6785. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  6786. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  6787. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  6788. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  6789. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  6790. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  6791. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  6792. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  6793. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  6794. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  6795. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  6796. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  6797. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  6798. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  6799. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  6800. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  6801. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  6802. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  6803. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  6804. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  6805. } elseif (is_object($object->thirdparty)) {
  6806. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  6807. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  6808. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  6809. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  6810. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  6811. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  6812. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  6813. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  6814. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  6815. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  6816. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  6817. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  6818. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  6819. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  6820. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  6821. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  6822. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  6823. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  6824. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  6825. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  6826. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  6827. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  6828. }
  6829. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  6830. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  6831. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  6832. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  6833. }
  6834. if (is_object($object->project)) {
  6835. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  6836. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  6837. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  6838. }
  6839. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  6840. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  6841. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  6842. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  6843. }
  6844. if (is_object($object) && $object->element == 'project') {
  6845. $substitutionarray['__PROJECT_NAME__'] = $object->title;
  6846. }
  6847. if (is_object($object) && $object->element == 'shipping') {
  6848. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  6849. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  6850. }
  6851. if (is_object($object) && $object->element == 'reception') {
  6852. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  6853. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  6854. }
  6855. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  6856. $dateplannedstart = '';
  6857. $datenextexpiration = '';
  6858. foreach ($object->lines as $line) {
  6859. if ($line->date_ouverture_prevue > $dateplannedstart) {
  6860. $dateplannedstart = $line->date_ouverture_prevue;
  6861. }
  6862. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
  6863. $datenextexpiration = $line->date_fin_prevue;
  6864. }
  6865. }
  6866. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  6867. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  6868. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  6869. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  6870. }
  6871. // add substition variable for ticket
  6872. if (is_object($object) && $object->element == 'ticket') {
  6873. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  6874. $substitutionarray['__REF__'] = $object->ref;
  6875. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  6876. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  6877. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  6878. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  6879. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  6880. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  6881. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  6882. $userstat = new User($db);
  6883. if ($object->fk_user_assign > 0) {
  6884. $userstat->fetch($object->fk_user_assign);
  6885. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  6886. }
  6887. if ($object->fk_user_create > 0) {
  6888. $userstat->fetch($object->fk_user_create);
  6889. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  6890. }
  6891. }
  6892. // Create dynamic tags for __EXTRAFIELD_FIELD__
  6893. if ($object->table_element && $object->id > 0) {
  6894. if (!is_object($extrafields)) {
  6895. $extrafields = new ExtraFields($db);
  6896. }
  6897. $extrafields->fetch_name_optionals_label($object->table_element, true);
  6898. if ($object->fetch_optionals() > 0) {
  6899. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  6900. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  6901. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6902. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  6903. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  6904. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  6905. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  6906. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  6907. $datetime = $object->array_options['options_'.$key];
  6908. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  6909. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  6910. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  6911. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  6912. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  6913. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  6914. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  6915. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  6916. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  6917. }
  6918. }
  6919. }
  6920. }
  6921. }
  6922. // Complete substitution array with the url to make online payment
  6923. $paymenturl = '';
  6924. if (empty($substitutionarray['__REF__'])) {
  6925. $paymenturl = '';
  6926. } else {
  6927. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  6928. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  6929. $outputlangs->loadLangs(array('paypal', 'other'));
  6930. $typeforonlinepayment = 'free';
  6931. if (is_object($object) && $object->element == 'commande') {
  6932. $typeforonlinepayment = 'order';
  6933. }
  6934. if (is_object($object) && $object->element == 'facture') {
  6935. $typeforonlinepayment = 'invoice';
  6936. }
  6937. if (is_object($object) && $object->element == 'member') {
  6938. $typeforonlinepayment = 'member';
  6939. }
  6940. if (is_object($object) && $object->element == 'contrat') {
  6941. $typeforonlinepayment = 'contract';
  6942. }
  6943. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  6944. $paymenturl = $url;
  6945. }
  6946. if ($object->id > 0) {
  6947. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  6948. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  6949. if (is_object($object) && $object->element == 'propal') {
  6950. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  6951. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  6952. }
  6953. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  6954. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6955. } else {
  6956. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  6957. }
  6958. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  6959. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  6960. } else {
  6961. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  6962. }
  6963. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  6964. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  6965. } else {
  6966. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  6967. }
  6968. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  6969. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  6970. } else {
  6971. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  6972. }
  6973. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  6974. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  6975. } else {
  6976. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  6977. }
  6978. if (is_object($object) && $object->element == 'propal') {
  6979. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  6980. }
  6981. if (is_object($object) && $object->element == 'commande') {
  6982. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  6983. }
  6984. if (is_object($object) && $object->element == 'facture') {
  6985. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  6986. }
  6987. if (is_object($object) && $object->element == 'contrat') {
  6988. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  6989. }
  6990. if (is_object($object) && $object->element == 'supplier_proposal') {
  6991. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  6992. }
  6993. if (is_object($object) && $object->element == 'shipping') {
  6994. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  6995. }
  6996. }
  6997. if (is_object($object) && $object->element == 'action') {
  6998. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  6999. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  7000. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  7001. }
  7002. }
  7003. }
  7004. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  7005. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  7006. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  7007. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  7008. $already_payed_all = 0;
  7009. if (is_object($object) && ($object instanceof Facture)) {
  7010. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  7011. }
  7012. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  7013. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  7014. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  7015. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  7016. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
  7017. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7018. $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)) : '';
  7019. $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)) : '';
  7020. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7021. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  7022. }
  7023. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7024. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  7025. }
  7026. // Amount keys formated in a currency
  7027. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7028. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7029. $substitutionarray['__AMOUNT_REMAIN_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc - $already_payed_all, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7030. $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)) : '';
  7031. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7032. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7033. }
  7034. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7035. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7036. }
  7037. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  7038. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  7039. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  7040. // TODO Add other keys for foreign multicurrency
  7041. // For backward compatibility
  7042. if ($onlykey != 2) {
  7043. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  7044. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  7045. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7046. }
  7047. }
  7048. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  7049. if (empty($exclude) || !in_array('date', $exclude)) {
  7050. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  7051. $tmp = dol_getdate(dol_now(), true);
  7052. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7053. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  7054. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7055. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  7056. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  7057. $substitutionarray = array_merge($substitutionarray, array(
  7058. '__DAY__' => (string) $tmp['mday'],
  7059. '__DAY_TEXT__' => $daytext, // Monday
  7060. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  7061. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  7062. '__MONTH__' => (string) $tmp['mon'],
  7063. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  7064. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  7065. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  7066. '__YEAR__' => (string) $tmp['year'],
  7067. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  7068. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  7069. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  7070. '__NEXT_DAY__' => (string) $tmp4['day'],
  7071. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7072. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7073. ));
  7074. }
  7075. if (!empty($conf->multicompany->enabled)) {
  7076. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7077. }
  7078. if (empty($exclude) || !in_array('system', $exclude)) {
  7079. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7080. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7081. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7082. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7083. }
  7084. return $substitutionarray;
  7085. }
  7086. /**
  7087. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7088. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7089. * Example of usage:
  7090. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7091. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7092. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7093. *
  7094. * @param string $text Source string in which we must do substitution
  7095. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7096. * @param Translate $outputlangs Output language
  7097. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7098. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7099. * @return string Output string after substitutions
  7100. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7101. */
  7102. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7103. {
  7104. global $conf, $langs;
  7105. if (!is_array($substitutionarray)) {
  7106. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7107. }
  7108. if (empty($outputlangs)) {
  7109. $outputlangs = $langs;
  7110. }
  7111. // Is initial text HTML or simple text ?
  7112. $msgishtml = 0;
  7113. if (dol_textishtml($text, 1)) {
  7114. $msgishtml = 1;
  7115. }
  7116. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7117. if (is_object($outputlangs)) {
  7118. $reg = array();
  7119. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7120. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7121. $tmp = explode('|', $reg[1]);
  7122. if (!empty($tmp[1])) {
  7123. $outputlangs->load($tmp[1]);
  7124. }
  7125. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7126. if (empty($converttextinhtmlifnecessary)) {
  7127. // convert $newval into HTML is necessary
  7128. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7129. } else {
  7130. if (! $msgishtml) {
  7131. $valueishtml = dol_textishtml($value, 1);
  7132. var_dump("valueishtml=".$valueishtml);
  7133. if ($valueishtml) {
  7134. $text = dol_htmlentitiesbr($text);
  7135. $msgishtml = 1;
  7136. }
  7137. } else {
  7138. $value = dol_nl2br("$value");
  7139. }
  7140. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7141. }
  7142. }
  7143. }
  7144. // Make substitution for constant keys.
  7145. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7146. $reg = array();
  7147. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7148. $keyfound = $reg[1];
  7149. if (isASecretKey($keyfound)) {
  7150. $value = '*****forbidden*****';
  7151. } else {
  7152. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7153. }
  7154. if (empty($converttextinhtmlifnecessary)) {
  7155. // convert $newval into HTML is necessary
  7156. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7157. } else {
  7158. if (! $msgishtml) {
  7159. $valueishtml = dol_textishtml($value, 1);
  7160. if ($valueishtml) {
  7161. $text = dol_htmlentitiesbr($text);
  7162. $msgishtml = 1;
  7163. }
  7164. } else {
  7165. $value = dol_nl2br("$value");
  7166. }
  7167. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7168. }
  7169. }
  7170. // Make substitition for array $substitutionarray
  7171. foreach ($substitutionarray as $key => $value) {
  7172. if (!isset($value)) {
  7173. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7174. }
  7175. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  7176. $value = ''; // Protection
  7177. }
  7178. if (empty($converttextinhtmlifnecessary)) {
  7179. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7180. } else {
  7181. if (! $msgishtml) {
  7182. $valueishtml = dol_textishtml($value, 1);
  7183. if ($valueishtml) {
  7184. $text = dol_htmlentitiesbr($text);
  7185. $msgishtml = 1;
  7186. }
  7187. } else {
  7188. $value = dol_nl2br("$value");
  7189. }
  7190. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7191. }
  7192. }
  7193. return $text;
  7194. }
  7195. /**
  7196. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  7197. * In this case, method completesubstitutionarray provided by module is called.
  7198. *
  7199. * @param array $substitutionarray Array substitution old value => new value value
  7200. * @param Translate $outputlangs Output language
  7201. * @param Object $object Source object
  7202. * @param mixed $parameters Add more parameters (useful to pass product lines)
  7203. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  7204. * @return void
  7205. * @see make_substitutions()
  7206. */
  7207. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  7208. {
  7209. global $conf, $user;
  7210. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7211. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7212. // Check if there is external substitution to do, requested by plugins
  7213. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7214. foreach ($dirsubstitutions as $reldir) {
  7215. $dir = dol_buildpath($reldir, 0);
  7216. // Check if directory exists
  7217. if (!dol_is_dir($dir)) {
  7218. continue;
  7219. }
  7220. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7221. foreach ($substitfiles as $substitfile) {
  7222. $reg = array();
  7223. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7224. $module = $reg[1];
  7225. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7226. // Include the user's functions file
  7227. require_once $dir.$substitfile['name'];
  7228. // Call the user's function, and only if it is defined
  7229. $function_name = $module."_".$callfunc;
  7230. if (function_exists($function_name)) {
  7231. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7232. }
  7233. }
  7234. }
  7235. }
  7236. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7237. // to list all tags in odt template
  7238. $tags = '';
  7239. foreach ($substitutionarray as $key => $value) {
  7240. $tags .= '{'.$key.'} => '.$value."\n";
  7241. }
  7242. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7243. }
  7244. }
  7245. /**
  7246. * Format output for start and end date
  7247. *
  7248. * @param int $date_start Start date
  7249. * @param int $date_end End date
  7250. * @param string $format Output format
  7251. * @param Translate $outputlangs Output language
  7252. * @return void
  7253. */
  7254. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7255. {
  7256. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7257. }
  7258. /**
  7259. * Format output for start and end date
  7260. *
  7261. * @param int $date_start Start date
  7262. * @param int $date_end End date
  7263. * @param string $format Output format
  7264. * @param Translate $outputlangs Output language
  7265. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7266. * @return string String
  7267. */
  7268. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7269. {
  7270. global $langs;
  7271. $out = '';
  7272. if (!is_object($outputlangs)) {
  7273. $outputlangs = $langs;
  7274. }
  7275. if ($date_start && $date_end) {
  7276. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7277. }
  7278. if ($date_start && !$date_end) {
  7279. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7280. }
  7281. if (!$date_start && $date_end) {
  7282. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7283. }
  7284. return $out;
  7285. }
  7286. /**
  7287. * Return firstname and lastname in correct order
  7288. *
  7289. * @param string $firstname Firstname
  7290. * @param string $lastname Lastname
  7291. * @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
  7292. * @return string Firstname + lastname or Lastname + firstname
  7293. */
  7294. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7295. {
  7296. global $conf;
  7297. $ret = '';
  7298. // If order not defined, we use the setup
  7299. if ($nameorder < 0) {
  7300. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7301. }
  7302. if ($nameorder == 1) {
  7303. $ret .= $firstname;
  7304. if ($firstname && $lastname) {
  7305. $ret .= ' ';
  7306. }
  7307. $ret .= $lastname;
  7308. } elseif ($nameorder == 2 || $nameorder == 3) {
  7309. $ret .= $firstname;
  7310. if (empty($ret) && $nameorder == 3) {
  7311. $ret .= $lastname;
  7312. }
  7313. } else { // 0, 4 or 5
  7314. $ret .= $lastname;
  7315. if (empty($ret) && $nameorder == 5) {
  7316. $ret .= $firstname;
  7317. }
  7318. if ($nameorder == 0) {
  7319. if ($firstname && $lastname) {
  7320. $ret .= ' ';
  7321. }
  7322. $ret .= $firstname;
  7323. }
  7324. }
  7325. return $ret;
  7326. }
  7327. /**
  7328. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  7329. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7330. * Note: Prefer to use setEventMessages instead.
  7331. *
  7332. * @param string|string[] $mesgs Message string or array
  7333. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7334. * @return void
  7335. * @see dol_htmloutput_events()
  7336. */
  7337. function setEventMessage($mesgs, $style = 'mesgs')
  7338. {
  7339. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  7340. if (!is_array($mesgs)) {
  7341. // If mesgs is a string
  7342. if ($mesgs) {
  7343. $_SESSION['dol_events'][$style][] = $mesgs;
  7344. }
  7345. } else {
  7346. // If mesgs is an array
  7347. foreach ($mesgs as $mesg) {
  7348. if ($mesg) {
  7349. $_SESSION['dol_events'][$style][] = $mesg;
  7350. }
  7351. }
  7352. }
  7353. }
  7354. /**
  7355. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7356. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7357. *
  7358. * @param string $mesg Message string
  7359. * @param array $mesgs Message array
  7360. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7361. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7362. * @return void
  7363. * @see dol_htmloutput_events()
  7364. */
  7365. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  7366. {
  7367. if (empty($mesg) && empty($mesgs)) {
  7368. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  7369. } else {
  7370. if ($messagekey) {
  7371. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7372. // TODO
  7373. $mesg .= '';
  7374. }
  7375. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7376. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7377. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7378. }
  7379. if (empty($mesgs)) {
  7380. setEventMessage($mesg, $style);
  7381. } else {
  7382. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7383. setEventMessage($mesg, $style); // Add message string if not already into array
  7384. }
  7385. setEventMessage($mesgs, $style);
  7386. }
  7387. }
  7388. }
  7389. }
  7390. /**
  7391. * Print formated messages to output (Used to show messages on html output).
  7392. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7393. * no need to call it explicitely.
  7394. *
  7395. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7396. * @return void
  7397. * @see dol_htmloutput_mesg()
  7398. */
  7399. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7400. {
  7401. // Show mesgs
  7402. if (isset($_SESSION['dol_events']['mesgs'])) {
  7403. if (empty($disabledoutputofmessages)) {
  7404. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7405. }
  7406. unset($_SESSION['dol_events']['mesgs']);
  7407. }
  7408. // Show errors
  7409. if (isset($_SESSION['dol_events']['errors'])) {
  7410. if (empty($disabledoutputofmessages)) {
  7411. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7412. }
  7413. unset($_SESSION['dol_events']['errors']);
  7414. }
  7415. // Show warnings
  7416. if (isset($_SESSION['dol_events']['warnings'])) {
  7417. if (empty($disabledoutputofmessages)) {
  7418. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7419. }
  7420. unset($_SESSION['dol_events']['warnings']);
  7421. }
  7422. }
  7423. /**
  7424. * Get formated messages to output (Used to show messages on html output).
  7425. * This include also the translation of the message key.
  7426. *
  7427. * @param string $mesgstring Message string or message key
  7428. * @param string[] $mesgarray Array of message strings or message keys
  7429. * @param string $style Style of message output ('ok' or 'error')
  7430. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7431. * @return string Return html output
  7432. *
  7433. * @see dol_print_error()
  7434. * @see dol_htmloutput_errors()
  7435. * @see setEventMessages()
  7436. */
  7437. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7438. {
  7439. global $conf, $langs;
  7440. $ret = 0;
  7441. $return = '';
  7442. $out = '';
  7443. $divstart = $divend = '';
  7444. // If inline message with no format, we add it.
  7445. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7446. $divstart = '<div class="'.$style.' clearboth">';
  7447. $divend = '</div>';
  7448. }
  7449. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7450. $langs->load("errors");
  7451. $out .= $divstart;
  7452. if (is_array($mesgarray) && count($mesgarray)) {
  7453. foreach ($mesgarray as $message) {
  7454. $ret++;
  7455. $out .= $langs->trans($message);
  7456. if ($ret < count($mesgarray)) {
  7457. $out .= "<br>\n";
  7458. }
  7459. }
  7460. }
  7461. if ($mesgstring) {
  7462. $ret++;
  7463. $out .= $langs->trans($mesgstring);
  7464. }
  7465. $out .= $divend;
  7466. }
  7467. if ($out) {
  7468. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7469. $return = '<script>
  7470. $(document).ready(function() {
  7471. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7472. if (block) {
  7473. $.dolEventValid("","'.dol_escape_js($out).'");
  7474. } else {
  7475. /* jnotify(message, preset of message type, keepmessage) */
  7476. $.jnotify("'.dol_escape_js($out).'",
  7477. "'.($style == "ok" ? 3000 : $style).'",
  7478. '.($style == "ok" ? "false" : "true").',
  7479. { remove: function (){} } );
  7480. }
  7481. });
  7482. </script>';
  7483. } else {
  7484. $return = $out;
  7485. }
  7486. }
  7487. return $return;
  7488. }
  7489. /**
  7490. * Get formated error messages to output (Used to show messages on html output).
  7491. *
  7492. * @param string $mesgstring Error message
  7493. * @param array $mesgarray Error messages array
  7494. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7495. * @return string Return html output
  7496. *
  7497. * @see dol_print_error()
  7498. * @see dol_htmloutput_mesg()
  7499. */
  7500. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7501. {
  7502. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7503. }
  7504. /**
  7505. * Print formated messages to output (Used to show messages on html output).
  7506. *
  7507. * @param string $mesgstring Message string or message key
  7508. * @param string[] $mesgarray Array of message strings or message keys
  7509. * @param string $style Which style to use ('ok', 'warning', 'error')
  7510. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7511. * @return void
  7512. *
  7513. * @see dol_print_error()
  7514. * @see dol_htmloutput_errors()
  7515. * @see setEventMessages()
  7516. */
  7517. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7518. {
  7519. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7520. return;
  7521. }
  7522. $iserror = 0;
  7523. $iswarning = 0;
  7524. if (is_array($mesgarray)) {
  7525. foreach ($mesgarray as $val) {
  7526. if ($val && preg_match('/class="error"/i', $val)) {
  7527. $iserror++;
  7528. break;
  7529. }
  7530. if ($val && preg_match('/class="warning"/i', $val)) {
  7531. $iswarning++;
  7532. break;
  7533. }
  7534. }
  7535. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7536. $iserror++;
  7537. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7538. $iswarning++;
  7539. }
  7540. if ($style == 'error') {
  7541. $iserror++;
  7542. }
  7543. if ($style == 'warning') {
  7544. $iswarning++;
  7545. }
  7546. if ($iserror || $iswarning) {
  7547. // Remove div from texts
  7548. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7549. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7550. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7551. // Remove div from texts array
  7552. if (is_array($mesgarray)) {
  7553. $newmesgarray = array();
  7554. foreach ($mesgarray as $val) {
  7555. if (is_string($val)) {
  7556. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7557. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7558. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7559. $newmesgarray[] = $tmpmesgstring;
  7560. } else {
  7561. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7562. }
  7563. }
  7564. $mesgarray = $newmesgarray;
  7565. }
  7566. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7567. } else {
  7568. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7569. }
  7570. }
  7571. /**
  7572. * Print formated error messages to output (Used to show messages on html output).
  7573. *
  7574. * @param string $mesgstring Error message
  7575. * @param array $mesgarray Error messages array
  7576. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7577. * @return void
  7578. *
  7579. * @see dol_print_error()
  7580. * @see dol_htmloutput_mesg()
  7581. */
  7582. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7583. {
  7584. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7585. }
  7586. /**
  7587. * Advanced sort array by second index function, which produces ascending (default)
  7588. * or descending output and uses optionally natural case insensitive sorting (which
  7589. * can be optionally case sensitive as well).
  7590. *
  7591. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7592. * @param string $index Key in array to use for sorting criteria
  7593. * @param int $order Sort order ('asc' or 'desc')
  7594. * @param int $natsort 1=use "natural" sort (natsort) for a search criteria thats is strings or unknown, 0=use "standard" sort (asort) for numbers
  7595. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7596. * @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.
  7597. * @return array Sorted array
  7598. */
  7599. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7600. {
  7601. // Clean parameters
  7602. $order = strtolower($order);
  7603. if (is_array($array)) {
  7604. $sizearray = count($array);
  7605. if ($sizearray > 0) {
  7606. $temp = array();
  7607. foreach (array_keys($array) as $key) {
  7608. if (is_object($array[$key])) {
  7609. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7610. } else {
  7611. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7612. }
  7613. }
  7614. if (!$natsort) {
  7615. if ($order == 'asc') {
  7616. asort($temp);
  7617. } else {
  7618. arsort($temp);
  7619. }
  7620. } else {
  7621. if ($case_sensitive) {
  7622. natsort($temp);
  7623. } else {
  7624. natcasesort($temp); // natecasesort is not sensible to case
  7625. }
  7626. if ($order != 'asc') {
  7627. $temp = array_reverse($temp, true);
  7628. }
  7629. }
  7630. $sorted = array();
  7631. foreach (array_keys($temp) as $key) {
  7632. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7633. }
  7634. return $sorted;
  7635. }
  7636. }
  7637. return $array;
  7638. }
  7639. /**
  7640. * Check if a string is in UTF8
  7641. *
  7642. * @param string $str String to check
  7643. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7644. */
  7645. function utf8_check($str)
  7646. {
  7647. $str = (string) $str; // Sometimes string is an int.
  7648. // We must use here a binary strlen function (so not dol_strlen)
  7649. $strLength = dol_strlen($str);
  7650. for ($i = 0; $i < $strLength; $i++) {
  7651. if (ord($str[$i]) < 0x80) {
  7652. continue; // 0bbbbbbb
  7653. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7654. $n = 1; // 110bbbbb
  7655. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7656. $n = 2; // 1110bbbb
  7657. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7658. $n = 3; // 11110bbb
  7659. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7660. $n = 4; // 111110bb
  7661. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7662. $n = 5; // 1111110b
  7663. } else {
  7664. return false; // Does not match any model
  7665. }
  7666. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7667. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7668. return false;
  7669. }
  7670. }
  7671. }
  7672. return true;
  7673. }
  7674. /**
  7675. * Check if a string is in ASCII
  7676. *
  7677. * @param string $str String to check
  7678. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7679. */
  7680. function ascii_check($str)
  7681. {
  7682. if (function_exists('mb_check_encoding')) {
  7683. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7684. if (!mb_check_encoding($str, 'ASCII')) {
  7685. return false;
  7686. }
  7687. } else {
  7688. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7689. return false; // Contains a byte > 7f
  7690. }
  7691. }
  7692. return true;
  7693. }
  7694. /**
  7695. * Return a string encoded into OS filesystem encoding. This function is used to define
  7696. * value to pass to filesystem PHP functions.
  7697. *
  7698. * @param string $str String to encode (UTF-8)
  7699. * @return string Encoded string (UTF-8, ISO-8859-1)
  7700. */
  7701. function dol_osencode($str)
  7702. {
  7703. global $conf;
  7704. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7705. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7706. $tmp = 'iso-8859-1'; // By default for windows
  7707. }
  7708. if (empty($tmp)) {
  7709. $tmp = 'utf-8'; // By default for other
  7710. }
  7711. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7712. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7713. }
  7714. if ($tmp == 'iso-8859-1') {
  7715. return utf8_decode($str);
  7716. }
  7717. return $str;
  7718. }
  7719. /**
  7720. * Return an id or code from a code or id.
  7721. * Store also Code-Id into a cache to speed up next request on same key.
  7722. *
  7723. * @param DoliDB $db Database handler
  7724. * @param string $key Code or Id to get Id or Code
  7725. * @param string $tablename Table name without prefix
  7726. * @param string $fieldkey Field to search the key into
  7727. * @param string $fieldid Field to get
  7728. * @param int $entityfilter Filter by entity
  7729. * @param string $filters Filters to add. WARNING: string must be escaped for SQL and not coming from user input.
  7730. * @return int <0 if KO, Id of code if OK
  7731. * @see $langs->getLabelFromKey
  7732. */
  7733. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '')
  7734. {
  7735. global $cache_codes;
  7736. // If key empty
  7737. if ($key == '') {
  7738. return '';
  7739. }
  7740. // Check in cache
  7741. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  7742. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  7743. }
  7744. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  7745. $sql = "SELECT ".$fieldid." as valuetoget";
  7746. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  7747. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  7748. if (!empty($entityfilter)) {
  7749. $sql .= " AND entity IN (".getEntity($tablename).")";
  7750. }
  7751. if ($filters) {
  7752. $sql .= $filters;
  7753. }
  7754. $resql = $db->query($sql);
  7755. if ($resql) {
  7756. $obj = $db->fetch_object($resql);
  7757. if ($obj) {
  7758. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  7759. } else {
  7760. $cache_codes[$tablename][$key][$fieldid] = '';
  7761. }
  7762. $db->free($resql);
  7763. return $cache_codes[$tablename][$key][$fieldid];
  7764. } else {
  7765. return -1;
  7766. }
  7767. }
  7768. /**
  7769. * Verify if condition in string is ok or not
  7770. *
  7771. * @param string $strToEvaluate String with condition to check
  7772. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  7773. */
  7774. function verifCond($strToEvaluate)
  7775. {
  7776. global $user, $conf, $langs;
  7777. global $leftmenu;
  7778. global $rights; // To export to dol_eval function
  7779. //print $strToEvaluate."<br>\n";
  7780. $rights = true;
  7781. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  7782. //$str = 'if(!('.$strToEvaluate.')) $rights = false;';
  7783. //dol_eval($str, 0, 1, '2'); // The dol_eval must contains all the global $xxx used into a condition
  7784. //var_dump($strToEvaluate);
  7785. $rep = dol_eval($strToEvaluate, 1, 1, '1'); // The dol_eval must contains all the global $xxx for all variables $xxx found into the string condition
  7786. $rights = $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
  7787. //var_dump($rights);
  7788. }
  7789. return $rights;
  7790. }
  7791. /**
  7792. * Replace eval function to add more security.
  7793. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  7794. *
  7795. * @param string $s String to evaluate
  7796. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  7797. * @param int $hideerrors 1=Hide errors
  7798. * @param string $onlysimplestring 0=Accept all chars, 1=Accept only simple string with char 'a-z0-9\s^$_+-.*\/>&|=!?():"\',/';', 2=Accept also ';[]'
  7799. * @return mixed Nothing or return result of eval
  7800. */
  7801. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  7802. {
  7803. // Only global variables can be changed by eval function and returned to caller
  7804. global $db, $langs, $user, $conf, $website, $websitepage;
  7805. global $action, $mainmenu, $leftmenu;
  7806. global $mysoc;
  7807. global $objectoffield;
  7808. // Old variables used
  7809. global $rights;
  7810. global $object;
  7811. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  7812. global $soc; // For backward compatibility
  7813. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  7814. if ($onlysimplestring == '1') {
  7815. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL'
  7816. // We must accept: '$conf->barcode->enabled && preg_match(\'/^(AAA|BBB)/\',$leftmenu)'
  7817. // We must accept: '$user->rights->cabinetmed->read && $object->canvas=="patient@cabinetmed"'
  7818. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@', '/').']/i', $s)) {
  7819. if ($returnvalue) {
  7820. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  7821. } else {
  7822. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  7823. return '';
  7824. }
  7825. // TODO We can exclude all () that is not '($db)' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match('
  7826. // ...
  7827. }
  7828. } elseif ($onlysimplestring == '2') {
  7829. // We must accept: (($reloadedobj = new Task($db)) && ($reloadedobj->fetchNoCompute($object->id) > 0) && ($secondloadedobj = new Project($db)) && ($secondloadedobj->fetchNoCompute($reloadedobj->fk_project) > 0)) ? $secondloadedobj->ref : "Parent project not found"
  7830. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@;[]', '/').']/i', $s)) {
  7831. if ($returnvalue) {
  7832. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  7833. } else {
  7834. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  7835. return '';
  7836. }
  7837. }
  7838. }
  7839. if (is_array($s) || $s === 'Array') {
  7840. return 'Bad string syntax to evaluate (value is Array) '.var_export($s, true);
  7841. }
  7842. if (strpos($s, '::') !== false) {
  7843. if ($returnvalue) {
  7844. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  7845. } else {
  7846. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  7847. return '';
  7848. }
  7849. }
  7850. if (strpos($s, '`') !== false) {
  7851. if ($returnvalue) {
  7852. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  7853. } else {
  7854. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  7855. return '';
  7856. }
  7857. }
  7858. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  7859. if ($returnvalue) {
  7860. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  7861. } else {
  7862. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  7863. return '';
  7864. }
  7865. }
  7866. // We block use of php exec or php file functions
  7867. $forbiddenphpstrings = array('$$');
  7868. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  7869. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI", "verifCond", "base64_decode");
  7870. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  7871. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  7872. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  7873. do {
  7874. $oldstringtoclean = $s;
  7875. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  7876. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  7877. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  7878. } while ($oldstringtoclean != $s);
  7879. if (strpos($s, '__forbiddenstring__') !== false) {
  7880. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  7881. if ($returnvalue) {
  7882. return 'Bad string syntax to evaluate: '.$s;
  7883. } else {
  7884. dol_syslog('Bad string syntax to evaluate: '.$s);
  7885. return '';
  7886. }
  7887. }
  7888. //print $s."<br>\n";
  7889. if ($returnvalue) {
  7890. if ($hideerrors) {
  7891. return @eval('return '.$s.';');
  7892. } else {
  7893. return eval('return '.$s.';');
  7894. }
  7895. } else {
  7896. if ($hideerrors) {
  7897. @eval($s);
  7898. } else {
  7899. eval($s);
  7900. }
  7901. }
  7902. }
  7903. /**
  7904. * Return if var element is ok
  7905. *
  7906. * @param string $element Variable to check
  7907. * @return boolean Return true of variable is not empty
  7908. */
  7909. function dol_validElement($element)
  7910. {
  7911. return (trim($element) != '');
  7912. }
  7913. /**
  7914. * Return img flag of country for a language code or country code.
  7915. *
  7916. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  7917. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  7918. * @param int $notitlealt No title alt
  7919. * @return string HTML img string with flag.
  7920. */
  7921. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  7922. {
  7923. if (empty($codelang)) {
  7924. return '';
  7925. }
  7926. if ($codelang == 'auto') {
  7927. return '<span class="fa fa-language"></span>';
  7928. }
  7929. $langtocountryflag = array(
  7930. 'ar_AR' => '',
  7931. 'ca_ES' => 'catalonia',
  7932. 'da_DA' => 'dk',
  7933. 'fr_CA' => 'mq',
  7934. 'sv_SV' => 'se',
  7935. 'sw_SW' => 'unknown',
  7936. 'AQ' => 'unknown',
  7937. 'CW' => 'unknown',
  7938. 'IM' => 'unknown',
  7939. 'JE' => 'unknown',
  7940. 'MF' => 'unknown',
  7941. 'BL' => 'unknown',
  7942. 'SX' => 'unknown'
  7943. );
  7944. if (isset($langtocountryflag[$codelang])) {
  7945. $flagImage = $langtocountryflag[$codelang];
  7946. } else {
  7947. $tmparray = explode('_', $codelang);
  7948. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  7949. }
  7950. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  7951. }
  7952. /**
  7953. * Return default language from country code.
  7954. * Return null if not found.
  7955. *
  7956. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  7957. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  7958. */
  7959. function getLanguageCodeFromCountryCode($countrycode)
  7960. {
  7961. global $mysoc;
  7962. if (empty($countrycode)) {
  7963. return null;
  7964. }
  7965. if (strtoupper($countrycode) == 'MQ') {
  7966. return 'fr_CA';
  7967. }
  7968. if (strtoupper($countrycode) == 'SE') {
  7969. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  7970. }
  7971. if (strtoupper($countrycode) == 'CH') {
  7972. if ($mysoc->country_code == 'FR') {
  7973. return 'fr_CH';
  7974. }
  7975. if ($mysoc->country_code == 'DE') {
  7976. return 'de_CH';
  7977. }
  7978. if ($mysoc->country_code == 'IT') {
  7979. return 'it_CH';
  7980. }
  7981. }
  7982. // Locale list taken from:
  7983. // http://stackoverflow.com/questions/3191664/
  7984. // list-of-all-locales-and-their-short-codes
  7985. $locales = array(
  7986. 'af-ZA',
  7987. 'am-ET',
  7988. 'ar-AE',
  7989. 'ar-BH',
  7990. 'ar-DZ',
  7991. 'ar-EG',
  7992. 'ar-IQ',
  7993. 'ar-JO',
  7994. 'ar-KW',
  7995. 'ar-LB',
  7996. 'ar-LY',
  7997. 'ar-MA',
  7998. 'ar-OM',
  7999. 'ar-QA',
  8000. 'ar-SA',
  8001. 'ar-SY',
  8002. 'ar-TN',
  8003. 'ar-YE',
  8004. //'as-IN', // Moved after en-IN
  8005. 'ba-RU',
  8006. 'be-BY',
  8007. 'bg-BG',
  8008. 'bn-BD',
  8009. //'bn-IN', // Moved after en-IN
  8010. 'bo-CN',
  8011. 'br-FR',
  8012. 'ca-ES',
  8013. 'co-FR',
  8014. 'cs-CZ',
  8015. 'cy-GB',
  8016. 'da-DK',
  8017. 'de-AT',
  8018. 'de-CH',
  8019. 'de-DE',
  8020. 'de-LI',
  8021. 'de-LU',
  8022. 'dv-MV',
  8023. 'el-GR',
  8024. 'en-AU',
  8025. 'en-BZ',
  8026. 'en-CA',
  8027. 'en-GB',
  8028. 'en-IE',
  8029. 'en-IN',
  8030. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  8031. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  8032. 'en-JM',
  8033. 'en-MY',
  8034. 'en-NZ',
  8035. 'en-PH',
  8036. 'en-SG',
  8037. 'en-TT',
  8038. 'en-US',
  8039. 'en-ZA',
  8040. 'en-ZW',
  8041. 'es-AR',
  8042. 'es-BO',
  8043. 'es-CL',
  8044. 'es-CO',
  8045. 'es-CR',
  8046. 'es-DO',
  8047. 'es-EC',
  8048. 'es-ES',
  8049. 'es-GT',
  8050. 'es-HN',
  8051. 'es-MX',
  8052. 'es-NI',
  8053. 'es-PA',
  8054. 'es-PE',
  8055. 'es-PR',
  8056. 'es-PY',
  8057. 'es-SV',
  8058. 'es-US',
  8059. 'es-UY',
  8060. 'es-VE',
  8061. 'et-EE',
  8062. 'eu-ES',
  8063. 'fa-IR',
  8064. 'fi-FI',
  8065. 'fo-FO',
  8066. 'fr-BE',
  8067. 'fr-CA',
  8068. 'fr-CH',
  8069. 'fr-FR',
  8070. 'fr-LU',
  8071. 'fr-MC',
  8072. 'fy-NL',
  8073. 'ga-IE',
  8074. 'gd-GB',
  8075. 'gl-ES',
  8076. 'gu-IN',
  8077. 'he-IL',
  8078. 'hi-IN',
  8079. 'hr-BA',
  8080. 'hr-HR',
  8081. 'hu-HU',
  8082. 'hy-AM',
  8083. 'id-ID',
  8084. 'ig-NG',
  8085. 'ii-CN',
  8086. 'is-IS',
  8087. 'it-CH',
  8088. 'it-IT',
  8089. 'ja-JP',
  8090. 'ka-GE',
  8091. 'kk-KZ',
  8092. 'kl-GL',
  8093. 'km-KH',
  8094. 'kn-IN',
  8095. 'ko-KR',
  8096. 'ky-KG',
  8097. 'lb-LU',
  8098. 'lo-LA',
  8099. 'lt-LT',
  8100. 'lv-LV',
  8101. 'mi-NZ',
  8102. 'mk-MK',
  8103. 'ml-IN',
  8104. 'mn-MN',
  8105. 'mr-IN',
  8106. 'ms-BN',
  8107. 'ms-MY',
  8108. 'mt-MT',
  8109. 'nb-NO',
  8110. 'ne-NP',
  8111. 'nl-BE',
  8112. 'nl-NL',
  8113. 'nn-NO',
  8114. 'oc-FR',
  8115. 'or-IN',
  8116. 'pa-IN',
  8117. 'pl-PL',
  8118. 'ps-AF',
  8119. 'pt-BR',
  8120. 'pt-PT',
  8121. 'rm-CH',
  8122. 'ro-MD',
  8123. 'ro-RO',
  8124. 'ru-RU',
  8125. 'rw-RW',
  8126. 'sa-IN',
  8127. 'se-FI',
  8128. 'se-NO',
  8129. 'se-SE',
  8130. 'si-LK',
  8131. 'sk-SK',
  8132. 'sl-SI',
  8133. 'sq-AL',
  8134. 'sv-FI',
  8135. 'sv-SE',
  8136. 'sw-KE',
  8137. 'ta-IN',
  8138. 'te-IN',
  8139. 'th-TH',
  8140. 'tk-TM',
  8141. 'tn-ZA',
  8142. 'tr-TR',
  8143. 'tt-RU',
  8144. 'ug-CN',
  8145. 'uk-UA',
  8146. 'ur-PK',
  8147. 'vi-VN',
  8148. 'wo-SN',
  8149. 'xh-ZA',
  8150. 'yo-NG',
  8151. 'zh-CN',
  8152. 'zh-HK',
  8153. 'zh-MO',
  8154. 'zh-SG',
  8155. 'zh-TW',
  8156. 'zu-ZA',
  8157. );
  8158. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  8159. if (in_array($buildprimarykeytotest, $locales)) {
  8160. return strtolower($countrycode).'_'.strtoupper($countrycode);
  8161. }
  8162. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  8163. foreach ($locales as $locale) {
  8164. $locale_language = locale_get_primary_language($locale);
  8165. $locale_region = locale_get_region($locale);
  8166. if (strtoupper($countrycode) == $locale_region) {
  8167. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  8168. return strtolower($locale_language).'_'.strtoupper($locale_region);
  8169. }
  8170. }
  8171. } else {
  8172. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  8173. }
  8174. return null;
  8175. }
  8176. /**
  8177. * Complete or removed entries into a head array (used to build tabs).
  8178. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  8179. * Or by change using hook completeTabsHead
  8180. *
  8181. * @param Conf $conf Object conf
  8182. * @param Translate $langs Object langs
  8183. * @param object|null $object Object object
  8184. * @param array $head Object head
  8185. * @param int $h New position to fill
  8186. * @param string $type Value for object where objectvalue can be
  8187. * 'thirdparty' to add a tab in third party view
  8188. * 'intervention' to add a tab in intervention view
  8189. * 'supplier_order' to add a tab in supplier order view
  8190. * 'supplier_invoice' to add a tab in supplier invoice view
  8191. * 'invoice' to add a tab in customer invoice view
  8192. * 'order' to add a tab in customer order view
  8193. * 'contract' to add a tabl in contract view
  8194. * 'product' to add a tab in product view
  8195. * 'propal' to add a tab in propal view
  8196. * 'user' to add a tab in user view
  8197. * 'group' to add a tab in group view
  8198. * 'member' to add a tab in fundation member view
  8199. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  8200. * 'ecm' to add a tab for another ecm view
  8201. * 'stock' to add a tab for warehouse view
  8202. * @param string $mode 'add' to complete head, 'remove' to remove entries
  8203. * @return void
  8204. */
  8205. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  8206. {
  8207. global $hookmanager, $db;
  8208. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  8209. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  8210. $values = explode(':', $value);
  8211. $reg = array();
  8212. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  8213. if (count($values) == 6) {
  8214. // new declaration with permissions:
  8215. // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8216. // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8217. if ($values[0] != $type) {
  8218. continue;
  8219. }
  8220. //var_dump(verifCond($values[4]));
  8221. if (verifCond($values[4])) {
  8222. if ($values[3]) {
  8223. $langs->load($values[3]);
  8224. }
  8225. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8226. $substitutionarray = array();
  8227. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8228. $label = make_substitutions($reg[1], $substitutionarray);
  8229. } else {
  8230. $labeltemp = explode(',', $values[2]);
  8231. $label = $langs->trans($labeltemp[0]);
  8232. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  8233. dol_include_once($labeltemp[2]);
  8234. $classtoload = $labeltemp[1];
  8235. if (class_exists($classtoload)) {
  8236. $obj = new $classtoload($db);
  8237. $function = $labeltemp[3];
  8238. if ($obj && $function && method_exists($obj, $function)) {
  8239. $nbrec = $obj->$function($object->id, $obj);
  8240. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  8241. }
  8242. }
  8243. }
  8244. }
  8245. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  8246. $head[$h][1] = $label;
  8247. $head[$h][2] = str_replace('+', '', $values[1]);
  8248. $h++;
  8249. }
  8250. } elseif (count($values) == 5) { // deprecated
  8251. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  8252. if ($values[0] != $type) {
  8253. continue;
  8254. }
  8255. if ($values[3]) {
  8256. $langs->load($values[3]);
  8257. }
  8258. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8259. $substitutionarray = array();
  8260. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8261. $label = make_substitutions($reg[1], $substitutionarray);
  8262. } else {
  8263. $label = $langs->trans($values[2]);
  8264. }
  8265. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  8266. $head[$h][1] = $label;
  8267. $head[$h][2] = str_replace('+', '', $values[1]);
  8268. $h++;
  8269. }
  8270. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  8271. if ($values[0] != $type) {
  8272. continue;
  8273. }
  8274. $tabname = str_replace('-', '', $values[1]);
  8275. foreach ($head as $key => $val) {
  8276. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  8277. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  8278. if ($head[$key][2] == $tabname && $condition) {
  8279. unset($head[$key]);
  8280. break;
  8281. }
  8282. }
  8283. }
  8284. }
  8285. }
  8286. // No need to make a return $head. Var is modified as a reference
  8287. if (!empty($hookmanager)) {
  8288. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head);
  8289. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  8290. if ($reshook > 0) { // Hook ask to replace completely the array
  8291. $head = $hookmanager->resArray;
  8292. } else { // Hook
  8293. $head = array_merge($head, $hookmanager->resArray);
  8294. }
  8295. $h = count($head);
  8296. }
  8297. }
  8298. /**
  8299. * Print common footer :
  8300. * conf->global->MAIN_HTML_FOOTER
  8301. * js for switch of menu hider
  8302. * js for conf->global->MAIN_GOOGLE_AN_ID
  8303. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  8304. * js for conf->logbuffer
  8305. *
  8306. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  8307. * @return void
  8308. */
  8309. function printCommonFooter($zone = 'private')
  8310. {
  8311. global $conf, $hookmanager, $user, $debugbar;
  8312. global $action;
  8313. global $micro_start_time;
  8314. if ($zone == 'private') {
  8315. print "\n".'<!-- Common footer for private page -->'."\n";
  8316. } else {
  8317. print "\n".'<!-- Common footer for public page -->'."\n";
  8318. }
  8319. // A div to store page_y POST parameter so we can read it using javascript
  8320. print "\n<!-- A div to store page_y POST parameter -->\n";
  8321. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  8322. $parameters = array();
  8323. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  8324. if (empty($reshook)) {
  8325. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  8326. print $conf->global->MAIN_HTML_FOOTER."\n";
  8327. }
  8328. print "\n";
  8329. if (!empty($conf->use_javascript_ajax)) {
  8330. print '<script>'."\n";
  8331. print 'jQuery(document).ready(function() {'."\n";
  8332. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  8333. print "\n";
  8334. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  8335. print 'jQuery("li.menuhider").click(function(event) {';
  8336. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  8337. print ' console.log("We click on .menuhider");'."\n";
  8338. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  8339. print '});'."\n";
  8340. }
  8341. // Management of focus and mandatory for fields
  8342. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  8343. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  8344. $relativepathstring = $_SERVER["PHP_SELF"];
  8345. // Clean $relativepathstring
  8346. if (constant('DOL_URL_ROOT')) {
  8347. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  8348. }
  8349. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  8350. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  8351. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  8352. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  8353. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  8354. $qualified = 0;
  8355. if ($defkey != '_noquery_') {
  8356. $tmpqueryarraytohave = explode('&', $defkey);
  8357. $foundintru = 0;
  8358. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8359. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8360. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8361. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8362. $foundintru = 1;
  8363. }
  8364. }
  8365. if (!$foundintru) {
  8366. $qualified = 1;
  8367. }
  8368. //var_dump($defkey.'-'.$qualified);
  8369. } else {
  8370. $qualified = 1;
  8371. }
  8372. if ($qualified) {
  8373. foreach ($defval as $paramkey => $paramval) {
  8374. // Set focus on field
  8375. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  8376. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  8377. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  8378. }
  8379. }
  8380. }
  8381. }
  8382. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  8383. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  8384. $qualified = 0;
  8385. if ($defkey != '_noquery_') {
  8386. $tmpqueryarraytohave = explode('&', $defkey);
  8387. $foundintru = 0;
  8388. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8389. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8390. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8391. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8392. $foundintru = 1;
  8393. }
  8394. }
  8395. if (!$foundintru) {
  8396. $qualified = 1;
  8397. }
  8398. //var_dump($defkey.'-'.$qualified);
  8399. } else {
  8400. $qualified = 1;
  8401. }
  8402. if ($qualified) {
  8403. foreach ($defval as $paramkey => $paramval) {
  8404. // Add property 'required' on input
  8405. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8406. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8407. 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";
  8408. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8409. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  8410. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  8411. // Add 'field required' class on closest td for all input elements : input, textarea and select
  8412. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  8413. }
  8414. }
  8415. }
  8416. }
  8417. }
  8418. print '});'."\n";
  8419. // End of tuning
  8420. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  8421. print "\n";
  8422. print "/* JS CODE TO ENABLE to add memory info */\n";
  8423. print 'window.console && console.log("';
  8424. if (!empty($conf->global->MEMCACHED_SERVER)) {
  8425. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  8426. }
  8427. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  8428. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  8429. $micro_end_time = microtime(true);
  8430. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  8431. }
  8432. if (function_exists("memory_get_usage")) {
  8433. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  8434. }
  8435. if (function_exists("memory_get_peak_usage")) {
  8436. print ' - Real mem peak: '.memory_get_peak_usage(true);
  8437. }
  8438. if (function_exists("zend_loader_file_encoded")) {
  8439. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8440. }
  8441. print '");'."\n";
  8442. }
  8443. print "\n".'</script>'."\n";
  8444. // Google Analytics
  8445. // TODO Add a hook here
  8446. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8447. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8448. foreach ($tmptagarray as $tmptag) {
  8449. print "\n";
  8450. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8451. print "
  8452. <!-- Global site tag (gtag.js) - Google Analytics -->
  8453. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  8454. <script>
  8455. window.dataLayer = window.dataLayer || [];
  8456. function gtag(){dataLayer.push(arguments);}
  8457. gtag('js', new Date());
  8458. gtag('config', '".trim($tmptag)."');
  8459. </script>";
  8460. print "\n";
  8461. }
  8462. }
  8463. }
  8464. // Add Xdebug coverage of code
  8465. if (defined('XDEBUGCOVERAGE')) {
  8466. print_r(xdebug_get_code_coverage());
  8467. }
  8468. // Add DebugBar data
  8469. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8470. $debugbar['time']->stopMeasure('pageaftermaster');
  8471. print '<!-- Output debugbar data -->'."\n";
  8472. $renderer = $debugbar->getRenderer();
  8473. print $debugbar->getRenderer()->render();
  8474. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8475. print "\n";
  8476. print "<!-- Start of log output\n";
  8477. //print '<div class="hidden">'."\n";
  8478. foreach ($conf->logbuffer as $logline) {
  8479. print $logline."<br>\n";
  8480. }
  8481. //print '</div>'."\n";
  8482. print "End of log output -->\n";
  8483. }
  8484. }
  8485. }
  8486. /**
  8487. * Split a string with 2 keys into key array.
  8488. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8489. *
  8490. * @param string $string String to explode
  8491. * @param string $delimiter Delimiter between each couple of data
  8492. * @param string $kv Delimiter between key and value
  8493. * @return array Array of data exploded
  8494. */
  8495. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8496. {
  8497. if ($a = explode($delimiter, $string)) {
  8498. $ka = array();
  8499. foreach ($a as $s) { // each part
  8500. if ($s) {
  8501. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8502. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8503. } else { // key delimiter not found
  8504. $ka[] = trim($s);
  8505. }
  8506. }
  8507. }
  8508. return $ka;
  8509. }
  8510. return array();
  8511. }
  8512. /**
  8513. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  8514. *
  8515. * @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.
  8516. * @return void
  8517. */
  8518. function dol_set_focus($selector)
  8519. {
  8520. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8521. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8522. }
  8523. /**
  8524. * Return getmypid() or random PID when function is disabled
  8525. * Some web hosts disable this php function for security reasons
  8526. * and sometimes we can't redeclare function
  8527. *
  8528. * @return int
  8529. */
  8530. function dol_getmypid()
  8531. {
  8532. if (!function_exists('getmypid')) {
  8533. return mt_rand(1, 32768);
  8534. } else {
  8535. return getmypid();
  8536. }
  8537. }
  8538. /**
  8539. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8540. *
  8541. * @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")
  8542. * @param string $value The value to look for.
  8543. * If param $mode is 0, can contains several keywords separated with a space or |
  8544. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8545. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8546. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8547. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8548. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8549. * @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')
  8550. * 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'
  8551. * @param integer $nofirstand 1=Do not output the first 'AND'
  8552. * @return string $res The statement to append to the SQL query
  8553. * @see dolSqlDateFilter()
  8554. */
  8555. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8556. {
  8557. global $db, $langs;
  8558. $value = trim($value);
  8559. if ($mode == 0) {
  8560. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8561. }
  8562. if ($mode == 1) {
  8563. $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
  8564. }
  8565. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8566. $crits = explode(' ', $value);
  8567. $res = '';
  8568. if (!is_array($fields)) {
  8569. $fields = array($fields);
  8570. }
  8571. $j = 0;
  8572. foreach ($crits as $crit) {
  8573. $crit = trim($crit);
  8574. $i = 0;
  8575. $i2 = 0;
  8576. $newres = '';
  8577. foreach ($fields as $field) {
  8578. if ($mode == 1) {
  8579. $operator = '=';
  8580. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8581. $reg = array();
  8582. preg_match('/([<>=]+)/', $crit, $reg);
  8583. if (!empty($reg[1])) {
  8584. $operator = $reg[1];
  8585. }
  8586. if ($newcrit != '') {
  8587. $numnewcrit = price2num($newcrit);
  8588. if (is_numeric($numnewcrit)) {
  8589. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  8590. } else {
  8591. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8592. }
  8593. $i2++; // a criteria was added to string
  8594. }
  8595. } elseif ($mode == 2 || $mode == -2) {
  8596. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8597. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8598. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8599. if ($mode == -2) {
  8600. $newres .= ' OR '.$field.' IS NULL';
  8601. }
  8602. $i2++; // a criteria was added to string
  8603. } elseif ($mode == 3 || $mode == -3) {
  8604. $tmparray = explode(',', $crit);
  8605. if (count($tmparray)) {
  8606. $listofcodes = '';
  8607. foreach ($tmparray as $val) {
  8608. $val = trim($val);
  8609. if ($val) {
  8610. $listofcodes .= ($listofcodes ? ',' : '');
  8611. $listofcodes .= "'".$db->escape($val)."'";
  8612. }
  8613. }
  8614. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8615. $i2++; // a criteria was added to string
  8616. }
  8617. if ($mode == -3) {
  8618. $newres .= ' OR '.$field.' IS NULL';
  8619. }
  8620. } elseif ($mode == 4) {
  8621. $tmparray = explode(',', $crit);
  8622. if (count($tmparray)) {
  8623. $listofcodes = '';
  8624. foreach ($tmparray as $val) {
  8625. $val = trim($val);
  8626. if ($val) {
  8627. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8628. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8629. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8630. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8631. $newres .= ')';
  8632. $i2++;
  8633. }
  8634. }
  8635. }
  8636. } else // $mode=0
  8637. {
  8638. $tmpcrits = explode('|', $crit);
  8639. $i3 = 0;
  8640. foreach ($tmpcrits as $tmpcrit) {
  8641. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8642. continue;
  8643. }
  8644. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8645. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8646. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? ((float) trim($tmpcrit)) : '0');
  8647. } else {
  8648. $tmpcrit = trim($tmpcrit);
  8649. $tmpcrit2 = $tmpcrit;
  8650. $tmpbefore = '%';
  8651. $tmpafter = '%';
  8652. if (preg_match('/^!/', $tmpcrit)) {
  8653. $newres .= $field." NOT LIKE '"; // ! as exclude character
  8654. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  8655. } else $newres .= $field." LIKE '";
  8656. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8657. $tmpbefore = '';
  8658. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8659. }
  8660. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8661. $tmpafter = '';
  8662. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8663. }
  8664. $newres .= $tmpbefore;
  8665. $newres .= $db->escape($tmpcrit2);
  8666. $newres .= $tmpafter;
  8667. $newres .= "'";
  8668. if ($tmpcrit2 == '') {
  8669. $newres .= " OR ".$field." IS NULL";
  8670. }
  8671. }
  8672. $i3++;
  8673. }
  8674. $i2++; // a criteria was added to string
  8675. }
  8676. $i++;
  8677. }
  8678. if ($newres) {
  8679. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8680. }
  8681. $j++;
  8682. }
  8683. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8684. //print 'xx'.$res.'yy';
  8685. return $res;
  8686. }
  8687. /**
  8688. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8689. *
  8690. * @param Object $object Object
  8691. * @return string Url string
  8692. */
  8693. function showDirectDownloadLink($object)
  8694. {
  8695. global $conf, $langs;
  8696. $out = '';
  8697. $url = $object->getLastMainDocLink($object->element);
  8698. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8699. if ($url) {
  8700. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8701. $out .= ajax_autoselect("directdownloadlink", 0);
  8702. } else {
  8703. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8704. }
  8705. return $out;
  8706. }
  8707. /**
  8708. * Return the filename of file to get the thumbs
  8709. *
  8710. * @param string $file Original filename (full or relative path)
  8711. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8712. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8713. * @return string New file name (full or relative path, including the thumbs/)
  8714. */
  8715. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  8716. {
  8717. $dirName = dirname($file);
  8718. if ($dirName == '.') {
  8719. $dirName = '';
  8720. }
  8721. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  8722. $fileName = basename($fileName);
  8723. if (empty($extImgTarget)) {
  8724. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  8725. }
  8726. if (empty($extImgTarget)) {
  8727. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  8728. }
  8729. if (empty($extImgTarget)) {
  8730. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  8731. }
  8732. if (empty($extImgTarget)) {
  8733. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  8734. }
  8735. if (empty($extImgTarget)) {
  8736. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  8737. }
  8738. if (empty($extImgTarget)) {
  8739. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  8740. }
  8741. if (!$extImgTarget) {
  8742. return $file;
  8743. }
  8744. $subdir = '';
  8745. if ($extName) {
  8746. $subdir = 'thumbs/';
  8747. }
  8748. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  8749. }
  8750. /**
  8751. * Return URL we can use for advanced preview links
  8752. *
  8753. * @param string $modulepart propal, facture, facture_fourn, ...
  8754. * @param string $relativepath Relative path of docs.
  8755. * @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)
  8756. * @param string $param More param on http links
  8757. * @return string|array Output string with href link or array with all components of link
  8758. */
  8759. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  8760. {
  8761. global $conf, $langs;
  8762. if (empty($conf->use_javascript_ajax)) {
  8763. return '';
  8764. }
  8765. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  8766. if ($alldata == 1) {
  8767. if ($isAllowedForPreview) {
  8768. 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));
  8769. } else {
  8770. return array();
  8771. }
  8772. }
  8773. // old behavior, return a string
  8774. if ($isAllowedForPreview) {
  8775. 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')).'\')';
  8776. } else {
  8777. return '';
  8778. }
  8779. }
  8780. /**
  8781. * Make content of an input box selected when we click into input field.
  8782. *
  8783. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  8784. * @param string $addlink Add a 'link to' after
  8785. * @param string $textonlink Text to show on link or 'image'
  8786. * @return string
  8787. */
  8788. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  8789. {
  8790. global $langs;
  8791. $out = '<script>
  8792. jQuery(document).ready(function () {
  8793. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  8794. });
  8795. </script>';
  8796. if ($addlink) {
  8797. if ($textonlink === 'image') {
  8798. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  8799. } else {
  8800. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  8801. }
  8802. }
  8803. return $out;
  8804. }
  8805. /**
  8806. * Return if a file is qualified for preview
  8807. *
  8808. * @param string $file Filename we looking for information
  8809. * @return int 1 If allowed, 0 otherwise
  8810. * @see dol_mimetype(), image_format_supported() from images.lib.php
  8811. */
  8812. function dolIsAllowedForPreview($file)
  8813. {
  8814. global $conf;
  8815. // Check .noexe extension in filename
  8816. if (preg_match('/\.noexe$/i', $file)) {
  8817. return 0;
  8818. }
  8819. // Check mime types
  8820. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  8821. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  8822. $mime_preview[] = 'svg+xml';
  8823. }
  8824. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  8825. //$mime_preview[]='archive';
  8826. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  8827. if ($num_mime !== false) {
  8828. return 1;
  8829. }
  8830. // By default, not allowed for preview
  8831. return 0;
  8832. }
  8833. /**
  8834. * Return MIME type of a file from its name with extension.
  8835. *
  8836. * @param string $file Filename we looking for MIME type
  8837. * @param string $default Default mime type if extension not found in known list
  8838. * @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
  8839. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  8840. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  8841. */
  8842. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  8843. {
  8844. $mime = $default;
  8845. $imgmime = 'other.png';
  8846. $famime = 'file-o';
  8847. $srclang = '';
  8848. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  8849. // Plain text files
  8850. if (preg_match('/\.txt$/i', $tmpfile)) {
  8851. $mime = 'text/plain';
  8852. $imgmime = 'text.png';
  8853. $famime = 'file-text-o';
  8854. }
  8855. if (preg_match('/\.rtx$/i', $tmpfile)) {
  8856. $mime = 'text/richtext';
  8857. $imgmime = 'text.png';
  8858. $famime = 'file-text-o';
  8859. }
  8860. if (preg_match('/\.csv$/i', $tmpfile)) {
  8861. $mime = 'text/csv';
  8862. $imgmime = 'text.png';
  8863. $famime = 'file-text-o';
  8864. }
  8865. if (preg_match('/\.tsv$/i', $tmpfile)) {
  8866. $mime = 'text/tab-separated-values';
  8867. $imgmime = 'text.png';
  8868. $famime = 'file-text-o';
  8869. }
  8870. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  8871. $mime = 'text/plain';
  8872. $imgmime = 'text.png';
  8873. $famime = 'file-text-o';
  8874. }
  8875. if (preg_match('/\.ini$/i', $tmpfile)) {
  8876. $mime = 'text/plain';
  8877. $imgmime = 'text.png';
  8878. $srclang = 'ini';
  8879. $famime = 'file-text-o';
  8880. }
  8881. if (preg_match('/\.md$/i', $tmpfile)) {
  8882. $mime = 'text/plain';
  8883. $imgmime = 'text.png';
  8884. $srclang = 'md';
  8885. $famime = 'file-text-o';
  8886. }
  8887. if (preg_match('/\.css$/i', $tmpfile)) {
  8888. $mime = 'text/css';
  8889. $imgmime = 'css.png';
  8890. $srclang = 'css';
  8891. $famime = 'file-text-o';
  8892. }
  8893. if (preg_match('/\.lang$/i', $tmpfile)) {
  8894. $mime = 'text/plain';
  8895. $imgmime = 'text.png';
  8896. $srclang = 'lang';
  8897. $famime = 'file-text-o';
  8898. }
  8899. // Certificate files
  8900. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  8901. $mime = 'text/plain';
  8902. $imgmime = 'text.png';
  8903. $famime = 'file-text-o';
  8904. }
  8905. // XML based (HTML/XML/XAML)
  8906. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  8907. $mime = 'text/html';
  8908. $imgmime = 'html.png';
  8909. $srclang = 'html';
  8910. $famime = 'file-text-o';
  8911. }
  8912. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  8913. $mime = 'text/xml';
  8914. $imgmime = 'other.png';
  8915. $srclang = 'xml';
  8916. $famime = 'file-text-o';
  8917. }
  8918. if (preg_match('/\.xaml$/i', $tmpfile)) {
  8919. $mime = 'text/xml';
  8920. $imgmime = 'other.png';
  8921. $srclang = 'xaml';
  8922. $famime = 'file-text-o';
  8923. }
  8924. // Languages
  8925. if (preg_match('/\.bas$/i', $tmpfile)) {
  8926. $mime = 'text/plain';
  8927. $imgmime = 'text.png';
  8928. $srclang = 'bas';
  8929. $famime = 'file-code-o';
  8930. }
  8931. if (preg_match('/\.(c)$/i', $tmpfile)) {
  8932. $mime = 'text/plain';
  8933. $imgmime = 'text.png';
  8934. $srclang = 'c';
  8935. $famime = 'file-code-o';
  8936. }
  8937. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  8938. $mime = 'text/plain';
  8939. $imgmime = 'text.png';
  8940. $srclang = 'cpp';
  8941. $famime = 'file-code-o';
  8942. }
  8943. if (preg_match('/\.cs$/i', $tmpfile)) {
  8944. $mime = 'text/plain';
  8945. $imgmime = 'text.png';
  8946. $srclang = 'cs';
  8947. $famime = 'file-code-o';
  8948. }
  8949. if (preg_match('/\.(h)$/i', $tmpfile)) {
  8950. $mime = 'text/plain';
  8951. $imgmime = 'text.png';
  8952. $srclang = 'h';
  8953. $famime = 'file-code-o';
  8954. }
  8955. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  8956. $mime = 'text/plain';
  8957. $imgmime = 'text.png';
  8958. $srclang = 'java';
  8959. $famime = 'file-code-o';
  8960. }
  8961. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  8962. $mime = 'text/plain';
  8963. $imgmime = 'php.png';
  8964. $srclang = 'php';
  8965. $famime = 'file-code-o';
  8966. }
  8967. if (preg_match('/\.phtml$/i', $tmpfile)) {
  8968. $mime = 'text/plain';
  8969. $imgmime = 'php.png';
  8970. $srclang = 'php';
  8971. $famime = 'file-code-o';
  8972. }
  8973. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  8974. $mime = 'text/plain';
  8975. $imgmime = 'pl.png';
  8976. $srclang = 'perl';
  8977. $famime = 'file-code-o';
  8978. }
  8979. if (preg_match('/\.sql$/i', $tmpfile)) {
  8980. $mime = 'text/plain';
  8981. $imgmime = 'text.png';
  8982. $srclang = 'sql';
  8983. $famime = 'file-code-o';
  8984. }
  8985. if (preg_match('/\.js$/i', $tmpfile)) {
  8986. $mime = 'text/x-javascript';
  8987. $imgmime = 'jscript.png';
  8988. $srclang = 'js';
  8989. $famime = 'file-code-o';
  8990. }
  8991. // Open office
  8992. if (preg_match('/\.odp$/i', $tmpfile)) {
  8993. $mime = 'application/vnd.oasis.opendocument.presentation';
  8994. $imgmime = 'ooffice.png';
  8995. $famime = 'file-powerpoint-o';
  8996. }
  8997. if (preg_match('/\.ods$/i', $tmpfile)) {
  8998. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  8999. $imgmime = 'ooffice.png';
  9000. $famime = 'file-excel-o';
  9001. }
  9002. if (preg_match('/\.odt$/i', $tmpfile)) {
  9003. $mime = 'application/vnd.oasis.opendocument.text';
  9004. $imgmime = 'ooffice.png';
  9005. $famime = 'file-word-o';
  9006. }
  9007. // MS Office
  9008. if (preg_match('/\.mdb$/i', $tmpfile)) {
  9009. $mime = 'application/msaccess';
  9010. $imgmime = 'mdb.png';
  9011. $famime = 'file-o';
  9012. }
  9013. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) {
  9014. $mime = 'application/msword';
  9015. $imgmime = 'doc.png';
  9016. $famime = 'file-word-o';
  9017. }
  9018. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) {
  9019. $mime = 'application/msword';
  9020. $imgmime = 'doc.png';
  9021. $famime = 'file-word-o';
  9022. }
  9023. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  9024. $mime = 'application/vnd.ms-excel';
  9025. $imgmime = 'xls.png';
  9026. $famime = 'file-excel-o';
  9027. }
  9028. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  9029. $mime = 'application/vnd.ms-excel';
  9030. $imgmime = 'xls.png';
  9031. $famime = 'file-excel-o';
  9032. }
  9033. if (preg_match('/\.xls$/i', $tmpfile)) {
  9034. $mime = 'application/vnd.ms-excel';
  9035. $imgmime = 'xls.png';
  9036. $famime = 'file-excel-o';
  9037. }
  9038. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) {
  9039. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  9040. $imgmime = 'xls.png';
  9041. $famime = 'file-excel-o';
  9042. }
  9043. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) {
  9044. $mime = 'application/vnd.ms-powerpoint';
  9045. $imgmime = 'ppt.png';
  9046. $famime = 'file-powerpoint-o';
  9047. }
  9048. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) {
  9049. $mime = 'application/x-mspowerpoint';
  9050. $imgmime = 'ppt.png';
  9051. $famime = 'file-powerpoint-o';
  9052. }
  9053. // Other
  9054. if (preg_match('/\.pdf$/i', $tmpfile)) {
  9055. $mime = 'application/pdf';
  9056. $imgmime = 'pdf.png';
  9057. $famime = 'file-pdf-o';
  9058. }
  9059. // Scripts
  9060. if (preg_match('/\.bat$/i', $tmpfile)) {
  9061. $mime = 'text/x-bat';
  9062. $imgmime = 'script.png';
  9063. $srclang = 'dos';
  9064. $famime = 'file-code-o';
  9065. }
  9066. if (preg_match('/\.sh$/i', $tmpfile)) {
  9067. $mime = 'text/x-sh';
  9068. $imgmime = 'script.png';
  9069. $srclang = 'bash';
  9070. $famime = 'file-code-o';
  9071. }
  9072. if (preg_match('/\.ksh$/i', $tmpfile)) {
  9073. $mime = 'text/x-ksh';
  9074. $imgmime = 'script.png';
  9075. $srclang = 'bash';
  9076. $famime = 'file-code-o';
  9077. }
  9078. if (preg_match('/\.bash$/i', $tmpfile)) {
  9079. $mime = 'text/x-bash';
  9080. $imgmime = 'script.png';
  9081. $srclang = 'bash';
  9082. $famime = 'file-code-o';
  9083. }
  9084. // Images
  9085. if (preg_match('/\.ico$/i', $tmpfile)) {
  9086. $mime = 'image/x-icon';
  9087. $imgmime = 'image.png';
  9088. $famime = 'file-image-o';
  9089. }
  9090. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  9091. $mime = 'image/jpeg';
  9092. $imgmime = 'image.png';
  9093. $famime = 'file-image-o';
  9094. }
  9095. if (preg_match('/\.png$/i', $tmpfile)) {
  9096. $mime = 'image/png';
  9097. $imgmime = 'image.png';
  9098. $famime = 'file-image-o';
  9099. }
  9100. if (preg_match('/\.gif$/i', $tmpfile)) {
  9101. $mime = 'image/gif';
  9102. $imgmime = 'image.png';
  9103. $famime = 'file-image-o';
  9104. }
  9105. if (preg_match('/\.bmp$/i', $tmpfile)) {
  9106. $mime = 'image/bmp';
  9107. $imgmime = 'image.png';
  9108. $famime = 'file-image-o';
  9109. }
  9110. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  9111. $mime = 'image/tiff';
  9112. $imgmime = 'image.png';
  9113. $famime = 'file-image-o';
  9114. }
  9115. if (preg_match('/\.svg$/i', $tmpfile)) {
  9116. $mime = 'image/svg+xml';
  9117. $imgmime = 'image.png';
  9118. $famime = 'file-image-o';
  9119. }
  9120. if (preg_match('/\.webp$/i', $tmpfile)) {
  9121. $mime = 'image/webp';
  9122. $imgmime = 'image.png';
  9123. $famime = 'file-image-o';
  9124. }
  9125. // Calendar
  9126. if (preg_match('/\.vcs$/i', $tmpfile)) {
  9127. $mime = 'text/calendar';
  9128. $imgmime = 'other.png';
  9129. $famime = 'file-text-o';
  9130. }
  9131. if (preg_match('/\.ics$/i', $tmpfile)) {
  9132. $mime = 'text/calendar';
  9133. $imgmime = 'other.png';
  9134. $famime = 'file-text-o';
  9135. }
  9136. // Other
  9137. if (preg_match('/\.torrent$/i', $tmpfile)) {
  9138. $mime = 'application/x-bittorrent';
  9139. $imgmime = 'other.png';
  9140. $famime = 'file-o';
  9141. }
  9142. // Audio
  9143. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  9144. $mime = 'audio';
  9145. $imgmime = 'audio.png';
  9146. $famime = 'file-audio-o';
  9147. }
  9148. // Video
  9149. if (preg_match('/\.mp4$/i', $tmpfile)) {
  9150. $mime = 'video/mp4';
  9151. $imgmime = 'video.png';
  9152. $famime = 'file-video-o';
  9153. }
  9154. if (preg_match('/\.ogv$/i', $tmpfile)) {
  9155. $mime = 'video/ogg';
  9156. $imgmime = 'video.png';
  9157. $famime = 'file-video-o';
  9158. }
  9159. if (preg_match('/\.webm$/i', $tmpfile)) {
  9160. $mime = 'video/webm';
  9161. $imgmime = 'video.png';
  9162. $famime = 'file-video-o';
  9163. }
  9164. if (preg_match('/\.avi$/i', $tmpfile)) {
  9165. $mime = 'video/x-msvideo';
  9166. $imgmime = 'video.png';
  9167. $famime = 'file-video-o';
  9168. }
  9169. if (preg_match('/\.divx$/i', $tmpfile)) {
  9170. $mime = 'video/divx';
  9171. $imgmime = 'video.png';
  9172. $famime = 'file-video-o';
  9173. }
  9174. if (preg_match('/\.xvid$/i', $tmpfile)) {
  9175. $mime = 'video/xvid';
  9176. $imgmime = 'video.png';
  9177. $famime = 'file-video-o';
  9178. }
  9179. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  9180. $mime = 'video';
  9181. $imgmime = 'video.png';
  9182. $famime = 'file-video-o';
  9183. }
  9184. // Archive
  9185. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  9186. $mime = 'archive';
  9187. $imgmime = 'archive.png';
  9188. $famime = 'file-archive-o';
  9189. } // application/xxx where zzz is zip, ...
  9190. // Exe
  9191. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  9192. $mime = 'application/octet-stream';
  9193. $imgmime = 'other.png';
  9194. $famime = 'file-o';
  9195. }
  9196. // Lib
  9197. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  9198. $mime = 'library';
  9199. $imgmime = 'library.png';
  9200. $famime = 'file-o';
  9201. }
  9202. // Err
  9203. if (preg_match('/\.err$/i', $tmpfile)) {
  9204. $mime = 'error';
  9205. $imgmime = 'error.png';
  9206. $famime = 'file-text-o';
  9207. }
  9208. // Return string
  9209. if ($mode == 1) {
  9210. $tmp = explode('/', $mime);
  9211. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  9212. }
  9213. if ($mode == 2) {
  9214. return $imgmime;
  9215. }
  9216. if ($mode == 3) {
  9217. return $srclang;
  9218. }
  9219. if ($mode == 4) {
  9220. return $famime;
  9221. }
  9222. return $mime;
  9223. }
  9224. /**
  9225. * Return the value of a filed into a dictionary for the record $id.
  9226. * This also set all the values into a cache for a next search.
  9227. *
  9228. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  9229. * @param string $field The name of field where to find the value to return
  9230. * @param int $id Id of line record
  9231. * @param bool $checkentity Add filter on entity
  9232. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  9233. * @return string The value of field $field. This also set $dictvalues cache.
  9234. */
  9235. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  9236. {
  9237. global $conf, $db;
  9238. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  9239. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  9240. if (is_null($dictvalues)) {
  9241. $dictvalues = array();
  9242. $sql = "SELECT * FROM ".MAIN_DB_PREFIX.$tablename." WHERE 1 = 1"; // Here select * is allowed as it is generic code and we don't have list of fields
  9243. if ($checkentity) {
  9244. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  9245. }
  9246. $resql = $db->query($sql);
  9247. if ($resql) {
  9248. while ($obj = $db->fetch_object($resql)) {
  9249. $dictvalues[$obj->{$rowidfield}] = $obj; // $obj is stdClass
  9250. }
  9251. } else {
  9252. dol_print_error($db);
  9253. }
  9254. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  9255. }
  9256. if (!empty($dictvalues[$id])) {
  9257. // Found
  9258. $tmp = $dictvalues[$id];
  9259. return (property_exists($tmp, $field) ? $tmp->$field : '');
  9260. } else {
  9261. // Not found
  9262. return '';
  9263. }
  9264. }
  9265. /**
  9266. * Return true if the color is light
  9267. *
  9268. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  9269. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  9270. */
  9271. function colorIsLight($stringcolor)
  9272. {
  9273. $stringcolor = str_replace('#', '', $stringcolor);
  9274. $res = -1;
  9275. if (!empty($stringcolor)) {
  9276. $res = 0;
  9277. $tmp = explode(',', $stringcolor);
  9278. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  9279. $r = $tmp[0];
  9280. $g = $tmp[1];
  9281. $b = $tmp[2];
  9282. } else {
  9283. $hexr = $stringcolor[0].$stringcolor[1];
  9284. $hexg = $stringcolor[2].$stringcolor[3];
  9285. $hexb = $stringcolor[4].$stringcolor[5];
  9286. $r = hexdec($hexr);
  9287. $g = hexdec($hexg);
  9288. $b = hexdec($hexb);
  9289. }
  9290. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  9291. if ($bright > 0.6) {
  9292. $res = 1;
  9293. }
  9294. }
  9295. return $res;
  9296. }
  9297. /**
  9298. * Function to test if an entry is enabled or not
  9299. *
  9300. * @param string $type_user 0=We test for internal user, 1=We test for external user
  9301. * @param array $menuentry Array for feature entry to test
  9302. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  9303. * @return int 0=Hide, 1=Show, 2=Show gray
  9304. */
  9305. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  9306. {
  9307. global $conf;
  9308. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  9309. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  9310. if (empty($menuentry['enabled'])) {
  9311. return 0; // Entry disabled by condition
  9312. }
  9313. if ($type_user && $menuentry['module']) {
  9314. $tmploops = explode('|', $menuentry['module']);
  9315. $found = 0;
  9316. foreach ($tmploops as $tmploop) {
  9317. if (in_array($tmploop, $listofmodulesforexternal)) {
  9318. $found++;
  9319. break;
  9320. }
  9321. }
  9322. if (!$found) {
  9323. return 0; // Entry is for menus all excluded to external users
  9324. }
  9325. }
  9326. if (!$menuentry['perms'] && $type_user) {
  9327. return 0; // No permissions and user is external
  9328. }
  9329. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  9330. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  9331. }
  9332. if (!$menuentry['perms']) {
  9333. return 2; // No permissions and user is external
  9334. }
  9335. return 1;
  9336. }
  9337. /**
  9338. * Round to next multiple.
  9339. *
  9340. * @param double $n Number to round up
  9341. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  9342. * @return integer Value rounded.
  9343. */
  9344. function roundUpToNextMultiple($n, $x = 5)
  9345. {
  9346. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  9347. }
  9348. /**
  9349. * Function dolGetBadge
  9350. *
  9351. * @param string $label label of badge no html : use in alt attribute for accessibility
  9352. * @param string $html optional : label of badge with html
  9353. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  9354. * @param string $mode default '' , 'pill', 'dot'
  9355. * @param string $url the url for link
  9356. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  9357. * @return string Html badge
  9358. */
  9359. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  9360. {
  9361. $attr = array(
  9362. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  9363. );
  9364. if (empty($html)) {
  9365. $html = $label;
  9366. }
  9367. if (!empty($url)) {
  9368. $attr['href'] = $url;
  9369. }
  9370. if ($mode === 'dot') {
  9371. $attr['class'] .= ' classfortooltip';
  9372. $attr['title'] = $html;
  9373. $attr['aria-label'] = $label;
  9374. $html = '';
  9375. }
  9376. // Override attr
  9377. if (!empty($params['attr']) && is_array($params['attr'])) {
  9378. foreach ($params['attr'] as $key => $value) {
  9379. if ($key == 'class') {
  9380. $attr['class'] .= ' '.$value;
  9381. } elseif ($key == 'classOverride') {
  9382. $attr['class'] = $value;
  9383. } else {
  9384. $attr[$key] = $value;
  9385. }
  9386. }
  9387. }
  9388. // TODO: add hook
  9389. // escape all attribute
  9390. $attr = array_map('dol_escape_htmltag', $attr);
  9391. $TCompiledAttr = array();
  9392. foreach ($attr as $key => $value) {
  9393. $TCompiledAttr[] = $key.'="'.$value.'"';
  9394. }
  9395. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9396. $tag = !empty($url) ? 'a' : 'span';
  9397. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  9398. }
  9399. /**
  9400. * Output the badge of a status.
  9401. *
  9402. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  9403. * @param string $statusLabelShort Short label of badge no html
  9404. * @param string $html Optional : label of badge with html
  9405. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  9406. * @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
  9407. * @param string $url The url for link
  9408. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  9409. * @return string Html status string
  9410. */
  9411. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  9412. {
  9413. global $conf;
  9414. $return = '';
  9415. $dolGetBadgeParams = array();
  9416. if (!empty($params['badgeParams'])) {
  9417. $dolGetBadgeParams = $params['badgeParams'];
  9418. }
  9419. // TODO : add a hook
  9420. if ($displayMode == 0) {
  9421. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  9422. } elseif ($displayMode == 1) {
  9423. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9424. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  9425. // Use status with images (for backward compatibility)
  9426. $return = '';
  9427. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  9428. $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>' : '');
  9429. // For small screen, we always use the short label instead of long label.
  9430. if (!empty($conf->dol_optimize_smallscreen)) {
  9431. if ($displayMode == 0) {
  9432. $displayMode = 1;
  9433. } elseif ($displayMode == 4) {
  9434. $displayMode = 2;
  9435. } elseif ($displayMode == 6) {
  9436. $displayMode = 5;
  9437. }
  9438. }
  9439. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  9440. $statusImg = array(
  9441. 'status0' => 'statut0',
  9442. 'status1' => 'statut1',
  9443. 'status2' => 'statut2',
  9444. 'status3' => 'statut3',
  9445. 'status4' => 'statut4',
  9446. 'status5' => 'statut5',
  9447. 'status6' => 'statut6',
  9448. 'status7' => 'statut7',
  9449. 'status8' => 'statut8',
  9450. 'status9' => 'statut9'
  9451. );
  9452. if (!empty($statusImg[$statusType])) {
  9453. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  9454. } else {
  9455. $htmlImg = img_picto($statusLabel, $statusType);
  9456. }
  9457. if ($displayMode === 2) {
  9458. $return = $htmlImg.' '.$htmlLabelShort;
  9459. } elseif ($displayMode === 3) {
  9460. $return = $htmlImg;
  9461. } elseif ($displayMode === 4) {
  9462. $return = $htmlImg.' '.$htmlLabel;
  9463. } elseif ($displayMode === 5) {
  9464. $return = $htmlLabelShort.' '.$htmlImg;
  9465. } else { // $displayMode >= 6
  9466. $return = $htmlLabel.' '.$htmlImg;
  9467. }
  9468. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9469. // Use new badge
  9470. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9471. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9472. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9473. if ($displayMode == 3) {
  9474. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9475. } elseif ($displayMode === 5) {
  9476. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9477. } else {
  9478. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9479. }
  9480. }
  9481. return $return;
  9482. }
  9483. /**
  9484. * Function dolGetButtonAction
  9485. *
  9486. * @param string $label label of button without HTML : use in alt attribute for accessibility $html is not empty
  9487. * @param string $html optional : content with html
  9488. * @param string $actionType default, delete, danger
  9489. * @param string $url the url for link
  9490. * @param string $id attribute id of button
  9491. * @param int $userRight user action right
  9492. * // phpcs:disable
  9493. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  9494. * 'attr' => [ // to add or override button attributes
  9495. * 'xxxxx' => '', // your xxxxx attribute you want
  9496. * 'class' => '', // to add more css class to the button class attribute
  9497. * 'classOverride' => '' // to replace class attribute of the button
  9498. * ],
  9499. * 'confirm' => [
  9500. * '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.
  9501. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  9502. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  9503. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  9504. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  9505. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  9506. * ],
  9507. * ]
  9508. * // phpcs:enable
  9509. * @return string html button
  9510. */
  9511. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  9512. {
  9513. global $hookmanager, $action, $object, $langs;
  9514. $class = 'butAction';
  9515. if ($actionType == 'danger' || $actionType == 'delete') {
  9516. $class = 'butActionDelete';
  9517. if (!empty($url) && strpos($url, 'token=') === false) $url .= '&token='.newToken();
  9518. }
  9519. $attr = array(
  9520. 'class' => $class,
  9521. 'href' => empty($url) ? '' : $url,
  9522. 'title' => $label
  9523. );
  9524. if (empty($html)) {
  9525. $html = $label;
  9526. $attr['title'] = ''; // if html not set, leave label on title is redundant
  9527. } else {
  9528. $attr['aria-label'] = $label;
  9529. }
  9530. if (empty($userRight)) {
  9531. $attr['class'] = 'butActionRefused';
  9532. $attr['href'] = '';
  9533. }
  9534. if (!empty($id)) {
  9535. $attr['id'] = $id;
  9536. }
  9537. // Override attr
  9538. if (!empty($params['attr']) && is_array($params['attr'])) {
  9539. foreach ($params['attr'] as $key => $value) {
  9540. if ($key == 'class') {
  9541. $attr['class'] .= ' '.$value;
  9542. } elseif ($key == 'classOverride') {
  9543. $attr['class'] = $value;
  9544. } else {
  9545. $attr[$key] = $value;
  9546. }
  9547. }
  9548. }
  9549. // automatic add tooltip when title is detected
  9550. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  9551. $attr['class'].= ' classfortooltip';
  9552. }
  9553. // Js Confirm button
  9554. if ($userRight && !empty($params['confirm'])) {
  9555. if (!is_array($params['confirm'])) {
  9556. $params['confirm'] = array();
  9557. }
  9558. if (empty($params['confirm']['url'])) {
  9559. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  9560. }
  9561. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9562. $attr['data-confirm-url'] = $params['confirm']['url'];
  9563. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9564. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9565. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9566. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9567. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9568. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9569. $attr['class'].= ' butActionConfirm';
  9570. }
  9571. if (isset($attr['href']) && empty($attr['href'])) {
  9572. unset($attr['href']);
  9573. }
  9574. // escape all attribute
  9575. $attr = array_map('dol_escape_htmltag', $attr);
  9576. $TCompiledAttr = array();
  9577. foreach ($attr as $key => $value) {
  9578. $TCompiledAttr[] = $key.'="'.$value.'"';
  9579. }
  9580. $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
  9581. $tag = !empty($attr['href']) ? 'a' : 'span';
  9582. $parameters = array(
  9583. 'TCompiledAttr' => $TCompiledAttr, // array
  9584. 'compiledAttributes' => $compiledAttributes, // string
  9585. 'attr' => $attr,
  9586. 'tag' => $tag,
  9587. 'label' => $label,
  9588. 'html' => $html,
  9589. 'actionType' => $actionType,
  9590. 'url' => $url,
  9591. 'id' => $id,
  9592. 'userRight' => $userRight,
  9593. 'params' => $params
  9594. );
  9595. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9596. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9597. if (empty($reshook)) {
  9598. return '<' . $tag . ' ' . $compiledAttributes . '>' . $html . '</' . $tag . '>';
  9599. } else {
  9600. return $hookmanager->resPrint;
  9601. }
  9602. }
  9603. /**
  9604. * Add space between dolGetButtonTitle
  9605. *
  9606. * @param string $moreClass more css class label
  9607. * @return string html of title separator
  9608. */
  9609. function dolGetButtonTitleSeparator($moreClass = "")
  9610. {
  9611. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9612. }
  9613. /**
  9614. * get field error icon
  9615. *
  9616. * @param string $fieldValidationErrorMsg message to add in tooltip
  9617. * @return string html output
  9618. */
  9619. function getFieldErrorIcon($fieldValidationErrorMsg)
  9620. {
  9621. $out = '';
  9622. if (!empty($fieldValidationErrorMsg)) {
  9623. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9624. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9625. $out.= '</span>';
  9626. }
  9627. return $out;
  9628. }
  9629. /**
  9630. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9631. *
  9632. * @param string $label label of button
  9633. * @param string $helpText optional : content for help tooltip
  9634. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9635. * @param string $url the url for link
  9636. * @param string $id attribute id of button
  9637. * @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
  9638. * @param array $params various params for future : recommended rather than adding more function arguments
  9639. * @return string html button
  9640. */
  9641. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9642. {
  9643. global $langs, $conf, $user;
  9644. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9645. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9646. return '';
  9647. }
  9648. $class = 'btnTitle';
  9649. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots'))) {
  9650. $class .= ' btnTitlePlus';
  9651. }
  9652. $useclassfortooltip = 1;
  9653. if (!empty($params['morecss'])) {
  9654. $class .= ' '.$params['morecss'];
  9655. }
  9656. $attr = array(
  9657. 'class' => $class,
  9658. 'href' => empty($url) ? '' : $url
  9659. );
  9660. if (!empty($helpText)) {
  9661. $attr['title'] = dol_escape_htmltag($helpText);
  9662. } elseif (empty($attr['title']) && $label) {
  9663. $attr['title'] = $label;
  9664. $useclassfortooltip = 0;
  9665. }
  9666. if ($status == 2) {
  9667. $attr['class'] .= ' btnTitleSelected';
  9668. } elseif ($status <= 0) {
  9669. $attr['class'] .= ' refused';
  9670. $attr['href'] = '';
  9671. if ($status == -1) { // disable
  9672. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9673. } elseif ($status == 0) { // Not enough permissions
  9674. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9675. }
  9676. }
  9677. if (!empty($attr['title']) && $useclassfortooltip) {
  9678. $attr['class'] .= ' classfortooltip';
  9679. }
  9680. if (!empty($id)) {
  9681. $attr['id'] = $id;
  9682. }
  9683. // Override attr
  9684. if (!empty($params['attr']) && is_array($params['attr'])) {
  9685. foreach ($params['attr'] as $key => $value) {
  9686. if ($key == 'class') {
  9687. $attr['class'] .= ' '.$value;
  9688. } elseif ($key == 'classOverride') {
  9689. $attr['class'] = $value;
  9690. } else {
  9691. $attr[$key] = $value;
  9692. }
  9693. }
  9694. }
  9695. if (isset($attr['href']) && empty($attr['href'])) {
  9696. unset($attr['href']);
  9697. }
  9698. // TODO : add a hook
  9699. // escape all attribute
  9700. $attr = array_map('dol_escape_htmltag', $attr);
  9701. $TCompiledAttr = array();
  9702. foreach ($attr as $key => $value) {
  9703. $TCompiledAttr[] = $key.'="'.$value.'"';
  9704. }
  9705. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  9706. $tag = (empty($attr['href']) ? 'span' : 'a');
  9707. $button = '<'.$tag.' '.$compiledAttributes.'>';
  9708. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  9709. if (!empty($params['forcenohideoftext'])) {
  9710. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  9711. }
  9712. $button .= '</'.$tag.'>';
  9713. return $button;
  9714. }
  9715. /**
  9716. * Get an array with properties of an element.
  9717. * Called by fetchObjectByElement.
  9718. *
  9719. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  9720. * @return array (module, classpath, element, subelement, classfile, classname)
  9721. */
  9722. function getElementProperties($element_type)
  9723. {
  9724. $regs = array();
  9725. $classfile = $classname = $classpath = '';
  9726. // Parse element/subelement (ex: project_task)
  9727. $module = $element_type;
  9728. $element = $element_type;
  9729. $subelement = $element_type;
  9730. // If we ask an resource form external module (instead of default path)
  9731. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  9732. $element = $subelement = $regs[1];
  9733. $module = $regs[2];
  9734. }
  9735. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  9736. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  9737. $module = $element = $regs[1];
  9738. $subelement = $regs[2];
  9739. }
  9740. // For compat
  9741. if ($element_type == "action") {
  9742. $classpath = 'comm/action/class';
  9743. $subelement = 'Actioncomm';
  9744. $module = 'agenda';
  9745. }
  9746. // To work with non standard path
  9747. if ($element_type == 'facture' || $element_type == 'invoice') {
  9748. $classpath = 'compta/facture/class';
  9749. $module = 'facture';
  9750. $subelement = 'facture';
  9751. }
  9752. if ($element_type == 'commande' || $element_type == 'order') {
  9753. $classpath = 'commande/class';
  9754. $module = 'commande';
  9755. $subelement = 'commande';
  9756. }
  9757. if ($element_type == 'propal') {
  9758. $classpath = 'comm/propal/class';
  9759. }
  9760. if ($element_type == 'supplier_proposal') {
  9761. $classpath = 'supplier_proposal/class';
  9762. }
  9763. if ($element_type == 'shipping') {
  9764. $classpath = 'expedition/class';
  9765. $subelement = 'expedition';
  9766. $module = 'expedition_bon';
  9767. }
  9768. if ($element_type == 'delivery') {
  9769. $classpath = 'delivery/class';
  9770. $subelement = 'delivery';
  9771. $module = 'delivery_note';
  9772. }
  9773. if ($element_type == 'contract') {
  9774. $classpath = 'contrat/class';
  9775. $module = 'contrat';
  9776. $subelement = 'contrat';
  9777. }
  9778. if ($element_type == 'member') {
  9779. $classpath = 'adherents/class';
  9780. $module = 'adherent';
  9781. $subelement = 'adherent';
  9782. }
  9783. if ($element_type == 'cabinetmed_cons') {
  9784. $classpath = 'cabinetmed/class';
  9785. $module = 'cabinetmed';
  9786. $subelement = 'cabinetmedcons';
  9787. }
  9788. if ($element_type == 'fichinter') {
  9789. $classpath = 'fichinter/class';
  9790. $module = 'ficheinter';
  9791. $subelement = 'fichinter';
  9792. }
  9793. if ($element_type == 'dolresource' || $element_type == 'resource') {
  9794. $classpath = 'resource/class';
  9795. $module = 'resource';
  9796. $subelement = 'dolresource';
  9797. }
  9798. if ($element_type == 'propaldet') {
  9799. $classpath = 'comm/propal/class';
  9800. $module = 'propal';
  9801. $subelement = 'propaleligne';
  9802. }
  9803. if ($element_type == 'order_supplier') {
  9804. $classpath = 'fourn/class';
  9805. $module = 'fournisseur';
  9806. $subelement = 'commandefournisseur';
  9807. $classfile = 'fournisseur.commande';
  9808. }
  9809. if ($element_type == 'invoice_supplier') {
  9810. $classpath = 'fourn/class';
  9811. $module = 'fournisseur';
  9812. $subelement = 'facturefournisseur';
  9813. $classfile = 'fournisseur.facture';
  9814. }
  9815. if ($element_type == "service") {
  9816. $classpath = 'product/class';
  9817. $subelement = 'product';
  9818. }
  9819. if (empty($classfile)) {
  9820. $classfile = strtolower($subelement);
  9821. }
  9822. if (empty($classname)) {
  9823. $classname = ucfirst($subelement);
  9824. }
  9825. if (empty($classpath)) {
  9826. $classpath = $module.'/class';
  9827. }
  9828. $element_properties = array(
  9829. 'module' => $module,
  9830. 'classpath' => $classpath,
  9831. 'element' => $element,
  9832. 'subelement' => $subelement,
  9833. 'classfile' => $classfile,
  9834. 'classname' => $classname
  9835. );
  9836. return $element_properties;
  9837. }
  9838. /**
  9839. * Fetch an object from its id and element_type
  9840. * Inclusion of classes is automatic
  9841. *
  9842. * @param int $element_id Element id
  9843. * @param string $element_type Element type
  9844. * @param string $element_ref Element ref (Use this or element_id but not both)
  9845. * @return int|object object || 0 || -1 if error
  9846. */
  9847. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  9848. {
  9849. global $conf, $db;
  9850. $element_prop = getElementProperties($element_type);
  9851. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  9852. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  9853. $objecttmp = new $element_prop['classname']($db);
  9854. $ret = $objecttmp->fetch($element_id, $element_ref);
  9855. if ($ret >= 0) {
  9856. return $objecttmp;
  9857. }
  9858. }
  9859. return 0;
  9860. }
  9861. /**
  9862. * Return if a file can contains executable content
  9863. *
  9864. * @param string $filename File name to test
  9865. * @return boolean True if yes, False if no
  9866. */
  9867. function isAFileWithExecutableContent($filename)
  9868. {
  9869. 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)) {
  9870. return true;
  9871. }
  9872. return false;
  9873. }
  9874. /**
  9875. * Return the value of token currently saved into session with name 'newtoken'.
  9876. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  9877. *
  9878. * @return string
  9879. */
  9880. function newToken()
  9881. {
  9882. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  9883. }
  9884. /**
  9885. * Return the value of token currently saved into session with name 'token'.
  9886. * For ajax call, you must use this token as a parameter of the call into the js calling script (the called ajax php page must also set constant NOTOKENRENEWAL).
  9887. *
  9888. * @return string
  9889. */
  9890. function currentToken()
  9891. {
  9892. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  9893. }
  9894. /**
  9895. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  9896. *
  9897. * @param string $header The first left header of the table (automatic translated)
  9898. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  9899. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  9900. * @param integer $emptyRows (optional) The count of empty rows after the first header
  9901. * @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"
  9902. * @return void
  9903. *
  9904. * @see finishSimpleTable()
  9905. */
  9906. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  9907. {
  9908. global $langs;
  9909. print '<div class="div-table-responsive-no-min">';
  9910. print '<table class="noborder centpercent">';
  9911. print '<tr class="liste_titre">';
  9912. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  9913. print $langs->trans($header);
  9914. // extra space between the first header and the number
  9915. if ($number > -1) {
  9916. print ' ';
  9917. }
  9918. if (!empty($link)) {
  9919. if (!empty($arguments)) {
  9920. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9921. } else {
  9922. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  9923. }
  9924. }
  9925. if ($number > -1) {
  9926. print '<span class="badge">'.$number.'</span>';
  9927. }
  9928. if (!empty($link)) {
  9929. print '</a>';
  9930. }
  9931. print '</th>';
  9932. if ($number < 0 && !empty($link)) {
  9933. print '<th class="right">';
  9934. if (!empty($arguments)) {
  9935. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  9936. } else {
  9937. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  9938. }
  9939. print $langs->trans("FullList");
  9940. print '</a>';
  9941. print '</th>';
  9942. }
  9943. print '</tr>';
  9944. }
  9945. /**
  9946. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  9947. *
  9948. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  9949. * @return void
  9950. *
  9951. * @see startSimpleTable()
  9952. */
  9953. function finishSimpleTable($addLineBreak = false)
  9954. {
  9955. print '</table>';
  9956. print '</div>';
  9957. if ($addLineBreak) {
  9958. print '<br>';
  9959. }
  9960. }
  9961. /**
  9962. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  9963. *
  9964. * @param integer $tableColumnCount The complete count columns of the table
  9965. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  9966. * @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)
  9967. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  9968. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  9969. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  9970. * @return void
  9971. */
  9972. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  9973. {
  9974. global $langs;
  9975. if ($num === 0) {
  9976. print '<tr class="oddeven">';
  9977. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  9978. print '</tr>';
  9979. return;
  9980. }
  9981. if ($nbofloop === 0) {
  9982. // don't show a summary line
  9983. return;
  9984. }
  9985. if ($num === 0) {
  9986. $colspan = $tableColumnCount;
  9987. } elseif ($num > $nbofloop) {
  9988. $colspan = $tableColumnCount;
  9989. } else {
  9990. $colspan = $tableColumnCount - 1;
  9991. }
  9992. if ($extraRightColumn) {
  9993. $colspan--;
  9994. }
  9995. print '<tr class="liste_total">';
  9996. if ($nbofloop > 0 && $num > $nbofloop) {
  9997. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  9998. } else {
  9999. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  10000. print '<td class="right" width="100">'.price($total).'</td>';
  10001. }
  10002. if ($extraRightColumn) {
  10003. print '<td></td>';
  10004. }
  10005. print '</tr>';
  10006. }
  10007. /**
  10008. * Return a file on output using a low memory. It can return very large files with no need of memory.
  10009. * WARNING: This close output buffers.
  10010. *
  10011. * @param string $fullpath_original_file_osencoded Full path of file to return.
  10012. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  10013. * @return void
  10014. */
  10015. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  10016. {
  10017. global $conf;
  10018. if ($method == -1) {
  10019. $method = 0;
  10020. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  10021. $method = 1;
  10022. }
  10023. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  10024. $method = 2;
  10025. }
  10026. }
  10027. // Be sure we don't have output buffering enabled to have readfile working correctly
  10028. while (ob_get_level()) {
  10029. ob_end_flush();
  10030. }
  10031. // Solution 0
  10032. if ($method == 0) {
  10033. readfile($fullpath_original_file_osencoded);
  10034. } elseif ($method == 1) {
  10035. // Solution 1
  10036. $handle = fopen($fullpath_original_file_osencoded, "rb");
  10037. while (!feof($handle)) {
  10038. print fread($handle, 8192);
  10039. }
  10040. fclose($handle);
  10041. } elseif ($method == 2) {
  10042. // Solution 2
  10043. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  10044. $handle2 = fopen("php://output", "wb");
  10045. stream_copy_to_stream($handle1, $handle2);
  10046. fclose($handle1);
  10047. fclose($handle2);
  10048. }
  10049. }
  10050. /**
  10051. * Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
  10052. * Code that handle the click is inside core/js/lib_foot.js.php.
  10053. *
  10054. * @param string $valuetocopy The value to print
  10055. * @param int $showonlyonhover Show the copy-paste button only on hover
  10056. * @param string $texttoshow Replace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
  10057. * @return string The string to print for the button
  10058. */
  10059. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  10060. {
  10061. /*
  10062. global $conf;
  10063. if (!empty($conf->dol_no_mouse_hover)) {
  10064. $showonlyonhover = 0;
  10065. }*/
  10066. $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
  10067. if ($texttoshow === 'none') {
  10068. $result = '<span class="clipboardCP'.($showonlyonhover ? ' clipboardCPShowOnHover' : '').'"><'.$tag.' class="clipboardCPValue hidewithsize">'.dol_escape_htmltag($valuetocopy, 1, 1).'</'.$tag.'><span class="clipboardCPValueToPrint"></span><span class="clipboardCPButton far fa-clipboard opacitymedium paddingleft paddingright"></span><span class="clipboardCPText"></span></span>';
  10069. } elseif ($texttoshow) {
  10070. $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>';
  10071. } else {
  10072. $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>';
  10073. }
  10074. return $result;
  10075. }
  10076. /**
  10077. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  10078. *
  10079. * @param string $stringtodecode String to decode (json or serialize coded)
  10080. * @return mixed The decoded object.
  10081. */
  10082. function jsonOrUnserialize($stringtodecode)
  10083. {
  10084. $result = json_decode($stringtodecode);
  10085. if ($result === null) {
  10086. $result = unserialize($stringtodecode);
  10087. }
  10088. return $result;
  10089. }
  10090. /**
  10091. * Return if a $sqlfilters parameter is valid and will pass the preg_replace_callback() to replace Generic filter string with SQL filter string
  10092. * Example of usage:
  10093. * if ($sqlfilters) {
  10094. * $errormessage = '';
  10095. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  10096. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  10097. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  10098. * }
  10099. * }
  10100. *
  10101. * @param string $sqlfilters sqlfilter string
  10102. * @param string $error Error message
  10103. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  10104. */
  10105. function dolCheckFilters($sqlfilters, &$error = '')
  10106. {
  10107. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  10108. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  10109. $tmp = $sqlfilters;
  10110. $i = 0; $nb = strlen($tmp);
  10111. $counter = 0;
  10112. while ($i < $nb) {
  10113. if ($tmp[$i] == '(') {
  10114. $counter++;
  10115. }
  10116. if ($tmp[$i] == ')') {
  10117. $counter--;
  10118. }
  10119. if ($counter < 0) {
  10120. $error = "Bad sqlfilters=".$sqlfilters;
  10121. dol_syslog($error, LOG_WARNING);
  10122. return false;
  10123. }
  10124. $i++;
  10125. }
  10126. return true;
  10127. }
  10128. /**
  10129. * Function to forge a SQL criteria from a Generic filter string.
  10130. * Example of usage:
  10131. * if ($sqlfilters) {
  10132. * $errormessage = '';
  10133. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  10134. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  10135. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  10136. * }
  10137. * }
  10138. *
  10139. * @param array $matches Array of found string by regex search.
  10140. * 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"
  10141. * @return string Forged criteria. Example: "t.field like 'abc%'"
  10142. */
  10143. function dolForgeCriteriaCallback($matches)
  10144. {
  10145. global $db;
  10146. dol_syslog("Convert matches ".$matches[1]);
  10147. if (empty($matches[1])) {
  10148. return '';
  10149. }
  10150. $tmp = explode(':', $matches[1], 3);
  10151. if (count($tmp) < 3) {
  10152. return '';
  10153. }
  10154. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  10155. $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
  10156. if ($operator == 'NOTLIKE') {
  10157. $operator = 'NOT LIKE';
  10158. }
  10159. $tmpescaped = trim($tmp[2]);
  10160. $regbis = array();
  10161. if ($operator == 'IN') {
  10162. $tmpescaped = "(".$db->sanitize($tmpescaped, 1).")";
  10163. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  10164. $tmpescaped = "'".$db->escape($regbis[1])."'";
  10165. } else {
  10166. $tmpescaped = $db->sanitize($db->escape($tmpescaped));
  10167. }
  10168. return $db->escape($operand).' '.$db->escape($operator)." ".$tmpescaped;
  10169. }