functions.lib.php 493 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237
  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-2022 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-2022 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. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  23. *
  24. * This program is free software; you can redistribute it and/or modify
  25. * it under the terms of the GNU General Public License as published by
  26. * the Free Software Foundation; either version 3 of the License, or
  27. * (at your option) any later version.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU General Public License
  35. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  36. * or see https://www.gnu.org/
  37. */
  38. /**
  39. * \file htdocs/core/lib/functions.lib.php
  40. * \brief A set of functions for Dolibarr
  41. * This file contains all frequently used functions.
  42. */
  43. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  44. if (!function_exists('utf8_encode')) {
  45. /**
  46. * Implement utf8_encode for PHP that does not support it.
  47. *
  48. * @param mixed $elements PHP Object to json encode
  49. * @return string Json encoded string
  50. */
  51. function utf8_encode($elements)
  52. {
  53. return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
  54. }
  55. }
  56. if (!function_exists('utf8_decode')) {
  57. /**
  58. * Implement utf8_decode for PHP that does not support it.
  59. *
  60. * @param mixed $elements PHP Object to json encode
  61. * @return string Json encoded string
  62. */
  63. function utf8_decode($elements)
  64. {
  65. return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
  66. }
  67. }
  68. /**
  69. * Return dolibarr global constant string value
  70. *
  71. * @param string $key key to return value, return '' if not set
  72. * @param string $default value to return
  73. * @return string
  74. */
  75. function getDolGlobalString($key, $default = '')
  76. {
  77. global $conf;
  78. // return $conf->global->$key ?? $default;
  79. return (string) (empty($conf->global->$key) ? $default : $conf->global->$key);
  80. }
  81. /**
  82. * Return dolibarr global constant int value
  83. *
  84. * @param string $key key to return value, return 0 if not set
  85. * @param int $default value to return
  86. * @return int
  87. */
  88. function getDolGlobalInt($key, $default = 0)
  89. {
  90. global $conf;
  91. // return $conf->global->$key ?? $default;
  92. return (int) (empty($conf->global->$key) ? $default : $conf->global->$key);
  93. }
  94. /**
  95. * Return dolibarr user constant string value
  96. *
  97. * @param string $key key to return value, return '' if not set
  98. * @param string $default value to return
  99. * @return string
  100. */
  101. function getDolUserString($key, $default = '')
  102. {
  103. global $user;
  104. // return $conf->global->$key ?? $default;
  105. return (string) (empty($user->conf->$key) ? $default : $user->conf->$key);
  106. }
  107. /**
  108. * Return dolibarr user constant int value
  109. *
  110. * @param string $key key to return value, return 0 if not set
  111. * @param int $default value to return
  112. * @return int
  113. */
  114. function getDolUserInt($key, $default = 0)
  115. {
  116. global $user;
  117. // return $conf->global->$key ?? $default;
  118. return (int) (empty($user->conf->$key) ? $default : $user->conf->$key);
  119. }
  120. /**
  121. * Is Dolibarr module enabled
  122. *
  123. * @param string $module module name to check
  124. * @return int
  125. */
  126. function isModEnabled($module)
  127. {
  128. global $conf;
  129. return !empty($conf->$module->enabled);
  130. }
  131. /**
  132. * Return a DoliDB instance (database handler).
  133. *
  134. * @param string $type Type of database (mysql, pgsql...)
  135. * @param string $host Address of database server
  136. * @param string $user Authorized username
  137. * @param string $pass Password
  138. * @param string $name Name of database
  139. * @param int $port Port of database server
  140. * @return DoliDB A DoliDB instance
  141. */
  142. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  143. {
  144. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  145. $class = 'DoliDB'.ucfirst($type);
  146. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  147. return $dolidb;
  148. }
  149. /**
  150. * Get list of entity id to use.
  151. *
  152. * @param string $element Current element
  153. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  154. * 'product', 'productprice', 'stock', 'bom', 'mo',
  155. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  156. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  157. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  158. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  159. * 'email_template', 'event', 'donation'
  160. * 'c_paiement', 'c_payment_term', ...
  161. * @param int $shared 0=Return id of current entity only,
  162. * 1=Return id of current entity + shared entities (default)
  163. * @param object $currentobject Current object if needed
  164. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  165. */
  166. function getEntity($element, $shared = 1, $currentobject = null)
  167. {
  168. global $conf, $mc, $hookmanager, $object, $action, $db;
  169. if (! is_object($hookmanager)) {
  170. $hookmanager = new HookManager($db);
  171. }
  172. // fix different element names (France to English)
  173. switch ($element) {
  174. case 'contrat':
  175. $element = 'contract';
  176. break; // "/contrat/class/contrat.class.php"
  177. case 'order_supplier':
  178. $element = 'supplier_order';
  179. break; // "/fourn/class/fournisseur.commande.class.php"
  180. case 'invoice_supplier':
  181. $element = 'supplier_invoice';
  182. break; // "/fourn/class/fournisseur.facture.class.php"
  183. }
  184. if (is_object($mc)) {
  185. $out = $mc->getEntity($element, $shared, $currentobject);
  186. } else {
  187. $out = '';
  188. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  189. if (in_array($element, $addzero)) {
  190. $out .= '0,';
  191. }
  192. $out .= ((int) $conf->entity);
  193. }
  194. // Manipulate entities to query on the fly
  195. $parameters = array(
  196. 'element' => $element,
  197. 'shared' => $shared,
  198. 'object' => $object,
  199. 'currentobject' => $currentobject,
  200. 'out' => $out
  201. );
  202. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  203. if (is_numeric($reshook)) {
  204. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  205. $out .= ','.$hookmanager->resPrint; // add
  206. } elseif ($reshook == 1) {
  207. $out = $hookmanager->resPrint; // replace
  208. }
  209. }
  210. return $out;
  211. }
  212. /**
  213. * Set entity id to use when to create an object
  214. *
  215. * @param object $currentobject Current object
  216. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  217. */
  218. function setEntity($currentobject)
  219. {
  220. global $conf, $mc;
  221. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  222. return $mc->setEntity($currentobject);
  223. } else {
  224. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  225. }
  226. }
  227. /**
  228. * Return if string has a name dedicated to store a secret
  229. *
  230. * @param string $keyname Name of key to test
  231. * @return boolean True if key is used to store a secret
  232. */
  233. function isASecretKey($keyname)
  234. {
  235. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  236. }
  237. /**
  238. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  239. *
  240. * @param int|string $n Numeric value
  241. * @return string Column in Excel format
  242. */
  243. function num2Alpha($n)
  244. {
  245. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
  246. $r = chr($n % 26 + 0x41) . $r;
  247. return $r;
  248. }
  249. /**
  250. * Return information about user browser
  251. *
  252. * Returns array with the following format:
  253. * array(
  254. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  255. * 'browserversion' => Browser version. Empty if unknown
  256. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  257. * 'layout' => (tablet|phone|classic)
  258. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  259. * 'tablet' => true/false
  260. * )
  261. *
  262. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  263. * @return array Check function documentation
  264. */
  265. function getBrowserInfo($user_agent)
  266. {
  267. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  268. $name = 'unknown';
  269. $version = '';
  270. $os = 'unknown';
  271. $phone = '';
  272. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  273. $detectmobile = new Mobile_Detect(null, $user_agent);
  274. $tablet = $detectmobile->isTablet();
  275. if ($detectmobile->isMobile()) {
  276. $phone = 'unknown';
  277. // If phone/smartphone, we set phone os name.
  278. if ($detectmobile->is('AndroidOS')) {
  279. $os = $phone = 'android';
  280. } elseif ($detectmobile->is('BlackBerryOS')) {
  281. $os = $phone = 'blackberry';
  282. } elseif ($detectmobile->is('iOS')) {
  283. $os = 'ios';
  284. $phone = 'iphone';
  285. } elseif ($detectmobile->is('PalmOS')) {
  286. $os = $phone = 'palm';
  287. } elseif ($detectmobile->is('SymbianOS')) {
  288. $os = 'symbian';
  289. } elseif ($detectmobile->is('webOS')) {
  290. $os = 'webos';
  291. } elseif ($detectmobile->is('MaemoOS')) {
  292. $os = 'maemo';
  293. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  294. $os = 'windows';
  295. }
  296. }
  297. // OS
  298. if (preg_match('/linux/i', $user_agent)) {
  299. $os = 'linux';
  300. } elseif (preg_match('/macintosh/i', $user_agent)) {
  301. $os = 'macintosh';
  302. } elseif (preg_match('/windows/i', $user_agent)) {
  303. $os = 'windows';
  304. }
  305. // Name
  306. $reg = array();
  307. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  308. $name = 'firefox';
  309. $version = $reg[2];
  310. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  311. $name = 'edge';
  312. $version = $reg[2];
  313. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  314. $name = 'chrome';
  315. $version = $reg[2];
  316. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  317. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  318. $name = 'chrome';
  319. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  320. $name = 'iceweasel';
  321. } elseif (preg_match('/epiphany/i', $user_agent)) {
  322. $name = 'epiphany';
  323. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  324. $name = 'safari';
  325. $version = $reg[2];
  326. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  327. // Safari is often present in string for mobile but its not.
  328. $name = 'opera';
  329. $version = $reg[2];
  330. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  331. $name = 'ie';
  332. $version = end($reg);
  333. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  334. // MS products at end
  335. $name = 'ie';
  336. $version = end($reg);
  337. } elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  338. // MS products at end
  339. $name = 'lynxlinks';
  340. $version = $reg[4];
  341. }
  342. if ($tablet) {
  343. $layout = 'tablet';
  344. } elseif ($phone) {
  345. $layout = 'phone';
  346. } else {
  347. $layout = 'classic';
  348. }
  349. return array(
  350. 'browsername' => $name,
  351. 'browserversion' => $version,
  352. 'browseros' => $os,
  353. 'layout' => $layout,
  354. 'phone' => $phone,
  355. 'tablet' => $tablet
  356. );
  357. }
  358. /**
  359. * Function called at end of web php process
  360. *
  361. * @return void
  362. */
  363. function dol_shutdown()
  364. {
  365. global $conf, $user, $langs, $db;
  366. $disconnectdone = false;
  367. $depth = 0;
  368. if (is_object($db) && !empty($db->connected)) {
  369. $depth = $db->transaction_opened;
  370. $disconnectdone = $db->close();
  371. }
  372. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
  373. }
  374. /**
  375. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  376. *
  377. * @param string $paramname Name or parameter to test
  378. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  379. */
  380. function GETPOSTISSET($paramname)
  381. {
  382. $isset = false;
  383. $relativepathstring = $_SERVER["PHP_SELF"];
  384. // Clean $relativepathstring
  385. if (constant('DOL_URL_ROOT')) {
  386. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  387. }
  388. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  389. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  390. //var_dump($relativepathstring);
  391. //var_dump($user->default_values);
  392. // Code for search criteria persistence.
  393. // Retrieve values if restore_lastsearch_values
  394. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  395. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  396. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  397. if (is_array($tmp)) {
  398. foreach ($tmp as $key => $val) {
  399. if ($key == $paramname) { // We are on the requested parameter
  400. $isset = true;
  401. break;
  402. }
  403. }
  404. }
  405. }
  406. // If there is saved contextpage, limit, page or mode
  407. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  408. $isset = true;
  409. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  410. $isset = true;
  411. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  412. $isset = true;
  413. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  414. $isset = true;
  415. }
  416. } else {
  417. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  418. }
  419. return $isset;
  420. }
  421. /**
  422. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  423. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  424. *
  425. * @param string $paramname Name or parameter to test
  426. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  427. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  428. */
  429. function GETPOSTISARRAY($paramname, $method = 0)
  430. {
  431. // for $method test need return the same $val as GETPOST
  432. if (empty($method)) {
  433. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  434. } elseif ($method == 1) {
  435. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  436. } elseif ($method == 2) {
  437. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  438. } elseif ($method == 3) {
  439. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  440. } else {
  441. $val = 'BadFirstParameterForGETPOST';
  442. }
  443. return is_array($val);
  444. }
  445. /**
  446. * Return value of a param into GET or POST supervariable.
  447. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  448. * Note: The property $user->default_values is loaded by main.php when loading the user.
  449. *
  450. * @param string $paramname Name of parameter to found
  451. * @param string $check Type of check
  452. * ''=no check (deprecated)
  453. * 'none'=no check (only for param that should have very rich content like passwords)
  454. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  455. * 'int'=check it's numeric (integer or float)
  456. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  457. * 'alpha'=Same than alphanohtml since v13
  458. * 'alphawithlgt'=alpha with lgt
  459. * 'alphanohtml'=check there is no html content and no " and no ../
  460. * 'aZ'=check it's a-z only
  461. * 'aZ09'=check it's simple alpha string (recommended for keys)
  462. * 'aZ09comma'=check it's a string for a sortfield or sortorder
  463. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  464. * 'nohtml'=check there is no html content and no " and no ../
  465. * 'restricthtml'=check html content is restricted to some tags only
  466. * 'custom'= custom filter specify $filter and $options)
  467. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  468. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  469. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  470. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  471. * @return string|array Value found (string or array), or '' if check fails
  472. */
  473. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  474. {
  475. global $mysoc, $user, $conf;
  476. if (empty($paramname)) {
  477. return 'BadFirstParameterForGETPOST';
  478. }
  479. if (empty($check)) {
  480. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  481. // Enable this line to know who call the GETPOST with '' $check parameter.
  482. //var_dump(debug_backtrace()[0]);
  483. }
  484. if (empty($method)) {
  485. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  486. } elseif ($method == 1) {
  487. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  488. } elseif ($method == 2) {
  489. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  490. } elseif ($method == 3) {
  491. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  492. } else {
  493. return 'BadThirdParameterForGETPOST';
  494. }
  495. if (empty($method) || $method == 3 || $method == 4) {
  496. $relativepathstring = $_SERVER["PHP_SELF"];
  497. // Clean $relativepathstring
  498. if (constant('DOL_URL_ROOT')) {
  499. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  500. }
  501. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  502. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  503. //var_dump($relativepathstring);
  504. //var_dump($user->default_values);
  505. // Code for search criteria persistence.
  506. // Retrieve values if restore_lastsearch_values
  507. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  508. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  509. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  510. if (is_array($tmp)) {
  511. foreach ($tmp as $key => $val) {
  512. if ($key == $paramname) { // We are on the requested parameter
  513. $out = $val;
  514. break;
  515. }
  516. }
  517. }
  518. }
  519. // If there is saved contextpage, page or limit
  520. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  521. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  522. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  523. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  524. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  525. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  526. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  527. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  528. }
  529. } elseif (!isset($_GET['sortfield'])) {
  530. // Else, retrieve default values if we are not doing a sort
  531. // 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
  532. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  533. // Search default value from $object->field
  534. global $object;
  535. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  536. $out = $object->fields[$paramname]['default'];
  537. }
  538. }
  539. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  540. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  541. // Now search in setup to overwrite default values
  542. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  543. if (isset($user->default_values[$relativepathstring]['createform'])) {
  544. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  545. $qualified = 0;
  546. if ($defkey != '_noquery_') {
  547. $tmpqueryarraytohave = explode('&', $defkey);
  548. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  549. $foundintru = 0;
  550. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  551. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  552. $foundintru = 1;
  553. }
  554. }
  555. if (!$foundintru) {
  556. $qualified = 1;
  557. }
  558. //var_dump($defkey.'-'.$qualified);
  559. } else {
  560. $qualified = 1;
  561. }
  562. if ($qualified) {
  563. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  564. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  565. break;
  566. }
  567. }
  568. }
  569. }
  570. }
  571. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  572. // Management of default search_filters and sort order
  573. if (!empty($user->default_values)) {
  574. // $user->default_values defined from menu 'Setup - Default values'
  575. //var_dump($user->default_values[$relativepathstring]);
  576. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  577. // Sorted on which fields ? ASC or DESC ?
  578. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  579. // Even if paramname is sortfield, data are stored into ['sortorder...']
  580. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  581. $qualified = 0;
  582. if ($defkey != '_noquery_') {
  583. $tmpqueryarraytohave = explode('&', $defkey);
  584. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  585. $foundintru = 0;
  586. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  587. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  588. $foundintru = 1;
  589. }
  590. }
  591. if (!$foundintru) {
  592. $qualified = 1;
  593. }
  594. //var_dump($defkey.'-'.$qualified);
  595. } else {
  596. $qualified = 1;
  597. }
  598. if ($qualified) {
  599. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  600. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  601. if ($out) {
  602. $out .= ', ';
  603. }
  604. if ($paramname == 'sortfield') {
  605. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  606. }
  607. if ($paramname == 'sortorder') {
  608. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  609. }
  610. }
  611. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  612. }
  613. }
  614. }
  615. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  616. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  617. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  618. continue;
  619. }
  620. $qualified = 0;
  621. if ($defkey != '_noquery_') {
  622. $tmpqueryarraytohave = explode('&', $defkey);
  623. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  624. $foundintru = 0;
  625. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  626. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  627. $foundintru = 1;
  628. }
  629. }
  630. if (!$foundintru) {
  631. $qualified = 1;
  632. }
  633. //var_dump($defkey.'-'.$qualified);
  634. } else {
  635. $qualified = 1;
  636. }
  637. if ($qualified) {
  638. // We must keep $_POST and $_GET here
  639. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  640. // We made a search from quick search menu, do we still use default filter ?
  641. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  642. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  643. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  644. }
  645. } else {
  646. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  647. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  648. }
  649. break;
  650. }
  651. }
  652. }
  653. }
  654. }
  655. }
  656. }
  657. }
  658. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  659. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  660. // 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.
  661. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  662. $reg = array();
  663. $maxloop = 20;
  664. $loopnb = 0; // Protection against infinite loop
  665. 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.
  666. $loopnb++;
  667. $newout = '';
  668. if ($reg[1] == 'DAY') {
  669. $tmp = dol_getdate(dol_now(), true);
  670. $newout = $tmp['mday'];
  671. } elseif ($reg[1] == 'MONTH') {
  672. $tmp = dol_getdate(dol_now(), true);
  673. $newout = $tmp['mon'];
  674. } elseif ($reg[1] == 'YEAR') {
  675. $tmp = dol_getdate(dol_now(), true);
  676. $newout = $tmp['year'];
  677. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  678. $tmp = dol_getdate(dol_now(), true);
  679. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  680. $newout = $tmp2['day'];
  681. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  682. $tmp = dol_getdate(dol_now(), true);
  683. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  684. $newout = $tmp2['month'];
  685. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  686. $tmp = dol_getdate(dol_now(), true);
  687. $newout = ($tmp['year'] - 1);
  688. } elseif ($reg[1] == 'NEXT_DAY') {
  689. $tmp = dol_getdate(dol_now(), true);
  690. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  691. $newout = $tmp2['day'];
  692. } elseif ($reg[1] == 'NEXT_MONTH') {
  693. $tmp = dol_getdate(dol_now(), true);
  694. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  695. $newout = $tmp2['month'];
  696. } elseif ($reg[1] == 'NEXT_YEAR') {
  697. $tmp = dol_getdate(dol_now(), true);
  698. $newout = ($tmp['year'] + 1);
  699. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  700. $newout = $mysoc->country_id;
  701. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  702. $newout = $user->id;
  703. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  704. $newout = $user->fk_user;
  705. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  706. $newout = $conf->entity;
  707. } else {
  708. $newout = ''; // Key not found, we replace with empty string
  709. }
  710. //var_dump('__'.$reg[1].'__ -> '.$newout);
  711. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  712. }
  713. }
  714. // Check rule
  715. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  716. if (!is_array($out) || empty($out)) {
  717. $out = array();
  718. } else {
  719. $tmparray = explode(':', $check);
  720. if (!empty($tmparray[1])) {
  721. $tmpcheck = $tmparray[1];
  722. } else {
  723. $tmpcheck = 'alphanohtml';
  724. }
  725. foreach ($out as $outkey => $outval) {
  726. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  727. }
  728. }
  729. } else {
  730. $out = sanitizeVal($out, $check, $filter, $options);
  731. }
  732. // Sanitizing for special parameters.
  733. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  734. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  735. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  736. $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.
  737. do {
  738. $oldstringtoclean = $out;
  739. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  740. $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'
  741. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  742. } while ($oldstringtoclean != $out);
  743. }
  744. // Code for search criteria persistence.
  745. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  746. if (empty($method) || $method == 3 || $method == 4) {
  747. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  748. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  749. // We save search key only if $out not empty that means:
  750. // - posted value not empty, or
  751. // - 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).
  752. if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
  753. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  754. }
  755. }
  756. }
  757. return $out;
  758. }
  759. /**
  760. * Return value of a param into GET or POST supervariable.
  761. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  762. * Note: The property $user->default_values is loaded by main.php when loading the user.
  763. *
  764. * @param string $paramname Name of parameter to found
  765. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  766. * @return int Value found (int)
  767. */
  768. function GETPOSTINT($paramname, $method = 0)
  769. {
  770. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  771. }
  772. /**
  773. * Return a sanitized or empty value after checking value against a rule.
  774. *
  775. * @deprecated
  776. * @param string|array $out Value to check/clear.
  777. * @param string $check Type of check/sanitizing
  778. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  779. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  780. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  781. */
  782. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  783. {
  784. return sanitizeVal($out, $check, $filter, $options);
  785. }
  786. /**
  787. * Return a sanitized or empty value after checking value against a rule.
  788. *
  789. * @param string|array $out Value to check/clear.
  790. * @param string $check Type of check/sanitizing
  791. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  792. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  793. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  794. */
  795. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  796. {
  797. global $conf;
  798. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  799. // Check is done after replacement
  800. switch ($check) {
  801. case 'none':
  802. break;
  803. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  804. if (!is_numeric($out)) {
  805. $out = '';
  806. }
  807. break;
  808. case 'intcomma':
  809. if (preg_match('/[^0-9,-]+/i', $out)) {
  810. $out = '';
  811. }
  812. break;
  813. case 'san_alpha':
  814. $out = filter_var($out, FILTER_SANITIZE_STRING);
  815. break;
  816. case 'email':
  817. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  818. break;
  819. case 'aZ':
  820. if (!is_array($out)) {
  821. $out = trim($out);
  822. if (preg_match('/[^a-z]+/i', $out)) {
  823. $out = '';
  824. }
  825. }
  826. break;
  827. case 'aZ09':
  828. if (!is_array($out)) {
  829. $out = trim($out);
  830. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  831. $out = '';
  832. }
  833. }
  834. break;
  835. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  836. if (!is_array($out)) {
  837. $out = trim($out);
  838. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  839. $out = '';
  840. }
  841. }
  842. break;
  843. case 'nohtml': // No html
  844. $out = dol_string_nohtmltag($out, 0);
  845. break;
  846. case 'alpha': // No html and no ../ and "
  847. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  848. if (!is_array($out)) {
  849. $out = trim($out);
  850. do {
  851. $oldstringtoclean = $out;
  852. // Remove html tags
  853. $out = dol_string_nohtmltag($out, 0);
  854. // Remove also other dangerous string sequences
  855. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  856. // '../' or '..\' is dangerous because it allows dir transversals
  857. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  858. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  859. } while ($oldstringtoclean != $out);
  860. // keep lines feed
  861. }
  862. break;
  863. 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'
  864. if (!is_array($out)) {
  865. $out = trim($out);
  866. do {
  867. $oldstringtoclean = $out;
  868. // Remove html tags
  869. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  870. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  871. // '../' or '..\' is dangerous because it allows dir transversals
  872. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  873. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  874. } while ($oldstringtoclean != $out);
  875. }
  876. break;
  877. case 'restricthtml': // Recommended for most html textarea
  878. case 'restricthtmlallowunvalid':
  879. $out = dol_htmlwithnojs($out, 1, $check);
  880. break;
  881. case 'custom':
  882. if (!empty($out)) {
  883. if (empty($filter)) {
  884. return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
  885. }
  886. /*if (empty($options)) {
  887. return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
  888. }*/
  889. $out = filter_var($out, $filter, $options);
  890. }
  891. break;
  892. }
  893. return $out;
  894. }
  895. if (!function_exists('dol_getprefix')) {
  896. /**
  897. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  898. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  899. * or two instances in same virtual servers.
  900. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  901. *
  902. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  903. * @return string A calculated prefix
  904. */
  905. function dol_getprefix($mode = '')
  906. {
  907. // If prefix is for email (we need to have $conf already loaded for this case)
  908. if ($mode == 'email') {
  909. global $conf;
  910. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  911. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  912. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  913. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  914. return $_SERVER["SERVER_NAME"];
  915. }
  916. }
  917. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  918. if (!empty($conf->file->instance_unique_id)) {
  919. return sha1('dolibarr'.$conf->file->instance_unique_id);
  920. }
  921. // For backward compatibility when instance_unique_id is not set
  922. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  923. }
  924. // If prefix is for session (no need to have $conf loaded)
  925. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  926. $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
  927. // The recommended value (may be not defined for old versions)
  928. if (!empty($tmp_instance_unique_id)) {
  929. return sha1('dolibarr'.$tmp_instance_unique_id);
  930. }
  931. // For backward compatibility when instance_unique_id is not set
  932. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  933. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  934. } else {
  935. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  936. }
  937. }
  938. }
  939. /**
  940. * Make an include_once using default root and alternate root if it fails.
  941. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  942. * To link to a module file from a module file, use include './mymodulefile';
  943. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  944. *
  945. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  946. * @param string $classname Class name (deprecated)
  947. * @return bool True if load is a success, False if it fails
  948. */
  949. function dol_include_once($relpath, $classname = '')
  950. {
  951. 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']
  952. $fullpath = dol_buildpath($relpath);
  953. if (!file_exists($fullpath)) {
  954. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  955. return false;
  956. }
  957. if (!empty($classname) && !class_exists($classname)) {
  958. return include $fullpath;
  959. } else {
  960. return include_once $fullpath;
  961. }
  962. }
  963. /**
  964. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  965. *
  966. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  967. * @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)
  968. * @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)
  969. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  970. * 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
  971. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  972. */
  973. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  974. {
  975. global $conf;
  976. $path = preg_replace('/^\//', '', $path);
  977. if (empty($type)) { // For a filesystem path
  978. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  979. if (is_array($conf->file->dol_document_root)) {
  980. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  981. if ($key == 'main') {
  982. continue;
  983. }
  984. if (file_exists($dirroot.'/'.$path)) {
  985. $res = $dirroot.'/'.$path;
  986. return $res;
  987. }
  988. }
  989. }
  990. if ($returnemptyifnotfound) {
  991. // Not found into alternate dir
  992. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  993. return '';
  994. }
  995. }
  996. } else {
  997. // For an url path
  998. // We try to get local path of file on filesystem from url
  999. // Note that trying to know if a file on disk exist by forging path on disk from url
  1000. // works only for some web server and some setup. This is bugged when
  1001. // using proxy, rewriting, virtual path, etc...
  1002. $res = '';
  1003. if ($type == 1) {
  1004. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  1005. }
  1006. if ($type == 2) {
  1007. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  1008. }
  1009. if ($type == 3) {
  1010. $res = DOL_URL_ROOT.'/'.$path;
  1011. }
  1012. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  1013. if ($key == 'main') {
  1014. if ($type == 3) {
  1015. global $dolibarr_main_url_root;
  1016. // Define $urlwithroot
  1017. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1018. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1019. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1020. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  1021. }
  1022. continue;
  1023. }
  1024. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  1025. if (!empty($regs[1])) {
  1026. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1027. if (file_exists($dirroot.'/'.$regs[1])) {
  1028. if ($type == 1) {
  1029. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1030. }
  1031. if ($type == 2) {
  1032. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1033. }
  1034. if ($type == 3) {
  1035. global $dolibarr_main_url_root;
  1036. // Define $urlwithroot
  1037. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1038. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1039. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1040. $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
  1041. }
  1042. break;
  1043. }
  1044. }
  1045. }
  1046. }
  1047. return $res;
  1048. }
  1049. /**
  1050. * Create a clone of instance of object (new instance with same value for each properties)
  1051. * With native = 0: Property that are reference are different memory area in the new object (full isolation clone). This means $this->db of new object may not be valid.
  1052. * 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.
  1053. * With native = 2: Property that are reference are different memory area in the new object (full isolation clone). Only scalar and array values are cloned. This means $this->db of new object is not valid.
  1054. *
  1055. * @param object $object Object to clone
  1056. * @param int $native 0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended)
  1057. * @return object Clone object
  1058. * @see https://php.net/manual/language.oop5.cloning.php
  1059. */
  1060. function dol_clone($object, $native = 0)
  1061. {
  1062. if ($native == 0) {
  1063. // deprecated method, use the method with native = 2 instead
  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 with pgsl (when object->db->db = 'PgSql\Connection')
  1068. }
  1069. $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
  1070. if (!empty($tmpsavdb)) {
  1071. $object->db = $tmpsavdb;
  1072. }
  1073. } elseif ($native == 2) {
  1074. // recommended method to have a full isolated cloned object
  1075. $myclone = new stdClass();
  1076. $tmparray = get_object_vars($object); // return only public properties
  1077. if (is_array($tmparray)) {
  1078. foreach ($tmparray as $propertykey => $propertyval) {
  1079. if (is_scalar($propertyval) || is_array($propertyval)) {
  1080. $myclone->$propertykey = $propertyval;
  1081. }
  1082. }
  1083. }
  1084. } else {
  1085. $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)
  1086. }
  1087. return $myclone;
  1088. }
  1089. /**
  1090. * Optimize a size for some browsers (phone, smarphone, ...)
  1091. *
  1092. * @param int $size Size we want
  1093. * @param string $type Type of optimizing:
  1094. * '' = function used to define a size for truncation
  1095. * 'width' = function is used to define a width
  1096. * @return int New size after optimizing
  1097. */
  1098. function dol_size($size, $type = '')
  1099. {
  1100. global $conf;
  1101. if (empty($conf->dol_optimize_smallscreen)) {
  1102. return $size;
  1103. }
  1104. if ($type == 'width' && $size > 250) {
  1105. return 250;
  1106. } else {
  1107. return 10;
  1108. }
  1109. }
  1110. /**
  1111. * Clean a string to use it as a file name.
  1112. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1113. *
  1114. * @param string $str String to clean
  1115. * @param string $newstr String to replace bad chars with.
  1116. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1117. * @return string String cleaned (a-zA-Z_)
  1118. *
  1119. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1120. */
  1121. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1122. {
  1123. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1124. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1125. // Char '/' and '\' are file delimiters.
  1126. // 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
  1127. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1128. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1129. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1130. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1131. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1132. $tmp = str_replace('..', '', $tmp);
  1133. return $tmp;
  1134. }
  1135. /**
  1136. * Clean a string to use it as a path name.
  1137. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1138. *
  1139. * @param string $str String to clean
  1140. * @param string $newstr String to replace bad chars with
  1141. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1142. * @return string String cleaned (a-zA-Z_)
  1143. *
  1144. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1145. */
  1146. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1147. {
  1148. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1149. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1150. // 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
  1151. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1152. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1153. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1154. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1155. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1156. $tmp = str_replace('..', '', $tmp);
  1157. return $tmp;
  1158. }
  1159. /**
  1160. * Clean a string to use it as an URL (into a href or src attribute)
  1161. *
  1162. * @param string $stringtoclean String to clean
  1163. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1164. * @return string Escaped string.
  1165. */
  1166. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1167. {
  1168. // 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)
  1169. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1170. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1171. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1172. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1173. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1174. if ($type == 1) {
  1175. // removing : should disable links to external url like http:aaa)
  1176. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1177. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1178. }
  1179. do {
  1180. $oldstringtoclean = $stringtoclean;
  1181. // removing '&colon' should disable links to external url like http:aaa)
  1182. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1183. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1184. } while ($oldstringtoclean != $stringtoclean);
  1185. if ($type == 1) {
  1186. // removing '//' should disable links to external url like //aaa or http//)
  1187. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1188. }
  1189. return $stringtoclean;
  1190. }
  1191. /**
  1192. * Clean a string to use it as an Email.
  1193. *
  1194. * @param string $stringtoclean String to clean. Example 'abc@mycompany.com <My name>'
  1195. * @return string Escaped string.
  1196. */
  1197. function dol_sanitizeEmail($stringtoclean)
  1198. {
  1199. do {
  1200. $oldstringtoclean = $stringtoclean;
  1201. $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
  1202. } while ($oldstringtoclean != $stringtoclean);
  1203. return $stringtoclean;
  1204. }
  1205. /**
  1206. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1207. *
  1208. * @param string $str String to clean
  1209. * @return string Cleaned string
  1210. *
  1211. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1212. */
  1213. function dol_string_unaccent($str)
  1214. {
  1215. global $conf;
  1216. if (utf8_check($str)) {
  1217. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1218. $transliterator = \Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', \Transliterator::FORWARD);
  1219. return $transliterator->transliterate($str);
  1220. }
  1221. // See http://www.utf8-chartable.de/
  1222. $string = rawurlencode($str);
  1223. $replacements = array(
  1224. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1225. '%C3%87' => 'C',
  1226. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1227. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1228. '%C3%91' => 'N',
  1229. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1230. '%C5%A0' => 'S',
  1231. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1232. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1233. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1234. '%C3%A7' => 'c',
  1235. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1236. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1237. '%C3%B1' => 'n',
  1238. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1239. '%C5%A1' => 's',
  1240. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1241. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1242. );
  1243. $string = strtr($string, $replacements);
  1244. return rawurldecode($string);
  1245. } else {
  1246. // See http://www.ascii-code.com/
  1247. $string = strtr(
  1248. $str,
  1249. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1250. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1251. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1252. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1253. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1254. \xF9\xFA\xFB\xFC\xFD\xFF",
  1255. "AAAAAAC
  1256. EEEEIIIIDN
  1257. OOOOOUUUY
  1258. aaaaaaceeee
  1259. iiiidnooooo
  1260. uuuuyy"
  1261. );
  1262. $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"));
  1263. return $string;
  1264. }
  1265. }
  1266. /**
  1267. * Clean a string from all punctuation characters to use it as a ref or login.
  1268. * This is a more complete function than dol_sanitizeFileName.
  1269. *
  1270. * @param string $str String to clean
  1271. * @param string $newstr String to replace forbidden chars with
  1272. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1273. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1274. * @return string Cleaned string
  1275. *
  1276. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1277. */
  1278. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '')
  1279. {
  1280. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  1281. $forbidden_chars_to_remove = array();
  1282. //$forbidden_chars_to_remove=array("(",")");
  1283. if (is_array($badcharstoreplace)) {
  1284. $forbidden_chars_to_replace = $badcharstoreplace;
  1285. }
  1286. if (is_array($badcharstoremove)) {
  1287. $forbidden_chars_to_remove = $badcharstoremove;
  1288. }
  1289. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1290. }
  1291. /**
  1292. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1293. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1294. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1295. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1296. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1297. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1298. * @param string $str String to clean
  1299. * @param int $removetabcrlf Remove also CR-LF
  1300. * @return string Cleaned string
  1301. *
  1302. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1303. */
  1304. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1305. {
  1306. if ($removetabcrlf) {
  1307. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1308. } else {
  1309. 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
  1310. }
  1311. }
  1312. /**
  1313. * Returns text escaped for inclusion into javascript code
  1314. *
  1315. * @param string $stringtoescape String to escape
  1316. * @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 \
  1317. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1318. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1319. */
  1320. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1321. {
  1322. // escape quotes and backslashes, newlines, etc.
  1323. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1324. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1325. if (empty($noescapebackslashn)) {
  1326. $substitjs["\n"] = '\\n';
  1327. $substitjs['\\'] = '\\\\';
  1328. }
  1329. if (empty($mode)) {
  1330. $substitjs["'"] = "\\'";
  1331. $substitjs['"'] = "\\'";
  1332. } elseif ($mode == 1) {
  1333. $substitjs["'"] = "\\'";
  1334. } elseif ($mode == 2) {
  1335. $substitjs['"'] = '\\"';
  1336. } elseif ($mode == 3) {
  1337. $substitjs["'"] = "\\'";
  1338. $substitjs['"'] = "\\\"";
  1339. }
  1340. return strtr($stringtoescape, $substitjs);
  1341. }
  1342. /**
  1343. * Returns text escaped for inclusion into javascript code
  1344. *
  1345. * @param string $stringtoescape String to escape
  1346. * @return string Escaped string for json content.
  1347. */
  1348. function dol_escape_json($stringtoescape)
  1349. {
  1350. return str_replace('"', '\"', $stringtoescape);
  1351. }
  1352. /**
  1353. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  1354. *
  1355. * @param string $stringtoescape String to escape
  1356. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1357. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1358. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes into tag.
  1359. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1360. * @return string Escaped string
  1361. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1362. */
  1363. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1364. {
  1365. if ($noescapetags == 'common') {
  1366. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1367. }
  1368. // escape quotes and backslashes, newlines, etc.
  1369. if ($escapeonlyhtmltags) {
  1370. $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
  1371. } else {
  1372. $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
  1373. }
  1374. if (!$keepb) {
  1375. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1376. }
  1377. if (!$keepn) {
  1378. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1379. }
  1380. if ($escapeonlyhtmltags) {
  1381. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1382. } else {
  1383. // Escape tags to keep
  1384. // TODO Does not works yet when there is attributes into tag
  1385. $tmparrayoftags = array();
  1386. if ($noescapetags) {
  1387. $tmparrayoftags = explode(',', $noescapetags);
  1388. }
  1389. if (count($tmparrayoftags)) {
  1390. foreach ($tmparrayoftags as $tagtoreplace) {
  1391. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1392. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1393. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1394. }
  1395. }
  1396. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1397. if (count($tmparrayoftags)) {
  1398. foreach ($tmparrayoftags as $tagtoreplace) {
  1399. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1400. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1401. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1402. }
  1403. }
  1404. return $result;
  1405. }
  1406. }
  1407. /**
  1408. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1409. *
  1410. * @param string $string String to encode
  1411. * @param string $encoding Character set encoding
  1412. * @return string String converted
  1413. */
  1414. function dol_strtolower($string, $encoding = "UTF-8")
  1415. {
  1416. if (function_exists('mb_strtolower')) {
  1417. return mb_strtolower($string, $encoding);
  1418. } else {
  1419. return strtolower($string);
  1420. }
  1421. }
  1422. /**
  1423. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1424. *
  1425. * @param string $string String to encode
  1426. * @param string $encoding Character set encoding
  1427. * @return string String converted
  1428. */
  1429. function dol_strtoupper($string, $encoding = "UTF-8")
  1430. {
  1431. if (function_exists('mb_strtoupper')) {
  1432. return mb_strtoupper($string, $encoding);
  1433. } else {
  1434. return strtoupper($string);
  1435. }
  1436. }
  1437. /**
  1438. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1439. *
  1440. * @param string $string String to encode
  1441. * @param string $encoding Character set encodign
  1442. * @return string String converted
  1443. */
  1444. function dol_ucfirst($string, $encoding = "UTF-8")
  1445. {
  1446. if (function_exists('mb_substr')) {
  1447. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1448. } else {
  1449. return ucfirst($string);
  1450. }
  1451. }
  1452. /**
  1453. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1454. *
  1455. * @param string $string String to encode
  1456. * @param string $encoding Character set encodign
  1457. * @return string String converted
  1458. */
  1459. function dol_ucwords($string, $encoding = "UTF-8")
  1460. {
  1461. if (function_exists('mb_convert_case')) {
  1462. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1463. } else {
  1464. return ucwords($string);
  1465. }
  1466. }
  1467. /**
  1468. * Write log message into outputs. Possible outputs can be:
  1469. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1470. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1471. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1472. * this, use logging to files instead of syslog (see setup of module).
  1473. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1474. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1475. * This function works only if syslog module is enabled.
  1476. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1477. *
  1478. * @param string $message Line to log. ''=Show nothing
  1479. * @param int $level Log level
  1480. * 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
  1481. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1482. * @param int $ident 1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log)
  1483. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1484. * @param string $restricttologhandler Force output of log only to this log handler
  1485. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1486. * @return void
  1487. */
  1488. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1489. {
  1490. global $conf, $user, $debugbar;
  1491. // If syslog module enabled
  1492. if (empty($conf->syslog->enabled)) {
  1493. return;
  1494. }
  1495. // Check if we are into execution of code of a website
  1496. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1497. global $website, $websitekey;
  1498. if (is_object($website) && !empty($website->ref)) {
  1499. $suffixinfilename .= '_website_'.$website->ref;
  1500. } elseif (!empty($websitekey)) {
  1501. $suffixinfilename .= '_website_'.$websitekey;
  1502. }
  1503. }
  1504. // Check if we have a forced suffix
  1505. if (defined('USESUFFIXINLOG')) {
  1506. $suffixinfilename .= constant('USESUFFIXINLOG');
  1507. }
  1508. if ($ident < 0) {
  1509. foreach ($conf->loghandlers as $loghandlerinstance) {
  1510. $loghandlerinstance->setIdent($ident);
  1511. }
  1512. }
  1513. if (!empty($message)) {
  1514. // Test log level
  1515. $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');
  1516. if (!array_key_exists($level, $logLevels)) {
  1517. throw new Exception('Incorrect log level');
  1518. }
  1519. if ($level > $conf->global->SYSLOG_LEVEL) {
  1520. return;
  1521. }
  1522. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1523. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1524. }
  1525. // If adding log inside HTML page is required
  1526. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1527. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1528. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1529. }
  1530. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1531. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1532. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1533. print "\n\n<!-- Log start\n";
  1534. print dol_escape_htmltag($message)."\n";
  1535. print "Log end -->\n";
  1536. }
  1537. $data = array(
  1538. 'message' => $message,
  1539. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1540. 'level' => $level,
  1541. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1542. 'ip' => false
  1543. );
  1544. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1545. if (!empty($remoteip)) {
  1546. $data['ip'] = $remoteip;
  1547. // This is when server run behind a reverse proxy
  1548. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1549. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1550. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1551. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1552. }
  1553. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1554. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1555. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1556. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1557. // 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).
  1558. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1559. } elseif (!empty($_SERVER['LOGNAME'])) {
  1560. // 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).
  1561. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1562. }
  1563. // Loop on each log handler and send output
  1564. foreach ($conf->loghandlers as $loghandlerinstance) {
  1565. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1566. continue;
  1567. }
  1568. $loghandlerinstance->export($data, $suffixinfilename);
  1569. }
  1570. unset($data);
  1571. }
  1572. if ($ident > 0) {
  1573. foreach ($conf->loghandlers as $loghandlerinstance) {
  1574. $loghandlerinstance->setIdent($ident);
  1575. }
  1576. }
  1577. }
  1578. /**
  1579. * Return HTML code to output a button to open a dialog popup box.
  1580. * Such buttons must be included inside a HTML form.
  1581. *
  1582. * @param string $name A name for the html component
  1583. * @param string $label Label shown in Popup title top bar
  1584. * @param string $buttonstring button string
  1585. * @param string $url Relative Url to open. For example '/project/card.php'
  1586. * @param string $disabled Disabled text
  1587. * @param string $morecss More CSS
  1588. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1589. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1590. * @return string HTML component with button
  1591. */
  1592. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'button bordertransp', $backtopagejsfields = '')
  1593. {
  1594. global $conf;
  1595. if (strpos($url, '?') > 0) {
  1596. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1597. } else {
  1598. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1599. }
  1600. $out = '';
  1601. $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
  1602. if ($backtopagejsfields) {
  1603. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1604. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1605. $backtopagejsfields = $name.":".$backtopagejsfields;
  1606. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1607. } else {
  1608. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1609. }
  1610. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1611. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1612. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1613. }
  1614. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1615. $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
  1616. $out .= '<a class="cursorpointer classlink button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
  1617. if (empty($conf->use_javascript_ajax)) {
  1618. $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
  1619. }
  1620. $out .= '>'.$buttonstring.'</a>';
  1621. if (!empty($conf->use_javascript_ajax)) {
  1622. // Add code to open url using the popup. Add also hidden field to retreive the returned variables
  1623. $out .= '<!-- code to open popup and variables to retreive returned variables -->';
  1624. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1625. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1626. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1627. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1628. $out .= '<script type="text/javascript">
  1629. jQuery(document).ready(function () {
  1630. jQuery(".button_'.$name.'").click(function () {
  1631. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1632. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1633. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1634. $tmpdialog.dialog({
  1635. autoOpen: false,
  1636. modal: true,
  1637. height: (window.innerHeight - 150),
  1638. width: \'80%\',
  1639. title: \''.dol_escape_js($label).'\',
  1640. open: function (event, ui) {
  1641. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1642. },
  1643. close: function (event, ui) {
  1644. returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1645. returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1646. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1647. if (returnedid != "" && returnedid != "div for returned id") {
  1648. jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
  1649. }
  1650. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1651. jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
  1652. }
  1653. }
  1654. });
  1655. $tmpdialog.dialog(\'open\');
  1656. });
  1657. });
  1658. </script>';
  1659. }
  1660. return $out;
  1661. }
  1662. /**
  1663. * Show tab header of a card
  1664. *
  1665. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1666. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1667. * @param string $title Title
  1668. * @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 sepaaration under tab (to start a tab just after), -3=Add tab header but no footer separation
  1669. * @param string $picto Add a picto on tab title
  1670. * @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.
  1671. * @param string $morehtmlright Add more html content on right of tabs title
  1672. * @param string $morecss More Css
  1673. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1674. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1675. * @return void
  1676. * @deprecated Use print dol_get_fiche_head() instead
  1677. */
  1678. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1679. {
  1680. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1681. }
  1682. /**
  1683. * Show tabs of a record
  1684. *
  1685. * @param array $links Array of tabs (0=>url, 1=>label, 2=>code, 3=>not used, 4=>text after link, 5=>morecssonlink). Currently initialized by calling a function xxx_admin_prepare_head. Note that label into $links[$i][1] must be already HTML escaped.
  1686. * @param string $active Active tab name
  1687. * @param string $title Title
  1688. * @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), -3=-2+'noborderbottom'
  1689. * @param string $picto Add a picto on tab title
  1690. * @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.
  1691. * @param string $morehtmlright Add more html content on right of tabs title
  1692. * @param string $morecss More CSS on the link <a>
  1693. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1694. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1695. * @return string
  1696. */
  1697. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1698. {
  1699. global $conf, $langs, $hookmanager;
  1700. // Show title
  1701. $showtitle = 1;
  1702. if (!empty($conf->dol_optimize_smallscreen)) {
  1703. $showtitle = 0;
  1704. }
  1705. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1706. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1707. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1708. }
  1709. // Show right part
  1710. if ($morehtmlright) {
  1711. $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.
  1712. }
  1713. // Show title
  1714. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1715. $limittitle = 30;
  1716. $out .= '<a class="tabTitle">';
  1717. if ($picto) {
  1718. $noprefix = $pictoisfullpath;
  1719. if (strpos($picto, 'fontawesome_') !== false) {
  1720. $noprefix = 1;
  1721. }
  1722. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1723. }
  1724. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1725. $out .= '</a>';
  1726. }
  1727. // Show tabs
  1728. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1729. $maxkey = -1;
  1730. if (is_array($links) && !empty($links)) {
  1731. $keys = array_keys($links);
  1732. if (count($keys)) {
  1733. $maxkey = max($keys);
  1734. }
  1735. }
  1736. // Show tabs
  1737. // if =0 we don't use the feature
  1738. if (empty($limittoshow)) {
  1739. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1740. }
  1741. if (!empty($conf->dol_optimize_smallscreen)) {
  1742. $limittoshow = 2;
  1743. }
  1744. $displaytab = 0;
  1745. $nbintab = 0;
  1746. $popuptab = 0;
  1747. $outmore = '';
  1748. for ($i = 0; $i <= $maxkey; $i++) {
  1749. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1750. // If active tab is already present
  1751. if ($i >= $limittoshow) {
  1752. $limittoshow--;
  1753. }
  1754. }
  1755. }
  1756. for ($i = 0; $i <= $maxkey; $i++) {
  1757. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1758. $isactive = true;
  1759. } else {
  1760. $isactive = false;
  1761. }
  1762. if ($i < $limittoshow || $isactive) {
  1763. // Output entry with a visible tab
  1764. $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])).' -->';
  1765. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1766. if (!empty($links[$i][0])) {
  1767. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1768. } else {
  1769. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1770. }
  1771. } elseif (!empty($links[$i][1])) {
  1772. //print "x $i $active ".$links[$i][2]." z";
  1773. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1774. if (!empty($links[$i][0])) {
  1775. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1776. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tab inline-block valignmiddle'.($morecss ? ' '.$morecss : '').(!empty($links[$i][5]) ? ' '.$links[$i][5] : '').'" href="'.$links[$i][0].'" title="'.dol_escape_htmltag($titletoshow).'">';
  1777. }
  1778. $out .= $links[$i][1];
  1779. if (!empty($links[$i][0])) {
  1780. $out .= '</a>'."\n";
  1781. }
  1782. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1783. $out .= '</div>';
  1784. }
  1785. $out .= '</div>';
  1786. } else {
  1787. // Add entry into the combo popup with the other tabs
  1788. if (!$popuptab) {
  1789. $popuptab = 1;
  1790. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1791. }
  1792. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1793. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1794. if (!empty($links[$i][0])) {
  1795. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1796. } else {
  1797. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1798. }
  1799. } elseif (!empty($links[$i][1])) {
  1800. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1801. $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.
  1802. $outmore .= '</a>'."\n";
  1803. }
  1804. $outmore .= '</div>';
  1805. $nbintab++;
  1806. }
  1807. $displaytab = $i;
  1808. }
  1809. if ($popuptab) {
  1810. $outmore .= '</div>';
  1811. }
  1812. if ($popuptab) { // If there is some tabs not shown
  1813. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1814. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1815. $widthofpopup = 200;
  1816. $tabsname = $moretabssuffix;
  1817. if (empty($tabsname)) {
  1818. $tabsname = str_replace("@", "", $picto);
  1819. }
  1820. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  1821. $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".
  1822. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1823. $out .= $outmore;
  1824. $out .= '</div>';
  1825. $out .= '<div></div>';
  1826. $out .= "</div>\n";
  1827. $out .= "<script>";
  1828. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1829. var x = this.offsetLeft, y = this.offsetTop;
  1830. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1831. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1832. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1833. }
  1834. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1835. });
  1836. ";
  1837. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1838. $out .= "</script>";
  1839. }
  1840. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1841. $out .= "</div>\n";
  1842. }
  1843. if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
  1844. $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
  1845. }
  1846. $parameters = array('tabname' => $active, 'out' => $out);
  1847. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1848. if ($reshook > 0) {
  1849. $out = $hookmanager->resPrint;
  1850. }
  1851. return $out;
  1852. }
  1853. /**
  1854. * Show tab footer of a card
  1855. *
  1856. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1857. * @return void
  1858. * @deprecated Use print dol_get_fiche_end() instead
  1859. */
  1860. function dol_fiche_end($notab = 0)
  1861. {
  1862. print dol_get_fiche_end($notab);
  1863. }
  1864. /**
  1865. * Return tab footer of a card
  1866. *
  1867. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1868. * @return string
  1869. */
  1870. function dol_get_fiche_end($notab = 0)
  1871. {
  1872. if (!$notab || $notab == -1) {
  1873. return "\n</div>\n";
  1874. } else {
  1875. return '';
  1876. }
  1877. }
  1878. /**
  1879. * Show tab footer of a card.
  1880. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1881. *
  1882. * @param Object $object Object to show
  1883. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1884. * @param string $morehtml More html content to output just before the nav bar
  1885. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1886. * @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.
  1887. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1888. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1889. * @param string $moreparam More param to add in nav link url.
  1890. * @param int $nodbprefix Do not include DB prefix to forge table name
  1891. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1892. * @param string $morehtmlstatus More html code to show under navigation arrows
  1893. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1894. * @param string $morehtmlright More html code to show before navigation arrows
  1895. * @return void
  1896. */
  1897. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1898. {
  1899. global $conf, $form, $user, $langs, $hookmanager, $action;
  1900. $error = 0;
  1901. $maxvisiblephotos = 1;
  1902. $showimage = 1;
  1903. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1904. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1905. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1906. $showbarcode = 0;
  1907. }
  1908. $modulepart = 'unknown';
  1909. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1910. $modulepart = $object->element;
  1911. } elseif ($object->element == 'member') {
  1912. $modulepart = 'memberphoto';
  1913. } elseif ($object->element == 'user') {
  1914. $modulepart = 'userphoto';
  1915. }
  1916. if (class_exists("Imagick")) {
  1917. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  1918. $modulepart = $object->element;
  1919. } elseif ($object->element == 'fichinter') {
  1920. $modulepart = 'ficheinter';
  1921. } elseif ($object->element == 'contrat') {
  1922. $modulepart = 'contract';
  1923. } elseif ($object->element == 'order_supplier') {
  1924. $modulepart = 'supplier_order';
  1925. } elseif ($object->element == 'invoice_supplier') {
  1926. $modulepart = 'supplier_invoice';
  1927. }
  1928. }
  1929. if ($object->element == 'product') {
  1930. $width = 80;
  1931. $cssclass = 'photowithmargin photoref';
  1932. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1933. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1934. if ($conf->browser->layout == 'phone') {
  1935. $maxvisiblephotos = 1;
  1936. }
  1937. if ($showimage) {
  1938. $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>';
  1939. } else {
  1940. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1941. $nophoto = '';
  1942. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1943. } else { // Show no photo link
  1944. $nophoto = '/public/theme/common/nophoto.png';
  1945. $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>';
  1946. }
  1947. }
  1948. } elseif ($object->element == 'ticket') {
  1949. $width = 80;
  1950. $cssclass = 'photoref';
  1951. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1952. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1953. if ($conf->browser->layout == 'phone') {
  1954. $maxvisiblephotos = 1;
  1955. }
  1956. if ($showimage) {
  1957. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1958. if ($object->nbphoto > 0) {
  1959. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1960. } else {
  1961. $showimage = 0;
  1962. }
  1963. }
  1964. if (!$showimage) {
  1965. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1966. $nophoto = '';
  1967. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1968. } else { // Show no photo link
  1969. $nophoto = img_picto('No photo', 'object_ticket');
  1970. $morehtmlleft .= '<!-- No photo to show -->';
  1971. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1972. $morehtmlleft .= $nophoto;
  1973. $morehtmlleft .= '</div></div>';
  1974. }
  1975. }
  1976. } else {
  1977. if ($showimage) {
  1978. if ($modulepart != 'unknown') {
  1979. $phototoshow = '';
  1980. // Check if a preview file is available
  1981. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  1982. $objectref = dol_sanitizeFileName($object->ref);
  1983. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1984. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  1985. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1986. $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
  1987. } else {
  1988. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1989. }
  1990. if (empty($subdir)) {
  1991. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1992. }
  1993. $filepath = $dir_output.$subdir."/";
  1994. $filepdf = $filepath.$objectref.".pdf";
  1995. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1996. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1997. $fileimage = $filepdf.'_preview.png';
  1998. $relativepathimage = $relativepath.'_preview.png';
  1999. $pdfexists = file_exists($filepdf);
  2000. // If PDF file exists
  2001. if ($pdfexists) {
  2002. // Conversion du PDF en image png si fichier png non existant
  2003. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  2004. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  2005. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2006. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  2007. if ($ret < 0) {
  2008. $error++;
  2009. }
  2010. }
  2011. }
  2012. }
  2013. if ($pdfexists && !$error) {
  2014. $heightforphotref = 80;
  2015. if (!empty($conf->dol_optimize_smallscreen)) {
  2016. $heightforphotref = 60;
  2017. }
  2018. // If the preview file is found
  2019. if (file_exists($fileimage)) {
  2020. $phototoshow = '<div class="photoref">';
  2021. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  2022. $phototoshow .= '</div>';
  2023. }
  2024. }
  2025. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  2026. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  2027. }
  2028. if ($phototoshow) {
  2029. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  2030. $morehtmlleft .= $phototoshow;
  2031. $morehtmlleft .= '</div>';
  2032. }
  2033. }
  2034. if (empty($phototoshow)) { // Show No photo link (picto of object)
  2035. if ($object->element == 'action') {
  2036. $width = 80;
  2037. $cssclass = 'photorefcenter';
  2038. $nophoto = img_picto('No photo', 'title_agenda');
  2039. } else {
  2040. $width = 14;
  2041. $cssclass = 'photorefcenter';
  2042. $picto = $object->picto;
  2043. $prefix = 'object_';
  2044. if ($object->element == 'project' && !$object->public) {
  2045. $picto = 'project'; // instead of projectpub
  2046. }
  2047. if (strpos($picto, 'fontawesome_') !== false) {
  2048. $prefix = '';
  2049. }
  2050. $nophoto = img_picto('No photo', $prefix.$picto);
  2051. }
  2052. $morehtmlleft .= '<!-- No photo to show -->';
  2053. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2054. $morehtmlleft .= $nophoto;
  2055. $morehtmlleft .= '</div></div>';
  2056. }
  2057. }
  2058. }
  2059. if ($showbarcode) {
  2060. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
  2061. }
  2062. if ($object->element == 'societe') {
  2063. if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2064. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  2065. } else {
  2066. $morehtmlstatus .= $object->getLibStatut(6);
  2067. }
  2068. } elseif ($object->element == 'product') {
  2069. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  2070. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2071. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  2072. } else {
  2073. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  2074. }
  2075. $morehtmlstatus .= ' &nbsp; ';
  2076. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2077. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2078. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2079. } else {
  2080. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2081. }
  2082. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  2083. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2084. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2085. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2086. }
  2087. $morehtmlstatus .= $tmptxt;
  2088. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2089. if ($object->statut == 0) {
  2090. $morehtmlstatus .= $object->getLibStatut(5);
  2091. } else {
  2092. $morehtmlstatus .= $object->getLibStatut(4);
  2093. }
  2094. } elseif ($object->element == 'facturerec') {
  2095. if ($object->frequency == 0) {
  2096. $morehtmlstatus .= $object->getLibStatut(2);
  2097. } else {
  2098. $morehtmlstatus .= $object->getLibStatut(5);
  2099. }
  2100. } elseif ($object->element == 'project_task') {
  2101. $object->fk_statut = 1;
  2102. if ($object->progress > 0) {
  2103. $object->fk_statut = 2;
  2104. }
  2105. if ($object->progress >= 100) {
  2106. $object->fk_statut = 3;
  2107. }
  2108. $tmptxt = $object->getLibStatut(5);
  2109. $morehtmlstatus .= $tmptxt; // No status on task
  2110. } else { // Generic case
  2111. if (isset($object->status)) {
  2112. $tmptxt = $object->getLibStatut(6);
  2113. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2114. $tmptxt = $object->getLibStatut(5);
  2115. }
  2116. $morehtmlstatus .= $tmptxt;
  2117. }
  2118. }
  2119. // Add if object was dispatched "into accountancy"
  2120. if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2121. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2122. if (method_exists($object, 'getVentilExportCompta')) {
  2123. $accounted = $object->getVentilExportCompta();
  2124. $langs->load("accountancy");
  2125. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2126. }
  2127. }
  2128. // Add alias for thirdparty
  2129. if (!empty($object->name_alias)) {
  2130. $morehtmlref .= '<div class="refidno opacitymedium">'.$object->name_alias.'</div>';
  2131. }
  2132. // Add label
  2133. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2134. if (!empty($object->label)) {
  2135. $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
  2136. }
  2137. }
  2138. // Show address and email
  2139. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2140. $moreaddress = $object->getBannerAddress('refaddress', $object);
  2141. if ($moreaddress) {
  2142. $morehtmlref .= '<div class="refidno">';
  2143. $morehtmlref .= $moreaddress;
  2144. $morehtmlref .= '</div>';
  2145. }
  2146. }
  2147. 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)) {
  2148. $morehtmlref .= '<div style="clear: both;"></div>';
  2149. $morehtmlref .= '<div class="refidno opacitymedium">';
  2150. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  2151. $morehtmlref .= '</div>';
  2152. }
  2153. $parameters=array('morehtmlref'=>$morehtmlref);
  2154. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2155. if ($reshook < 0) {
  2156. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2157. } elseif (empty($reshook)) {
  2158. $morehtmlref .= $hookmanager->resPrint;
  2159. } elseif ($reshook > 0) {
  2160. $morehtmlref = $hookmanager->resPrint;
  2161. }
  2162. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2163. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2164. print '</div>';
  2165. print '<div class="underrefbanner clearboth"></div>';
  2166. }
  2167. /**
  2168. * Show a string with the label tag dedicated to the HTML edit field.
  2169. *
  2170. * @param string $langkey Translation key
  2171. * @param string $fieldkey Key of the html select field the text refers to
  2172. * @param int $fieldrequired 1=Field is mandatory
  2173. * @return string
  2174. * @deprecated Form::editfieldkey
  2175. */
  2176. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2177. {
  2178. global $langs;
  2179. $ret = '';
  2180. if ($fieldrequired) {
  2181. $ret .= '<span class="fieldrequired">';
  2182. }
  2183. $ret .= '<label for="'.$fieldkey.'">';
  2184. $ret .= $langs->trans($langkey);
  2185. $ret .= '</label>';
  2186. if ($fieldrequired) {
  2187. $ret .= '</span>';
  2188. }
  2189. return $ret;
  2190. }
  2191. /**
  2192. * Return string to add class property on html element with pair/impair.
  2193. *
  2194. * @param string $var 0 or 1
  2195. * @param string $moreclass More class to add
  2196. * @return string String to add class onto HTML element
  2197. */
  2198. function dol_bc($var, $moreclass = '')
  2199. {
  2200. global $bc;
  2201. $ret = ' '.$bc[$var];
  2202. if ($moreclass) {
  2203. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2204. }
  2205. return $ret;
  2206. }
  2207. /**
  2208. * Return a formated address (part address/zip/town/state) according to country rules.
  2209. * See https://en.wikipedia.org/wiki/Address
  2210. *
  2211. * @param Object $object A company or contact object
  2212. * @param int $withcountry 1=Add country into address string
  2213. * @param string $sep Separator to use to build string
  2214. * @param Translate $outputlangs Object lang that contains language for text translation.
  2215. * @param int $mode 0=Standard output, 1=Remove address
  2216. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2217. * @return string Formated string
  2218. * @see dol_print_address()
  2219. */
  2220. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2221. {
  2222. global $conf, $langs, $hookmanager;
  2223. $ret = '';
  2224. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2225. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2226. // Address
  2227. if (empty($mode)) {
  2228. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2229. }
  2230. // Zip/Town/State
  2231. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2232. // US: title firstname name \n address lines \n town, state, zip \n country
  2233. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2234. $ret .= (($ret && $town) ? $sep : '').$town;
  2235. if (!empty($object->state)) {
  2236. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2237. }
  2238. if (!empty($object->zip)) {
  2239. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2240. }
  2241. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2242. // UK: title firstname name \n address lines \n town state \n zip \n country
  2243. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2244. $ret .= ($ret ? $sep : '').$town;
  2245. if (!empty($object->state)) {
  2246. $ret .= ($ret ? ", " : '').$object->state;
  2247. }
  2248. if (!empty($object->zip)) {
  2249. $ret .= ($ret ? $sep : '').$object->zip;
  2250. }
  2251. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2252. // ES: title firstname name \n address lines \n zip town \n state \n country
  2253. $ret .= ($ret ? $sep : '').$object->zip;
  2254. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2255. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2256. if (!empty($object->state)) {
  2257. $ret .= "\n".$object->state;
  2258. }
  2259. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2260. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2261. // See https://www.sljfaq.org/afaq/addresses.html
  2262. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2263. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2264. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2265. // IT: title firstname name\n address lines \n zip town state_code \n country
  2266. $ret .= ($ret ? $sep : '').$object->zip;
  2267. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2268. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2269. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2270. } else {
  2271. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2272. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2273. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2274. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2275. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2276. $ret .= ($ret ? ", " : '').$object->state;
  2277. }
  2278. }
  2279. if (!is_object($outputlangs)) {
  2280. $outputlangs = $langs;
  2281. }
  2282. if ($withcountry) {
  2283. $langs->load("dict");
  2284. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2285. }
  2286. if ($hookmanager) {
  2287. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2288. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2289. if ($reshook > 0) {
  2290. $ret = '';
  2291. }
  2292. $ret .= $hookmanager->resPrint;
  2293. }
  2294. return $ret;
  2295. }
  2296. /**
  2297. * Format a string.
  2298. *
  2299. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2300. * @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)
  2301. * @param int $is_gmt See comment of timestamp parameter
  2302. * @return string A formatted string
  2303. */
  2304. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2305. {
  2306. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2307. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2308. } else {
  2309. return 'Error date into a not supported range';
  2310. }
  2311. }
  2312. /**
  2313. * Output date in a string format according to outputlangs (or langs if not defined).
  2314. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2315. *
  2316. * @param int $time GM Timestamps date
  2317. * @param string $format Output date format (tag of strftime function)
  2318. * "%d %b %Y",
  2319. * "%d/%m/%Y %H:%M",
  2320. * "%d/%m/%Y %H:%M:%S",
  2321. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2322. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2323. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2324. * false or 'tzserver' => output string is for local PHP server TZ usage
  2325. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2326. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2327. * @param Translate $outputlangs Object lang that contains language for text translation.
  2328. * @param boolean $encodetooutput false=no convert into output pagecode
  2329. * @return string Formated date or '' if time is null
  2330. *
  2331. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2332. */
  2333. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2334. {
  2335. global $conf, $langs;
  2336. // If date undefined or "", we return ""
  2337. if (dol_strlen($time) == 0) {
  2338. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2339. }
  2340. if ($tzoutput === 'auto') {
  2341. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2342. }
  2343. // Clean parameters
  2344. $to_gmt = false;
  2345. $offsettz = $offsetdst = 0;
  2346. if ($tzoutput) {
  2347. $to_gmt = true; // For backward compatibility
  2348. if (is_string($tzoutput)) {
  2349. if ($tzoutput == 'tzserver') {
  2350. $to_gmt = false;
  2351. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2352. $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
  2353. $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
  2354. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2355. $to_gmt = true;
  2356. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2357. if (class_exists('DateTimeZone')) {
  2358. $user_date_tz = new DateTimeZone($offsettzstring);
  2359. $user_dt = new DateTime();
  2360. $user_dt->setTimezone($user_date_tz);
  2361. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2362. $offsettz = $user_dt->getOffset(); // should include dst ?
  2363. } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
  2364. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2365. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2366. }
  2367. }
  2368. }
  2369. }
  2370. if (!is_object($outputlangs)) {
  2371. $outputlangs = $langs;
  2372. }
  2373. if (!$format) {
  2374. $format = 'daytextshort';
  2375. }
  2376. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2377. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2378. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2379. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2380. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2381. if ($formatwithoutreduce != $format) {
  2382. $format = $formatwithoutreduce;
  2383. $reduceformat = 1;
  2384. } // so format 'dayreduceformat' is processed like day
  2385. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2386. // TODO Add format daysmallyear and dayhoursmallyear
  2387. if ($format == 'day') {
  2388. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2389. } elseif ($format == 'hour') {
  2390. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2391. } elseif ($format == 'hourduration') {
  2392. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2393. } elseif ($format == 'daytext') {
  2394. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2395. } elseif ($format == 'daytextshort') {
  2396. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2397. } elseif ($format == 'dayhour') {
  2398. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2399. } elseif ($format == 'dayhoursec') {
  2400. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2401. } elseif ($format == 'dayhourtext') {
  2402. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2403. } elseif ($format == 'dayhourtextshort') {
  2404. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2405. } elseif ($format == 'dayhourlog') {
  2406. // Format not sensitive to language
  2407. $format = '%Y%m%d%H%M%S';
  2408. } elseif ($format == 'dayhourlogsmall') {
  2409. // Format not sensitive to language
  2410. $format = '%Y%m%d%H%M';
  2411. } elseif ($format == 'dayhourldap') {
  2412. $format = '%Y%m%d%H%M%SZ';
  2413. } elseif ($format == 'dayhourxcard') {
  2414. $format = '%Y%m%dT%H%M%SZ';
  2415. } elseif ($format == 'dayxcard') {
  2416. $format = '%Y%m%d';
  2417. } elseif ($format == 'dayrfc') {
  2418. $format = '%Y-%m-%d'; // DATE_RFC3339
  2419. } elseif ($format == 'dayhourrfc') {
  2420. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2421. } elseif ($format == 'standard') {
  2422. $format = '%Y-%m-%d %H:%M:%S';
  2423. }
  2424. if ($reduceformat) {
  2425. $format = str_replace('%Y', '%y', $format);
  2426. $format = str_replace('yyyy', 'yy', $format);
  2427. }
  2428. // Clean format
  2429. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2430. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2431. $format = str_replace('%b', '__b__', $format);
  2432. $format = str_replace('%B', '__B__', $format);
  2433. }
  2434. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2435. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2436. $format = str_replace('%a', '__a__', $format);
  2437. $format = str_replace('%A', '__A__', $format);
  2438. }
  2439. // Analyze date
  2440. $reg = array();
  2441. 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
  2442. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2443. return '';
  2444. } 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
  2445. // This part of code should not be used anymore.
  2446. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2447. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2448. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2449. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2450. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2451. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2452. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2453. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2454. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2455. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2456. if ($to_gmt) {
  2457. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2458. } else {
  2459. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2460. }
  2461. $dtts = new DateTime();
  2462. $dtts->setTimestamp($time);
  2463. $dtts->setTimezone($tzo);
  2464. $newformat = str_replace(
  2465. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2466. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2467. $format);
  2468. $ret = $dtts->format($newformat);
  2469. $ret = str_replace(
  2470. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2471. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2472. $ret
  2473. );
  2474. } else {
  2475. // Date is a timestamps
  2476. if ($time < 100000000000) { // Protection against bad date values
  2477. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2478. if ($to_gmt) {
  2479. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2480. } else {
  2481. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2482. }
  2483. $dtts = new DateTime();
  2484. $dtts->setTimestamp($timetouse);
  2485. $dtts->setTimezone($tzo);
  2486. $newformat = str_replace(
  2487. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2488. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2489. $format);
  2490. $ret = $dtts->format($newformat);
  2491. $ret = str_replace(
  2492. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2493. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2494. $ret
  2495. );
  2496. //var_dump($ret);exit;
  2497. } else {
  2498. $ret = 'Bad value '.$time.' for date';
  2499. }
  2500. }
  2501. if (preg_match('/__b__/i', $format)) {
  2502. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2503. if ($to_gmt) {
  2504. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2505. } else {
  2506. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2507. }
  2508. $dtts = new DateTime();
  2509. $dtts->setTimestamp($timetouse);
  2510. $dtts->setTimezone($tzo);
  2511. $month = $dtts->format("m");
  2512. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2513. if ($encodetooutput) {
  2514. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2515. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2516. } else {
  2517. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2518. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2519. }
  2520. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2521. $ret = str_replace('__b__', $monthtextshort, $ret);
  2522. $ret = str_replace('__B__', $monthtext, $ret);
  2523. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2524. //return $ret;
  2525. }
  2526. if (preg_match('/__a__/i', $format)) {
  2527. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2528. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2529. if ($to_gmt) {
  2530. $tzo = new DateTimeZone('UTC');
  2531. } else {
  2532. $tzo = new DateTimeZone(date_default_timezone_get());
  2533. }
  2534. $dtts = new DateTime();
  2535. $dtts->setTimestamp($timetouse);
  2536. $dtts->setTimezone($tzo);
  2537. $w = $dtts->format("w");
  2538. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2539. $ret = str_replace('__A__', $dayweek, $ret);
  2540. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2541. }
  2542. return $ret;
  2543. }
  2544. /**
  2545. * Return an array with locale date info.
  2546. * WARNING: This function use PHP server timezone by default to return locale informations.
  2547. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2548. *
  2549. * @param int $timestamp Timestamp
  2550. * @param boolean $fast Fast mode. deprecated.
  2551. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2552. * @return array Array of informations
  2553. * 'seconds' => $secs,
  2554. * 'minutes' => $min,
  2555. * 'hours' => $hour,
  2556. * 'mday' => $day,
  2557. * 'wday' => $dow, 0=sunday, 6=saturday
  2558. * 'mon' => $month,
  2559. * 'year' => $year,
  2560. * 'yday' => floor($secsInYear/$_day_power)
  2561. * '0' => original timestamp
  2562. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2563. */
  2564. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2565. {
  2566. $datetimeobj = new DateTime();
  2567. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2568. if ($forcetimezone) {
  2569. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2570. }
  2571. $arrayinfo = array(
  2572. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2573. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2574. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2575. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2576. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2577. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2578. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2579. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2580. '0'=>$timestamp
  2581. );
  2582. return $arrayinfo;
  2583. }
  2584. /**
  2585. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2586. * Replace function mktime not available under Windows if year < 1970
  2587. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2588. *
  2589. * @param int $hour Hour (can be -1 for undefined)
  2590. * @param int $minute Minute (can be -1 for undefined)
  2591. * @param int $second Second (can be -1 for undefined)
  2592. * @param int $month Month (1 to 12)
  2593. * @param int $day Day (1 to 31)
  2594. * @param int $year Year
  2595. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2596. * False or 0 or 'tzserver' = local to server TZ
  2597. * 'auto'
  2598. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2599. * '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.
  2600. * 'tz,TimeZone' = use specified timezone
  2601. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2602. * @return int|string Date as a timestamp, '' or false if error
  2603. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2604. */
  2605. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2606. {
  2607. global $conf;
  2608. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2609. if ($gm === 'auto') {
  2610. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2611. }
  2612. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2613. // Clean parameters
  2614. if ($hour == -1 || empty($hour)) {
  2615. $hour = 0;
  2616. }
  2617. if ($minute == -1 || empty($minute)) {
  2618. $minute = 0;
  2619. }
  2620. if ($second == -1 || empty($second)) {
  2621. $second = 0;
  2622. }
  2623. // Check parameters
  2624. if ($check) {
  2625. if (!$month || !$day) {
  2626. return '';
  2627. }
  2628. if ($day > 31) {
  2629. return '';
  2630. }
  2631. if ($month > 12) {
  2632. return '';
  2633. }
  2634. if ($hour < 0 || $hour > 24) {
  2635. return '';
  2636. }
  2637. if ($minute < 0 || $minute > 60) {
  2638. return '';
  2639. }
  2640. if ($second < 0 || $second > 60) {
  2641. return '';
  2642. }
  2643. }
  2644. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2645. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2646. $localtz = new DateTimeZone($default_timezone);
  2647. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2648. // We use dol_tz_string first because it is more reliable.
  2649. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2650. try {
  2651. $localtz = new DateTimeZone($default_timezone);
  2652. } catch (Exception $e) {
  2653. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2654. $default_timezone = @date_default_timezone_get();
  2655. }
  2656. } elseif (strrpos($gm, "tz,") !== false) {
  2657. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2658. try {
  2659. $localtz = new DateTimeZone($timezone);
  2660. } catch (Exception $e) {
  2661. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2662. }
  2663. }
  2664. if (empty($localtz)) {
  2665. $localtz = new DateTimeZone('UTC');
  2666. }
  2667. //var_dump($localtz);
  2668. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2669. $dt = new DateTime('now', $localtz);
  2670. $dt->setDate((int) $year, (int) $month, (int) $day);
  2671. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2672. $date = $dt->getTimestamp(); // should include daylight saving time
  2673. //var_dump($date);
  2674. return $date;
  2675. }
  2676. /**
  2677. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2678. *
  2679. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2680. * 'gmt' => we return GMT timestamp,
  2681. * 'tzserver' => we add the PHP server timezone
  2682. * 'tzref' => we add the company timezone. Not implemented.
  2683. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2684. * @return int $date Timestamp
  2685. */
  2686. function dol_now($mode = 'auto')
  2687. {
  2688. $ret = 0;
  2689. if ($mode === 'auto') {
  2690. $mode = 'gmt';
  2691. }
  2692. if ($mode == 'gmt') {
  2693. $ret = time(); // Time for now at greenwich.
  2694. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2695. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2696. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2697. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2698. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2699. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2700. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2701. // $ret=dol_now('gmt')+($tzsecond*3600);
  2702. //}
  2703. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2704. // Time for now with user timezone added
  2705. //print 'time: '.time();
  2706. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2707. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2708. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2709. }
  2710. return $ret;
  2711. }
  2712. /**
  2713. * Return string with formated size
  2714. *
  2715. * @param int $size Size to print
  2716. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2717. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2718. * @return string Link
  2719. */
  2720. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2721. {
  2722. global $conf, $langs;
  2723. $level = 1024;
  2724. if (!empty($conf->dol_optimize_smallscreen)) {
  2725. $shortunit = 1;
  2726. }
  2727. // Set value text
  2728. if (empty($shortvalue) || $size < ($level * 10)) {
  2729. $ret = $size;
  2730. $textunitshort = $langs->trans("b");
  2731. $textunitlong = $langs->trans("Bytes");
  2732. } else {
  2733. $ret = round($size / $level, 0);
  2734. $textunitshort = $langs->trans("Kb");
  2735. $textunitlong = $langs->trans("KiloBytes");
  2736. }
  2737. // Use long or short text unit
  2738. if (empty($shortunit)) {
  2739. $ret .= ' '.$textunitlong;
  2740. } else {
  2741. $ret .= ' '.$textunitshort;
  2742. }
  2743. return $ret;
  2744. }
  2745. /**
  2746. * Show Url link
  2747. *
  2748. * @param string $url Url to show
  2749. * @param string $target Target for link
  2750. * @param int $max Max number of characters to show
  2751. * @param int $withpicto With picto
  2752. * @return string HTML Link
  2753. */
  2754. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2755. {
  2756. global $langs;
  2757. if (empty($url)) {
  2758. return '';
  2759. }
  2760. $link = '<a href="';
  2761. if (!preg_match('/^http/i', $url)) {
  2762. $link .= 'http://';
  2763. }
  2764. $link .= $url;
  2765. $link .= '"';
  2766. if ($target) {
  2767. $link .= ' target="'.$target.'"';
  2768. }
  2769. $link .= '>';
  2770. if (!preg_match('/^http/i', $url)) {
  2771. $link .= 'http://';
  2772. }
  2773. $link .= dol_trunc($url, $max);
  2774. $link .= '</a>';
  2775. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2776. }
  2777. /**
  2778. * Show EMail link formatted for HTML output.
  2779. *
  2780. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2781. * @param int $cid Id of contact if known
  2782. * @param int $socid Id of third party if known
  2783. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2784. * @param int $max Max number of characters to show
  2785. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2786. * @param int|string $withpicto Show picto
  2787. * @return string HTML Link
  2788. */
  2789. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2790. {
  2791. global $conf, $user, $langs, $hookmanager;
  2792. $newemail = dol_escape_htmltag($email);
  2793. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2794. $withpicto = 0;
  2795. }
  2796. if (empty($email)) {
  2797. return '&nbsp;';
  2798. }
  2799. if (!empty($addlink)) {
  2800. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2801. if (!preg_match('/^mailto:/i', $email)) {
  2802. $newemail .= 'mailto:';
  2803. }
  2804. $newemail .= $email;
  2805. $newemail .= '">';
  2806. $newemail .= dol_trunc($email, $max);
  2807. $newemail .= '</a>';
  2808. if ($showinvalid && !isValidEmail($email)) {
  2809. $langs->load("errors");
  2810. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2811. }
  2812. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  2813. $type = 'AC_EMAIL';
  2814. $link = '';
  2815. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2816. $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>';
  2817. }
  2818. if ($link) {
  2819. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2820. }
  2821. }
  2822. } else {
  2823. if ($showinvalid && !isValidEmail($email)) {
  2824. $langs->load("errors");
  2825. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2826. }
  2827. }
  2828. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2829. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  2830. //$rep .= '</div>';
  2831. if ($hookmanager) {
  2832. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2833. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2834. if ($reshook > 0) {
  2835. $rep = '';
  2836. }
  2837. $rep .= $hookmanager->resPrint;
  2838. }
  2839. return $rep;
  2840. }
  2841. /**
  2842. * Get array of social network dictionary
  2843. *
  2844. * @return array Array of Social Networks Dictionary
  2845. */
  2846. function getArrayOfSocialNetworks()
  2847. {
  2848. global $conf, $db;
  2849. $socialnetworks = array();
  2850. // Enable caching of array
  2851. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2852. $cachekey = 'socialnetworks_' . $conf->entity;
  2853. $dataretrieved = dol_getcache($cachekey);
  2854. if (!is_null($dataretrieved)) {
  2855. $socialnetworks = $dataretrieved;
  2856. } else {
  2857. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2858. $sql .= " WHERE entity=".$conf->entity;
  2859. $resql = $db->query($sql);
  2860. if ($resql) {
  2861. while ($obj = $db->fetch_object($resql)) {
  2862. $socialnetworks[$obj->code] = array(
  2863. 'rowid' => $obj->rowid,
  2864. 'label' => $obj->label,
  2865. 'url' => $obj->url,
  2866. 'icon' => $obj->icon,
  2867. 'active' => $obj->active,
  2868. );
  2869. }
  2870. }
  2871. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2872. }
  2873. return $socialnetworks;
  2874. }
  2875. /**
  2876. * Show social network link
  2877. *
  2878. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2879. * @param int $cid Id of contact if known
  2880. * @param int $socid Id of third party if known
  2881. * @param string $type 'skype','facebook',...
  2882. * @param array $dictsocialnetworks socialnetworks availables
  2883. * @return string HTML Link
  2884. */
  2885. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2886. {
  2887. global $conf, $user, $langs;
  2888. $htmllink = $value;
  2889. if (empty($value)) {
  2890. return '&nbsp;';
  2891. }
  2892. if (!empty($type)) {
  2893. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2894. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2895. $htmllink .= '<span class="fa paddingright '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2896. if ($type == 'skype') {
  2897. $htmllink .= dol_escape_htmltag($value);
  2898. $htmllink .= '&nbsp;';
  2899. $htmllink .= '<a href="skype:';
  2900. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2901. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  2902. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2903. $htmllink .= '</a><a href="skype:';
  2904. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2905. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  2906. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2907. $htmllink .= '</a>';
  2908. if (($cid || $socid) && isModEnabled('agenda') && $user->rights->agenda->myactions->create) {
  2909. $addlink = 'AC_SKYPE';
  2910. $link = '';
  2911. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  2912. $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>';
  2913. }
  2914. $htmllink .= ($link ? ' '.$link : '');
  2915. }
  2916. } else {
  2917. if (!empty($dictsocialnetworks[$type]['url'])) {
  2918. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  2919. if ($tmpvirginurl) {
  2920. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  2921. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  2922. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  2923. if ($tmpvirginurl3) {
  2924. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  2925. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  2926. }
  2927. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  2928. if ($tmpvirginurl2) {
  2929. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  2930. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  2931. }
  2932. }
  2933. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  2934. if (preg_match('/^https?:\/\//i', $link)) {
  2935. $htmllink .= '&nbsp;<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  2936. } else {
  2937. $htmllink .= '&nbsp;<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  2938. }
  2939. } else {
  2940. $htmllink .= dol_escape_htmltag($value);
  2941. }
  2942. }
  2943. $htmllink .= '</div>';
  2944. } else {
  2945. $langs->load("errors");
  2946. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2947. }
  2948. return $htmllink;
  2949. }
  2950. /**
  2951. * Format profIDs according to country
  2952. *
  2953. * @param string $profID Value of profID to format
  2954. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  2955. * @param string $countrycode Country code to use for formatting
  2956. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  2957. * @param string $separ Separation between numbers for a better visibility example : xxx xxx xxx xxxxx
  2958. * @return string Formated profID
  2959. */
  2960. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
  2961. {
  2962. global $mysoc;
  2963. if (empty($profID) || empty($profIDtype)) {
  2964. return '';
  2965. }
  2966. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2967. $newProfID = $profID;
  2968. $id = substr($profIDtype, -1);
  2969. $ret = '';
  2970. if (strtoupper($countrycode) == 'FR') {
  2971. // France
  2972. if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
  2973. 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);
  2974. 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);
  2975. }
  2976. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  2977. else $ret = $newProfID;
  2978. return $ret;
  2979. }
  2980. /**
  2981. * Format phone numbers according to country
  2982. *
  2983. * @param string $phone Phone number to format
  2984. * @param string $countrycode Country code to use for formatting
  2985. * @param int $cid Id of contact if known
  2986. * @param int $socid Id of third party if known
  2987. * @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)
  2988. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2989. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  2990. * @param string $titlealt Text to show on alt
  2991. * @param int $adddivfloat Add div float around phone.
  2992. * @return string Formated phone number
  2993. */
  2994. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2995. {
  2996. global $conf, $user, $langs, $mysoc, $hookmanager;
  2997. // Clean phone parameter
  2998. $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
  2999. if (empty($phone)) {
  3000. return '';
  3001. }
  3002. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  3003. $separ = $conf->global->MAIN_PHONE_SEPAR;
  3004. }
  3005. if (empty($countrycode) && is_object($mysoc)) {
  3006. $countrycode = $mysoc->country_code;
  3007. }
  3008. // Short format for small screens
  3009. if ($conf->dol_optimize_smallscreen) {
  3010. $separ = '';
  3011. }
  3012. $newphone = $phone;
  3013. if (strtoupper($countrycode) == "FR") {
  3014. // France
  3015. if (dol_strlen($phone) == 10) {
  3016. $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);
  3017. } elseif (dol_strlen($phone) == 7) {
  3018. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  3019. } elseif (dol_strlen($phone) == 9) {
  3020. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  3021. } elseif (dol_strlen($phone) == 11) {
  3022. $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);
  3023. } elseif (dol_strlen($phone) == 12) {
  3024. $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);
  3025. } elseif (dol_strlen($phone) == 13) {
  3026. $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);
  3027. }
  3028. } elseif (strtoupper($countrycode) == "CA") {
  3029. if (dol_strlen($phone) == 10) {
  3030. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  3031. }
  3032. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  3033. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  3034. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3035. }
  3036. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  3037. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  3038. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  3039. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  3040. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  3041. }
  3042. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  3043. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  3044. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  3045. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  3046. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  3047. }
  3048. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  3049. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  3050. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3051. }
  3052. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  3053. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  3054. $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);
  3055. }
  3056. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  3057. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  3058. $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);
  3059. }
  3060. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  3061. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  3062. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3063. }
  3064. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  3065. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  3066. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3067. }
  3068. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  3069. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  3070. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3071. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  3072. $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);
  3073. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  3074. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3075. }
  3076. } elseif (strtoupper($countrycode) == "ML") {//Mali
  3077. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  3078. $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);
  3079. }
  3080. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  3081. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  3082. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3083. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  3084. $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);
  3085. }
  3086. } elseif (strtoupper($countrycode) == "MU") {
  3087. //Maurice
  3088. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  3089. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  3090. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  3091. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  3092. }
  3093. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  3094. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  3095. $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);
  3096. }
  3097. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  3098. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  3099. $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);
  3100. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  3101. $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);
  3102. }
  3103. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  3104. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  3105. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3106. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  3107. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3108. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  3109. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  3110. }
  3111. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  3112. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  3113. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3114. }
  3115. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  3116. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  3117. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3118. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  3119. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3120. }
  3121. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  3122. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  3123. $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);
  3124. }
  3125. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  3126. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  3127. $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);
  3128. }
  3129. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3130. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3131. $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);
  3132. }
  3133. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3134. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3135. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3136. }
  3137. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3138. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
  3139. $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);
  3140. }
  3141. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3142. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3143. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3144. }
  3145. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3146. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3147. $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);
  3148. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3149. $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);
  3150. }
  3151. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3152. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3153. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3154. }
  3155. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3156. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3157. $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);
  3158. }
  3159. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3160. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3161. $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);
  3162. }
  3163. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3164. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3165. $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);
  3166. }
  3167. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3168. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3169. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3170. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3171. $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);
  3172. }
  3173. } elseif (strtoupper($countrycode) == "AU") {
  3174. //Australie
  3175. if (dol_strlen($phone) == 12) {
  3176. //ex: +61_A_BCDE_FGHI
  3177. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3178. }
  3179. } elseif (strtoupper($countrycode) == "LU") {
  3180. // Luxembourg
  3181. if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
  3182. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
  3183. } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
  3184. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 1);
  3185. } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
  3186. $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);
  3187. } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
  3188. $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);
  3189. }
  3190. }
  3191. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3192. if ($conf->browser->layout == 'phone' || (isModEnabled('clicktodial') && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) { // If phone or option for, we use link of phone
  3193. $newphoneform = $newphone;
  3194. $newphone = '<a href="tel:'.$phone.'"';
  3195. $newphone .= '>'.$newphoneform.'</a>';
  3196. } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3197. if (empty($user->clicktodial_loaded)) {
  3198. $user->fetch_clicktodial();
  3199. }
  3200. // Define urlmask
  3201. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  3202. if (!empty($conf->global->CLICKTODIAL_URL)) {
  3203. $urlmask = $conf->global->CLICKTODIAL_URL;
  3204. }
  3205. if (!empty($user->clicktodial_url)) {
  3206. $urlmask = $user->clicktodial_url;
  3207. }
  3208. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  3209. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  3210. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  3211. // This line is for backward compatibility
  3212. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3213. // Thoose lines are for substitution
  3214. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3215. '__PHONETO__'=>urlencode($phone),
  3216. '__LOGIN__'=>$clicktodial_login,
  3217. '__PASS__'=>$clicktodial_password);
  3218. $url = make_substitutions($url, $substitarray);
  3219. $newphonesav = $newphone;
  3220. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  3221. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3222. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3223. $newphone .= '>'.$newphonesav.'</a>';
  3224. } else {
  3225. // Old method
  3226. $newphone = '<a href="'.$url.'"';
  3227. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  3228. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  3229. }
  3230. $newphone .= '>'.$newphonesav.'</a>';
  3231. }
  3232. }
  3233. //if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  3234. if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3235. $type = 'AC_TEL';
  3236. $link = '';
  3237. if ($addlink == 'AC_FAX') {
  3238. $type = 'AC_FAX';
  3239. }
  3240. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  3241. $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  3242. }
  3243. if ($link) {
  3244. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  3245. }
  3246. }
  3247. }
  3248. if (empty($titlealt)) {
  3249. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3250. }
  3251. $rep = '';
  3252. if ($hookmanager) {
  3253. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3254. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3255. $rep .= $hookmanager->resPrint;
  3256. }
  3257. if (empty($reshook)) {
  3258. $picto = '';
  3259. if ($withpicto) {
  3260. if ($withpicto == 'fax') {
  3261. $picto = 'phoning_fax';
  3262. } elseif ($withpicto == 'phone') {
  3263. $picto = 'phoning';
  3264. } elseif ($withpicto == 'mobile') {
  3265. $picto = 'phoning_mobile';
  3266. } else {
  3267. $picto = '';
  3268. }
  3269. }
  3270. if ($adddivfloat) {
  3271. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3272. } else {
  3273. $rep .= '<span style="margin-right: 10px;">';
  3274. }
  3275. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  3276. if ($adddivfloat) {
  3277. $rep .= '</div>';
  3278. } else {
  3279. $rep .= '</span>';
  3280. }
  3281. }
  3282. return $rep;
  3283. }
  3284. /**
  3285. * Return an IP formated to be shown on screen
  3286. *
  3287. * @param string $ip IP
  3288. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3289. * @return string Formated IP, with country if GeoIP module is enabled
  3290. */
  3291. function dol_print_ip($ip, $mode = 0)
  3292. {
  3293. global $conf, $langs;
  3294. $ret = '';
  3295. if (empty($mode)) {
  3296. $ret .= $ip;
  3297. }
  3298. if ($mode != 2) {
  3299. $countrycode = dolGetCountryCodeFromIp($ip);
  3300. if ($countrycode) { // If success, countrycode is us, fr, ...
  3301. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3302. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3303. } else {
  3304. $ret .= ' ('.$countrycode.')';
  3305. }
  3306. } else {
  3307. // Nothing
  3308. }
  3309. }
  3310. return $ret;
  3311. }
  3312. /**
  3313. * Return the IP of remote user.
  3314. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3315. * Then HTTP_CLIENT_IP if defined (rare)
  3316. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3317. *
  3318. * @return string Ip of remote user.
  3319. */
  3320. function getUserRemoteIP()
  3321. {
  3322. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3323. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3324. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3325. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3326. } else {
  3327. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3328. }
  3329. } else {
  3330. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3331. }
  3332. } else {
  3333. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3334. }
  3335. return $ip;
  3336. }
  3337. /**
  3338. * Return if we are using a HTTPS connexion
  3339. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3340. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3341. * Then HTTP_X_FORWARDED_SSL
  3342. *
  3343. * @return boolean True if user is using HTTPS
  3344. */
  3345. function isHTTPS()
  3346. {
  3347. $isSecure = false;
  3348. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3349. $isSecure = true;
  3350. } 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') {
  3351. $isSecure = true;
  3352. }
  3353. return $isSecure;
  3354. }
  3355. /**
  3356. * Return a country code from IP. Empty string if not found.
  3357. *
  3358. * @param string $ip IP
  3359. * @return string Country code ('us', 'fr', ...)
  3360. */
  3361. function dolGetCountryCodeFromIp($ip)
  3362. {
  3363. global $conf;
  3364. $countrycode = '';
  3365. if (!empty($conf->geoipmaxmind->enabled)) {
  3366. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3367. //$ip='24.24.24.24';
  3368. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3369. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3370. $geoip = new DolGeoIP('country', $datafile);
  3371. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3372. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3373. }
  3374. return $countrycode;
  3375. }
  3376. /**
  3377. * Return country code for current user.
  3378. * If software is used inside a local network, detection may fails (we need a public ip)
  3379. *
  3380. * @return string Country code (fr, es, it, us, ...)
  3381. */
  3382. function dol_user_country()
  3383. {
  3384. global $conf, $langs, $user;
  3385. //$ret=$user->xxx;
  3386. $ret = '';
  3387. if (!empty($conf->geoipmaxmind->enabled)) {
  3388. $ip = getUserRemoteIP();
  3389. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3390. //$ip='24.24.24.24';
  3391. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3392. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3393. $geoip = new DolGeoIP('country', $datafile);
  3394. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3395. $ret = $countrycode;
  3396. }
  3397. return $ret;
  3398. }
  3399. /**
  3400. * Format address string
  3401. *
  3402. * @param string $address Address string, already formatted with dol_format_address()
  3403. * @param int $htmlid Html ID (for example 'gmap')
  3404. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3405. * @param int $id Id of object
  3406. * @param int $noprint No output. Result is the function return
  3407. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3408. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3409. * @see dol_format_address()
  3410. */
  3411. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3412. {
  3413. global $conf, $user, $langs, $hookmanager;
  3414. $out = '';
  3415. if ($address) {
  3416. if ($hookmanager) {
  3417. $parameters = array('element' => $element, 'id' => $id);
  3418. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3419. $out .= $hookmanager->resPrint;
  3420. }
  3421. if (empty($reshook)) {
  3422. if (empty($charfornl)) {
  3423. $out .= nl2br($address);
  3424. } else {
  3425. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3426. }
  3427. // TODO Remove this block, we can add this using the hook now
  3428. $showgmap = $showomap = 0;
  3429. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3430. $showgmap = 1;
  3431. }
  3432. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3433. $showgmap = 1;
  3434. }
  3435. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3436. $showgmap = 1;
  3437. }
  3438. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3439. $showomap = 1;
  3440. }
  3441. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3442. $showomap = 1;
  3443. }
  3444. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3445. $showomap = 1;
  3446. }
  3447. if ($showgmap) {
  3448. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3449. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3450. }
  3451. if ($showomap) {
  3452. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3453. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3454. }
  3455. }
  3456. }
  3457. if ($noprint) {
  3458. return $out;
  3459. } else {
  3460. print $out;
  3461. }
  3462. }
  3463. /**
  3464. * Return true if email syntax is ok.
  3465. *
  3466. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3467. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3468. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3469. * @return boolean true if email syntax is OK, false if KO or empty string
  3470. * @see isValidMXRecord()
  3471. */
  3472. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3473. {
  3474. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3475. return true;
  3476. }
  3477. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3478. return true;
  3479. }
  3480. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3481. return true;
  3482. }
  3483. return false;
  3484. }
  3485. /**
  3486. * Return if the domain name has a valid MX record.
  3487. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3488. *
  3489. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3490. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3491. * @see isValidEmail()
  3492. */
  3493. function isValidMXRecord($domain)
  3494. {
  3495. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3496. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3497. return 0;
  3498. }
  3499. if (function_exists('getmxrr')) {
  3500. $mxhosts = array();
  3501. $weight = array();
  3502. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3503. if (count($mxhosts) > 1) {
  3504. return 1;
  3505. }
  3506. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3507. return 1;
  3508. }
  3509. return 0;
  3510. }
  3511. }
  3512. // function idn_to_ascii or checkdnsrr or getmxrr does not exists
  3513. return -1;
  3514. }
  3515. /**
  3516. * Return true if phone number syntax is ok
  3517. * TODO Decide what to do with this
  3518. *
  3519. * @param string $phone phone (Ex: "0601010101")
  3520. * @return boolean true if phone syntax is OK, false if KO or empty string
  3521. */
  3522. function isValidPhone($phone)
  3523. {
  3524. return true;
  3525. }
  3526. /**
  3527. * Return first letters of a strings.
  3528. * Example with nbofchar=1: 'ghi' will return 'g' but 'abc def' will return 'ad'
  3529. * Example with nbofchar=2: 'ghi' will return 'gh' but 'abc def' will return 'abde'
  3530. *
  3531. * @param string $s String to truncate
  3532. * @param int $nbofchar Nb of characters to keep
  3533. * @return string Return first chars.
  3534. */
  3535. function dolGetFirstLetters($s, $nbofchar = 1)
  3536. {
  3537. $ret = '';
  3538. $tmparray = explode(' ', $s);
  3539. foreach ($tmparray as $tmps) {
  3540. $ret .= dol_substr($tmps, 0, $nbofchar);
  3541. }
  3542. return $ret;
  3543. }
  3544. /**
  3545. * Make a strlen call. Works even if mbstring module not enabled
  3546. *
  3547. * @param string $string String to calculate length
  3548. * @param string $stringencoding Encoding of string
  3549. * @return int Length of string
  3550. */
  3551. function dol_strlen($string, $stringencoding = 'UTF-8')
  3552. {
  3553. if (is_null($string)) {
  3554. return 0;
  3555. }
  3556. if (function_exists('mb_strlen')) {
  3557. return mb_strlen($string, $stringencoding);
  3558. } else {
  3559. return strlen($string);
  3560. }
  3561. }
  3562. /**
  3563. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3564. *
  3565. * @param string $string String to scan
  3566. * @param string $start Start position
  3567. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3568. * @param string $stringencoding Page code used for input string encoding
  3569. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3570. * @return string substring
  3571. */
  3572. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  3573. {
  3574. global $langs;
  3575. if (empty($stringencoding)) {
  3576. $stringencoding = $langs->charset_output;
  3577. }
  3578. $ret = '';
  3579. if (empty($trunconbytes)) {
  3580. if (function_exists('mb_substr')) {
  3581. $ret = mb_substr($string, $start, $length, $stringencoding);
  3582. } else {
  3583. $ret = substr($string, $start, $length);
  3584. }
  3585. } else {
  3586. if (function_exists('mb_strcut')) {
  3587. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3588. } else {
  3589. $ret = substr($string, $start, $length);
  3590. }
  3591. }
  3592. return $ret;
  3593. }
  3594. /**
  3595. * Truncate a string to a particular length adding '…' if string larger than length.
  3596. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3597. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3598. *
  3599. * @param string $string String to truncate
  3600. * @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 ...)
  3601. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3602. * @param string $stringencoding Tell what is source string encoding
  3603. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3604. * @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)
  3605. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3606. */
  3607. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3608. {
  3609. global $conf;
  3610. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3611. return $string;
  3612. }
  3613. if (empty($stringencoding)) {
  3614. $stringencoding = 'UTF-8';
  3615. }
  3616. // reduce for small screen
  3617. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3618. $size = round($size / 3);
  3619. }
  3620. // We go always here
  3621. if ($trunc == 'right') {
  3622. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3623. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3624. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3625. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3626. } else {
  3627. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3628. return $string;
  3629. }
  3630. } elseif ($trunc == 'middle') {
  3631. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3632. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3633. $size1 = round($size / 2);
  3634. $size2 = round($size / 2);
  3635. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3636. } else {
  3637. return $string;
  3638. }
  3639. } elseif ($trunc == 'left') {
  3640. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3641. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3642. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3643. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3644. } else {
  3645. return $string;
  3646. }
  3647. } elseif ($trunc == 'wrap') {
  3648. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3649. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3650. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3651. } else {
  3652. return $string;
  3653. }
  3654. } else {
  3655. return 'BadParam3CallingDolTrunc';
  3656. }
  3657. }
  3658. /**
  3659. * Show picto whatever it's its name (generic function)
  3660. *
  3661. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3662. * @param string $picto Name of image file to show ('filenew', ...)
  3663. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3664. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3665. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3666. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3667. * 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)
  3668. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3669. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3670. * @param int $srconly Return only content of the src attribute of img.
  3671. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3672. * @param string $alt Force alt for bind people
  3673. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3674. * @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.
  3675. * @return string Return img tag
  3676. * @see img_object(), img_picto_common()
  3677. */
  3678. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3679. {
  3680. global $conf, $langs;
  3681. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3682. $url = DOL_URL_ROOT;
  3683. $theme = isset($conf->theme) ? $conf->theme : null;
  3684. $path = 'theme/'.$theme;
  3685. // Define fullpathpicto to use into src
  3686. if ($pictoisfullpath) {
  3687. // Clean parameters
  3688. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3689. $picto .= '.png';
  3690. }
  3691. $fullpathpicto = $picto;
  3692. $reg = array();
  3693. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3694. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3695. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3696. }
  3697. } else {
  3698. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3699. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3700. if (strpos($pictowithouttext, 'fontawesome_') !== false || preg_match('/^fa-/', $pictowithouttext)) {
  3701. // This is a font awesome image 'fonwtawesome_xxx' or 'fa-xxx'
  3702. $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
  3703. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  3704. $pictowithouttextarray = explode('_', $pictowithouttext);
  3705. $marginleftonlyshort = 0;
  3706. if (!empty($pictowithouttextarray[1])) {
  3707. // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
  3708. $fakey = 'fa-'.$pictowithouttextarray[0];
  3709. $fa = empty($pictowithouttextarray[1]) ? 'fa' : $pictowithouttextarray[1];
  3710. $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
  3711. $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  3712. } else {
  3713. $fakey = 'fa-'.$pictowithouttext;
  3714. $fa = 'fa';
  3715. $facolor = '';
  3716. $fasize = '';
  3717. }
  3718. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3719. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3720. $morestyle = '';
  3721. $reg = array();
  3722. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3723. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3724. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3725. }
  3726. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3727. $morestyle = $reg[1];
  3728. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3729. }
  3730. $moreatt = trim($moreatt);
  3731. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3732. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3733. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3734. $enabledisablehtml .= $titlealt;
  3735. }*/
  3736. $enabledisablehtml .= '</span>';
  3737. return $enabledisablehtml;
  3738. }
  3739. if (empty($srconly) && in_array($pictowithouttext, array(
  3740. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3741. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3742. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  3743. 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3744. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cubes',
  3745. 'currency', 'multicurrency',
  3746. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3747. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
  3748. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3749. 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3750. 'help', 'holiday',
  3751. 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'knowledgemanagement',
  3752. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
  3753. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3754. 'off', 'on', 'order',
  3755. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
  3756. 'stock', 'resize', 'service', 'stats', 'trip',
  3757. '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',
  3758. 'github', 'google', 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3759. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3760. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3761. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3762. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3763. 'technic', 'ticket',
  3764. 'error', 'warning',
  3765. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
  3766. 'shapes', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3767. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3768. 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
  3769. 'conferenceorbooth', 'eventorganization',
  3770. 'stamp', 'signature'
  3771. ))) {
  3772. $fakey = $pictowithouttext;
  3773. $facolor = '';
  3774. $fasize = '';
  3775. $fa = 'fas';
  3776. 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'))) {
  3777. $fa = 'far';
  3778. }
  3779. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3780. $fa = 'fab';
  3781. }
  3782. $arrayconvpictotofa = array(
  3783. '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',
  3784. 'bank_account'=>'university',
  3785. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3786. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3787. 'bom'=>'shapes',
  3788. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time',
  3789. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3790. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3791. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3792. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3793. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3794. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3795. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3796. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3797. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  3798. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3799. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3800. 'sign-out'=>'sign-out-alt',
  3801. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3802. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3803. 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3804. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'currency'=>'dollar-sign', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3805. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3806. 'other'=>'square',
  3807. 'playdisabled'=>'play', 'pdf'=>'file-pdf', 'poll'=>'check-double', 'pos'=>'cash-register', 'preview'=>'binoculars', 'project'=>'project-diagram', 'projectpub'=>'project-diagram', 'projecttask'=>'tasks', 'propal'=>'file-signature', 'proposal'=>'file-signature',
  3808. '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',
  3809. 'recent' => 'question', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3810. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3811. 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
  3812. 'service'=>'concierge-bell',
  3813. 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3814. 'supplier'=>'building', 'technic'=>'cogs',
  3815. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3816. 'title_agenda'=>'calendar-alt',
  3817. 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'address-card',
  3818. 'jabber'=>'comment-o',
  3819. 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
  3820. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3821. );
  3822. if ($pictowithouttext == 'off') {
  3823. $fakey = 'fa-square';
  3824. $fasize = '1.3em';
  3825. } elseif ($pictowithouttext == 'on') {
  3826. $fakey = 'fa-check-square';
  3827. $fasize = '1.3em';
  3828. } elseif ($pictowithouttext == 'listlight') {
  3829. $fakey = 'fa-download';
  3830. $marginleftonlyshort = 1;
  3831. } elseif ($pictowithouttext == 'printer') {
  3832. $fakey = 'fa-print';
  3833. $fasize = '1.2em';
  3834. } elseif ($pictowithouttext == 'note') {
  3835. $fakey = 'fa-sticky-note';
  3836. $marginleftonlyshort = 1;
  3837. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3838. $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');
  3839. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3840. if (preg_match('/selected/', $pictowithouttext)) {
  3841. $facolor = '#888';
  3842. }
  3843. $marginleftonlyshort = 1;
  3844. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3845. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3846. } else {
  3847. $fakey = 'fa-'.$pictowithouttext;
  3848. }
  3849. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3850. $morecss .= ' em092';
  3851. }
  3852. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3853. $morecss .= ' em088';
  3854. }
  3855. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3856. $morecss .= ' em080';
  3857. }
  3858. // Define $marginleftonlyshort
  3859. $arrayconvpictotomarginleftonly = array(
  3860. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3861. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3862. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3863. );
  3864. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3865. $marginleftonlyshort = 0;
  3866. }
  3867. // Add CSS
  3868. $arrayconvpictotomorcess = array(
  3869. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3870. 'bank_account'=>'infobox-bank_account',
  3871. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3872. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3873. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3874. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3875. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3876. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3877. 'incoterm'=>'infobox-supplier_proposal',
  3878. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  3879. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3880. 'order'=>'infobox-commande',
  3881. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3882. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_red'=>'font-status8',
  3883. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3884. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3885. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  3886. 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
  3887. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3888. 'resource'=>'infobox-action',
  3889. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3890. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3891. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3892. 'vat'=>'infobox-bank_account',
  3893. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3894. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3895. );
  3896. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3897. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3898. }
  3899. // Define $color
  3900. $arrayconvpictotocolor = array(
  3901. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3902. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3903. 'dynamicprice'=>'#a69944',
  3904. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3905. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3906. 'lock'=>'#ddd', 'lot'=>'#a69944',
  3907. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  3908. 'other'=>'#ddd', 'world'=>'#986c6a',
  3909. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  3910. //'shipment'=>'#a69944',
  3911. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  3912. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  3913. 'website'=>'#304', 'workstation'=>'#a69944'
  3914. );
  3915. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3916. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3917. }
  3918. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3919. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3920. $morestyle = '';
  3921. $reg = array();
  3922. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3923. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3924. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3925. }
  3926. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3927. $morestyle = $reg[1];
  3928. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3929. }
  3930. $moreatt = trim($moreatt);
  3931. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3932. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3933. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3934. $enabledisablehtml .= $titlealt;
  3935. }*/
  3936. $enabledisablehtml .= '</span>';
  3937. return $enabledisablehtml;
  3938. }
  3939. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3940. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3941. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3942. $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
  3943. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3944. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3945. }
  3946. // If we ask an image into $url/$mymodule/img (instead of default path)
  3947. $regs = array();
  3948. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3949. $picto = $regs[1];
  3950. $path = $regs[2]; // $path is $mymodule
  3951. }
  3952. // Clean parameters
  3953. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3954. $picto .= '.png';
  3955. }
  3956. // If alt path are defined, define url where img file is, according to physical path
  3957. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3958. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3959. if ($type == 'main') {
  3960. continue;
  3961. }
  3962. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3963. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3964. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3965. break;
  3966. }
  3967. }
  3968. // $url is '' or '/custom', $path is current theme or
  3969. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3970. }
  3971. if ($srconly) {
  3972. return $fullpathpicto;
  3973. }
  3974. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3975. 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
  3976. }
  3977. /**
  3978. * Show a picto called object_picto (generic function)
  3979. *
  3980. * @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.
  3981. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3982. * For external modules use imagename@mymodule to search into directory "img" of module.
  3983. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3984. * @param int $pictoisfullpath If 1, image path is a full path
  3985. * @param int $srconly Return only content of the src attribute of img.
  3986. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3987. * @return string Return img tag
  3988. * @see img_picto(), img_picto_common()
  3989. */
  3990. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3991. {
  3992. if (strpos($picto, '^') === 0) {
  3993. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3994. } else {
  3995. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3996. }
  3997. }
  3998. /**
  3999. * Show weather picto
  4000. *
  4001. * @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.
  4002. * @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).
  4003. * @param string $moreatt Add more attribute on img tag
  4004. * @param int $pictoisfullpath If 1, image path is a full path
  4005. * @param string $morecss More CSS
  4006. * @return string Return img tag
  4007. * @see img_object(), img_picto()
  4008. */
  4009. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  4010. {
  4011. global $conf;
  4012. if (is_numeric($picto)) {
  4013. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  4014. //$picto = $leveltopicto[$picto];
  4015. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  4016. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4017. $picto .= '.png';
  4018. }
  4019. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  4020. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  4021. }
  4022. /**
  4023. * Show picto (generic function)
  4024. *
  4025. * @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.
  4026. * @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.
  4027. * @param string $moreatt Add more attribute on img tag
  4028. * @param int $pictoisfullpath If 1, image path is a full path
  4029. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4030. * @return string Return img tag
  4031. * @see img_object(), img_picto()
  4032. */
  4033. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  4034. {
  4035. global $conf;
  4036. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4037. $picto .= '.png';
  4038. }
  4039. if ($pictoisfullpath) {
  4040. $path = $picto;
  4041. } else {
  4042. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  4043. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  4044. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  4045. if (file_exists($themepath)) {
  4046. $path = $themepath;
  4047. }
  4048. }
  4049. }
  4050. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  4051. }
  4052. /**
  4053. * Show logo action
  4054. *
  4055. * @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.
  4056. * @param string $numaction Action id or code to show
  4057. * @param string $picto Name of image file to show ('filenew', ...)
  4058. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  4059. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4060. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4061. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4062. * @return string Return an img tag
  4063. */
  4064. function img_action($titlealt, $numaction, $picto = '')
  4065. {
  4066. global $langs;
  4067. if (empty($titlealt) || $titlealt == 'default') {
  4068. if ($numaction == '-1' || $numaction == 'ST_NO') {
  4069. $numaction = -1;
  4070. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  4071. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  4072. $numaction = 0;
  4073. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  4074. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  4075. $numaction = 1;
  4076. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  4077. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  4078. $numaction = 2;
  4079. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  4080. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  4081. $numaction = 3;
  4082. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  4083. } else {
  4084. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  4085. $numaction = 0;
  4086. }
  4087. }
  4088. if (!is_numeric($numaction)) {
  4089. $numaction = 0;
  4090. }
  4091. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  4092. }
  4093. /**
  4094. * Show pdf logo
  4095. *
  4096. * @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.
  4097. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  4098. * @return string Retourne tag img
  4099. */
  4100. function img_pdf($titlealt = 'default', $size = 3)
  4101. {
  4102. global $langs;
  4103. if ($titlealt == 'default') {
  4104. $titlealt = $langs->trans('Show');
  4105. }
  4106. return img_picto($titlealt, 'pdf'.$size.'.png');
  4107. }
  4108. /**
  4109. * Show logo +
  4110. *
  4111. * @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.
  4112. * @param string $other Add more attributes on img
  4113. * @return string Return tag img
  4114. */
  4115. function img_edit_add($titlealt = 'default', $other = '')
  4116. {
  4117. global $langs;
  4118. if ($titlealt == 'default') {
  4119. $titlealt = $langs->trans('Add');
  4120. }
  4121. return img_picto($titlealt, 'edit_add.png', $other);
  4122. }
  4123. /**
  4124. * Show logo -
  4125. *
  4126. * @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.
  4127. * @param string $other Add more attributes on img
  4128. * @return string Return tag img
  4129. */
  4130. function img_edit_remove($titlealt = 'default', $other = '')
  4131. {
  4132. global $langs;
  4133. if ($titlealt == 'default') {
  4134. $titlealt = $langs->trans('Remove');
  4135. }
  4136. return img_picto($titlealt, 'edit_remove.png', $other);
  4137. }
  4138. /**
  4139. * Show logo editer/modifier fiche
  4140. *
  4141. * @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.
  4142. * @param integer $float If you have to put the style "float: right"
  4143. * @param string $other Add more attributes on img
  4144. * @return string Return tag img
  4145. */
  4146. function img_edit($titlealt = 'default', $float = 0, $other = '')
  4147. {
  4148. global $langs;
  4149. if ($titlealt == 'default') {
  4150. $titlealt = $langs->trans('Modify');
  4151. }
  4152. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  4153. }
  4154. /**
  4155. * Show logo view card
  4156. *
  4157. * @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.
  4158. * @param integer $float If you have to put the style "float: right"
  4159. * @param string $other Add more attributes on img
  4160. * @return string Return tag img
  4161. */
  4162. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  4163. {
  4164. global $langs;
  4165. if ($titlealt == 'default') {
  4166. $titlealt = $langs->trans('View');
  4167. }
  4168. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4169. return img_picto($titlealt, 'eye', $moreatt);
  4170. }
  4171. /**
  4172. * Show delete logo
  4173. *
  4174. * @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.
  4175. * @param string $other Add more attributes on img
  4176. * @param string $morecss More CSS
  4177. * @return string Retourne tag img
  4178. */
  4179. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4180. {
  4181. global $langs;
  4182. if ($titlealt == 'default') {
  4183. $titlealt = $langs->trans('Delete');
  4184. }
  4185. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4186. }
  4187. /**
  4188. * Show printer logo
  4189. *
  4190. * @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.
  4191. * @param string $other Add more attributes on img
  4192. * @return string Retourne tag img
  4193. */
  4194. function img_printer($titlealt = "default", $other = '')
  4195. {
  4196. global $langs;
  4197. if ($titlealt == "default") {
  4198. $titlealt = $langs->trans("Print");
  4199. }
  4200. return img_picto($titlealt, 'printer.png', $other);
  4201. }
  4202. /**
  4203. * Show split logo
  4204. *
  4205. * @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.
  4206. * @param string $other Add more attributes on img
  4207. * @return string Retourne tag img
  4208. */
  4209. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4210. {
  4211. global $langs;
  4212. if ($titlealt == 'default') {
  4213. $titlealt = $langs->trans('Split');
  4214. }
  4215. return img_picto($titlealt, 'split.png', $other);
  4216. }
  4217. /**
  4218. * Show help logo with cursor "?"
  4219. *
  4220. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4221. * @param int|string $usealttitle Text to use as alt title
  4222. * @return string Return tag img
  4223. */
  4224. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4225. {
  4226. global $langs;
  4227. if ($usealttitle) {
  4228. if (is_string($usealttitle)) {
  4229. $usealttitle = dol_escape_htmltag($usealttitle);
  4230. } else {
  4231. $usealttitle = $langs->trans('Info');
  4232. }
  4233. }
  4234. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4235. }
  4236. /**
  4237. * Show info logo
  4238. *
  4239. * @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.
  4240. * @return string Return img tag
  4241. */
  4242. function img_info($titlealt = 'default')
  4243. {
  4244. global $langs;
  4245. if ($titlealt == 'default') {
  4246. $titlealt = $langs->trans('Informations');
  4247. }
  4248. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4249. }
  4250. /**
  4251. * Show warning logo
  4252. *
  4253. * @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.
  4254. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4255. * @param string $morecss Add more CSS
  4256. * @return string Return img tag
  4257. */
  4258. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4259. {
  4260. global $langs;
  4261. if ($titlealt == 'default') {
  4262. $titlealt = $langs->trans('Warning');
  4263. }
  4264. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4265. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4266. }
  4267. /**
  4268. * Show error logo
  4269. *
  4270. * @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.
  4271. * @return string Return img tag
  4272. */
  4273. function img_error($titlealt = 'default')
  4274. {
  4275. global $langs;
  4276. if ($titlealt == 'default') {
  4277. $titlealt = $langs->trans('Error');
  4278. }
  4279. return img_picto($titlealt, 'error.png');
  4280. }
  4281. /**
  4282. * Show next logo
  4283. *
  4284. * @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.
  4285. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4286. * @return string Return img tag
  4287. */
  4288. function img_next($titlealt = 'default', $moreatt = '')
  4289. {
  4290. global $langs;
  4291. if ($titlealt == 'default') {
  4292. $titlealt = $langs->trans('Next');
  4293. }
  4294. //return img_picto($titlealt, 'next.png', $moreatt);
  4295. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4296. }
  4297. /**
  4298. * Show previous logo
  4299. *
  4300. * @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.
  4301. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4302. * @return string Return img tag
  4303. */
  4304. function img_previous($titlealt = 'default', $moreatt = '')
  4305. {
  4306. global $langs;
  4307. if ($titlealt == 'default') {
  4308. $titlealt = $langs->trans('Previous');
  4309. }
  4310. //return img_picto($titlealt, 'previous.png', $moreatt);
  4311. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4312. }
  4313. /**
  4314. * Show down arrow logo
  4315. *
  4316. * @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.
  4317. * @param int $selected Selected
  4318. * @param string $moreclass Add more CSS classes
  4319. * @return string Return img tag
  4320. */
  4321. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4322. {
  4323. global $langs;
  4324. if ($titlealt == 'default') {
  4325. $titlealt = $langs->trans('Down');
  4326. }
  4327. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4328. }
  4329. /**
  4330. * Show top arrow logo
  4331. *
  4332. * @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.
  4333. * @param int $selected Selected
  4334. * @param string $moreclass Add more CSS classes
  4335. * @return string Return img tag
  4336. */
  4337. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4338. {
  4339. global $langs;
  4340. if ($titlealt == 'default') {
  4341. $titlealt = $langs->trans('Up');
  4342. }
  4343. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4344. }
  4345. /**
  4346. * Show left arrow logo
  4347. *
  4348. * @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.
  4349. * @param int $selected Selected
  4350. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4351. * @return string Return img tag
  4352. */
  4353. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4354. {
  4355. global $langs;
  4356. if ($titlealt == 'default') {
  4357. $titlealt = $langs->trans('Left');
  4358. }
  4359. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4360. }
  4361. /**
  4362. * Show right arrow logo
  4363. *
  4364. * @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.
  4365. * @param int $selected Selected
  4366. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4367. * @return string Return img tag
  4368. */
  4369. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4370. {
  4371. global $langs;
  4372. if ($titlealt == 'default') {
  4373. $titlealt = $langs->trans('Right');
  4374. }
  4375. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4376. }
  4377. /**
  4378. * Show tick logo if allowed
  4379. *
  4380. * @param string $allow Allow
  4381. * @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.
  4382. * @return string Return img tag
  4383. */
  4384. function img_allow($allow, $titlealt = 'default')
  4385. {
  4386. global $langs;
  4387. if ($titlealt == 'default') {
  4388. $titlealt = $langs->trans('Active');
  4389. }
  4390. if ($allow == 1) {
  4391. return img_picto($titlealt, 'tick.png');
  4392. }
  4393. return '-';
  4394. }
  4395. /**
  4396. * Return image of a credit card according to its brand name
  4397. *
  4398. * @param string $brand Brand name of credit card
  4399. * @param string $morecss More CSS
  4400. * @return string Return img tag
  4401. */
  4402. function img_credit_card($brand, $morecss = null)
  4403. {
  4404. if (is_null($morecss)) {
  4405. $morecss = 'fa-2x';
  4406. }
  4407. if ($brand == 'visa' || $brand == 'Visa') {
  4408. $brand = 'cc-visa';
  4409. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4410. $brand = 'cc-mastercard';
  4411. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4412. $brand = 'cc-amex';
  4413. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4414. $brand = 'cc-discover';
  4415. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4416. $brand = 'cc-jcb';
  4417. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4418. $brand = 'cc-diners-club';
  4419. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4420. $brand = 'credit-card';
  4421. }
  4422. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4423. }
  4424. /**
  4425. * Show MIME img of a file
  4426. *
  4427. * @param string $file Filename
  4428. * @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.
  4429. * @param string $morecss More css
  4430. * @return string Return img tag
  4431. */
  4432. function img_mime($file, $titlealt = '', $morecss = '')
  4433. {
  4434. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4435. $mimetype = dol_mimetype($file, '', 1);
  4436. $mimeimg = dol_mimetype($file, '', 2);
  4437. $mimefa = dol_mimetype($file, '', 4);
  4438. if (empty($titlealt)) {
  4439. $titlealt = 'Mime type: '.$mimetype;
  4440. }
  4441. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4442. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4443. }
  4444. /**
  4445. * Show search logo
  4446. *
  4447. * @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.
  4448. * @param string $other Add more attributes on img
  4449. * @return string Retourne tag img
  4450. */
  4451. function img_search($titlealt = 'default', $other = '')
  4452. {
  4453. global $conf, $langs;
  4454. if ($titlealt == 'default') {
  4455. $titlealt = $langs->trans('Search');
  4456. }
  4457. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4458. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4459. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4460. return $input;
  4461. }
  4462. /**
  4463. * Show search logo
  4464. *
  4465. * @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.
  4466. * @param string $other Add more attributes on img
  4467. * @return string Retourne tag img
  4468. */
  4469. function img_searchclear($titlealt = 'default', $other = '')
  4470. {
  4471. global $conf, $langs;
  4472. if ($titlealt == 'default') {
  4473. $titlealt = $langs->trans('Search');
  4474. }
  4475. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4476. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4477. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4478. return $input;
  4479. }
  4480. /**
  4481. * Show information for admin users or standard users
  4482. *
  4483. * @param string $text Text info
  4484. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4485. * @param int $nodiv No div
  4486. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4487. * @param string $morecss More CSS ('', 'warning', 'error')
  4488. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4489. * @return string String with info text
  4490. */
  4491. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4492. {
  4493. global $conf, $langs;
  4494. if ($infoonimgalt) {
  4495. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4496. } else {
  4497. if (empty($conf->use_javascript_ajax)) {
  4498. $textfordropdown = '';
  4499. }
  4500. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4501. $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>');
  4502. if ($textfordropdown) {
  4503. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4504. $tmpresult .= '<script type="text/javascript">
  4505. jQuery(document).ready(function() {
  4506. jQuery(".'.$class.'text").click(function() {
  4507. console.log("toggle text");
  4508. jQuery(".'.$class.'").toggle();
  4509. });
  4510. });
  4511. </script>';
  4512. $result = $tmpresult.$result;
  4513. }
  4514. }
  4515. return $result;
  4516. }
  4517. /**
  4518. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4519. * This function must be called when a blocking technical error is encountered.
  4520. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4521. *
  4522. * @param DoliDB|string $db Database handler
  4523. * @param string|string[] $error String or array of errors strings to show
  4524. * @param array $errors Array of errors
  4525. * @return void
  4526. * @see dol_htmloutput_errors()
  4527. */
  4528. function dol_print_error($db = '', $error = '', $errors = null)
  4529. {
  4530. global $conf, $langs, $argv;
  4531. global $dolibarr_main_prod;
  4532. $out = '';
  4533. $syslog = '';
  4534. // If error occurs before the $lang object was loaded
  4535. if (!$langs) {
  4536. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4537. $langs = new Translate('', $conf);
  4538. $langs->load("main");
  4539. }
  4540. // Load translation files required by the error messages
  4541. $langs->loadLangs(array('main', 'errors'));
  4542. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4543. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4544. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4545. $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";
  4546. }
  4547. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4548. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4549. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4550. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4551. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4552. }
  4553. if (function_exists("phpversion")) {
  4554. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4555. }
  4556. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4557. if (function_exists("php_uname")) {
  4558. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4559. }
  4560. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4561. $out .= "<br>\n";
  4562. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4563. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4564. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4565. $out .= "<br>\n";
  4566. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4567. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4568. } else // Mode CLI
  4569. {
  4570. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4571. $syslog .= "pid=".dol_getmypid();
  4572. }
  4573. if (!empty($conf->modules)) {
  4574. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4575. }
  4576. if (is_object($db)) {
  4577. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4578. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4579. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4580. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4581. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4582. $out .= "<br>\n";
  4583. } else // Mode CLI
  4584. {
  4585. // No dol_escape_htmltag for output, we are in CLI mode
  4586. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4587. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4588. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4589. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4590. }
  4591. $syslog .= ", sql=".$db->lastquery();
  4592. $syslog .= ", db_error=".$db->lasterror();
  4593. }
  4594. if ($error || $errors) {
  4595. $langs->load("errors");
  4596. // Merge all into $errors array
  4597. if (is_array($error) && is_array($errors)) {
  4598. $errors = array_merge($error, $errors);
  4599. } elseif (is_array($error)) {
  4600. $errors = $error;
  4601. } elseif (is_array($errors)) {
  4602. $errors = array_merge(array($error), $errors);
  4603. } else {
  4604. $errors = array_merge(array($error), array($errors));
  4605. }
  4606. foreach ($errors as $msg) {
  4607. if (empty($msg)) {
  4608. continue;
  4609. }
  4610. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4611. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4612. } else // Mode CLI
  4613. {
  4614. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4615. }
  4616. $syslog .= ", msg=".$msg;
  4617. }
  4618. }
  4619. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4620. xdebug_print_function_stack();
  4621. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4622. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4623. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4624. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4625. $out .= "<br>\n";
  4626. }
  4627. // Return a http header with error code if possible
  4628. if (!headers_sent()) {
  4629. if (function_exists('top_httphead')) { // In CLI context, the method does not exists
  4630. top_httphead();
  4631. }
  4632. http_response_code(500);
  4633. }
  4634. if (empty($dolibarr_main_prod)) {
  4635. print $out;
  4636. } else {
  4637. if (empty($langs->defaultlang)) {
  4638. $langs->setDefaultLang();
  4639. }
  4640. $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.
  4641. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4642. 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";
  4643. print $langs->trans("DolibarrHasDetectedError").'. ';
  4644. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4645. define("MAIN_CORE_ERROR", 1);
  4646. }
  4647. dol_syslog("Error ".$syslog, LOG_ERR);
  4648. }
  4649. /**
  4650. * Show a public email and error code to contact if technical error
  4651. *
  4652. * @param string $prefixcode Prefix of public error code
  4653. * @param string $errormessage Complete error message
  4654. * @param array $errormessages Array of error messages
  4655. * @param string $morecss More css
  4656. * @param string $email Email
  4657. * @return void
  4658. */
  4659. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4660. {
  4661. global $langs, $conf;
  4662. if (empty($email)) {
  4663. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4664. }
  4665. $langs->load("errors");
  4666. $now = dol_now();
  4667. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4668. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4669. if ($errormessage) {
  4670. print '<br><br>'.$errormessage;
  4671. }
  4672. if (is_array($errormessages) && count($errormessages)) {
  4673. foreach ($errormessages as $mesgtoshow) {
  4674. print '<br><br>'.$mesgtoshow;
  4675. }
  4676. }
  4677. print '</div></div>';
  4678. }
  4679. /**
  4680. * Show title line of an array
  4681. *
  4682. * @param string $name Label of field
  4683. * @param string $file Url used when we click on sort picto
  4684. * @param string $field Field to use for new sorting
  4685. * @param string $begin ("" by defaut)
  4686. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4687. * @param string $moreattrib Options of attribute td ("" by defaut)
  4688. * @param string $sortfield Current field used to sort
  4689. * @param string $sortorder Current sort order
  4690. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  4691. * @param string $tooltip Tooltip
  4692. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4693. * @return void
  4694. */
  4695. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4696. {
  4697. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4698. }
  4699. /**
  4700. * Get title line of an array
  4701. *
  4702. * @param string $name Translation key of field to show or complete HTML string to show
  4703. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4704. * @param string $file Url used when we click on sort picto
  4705. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4706. * @param string $begin ("" by defaut)
  4707. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4708. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  4709. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4710. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4711. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4712. * @param string $disablesortlink 1=Disable sort link
  4713. * @param string $tooltip Tooltip
  4714. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4715. * @return string
  4716. */
  4717. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4718. {
  4719. global $conf, $langs, $form;
  4720. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4721. if ($moreattrib == 'class="right"') {
  4722. $prefix .= 'right '; // For backward compatibility
  4723. }
  4724. $sortorder = strtoupper($sortorder);
  4725. $out = '';
  4726. $sortimg = '';
  4727. $tag = 'th';
  4728. if ($thead == 2) {
  4729. $tag = 'div';
  4730. }
  4731. $tmpsortfield = explode(',', $sortfield);
  4732. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4733. $tmpfield = explode(',', $field);
  4734. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4735. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4736. $prefix = 'wrapcolumntitle '.$prefix;
  4737. }
  4738. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4739. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4740. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4741. $liste_titre = 'liste_titre';
  4742. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4743. $liste_titre = 'liste_titre_sel';
  4744. }
  4745. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4746. //$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)).'"' : '');
  4747. $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4748. $tagstart .= '>';
  4749. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4750. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4751. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4752. $options = preg_replace('/&+/i', '&', $options);
  4753. if (!preg_match('/^&/', $options)) {
  4754. $options = '&'.$options;
  4755. }
  4756. $sortordertouseinlink = '';
  4757. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4758. if (preg_match('/^DESC/i', $sortorder)) {
  4759. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4760. } else { // We reverse the var $sortordertouseinlink
  4761. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4762. }
  4763. } else { // We are on field that is the first current sorting criteria
  4764. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4765. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4766. } else {
  4767. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4768. }
  4769. }
  4770. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4771. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4772. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4773. $out .= '>';
  4774. }
  4775. if ($tooltip) {
  4776. // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
  4777. if (preg_match('/:\w+$/', $tooltip)) {
  4778. $tmptooltip = explode(':', $tooltip);
  4779. } else {
  4780. $tmptooltip = array($tooltip);
  4781. }
  4782. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4783. } else {
  4784. $out .= $langs->trans($name);
  4785. }
  4786. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4787. $out .= '</a>';
  4788. }
  4789. if (empty($thead) && $field) { // If this is a sort field
  4790. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4791. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4792. $options = preg_replace('/&+/i', '&', $options);
  4793. if (!preg_match('/^&/', $options)) {
  4794. $options = '&'.$options;
  4795. }
  4796. if (!$sortorder || $field1 != $sortfield1) {
  4797. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4798. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4799. } else {
  4800. if (preg_match('/^DESC/', $sortorder)) {
  4801. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4802. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4803. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  4804. }
  4805. if (preg_match('/^ASC/', $sortorder)) {
  4806. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4807. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4808. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  4809. }
  4810. }
  4811. }
  4812. $tagend = '</'.$tag.'>';
  4813. $out = $tagstart.$sortimg.$out.$tagend;
  4814. return $out;
  4815. }
  4816. /**
  4817. * Show a title.
  4818. *
  4819. * @param string $title Title to show
  4820. * @return void
  4821. * @deprecated Use load_fiche_titre instead
  4822. * @see load_fiche_titre()
  4823. */
  4824. function print_titre($title)
  4825. {
  4826. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4827. print '<div class="titre">'.$title.'</div>';
  4828. }
  4829. /**
  4830. * Show a title with picto
  4831. *
  4832. * @param string $title Title to show
  4833. * @param string $mesg Added message to show on right
  4834. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4835. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4836. * @param int $id To force an id on html objects
  4837. * @return void
  4838. * @deprecated Use print load_fiche_titre instead
  4839. */
  4840. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4841. {
  4842. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4843. }
  4844. /**
  4845. * Load a title with picto
  4846. *
  4847. * @param string $titre Title to show
  4848. * @param string $morehtmlright Added message to show on right
  4849. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4850. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4851. * @param string $id To force an id on html objects
  4852. * @param string $morecssontable More css on table
  4853. * @param string $morehtmlcenter Added message to show on center
  4854. * @return string
  4855. * @see print_barre_liste()
  4856. */
  4857. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4858. {
  4859. global $conf;
  4860. $return = '';
  4861. if ($picto == 'setup') {
  4862. $picto = 'generic';
  4863. }
  4864. $return .= "\n";
  4865. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4866. $return .= '<tr class="titre">';
  4867. if ($picto) {
  4868. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4869. }
  4870. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4871. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4872. $return .= '</td>';
  4873. if (dol_strlen($morehtmlcenter)) {
  4874. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4875. }
  4876. if (dol_strlen($morehtmlright)) {
  4877. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  4878. }
  4879. $return .= '</tr></table>'."\n";
  4880. return $return;
  4881. }
  4882. /**
  4883. * Print a title with navigation controls for pagination
  4884. *
  4885. * @param string $titre Title to show (required)
  4886. * @param int $page Numero of page to show in navigation links (required)
  4887. * @param string $file Url of page (required)
  4888. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4889. * @param string $sortfield Field to sort on ('' by default)
  4890. * @param string $sortorder Order to sort ('' by default)
  4891. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4892. * @param int $num Number of records found by select with limit+1
  4893. * @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.
  4894. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4895. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4896. * @param string $morehtmlright More html to show (after arrows)
  4897. * @param string $morecss More css to the table
  4898. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4899. * @param int $hideselectlimit Force to hide select limit
  4900. * @param int $hidenavigation Force to hide all navigation tools
  4901. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4902. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4903. * @return void
  4904. */
  4905. 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 = '')
  4906. {
  4907. global $conf, $langs;
  4908. $savlimit = $limit;
  4909. $savtotalnboflines = $totalnboflines;
  4910. $totalnboflines = abs((int) $totalnboflines);
  4911. if ($picto == 'setup') {
  4912. $picto = 'title_setup.png';
  4913. }
  4914. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  4915. $picto = 'title.gif';
  4916. }
  4917. if ($limit < 0) {
  4918. $limit = $conf->liste_limit;
  4919. }
  4920. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  4921. $nextpage = 1;
  4922. } else {
  4923. $nextpage = 0;
  4924. }
  4925. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4926. print "\n";
  4927. print "<!-- Begin title -->\n";
  4928. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4929. // Left
  4930. if ($picto && $titre) {
  4931. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4932. }
  4933. print '<td class="nobordernopadding valignmiddle col-title">';
  4934. print '<div class="titre inline-block">'.$titre;
  4935. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  4936. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4937. }
  4938. print '</div></td>';
  4939. // Center
  4940. if ($morehtmlcenter) {
  4941. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4942. }
  4943. // Right
  4944. print '<td class="nobordernopadding valignmiddle right">';
  4945. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4946. if ($sortfield) {
  4947. $options .= "&sortfield=".urlencode($sortfield);
  4948. }
  4949. if ($sortorder) {
  4950. $options .= "&sortorder=".urlencode($sortorder);
  4951. }
  4952. // Show navigation bar
  4953. $pagelist = '';
  4954. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  4955. if ($totalnboflines) { // If we know total nb of lines
  4956. // Define nb of extra page links before and after selected page + ... + first or last
  4957. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4958. if ($limit > 0) {
  4959. $nbpages = ceil($totalnboflines / $limit);
  4960. } else {
  4961. $nbpages = 1;
  4962. }
  4963. $cpt = ($page - $maxnbofpage);
  4964. if ($cpt < 0) {
  4965. $cpt = 0;
  4966. }
  4967. if ($cpt >= 1) {
  4968. if (empty($pagenavastextinput)) {
  4969. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4970. if ($cpt > 2) {
  4971. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4972. } elseif ($cpt == 2) {
  4973. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4974. }
  4975. }
  4976. }
  4977. do {
  4978. if ($pagenavastextinput) {
  4979. if ($cpt == $page) {
  4980. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4981. $pagelist .= '/';
  4982. }
  4983. } else {
  4984. if ($cpt == $page) {
  4985. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4986. } else {
  4987. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4988. }
  4989. }
  4990. $cpt++;
  4991. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4992. if (empty($pagenavastextinput)) {
  4993. if ($cpt < $nbpages) {
  4994. if ($cpt < $nbpages - 2) {
  4995. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4996. } elseif ($cpt == $nbpages - 2) {
  4997. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4998. }
  4999. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5000. }
  5001. } else {
  5002. //var_dump($page.' '.$cpt.' '.$nbpages);
  5003. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5004. }
  5005. } else {
  5006. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  5007. }
  5008. }
  5009. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  5010. 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
  5011. }
  5012. // js to autoselect page field on focus
  5013. if ($pagenavastextinput) {
  5014. print ajax_autoselect('.pageplusone');
  5015. }
  5016. print '</td>';
  5017. print '</tr></table>'."\n";
  5018. print "<!-- End title -->\n\n";
  5019. }
  5020. /**
  5021. * Function to show navigation arrows into lists
  5022. *
  5023. * @param int $page Number of page
  5024. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  5025. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  5026. * @param integer $nextpage Do we show a next page button
  5027. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  5028. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  5029. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  5030. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  5031. * @param int $hideselectlimit Force to hide select limit
  5032. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  5033. * @return void
  5034. */
  5035. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  5036. {
  5037. global $conf, $langs;
  5038. print '<div class="pagination"><ul>';
  5039. if ($beforearrows) {
  5040. print '<li class="paginationbeforearrows">';
  5041. print $beforearrows;
  5042. print '</li>';
  5043. }
  5044. if ((int) $limit > 0 && empty($hideselectlimit)) {
  5045. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
  5046. $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
  5047. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  5048. //$pagesizechoices.=',2:2';
  5049. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  5050. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  5051. }
  5052. print '<li class="pagination">';
  5053. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  5054. $tmpchoice = explode(',', $pagesizechoices);
  5055. $tmpkey = $limit.':'.$limit;
  5056. if (!in_array($tmpkey, $tmpchoice)) {
  5057. $tmpchoice[] = $tmpkey;
  5058. }
  5059. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  5060. if (!in_array($tmpkey, $tmpchoice)) {
  5061. $tmpchoice[] = $tmpkey;
  5062. }
  5063. asort($tmpchoice, SORT_NUMERIC);
  5064. foreach ($tmpchoice as $val) {
  5065. $selected = '';
  5066. $tmp = explode(':', $val);
  5067. $key = $tmp[0];
  5068. $val = $tmp[1];
  5069. if ($key != '' && $val != '') {
  5070. if ((int) $key == (int) $limit) {
  5071. $selected = ' selected="selected"';
  5072. }
  5073. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  5074. }
  5075. }
  5076. print '</select>';
  5077. if ($conf->use_javascript_ajax) {
  5078. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  5079. <script>
  5080. jQuery(document).ready(function () {
  5081. jQuery(".selectlimit").change(function() {
  5082. console.log("Change limit. Send submit");
  5083. $(this).parents(\'form:first\').submit();
  5084. });
  5085. });
  5086. </script>
  5087. ';
  5088. }
  5089. print '</li>';
  5090. }
  5091. if ($page > 0) {
  5092. 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>';
  5093. }
  5094. if ($betweenarrows) {
  5095. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  5096. print $betweenarrows;
  5097. print '<!--</div>-->';
  5098. }
  5099. if ($nextpage > 0) {
  5100. 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>';
  5101. }
  5102. if ($afterarrows) {
  5103. print '<li class="paginationafterarrows">';
  5104. print $afterarrows;
  5105. print '</li>';
  5106. }
  5107. print '</ul></div>'."\n";
  5108. }
  5109. /**
  5110. * Return a string with VAT rate label formated for view output
  5111. * Used into pdf and HTML pages
  5112. *
  5113. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  5114. * @param boolean $addpercent Add a percent % sign in output
  5115. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  5116. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  5117. * @param int $html Used for html output
  5118. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  5119. */
  5120. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
  5121. {
  5122. $morelabel = '';
  5123. if (preg_match('/%/', $rate)) {
  5124. $rate = str_replace('%', '', $rate);
  5125. $addpercent = true;
  5126. }
  5127. $reg = array();
  5128. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  5129. $morelabel = ' ('.$reg[1].')';
  5130. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  5131. $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
  5132. }
  5133. if (preg_match('/\*/', $rate)) {
  5134. $rate = str_replace('*', '', $rate);
  5135. $info_bits |= 1;
  5136. }
  5137. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  5138. if (!preg_match('/\//', $rate)) {
  5139. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  5140. } else {
  5141. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  5142. $ret = $rate.($addpercent ? '%' : '');
  5143. }
  5144. if (($info_bits & 1) && $usestarfornpr >= 0) {
  5145. $ret .= ' *';
  5146. }
  5147. $ret .= $morelabel;
  5148. return $ret;
  5149. }
  5150. /**
  5151. * Function to format a value into an amount for visual output
  5152. * Function used into PDF and HTML pages
  5153. *
  5154. * @param float $amount Amount to format
  5155. * @param integer $form Type of format, HTML or not (not by default)
  5156. * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators.
  5157. * @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.
  5158. * @param int $rounding MINIMUM number of decimal to show. 0=no change, -1=we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  5159. * @param int|string $forcerounding Force the MAXIMUM of decimal to forcerounding decimal (-1=no change, 'MU' or 'MT' or numeric to round to MU or MT or to a given number of decimal)
  5160. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  5161. * @return string String with formated amount
  5162. *
  5163. * @see price2num() Revert function of price
  5164. */
  5165. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  5166. {
  5167. global $langs, $conf;
  5168. // Clean parameters
  5169. if (empty($amount)) {
  5170. $amount = 0; // To have a numeric value if amount not defined or = ''
  5171. }
  5172. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  5173. if ($rounding < 0) {
  5174. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  5175. }
  5176. $nbdecimal = $rounding;
  5177. if ($outlangs === 'none') {
  5178. // Use international separators
  5179. $dec = '.';
  5180. $thousand = '';
  5181. } else {
  5182. // Output separators by default (french)
  5183. $dec = ',';
  5184. $thousand = ' ';
  5185. // If $outlangs not forced, we use use language
  5186. if (!is_object($outlangs)) {
  5187. $outlangs = $langs;
  5188. }
  5189. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5190. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5191. }
  5192. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5193. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5194. }
  5195. if ($thousand == 'None') {
  5196. $thousand = '';
  5197. } elseif ($thousand == 'Space') {
  5198. $thousand = ' ';
  5199. }
  5200. }
  5201. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5202. //print "amount=".$amount."-";
  5203. $amount = str_replace(',', '.', $amount); // should be useless
  5204. //print $amount."-";
  5205. $datas = explode('.', $amount);
  5206. $decpart = isset($datas[1]) ? $datas[1] : '';
  5207. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5208. //print "decpart=".$decpart."<br>";
  5209. $end = '';
  5210. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5211. if (dol_strlen($decpart) > $nbdecimal) {
  5212. $nbdecimal = dol_strlen($decpart);
  5213. }
  5214. // Si on depasse max
  5215. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5216. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5217. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5218. // Si un affichage est tronque, on montre des ...
  5219. $end = '...';
  5220. }
  5221. }
  5222. // If force rounding
  5223. if ((string) $forcerounding != '-1') {
  5224. if ($forcerounding == 'MU') {
  5225. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5226. } elseif ($forcerounding == 'MT') {
  5227. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5228. } elseif ($forcerounding >= 0) {
  5229. $nbdecimal = $forcerounding;
  5230. }
  5231. }
  5232. // Format number
  5233. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5234. if ($form) {
  5235. $output = preg_replace('/\s/', '&nbsp;', $output);
  5236. $output = preg_replace('/\'/', '&#039;', $output);
  5237. }
  5238. // Add symbol of currency if requested
  5239. $cursymbolbefore = $cursymbolafter = '';
  5240. if ($currency_code && is_object($outlangs)) {
  5241. if ($currency_code == 'auto') {
  5242. $currency_code = $conf->currency;
  5243. }
  5244. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  5245. $listoflanguagesbefore = array('nl_NL');
  5246. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5247. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5248. } else {
  5249. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5250. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5251. }
  5252. }
  5253. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5254. return $output;
  5255. }
  5256. /**
  5257. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5258. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5259. * should be roundtext2num().
  5260. *
  5261. * @param string|float $amount Amount to convert/clean or round
  5262. * @param string|int $rounding ''=No rounding
  5263. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5264. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5265. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5266. * 'CU'=Round to Max unit price of foreign currency accuracy
  5267. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5268. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5269. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5270. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5271. * @return string Amount with universal numeric format (Example: '99.99999').
  5272. * If conversion fails to return a numeric, it returns:
  5273. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5274. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5275. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5276. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  5277. *
  5278. * @see price() Opposite function of price2num
  5279. */
  5280. function price2num($amount, $rounding = '', $option = 0)
  5281. {
  5282. global $langs, $conf;
  5283. // Clean parameters
  5284. if (is_null($amount)) {
  5285. $amount = '';
  5286. }
  5287. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5288. // Numbers must be '1234.56'
  5289. // Decimal delimiter for PHP and database SQL requests must be '.'
  5290. $dec = ',';
  5291. $thousand = ' ';
  5292. if (is_null($langs)) { // $langs is not defined, we use english values.
  5293. $dec = '.';
  5294. $thousand = ',';
  5295. } else {
  5296. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5297. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5298. }
  5299. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5300. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5301. }
  5302. }
  5303. if ($thousand == 'None') {
  5304. $thousand = '';
  5305. } elseif ($thousand == 'Space') {
  5306. $thousand = ' ';
  5307. }
  5308. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5309. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5310. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5311. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5312. if (!is_numeric($amount)) {
  5313. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5314. }
  5315. 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
  5316. $amount = str_replace($thousand, '', $amount);
  5317. }
  5318. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5319. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5320. // So if number was already a good number, it is converted into local Dolibarr setup.
  5321. if (is_numeric($amount)) {
  5322. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5323. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5324. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5325. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5326. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5327. }
  5328. //print "QQ".$amount."<br>\n";
  5329. // Now make replace (the main goal of function)
  5330. if ($thousand != ',' && $thousand != '.') {
  5331. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5332. }
  5333. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5334. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5335. $amount = str_replace($dec, '.', $amount);
  5336. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5337. }
  5338. //print ' XX'.$amount.' '.$rounding;
  5339. // Now, $amount is a real PHP float number. We make a rounding if required.
  5340. if ($rounding) {
  5341. $nbofdectoround = '';
  5342. if ($rounding == 'MU') {
  5343. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5344. } elseif ($rounding == 'MT') {
  5345. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5346. } elseif ($rounding == 'MS') {
  5347. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5348. } elseif ($rounding == 'CU') {
  5349. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5350. } elseif ($rounding == 'CT') {
  5351. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5352. } elseif (is_numeric($rounding)) {
  5353. $nbofdectoround = (int) $rounding;
  5354. }
  5355. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5356. if (dol_strlen($nbofdectoround)) {
  5357. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5358. } else {
  5359. return 'ErrorBadParameterProvidedToFunction';
  5360. }
  5361. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5362. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5363. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5364. if (is_numeric($amount)) {
  5365. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5366. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5367. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5368. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5369. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5370. }
  5371. //print "TT".$amount.'<br>';
  5372. // Always make replace because each math function (like round) replace
  5373. // with local values and we want a number that has a SQL string format x.y
  5374. if ($thousand != ',' && $thousand != '.') {
  5375. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5376. }
  5377. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5378. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5379. $amount = str_replace($dec, '.', $amount);
  5380. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5381. }
  5382. return $amount;
  5383. }
  5384. /**
  5385. * Output a dimension with best unit
  5386. *
  5387. * @param float $dimension Dimension
  5388. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5389. * @param string $type 'weight', 'volume', ...
  5390. * @param Translate $outputlangs Translate language object
  5391. * @param int $round -1 = non rounding, x = number of decimal
  5392. * @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)
  5393. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5394. * @return string String to show dimensions
  5395. */
  5396. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5397. {
  5398. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5399. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5400. $dimension = $dimension * 1000000;
  5401. $unit = $unit - 6;
  5402. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5403. $dimension = $dimension * 1000;
  5404. $unit = $unit - 3;
  5405. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5406. $dimension = $dimension / 1000000;
  5407. $unit = $unit + 6;
  5408. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5409. $dimension = $dimension / 1000;
  5410. $unit = $unit + 3;
  5411. }
  5412. // Special case when we want output unit into pound or ounce
  5413. /* TODO
  5414. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5415. {
  5416. $dimension = // convert dimension from standard unit into ounce or pound
  5417. $unit = $forceunitoutput;
  5418. }
  5419. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5420. {
  5421. $dimension = // convert dimension from standard unit into ounce or pound
  5422. $unit = $forceunitoutput;
  5423. }*/
  5424. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5425. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5426. return $ret;
  5427. }
  5428. /**
  5429. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5430. * Note: This function applies same rules than get_default_tva
  5431. *
  5432. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5433. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5434. * @param Societe $thirdparty_buyer Object of buying third party
  5435. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5436. * @param int $vatnpr If vat rate is NPR or not
  5437. * @return mixed 0 if not found, localtax rate if found
  5438. * @see get_default_tva()
  5439. */
  5440. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5441. {
  5442. global $db, $conf, $mysoc;
  5443. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5444. $thirdparty_seller = $mysoc;
  5445. }
  5446. 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);
  5447. $vatratecleaned = $vatrate;
  5448. $reg = array();
  5449. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5450. $vatratecleaned = trim($reg[1]);
  5451. $vatratecode = $reg[2];
  5452. }
  5453. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5454. {
  5455. return 0;
  5456. }*/
  5457. // Some test to guess with no need to make database access
  5458. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5459. if ($local == 1) {
  5460. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5461. return 0;
  5462. }
  5463. if ($thirdparty_seller->id == $mysoc->id) {
  5464. if (!$thirdparty_buyer->localtax1_assuj) {
  5465. return 0;
  5466. }
  5467. } else {
  5468. if (!$thirdparty_seller->localtax1_assuj) {
  5469. return 0;
  5470. }
  5471. }
  5472. }
  5473. if ($local == 2) {
  5474. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5475. if (!$mysoc->localtax2_assuj) {
  5476. return 0; // If main vat is 0, IRPF may be different than 0.
  5477. }
  5478. if ($thirdparty_seller->id == $mysoc->id) {
  5479. if (!$thirdparty_buyer->localtax2_assuj) {
  5480. return 0;
  5481. }
  5482. } else {
  5483. if (!$thirdparty_seller->localtax2_assuj) {
  5484. return 0;
  5485. }
  5486. }
  5487. }
  5488. } else {
  5489. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5490. return 0;
  5491. }
  5492. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5493. return 0;
  5494. }
  5495. }
  5496. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5497. if (in_array($mysoc->country_code, array('ES'))) {
  5498. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5499. }
  5500. // Search local taxes
  5501. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5502. if ($local == 1) {
  5503. if ($thirdparty_seller != $mysoc) {
  5504. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5505. return $thirdparty_seller->localtax1_value;
  5506. }
  5507. } else { // i am the seller
  5508. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5509. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5510. }
  5511. }
  5512. }
  5513. if ($local == 2) {
  5514. if ($thirdparty_seller != $mysoc) {
  5515. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5516. // TODO We should also return value defined on thirdparty only if defined
  5517. return $thirdparty_seller->localtax2_value;
  5518. }
  5519. } else { // i am the seller
  5520. if (in_array($mysoc->country_code, array('ES'))) {
  5521. return $thirdparty_buyer->localtax2_value;
  5522. } else {
  5523. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5524. }
  5525. }
  5526. }
  5527. }
  5528. // By default, search value of local tax on line of common tax
  5529. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5530. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5531. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5532. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5533. if (!empty($vatratecode)) {
  5534. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5535. } else {
  5536. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5537. }
  5538. $resql = $db->query($sql);
  5539. if ($resql) {
  5540. $obj = $db->fetch_object($resql);
  5541. if ($obj) {
  5542. if ($local == 1) {
  5543. return $obj->localtax1;
  5544. } elseif ($local == 2) {
  5545. return $obj->localtax2;
  5546. }
  5547. }
  5548. }
  5549. return 0;
  5550. }
  5551. /**
  5552. * Return true if LocalTax (1 or 2) is unique.
  5553. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5554. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5555. *
  5556. * @param int $local Local tax to test (1 or 2)
  5557. * @return boolean True if LocalTax have multiple values, False if not
  5558. */
  5559. function isOnlyOneLocalTax($local)
  5560. {
  5561. $tax = get_localtax_by_third($local);
  5562. $valors = explode(":", $tax);
  5563. if (count($valors) > 1) {
  5564. return false;
  5565. } else {
  5566. return true;
  5567. }
  5568. }
  5569. /**
  5570. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5571. *
  5572. * @param int $local LocalTax to get
  5573. * @return number Values of localtax
  5574. */
  5575. function get_localtax_by_third($local)
  5576. {
  5577. global $db, $mysoc;
  5578. $sql = "SELECT t.localtax1, t.localtax2 ";
  5579. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  5580. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  5581. $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";
  5582. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  5583. $sql .= " )";
  5584. $resql = $db->query($sql);
  5585. if ($resql) {
  5586. $obj = $db->fetch_object($resql);
  5587. if ($local == 1) {
  5588. return $obj->localtax1;
  5589. } elseif ($local == 2) {
  5590. return $obj->localtax2;
  5591. }
  5592. }
  5593. return 0;
  5594. }
  5595. /**
  5596. * Get tax (VAT) main information from Id.
  5597. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5598. *
  5599. * @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.
  5600. * @param Societe $buyer Company object
  5601. * @param Societe $seller Company object
  5602. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5603. * @return array array('rowid'=> , 'code'=> ...)
  5604. * @see getLocalTaxesFromRate()
  5605. */
  5606. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5607. {
  5608. global $db, $mysoc;
  5609. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5610. // Search local taxes
  5611. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5612. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5613. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5614. if ($firstparamisid) {
  5615. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5616. } else {
  5617. $vatratecleaned = $vatrate;
  5618. $vatratecode = '';
  5619. $reg = array();
  5620. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5621. $vatratecleaned = $reg[1];
  5622. $vatratecode = $reg[2];
  5623. }
  5624. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5625. /*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 ??
  5626. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5627. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5628. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5629. if ($vatratecode) {
  5630. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5631. }
  5632. }
  5633. $resql = $db->query($sql);
  5634. if ($resql) {
  5635. $obj = $db->fetch_object($resql);
  5636. if ($obj) {
  5637. return array(
  5638. 'rowid'=>$obj->rowid,
  5639. 'code'=>$obj->code,
  5640. 'rate'=>$obj->rate,
  5641. 'localtax1'=>$obj->localtax1,
  5642. 'localtax1_type'=>$obj->localtax1_type,
  5643. 'localtax2'=>$obj->localtax2,
  5644. 'localtax2_type'=>$obj->localtax2_type,
  5645. 'npr'=>$obj->npr,
  5646. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5647. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5648. );
  5649. } else {
  5650. return array();
  5651. }
  5652. } else {
  5653. dol_print_error($db);
  5654. }
  5655. return array();
  5656. }
  5657. /**
  5658. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5659. * This does not take into account the seller setup if subject to vat or not, only country.
  5660. *
  5661. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5662. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5663. * provide the selected value to the function calcul_price_total.
  5664. *
  5665. * @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.
  5666. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5667. * @param Societe $buyer Company object
  5668. * @param Societe $seller Company object
  5669. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5670. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5671. * @see getTaxesFromId()
  5672. */
  5673. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5674. {
  5675. global $db, $mysoc;
  5676. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5677. // Search local taxes
  5678. $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";
  5679. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5680. if ($firstparamisid) {
  5681. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5682. } else {
  5683. $vatratecleaned = $vatrate;
  5684. $vatratecode = '';
  5685. $reg = array();
  5686. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5687. $vatratecleaned = $reg[1];
  5688. $vatratecode = $reg[2];
  5689. }
  5690. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5691. if ($mysoc->country_code == 'ES') {
  5692. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  5693. } else {
  5694. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape(empty($seller->country_code) ? $mysoc->country_code : $seller->country_code)."'";
  5695. }
  5696. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5697. if ($vatratecode) {
  5698. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5699. }
  5700. }
  5701. $resql = $db->query($sql);
  5702. if ($resql) {
  5703. $obj = $db->fetch_object($resql);
  5704. if ($obj) {
  5705. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5706. if ($local == 1) {
  5707. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5708. } elseif ($local == 2) {
  5709. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5710. } else {
  5711. 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);
  5712. }
  5713. }
  5714. }
  5715. return array();
  5716. }
  5717. /**
  5718. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5719. * Function called by get_default_tva().
  5720. *
  5721. * @param int $idprod Id of product or 0 if not a predefined product
  5722. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5723. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5724. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5725. * @see get_product_localtax_for_country()
  5726. */
  5727. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5728. {
  5729. global $db, $conf, $mysoc;
  5730. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5731. $ret = 0;
  5732. $found = 0;
  5733. if ($idprod > 0) {
  5734. // Load product
  5735. $product = new Product($db);
  5736. $product->fetch($idprod);
  5737. if ($mysoc->country_code == $thirdpartytouse->country_code) {
  5738. // If country to consider is ours
  5739. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5740. $result = $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5741. if ($result > 0) {
  5742. $ret = $product->vatrate_supplier;
  5743. if ($product->default_vat_code_supplier) {
  5744. $ret .= ' ('.$product->default_vat_code_supplier.')';
  5745. }
  5746. $found = 1;
  5747. }
  5748. }
  5749. if (!$found) {
  5750. $ret = $product->tva_tx; // Default sales vat of product
  5751. if ($product->default_vat_code) {
  5752. $ret .= ' ('.$product->default_vat_code.')';
  5753. }
  5754. $found = 1;
  5755. }
  5756. } else {
  5757. // TODO Read default product vat according to product and another countrycode.
  5758. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5759. }
  5760. }
  5761. if (!$found) {
  5762. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5763. // If vat of product for the country not found or not defined, we return the first rate found (sorting on use_default, then on higher vat of country).
  5764. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5765. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5766. $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
  5767. $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5768. $sql .= $db->plimit(1);
  5769. $resql = $db->query($sql);
  5770. if ($resql) {
  5771. $obj = $db->fetch_object($resql);
  5772. if ($obj) {
  5773. $ret = $obj->vat_rate;
  5774. if ($obj->default_vat_code) {
  5775. $ret .= ' ('.$obj->default_vat_code.')';
  5776. }
  5777. }
  5778. $db->free($resql);
  5779. } else {
  5780. dol_print_error($db);
  5781. }
  5782. } else {
  5783. // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
  5784. // '1.23'
  5785. // or '1.23 (CODE)'
  5786. $defaulttx = '';
  5787. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5788. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5789. }
  5790. /*if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5791. $defaultcode = $reg[1];
  5792. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5793. }*/
  5794. $ret = $defaulttx;
  5795. }
  5796. }
  5797. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5798. return $ret;
  5799. }
  5800. /**
  5801. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5802. *
  5803. * @param int $idprod Id of product
  5804. * @param int $local 1 for localtax1, 2 for localtax 2
  5805. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5806. * @return int <0 if KO, Vat rate if OK
  5807. * @see get_product_vat_for_country()
  5808. */
  5809. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5810. {
  5811. global $db, $mysoc;
  5812. if (!class_exists('Product')) {
  5813. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5814. }
  5815. $ret = 0;
  5816. $found = 0;
  5817. if ($idprod > 0) {
  5818. // Load product
  5819. $product = new Product($db);
  5820. $result = $product->fetch($idprod);
  5821. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5822. /* Not defined yet, so we don't use this
  5823. if ($local==1) $ret=$product->localtax1_tx;
  5824. elseif ($local==2) $ret=$product->localtax2_tx;
  5825. $found=1;
  5826. */
  5827. } else {
  5828. // TODO Read default product vat according to product and another countrycode.
  5829. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5830. }
  5831. }
  5832. if (!$found) {
  5833. // If vat of product for the country not found or not defined, we return higher vat of country.
  5834. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5835. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5836. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5837. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5838. $sql .= $db->plimit(1);
  5839. $resql = $db->query($sql);
  5840. if ($resql) {
  5841. $obj = $db->fetch_object($resql);
  5842. if ($obj) {
  5843. if ($local == 1) {
  5844. $ret = $obj->localtax1;
  5845. } elseif ($local == 2) {
  5846. $ret = $obj->localtax2;
  5847. }
  5848. }
  5849. } else {
  5850. dol_print_error($db);
  5851. }
  5852. }
  5853. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5854. return $ret;
  5855. }
  5856. /**
  5857. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5858. * VATRULE 1: Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5859. * VATRULE 2: Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5860. * 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.
  5861. * VATRULE 4: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5862. * VATRULE 5: Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5863. * VATRULE 6: Sinon TVA proposee par defaut=0. Fin de regle.
  5864. *
  5865. * @param Societe $thirdparty_seller Objet societe vendeuse
  5866. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5867. * @param int $idprod Id product
  5868. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5869. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5870. * @see get_default_npr(), get_default_localtax()
  5871. */
  5872. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5873. {
  5874. global $conf;
  5875. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5876. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5877. $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;
  5878. $seller_country_code = $thirdparty_seller->country_code;
  5879. $seller_in_cee = isInEEC($thirdparty_seller);
  5880. $buyer_country_code = $thirdparty_buyer->country_code;
  5881. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5882. 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 : ''));
  5883. // 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)
  5884. // we use the buyer VAT.
  5885. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5886. if ($seller_in_cee && $buyer_in_cee) {
  5887. $isacompany = $thirdparty_buyer->isACompany();
  5888. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5889. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5890. if (!isValidVATID($thirdparty_buyer)) {
  5891. $isacompany = 0;
  5892. }
  5893. }
  5894. if (!$isacompany) {
  5895. //print 'VATRULE 0';
  5896. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  5897. }
  5898. }
  5899. }
  5900. // If seller does not use VAT
  5901. if (!$seller_use_vat) {
  5902. //print 'VATRULE 1';
  5903. return 0;
  5904. }
  5905. // 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.
  5906. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  5907. if (($seller_country_code == $buyer_country_code)
  5908. || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  5909. //print 'VATRULE 2';
  5910. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5911. }
  5912. // 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.
  5913. // 'VATRULE 3' - Not supported
  5914. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  5915. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5916. if (($seller_in_cee && $buyer_in_cee)) {
  5917. $isacompany = $thirdparty_buyer->isACompany();
  5918. if ($isacompany && !empty($conf->global->MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL)) {
  5919. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5920. if (!isValidVATID($thirdparty_buyer)) {
  5921. $isacompany = 0;
  5922. }
  5923. }
  5924. if (!$isacompany) {
  5925. //print 'VATRULE 4';
  5926. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5927. } else {
  5928. //print 'VATRULE 5';
  5929. return 0;
  5930. }
  5931. }
  5932. // Si (vendeur dans Communaute europeene et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  5933. // I don't see any use case that need this rule.
  5934. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  5935. $isacompany = $thirdparty_buyer->isACompany();
  5936. if (!$isacompany) {
  5937. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  5938. //print 'VATRULE extra';
  5939. }
  5940. }
  5941. // Sinon la TVA proposee par defaut=0. Fin de regle.
  5942. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  5943. //print 'VATRULE 6';
  5944. return 0;
  5945. }
  5946. /**
  5947. * Fonction qui renvoie si tva doit etre tva percue recuperable
  5948. *
  5949. * @param Societe $thirdparty_seller Thirdparty seller
  5950. * @param Societe $thirdparty_buyer Thirdparty buyer
  5951. * @param int $idprod Id product
  5952. * @param int $idprodfournprice Id supplier price for product
  5953. * @return float 0 or 1
  5954. * @see get_default_tva(), get_default_localtax()
  5955. */
  5956. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5957. {
  5958. global $db;
  5959. if ($idprodfournprice > 0) {
  5960. if (!class_exists('ProductFournisseur')) {
  5961. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5962. }
  5963. $prodprice = new ProductFournisseur($db);
  5964. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  5965. return $prodprice->fourn_tva_npr;
  5966. } elseif ($idprod > 0) {
  5967. if (!class_exists('Product')) {
  5968. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5969. }
  5970. $prod = new Product($db);
  5971. $prod->fetch($idprod);
  5972. return $prod->tva_npr;
  5973. }
  5974. return 0;
  5975. }
  5976. /**
  5977. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  5978. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  5979. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  5980. * Sinon TVA proposee par defaut=0. Fin de regle.
  5981. *
  5982. * @param Societe $thirdparty_seller Thirdparty seller
  5983. * @param Societe $thirdparty_buyer Thirdparty buyer
  5984. * @param int $local Localtax to process (1 or 2)
  5985. * @param int $idprod Id product
  5986. * @return integer localtax, -1 si ne peut etre determine
  5987. * @see get_default_tva(), get_default_npr()
  5988. */
  5989. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  5990. {
  5991. global $mysoc;
  5992. if (!is_object($thirdparty_seller)) {
  5993. return -1;
  5994. }
  5995. if (!is_object($thirdparty_buyer)) {
  5996. return -1;
  5997. }
  5998. if ($local == 1) { // Localtax 1
  5999. if ($mysoc->country_code == 'ES') {
  6000. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  6001. return 0;
  6002. }
  6003. } else {
  6004. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  6005. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  6006. return 0;
  6007. }
  6008. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  6009. return 0;
  6010. }
  6011. }
  6012. } elseif ($local == 2) { //I Localtax 2
  6013. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  6014. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  6015. return 0;
  6016. }
  6017. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  6018. return 0;
  6019. }
  6020. }
  6021. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  6022. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  6023. }
  6024. return 0;
  6025. }
  6026. /**
  6027. * Return yes or no in current language
  6028. *
  6029. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  6030. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  6031. * @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.
  6032. * @return string HTML string
  6033. */
  6034. function yn($yesno, $case = 1, $color = 0)
  6035. {
  6036. global $langs;
  6037. $result = 'unknown';
  6038. $classname = '';
  6039. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  6040. $result = $langs->trans('yes');
  6041. if ($case == 1 || $case == 3) {
  6042. $result = $langs->trans("Yes");
  6043. }
  6044. if ($case == 2) {
  6045. $result = '<input type="checkbox" value="1" checked disabled>';
  6046. }
  6047. if ($case == 3) {
  6048. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  6049. }
  6050. $classname = 'ok';
  6051. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  6052. $result = $langs->trans("no");
  6053. if ($case == 1 || $case == 3) {
  6054. $result = $langs->trans("No");
  6055. }
  6056. if ($case == 2) {
  6057. $result = '<input type="checkbox" value="0" disabled>';
  6058. }
  6059. if ($case == 3) {
  6060. $result = '<input type="checkbox" value="0" disabled> '.$result;
  6061. }
  6062. if ($color == 2) {
  6063. $classname = 'ok';
  6064. } else {
  6065. $classname = 'error';
  6066. }
  6067. }
  6068. if ($color) {
  6069. return '<span class="'.$classname.'">'.$result.'</span>';
  6070. }
  6071. return $result;
  6072. }
  6073. /**
  6074. * Return a path to have a the directory according to object where files are stored.
  6075. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  6076. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  6077. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  6078. * 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/"
  6079. *
  6080. * @param string|int $num Id of object (deprecated, $object will be used in future)
  6081. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  6082. * @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)
  6083. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  6084. * @param Object $object Object to use to get ref to forge the path.
  6085. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  6086. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  6087. */
  6088. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  6089. {
  6090. global $conf;
  6091. if (empty($modulepart) && !empty($object->module)) {
  6092. $modulepart = $object->module;
  6093. }
  6094. $path = '';
  6095. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  6096. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  6097. $arrayforoldpath[] = 'product';
  6098. }
  6099. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  6100. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  6101. if (empty($alpha)) {
  6102. $num = preg_replace('/([^0-9])/i', '', $num);
  6103. } else {
  6104. $num = preg_replace('/^.*\-/i', '', $num);
  6105. }
  6106. $num = substr("000".$num, -$level);
  6107. if ($level == 1) {
  6108. $path = substr($num, 0, 1);
  6109. }
  6110. if ($level == 2) {
  6111. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  6112. }
  6113. if ($level == 3) {
  6114. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  6115. }
  6116. } else {
  6117. // We will enhance here a common way of forging path for document storage.
  6118. // In a future, we may distribute directories on several levels depending on setup and object.
  6119. // Here, $object->id, $object->ref and $modulepart are required.
  6120. //var_dump($modulepart);
  6121. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  6122. }
  6123. if (empty($withoutslash) && !empty($path)) {
  6124. $path .= '/';
  6125. }
  6126. return $path;
  6127. }
  6128. /**
  6129. * Creation of a directory (this can create recursive subdir)
  6130. *
  6131. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  6132. * @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)
  6133. * @param string $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  6134. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  6135. */
  6136. function dol_mkdir($dir, $dataroot = '', $newmask = '')
  6137. {
  6138. global $conf;
  6139. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  6140. $dir_osencoded = dol_osencode($dir);
  6141. if (@is_dir($dir_osencoded)) {
  6142. return 0;
  6143. }
  6144. $nberr = 0;
  6145. $nbcreated = 0;
  6146. $ccdir = '';
  6147. if (!empty($dataroot)) {
  6148. // Remove data root from loop
  6149. $dir = str_replace($dataroot.'/', '', $dir);
  6150. $ccdir = $dataroot.'/';
  6151. }
  6152. $cdir = explode("/", $dir);
  6153. $num = count($cdir);
  6154. for ($i = 0; $i < $num; $i++) {
  6155. if ($i > 0) {
  6156. $ccdir .= '/'.$cdir[$i];
  6157. } else {
  6158. $ccdir .= $cdir[$i];
  6159. }
  6160. if (preg_match("/^.:$/", $ccdir, $regs)) {
  6161. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  6162. }
  6163. // Attention, le is_dir() peut echouer bien que le rep existe.
  6164. // (ex selon config de open_basedir)
  6165. if ($ccdir) {
  6166. $ccdir_osencoded = dol_osencode($ccdir);
  6167. if (!@is_dir($ccdir_osencoded)) {
  6168. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  6169. umask(0);
  6170. $dirmaskdec = octdec((string) $newmask);
  6171. if (empty($newmask)) {
  6172. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  6173. }
  6174. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  6175. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  6176. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  6177. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  6178. $nberr++;
  6179. } else {
  6180. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  6181. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  6182. $nbcreated++;
  6183. }
  6184. } else {
  6185. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  6186. }
  6187. }
  6188. }
  6189. return ($nberr ? -$nberr : $nbcreated);
  6190. }
  6191. /**
  6192. * Return picto saying a field is required
  6193. *
  6194. * @return string Chaine avec picto obligatoire
  6195. */
  6196. function picto_required()
  6197. {
  6198. return '<span class="fieldrequired">*</span>';
  6199. }
  6200. /**
  6201. * Clean a string from all HTML tags and entities.
  6202. * This function differs from strip_tags because:
  6203. * - <br> are replaced with \n if removelinefeed=0 or 1
  6204. * - if entities are found, they are decoded BEFORE the strip
  6205. * - you can decide to convert line feed into a space
  6206. *
  6207. * @param string $stringtoclean String to clean
  6208. * @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..."
  6209. * @param string $pagecodeto Encoding of input/output string
  6210. * @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')
  6211. * @param integer $removedoublespaces Replace double space into one space
  6212. * @return string String cleaned
  6213. *
  6214. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6215. */
  6216. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6217. {
  6218. if (is_null($stringtoclean)) {
  6219. return '';
  6220. }
  6221. if ($removelinefeed == 2) {
  6222. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6223. }
  6224. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6225. // 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)
  6226. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6227. $temp = str_replace('< ', '__ltspace__', $temp);
  6228. if ($strip_tags) {
  6229. $temp = strip_tags($temp);
  6230. } else {
  6231. // 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).
  6232. $pattern = "/<[^<>]+>/";
  6233. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6234. // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6235. // pass 2 - $temp after pass 2: 0000-021
  6236. $tempbis = $temp;
  6237. do {
  6238. $temp = $tempbis;
  6239. $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6240. $tempbis = preg_replace($pattern, '', $tempbis);
  6241. //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
  6242. } while ($tempbis != $temp);
  6243. $temp = $tempbis;
  6244. // 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).
  6245. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6246. }
  6247. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6248. // Remove also carriage returns
  6249. if ($removelinefeed == 1) {
  6250. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6251. }
  6252. // And double quotes
  6253. if ($removedoublespaces) {
  6254. while (strpos($temp, " ")) {
  6255. $temp = str_replace(" ", " ", $temp);
  6256. }
  6257. }
  6258. $temp = str_replace('__ltspace__', '< ', $temp);
  6259. return trim($temp);
  6260. }
  6261. /**
  6262. * Clean a string to keep only desirable HTML tags.
  6263. * WARNING: This also clean HTML comments (because they can be used to obfuscate tag name).
  6264. *
  6265. * @param string $stringtoclean String to clean
  6266. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6267. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6268. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6269. * @param int $allowiframe Allow iframe tags.
  6270. * @param array $allowed_tags List of allowed tags to replace the default list
  6271. * @return string String cleaned
  6272. *
  6273. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6274. */
  6275. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array())
  6276. {
  6277. if (empty($allowed_tags)) {
  6278. $allowed_tags = array(
  6279. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  6280. "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"
  6281. );
  6282. }
  6283. $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6284. if ($allowiframe) {
  6285. $allowed_tags[] = "iframe";
  6286. }
  6287. $allowed_tags_string = join("><", $allowed_tags);
  6288. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6289. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6290. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6291. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6292. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6293. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6294. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6295. $temp = strip_tags($stringtoclean, $allowed_tags_string); // Warning: This remove also undesired </>, so may changes string obfuscated with </> that pass the injection detection into a harmfull string
  6296. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6297. $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
  6298. }
  6299. if ($removeclassattribute) { // Clean for remaining html tags
  6300. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6301. }
  6302. // Remove 'javascript:' that we should not find into a text with
  6303. // 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)).
  6304. if ($cleanalsojavascript) {
  6305. $temp = preg_replace('/j\s*a\s*v\s*a\s*s\s*c\s*r\s*i\s*p\s*t\s*:/i', '', $temp);
  6306. }
  6307. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6308. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6309. return $temp;
  6310. }
  6311. /**
  6312. * Clean a string from some undesirable HTML tags.
  6313. * Note: Complementary to dol_string_onlythesehtmltags().
  6314. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6315. *
  6316. * @param string $stringtoclean String to clean
  6317. * @param array $allowed_attributes Array of tags not allowed
  6318. * @return string String cleaned
  6319. *
  6320. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6321. */
  6322. 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"))
  6323. {
  6324. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6325. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6326. $dom = new DOMDocument(null, 'UTF-8');
  6327. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6328. if (is_object($dom)) {
  6329. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6330. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6331. //var_dump($attrs->item($ii));
  6332. if (!empty($attrs->item($ii)->name)) {
  6333. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6334. // Delete attribute if not into allowed_attributes
  6335. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6336. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6337. // If attribute is 'style'
  6338. $valuetoclean = $attrs->item($ii)->value;
  6339. if (isset($valuetoclean)) {
  6340. do {
  6341. $oldvaluetoclean = $valuetoclean;
  6342. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6343. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6344. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6345. $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
  6346. $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
  6347. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
  6348. }
  6349. // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
  6350. $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
  6351. $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
  6352. } while ($oldvaluetoclean != $valuetoclean);
  6353. }
  6354. $attrs->item($ii)->value = $valuetoclean;
  6355. }
  6356. }
  6357. }
  6358. }
  6359. }
  6360. $return = $dom->saveHTML();
  6361. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6362. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6363. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6364. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6365. return trim($return);
  6366. } else {
  6367. return $stringtoclean;
  6368. }
  6369. }
  6370. /**
  6371. * Clean a string from some undesirable HTML tags.
  6372. * Note. Not as secured as dol_string_onlythesehtmltags().
  6373. *
  6374. * @param string $stringtoclean String to clean
  6375. * @param array $disallowed_tags Array of tags not allowed
  6376. * @param string $cleanalsosomestyles Clean also some tags
  6377. * @return string String cleaned
  6378. *
  6379. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6380. */
  6381. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6382. {
  6383. $temp = $stringtoclean;
  6384. foreach ($disallowed_tags as $tagtoremove) {
  6385. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6386. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6387. }
  6388. if ($cleanalsosomestyles) {
  6389. $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
  6390. }
  6391. return $temp;
  6392. }
  6393. /**
  6394. * Return first line of text. Cut will depends if content is HTML or not.
  6395. *
  6396. * @param string $text Input text
  6397. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6398. * @param string $charset Charset of $text string (UTF-8 by default)
  6399. * @return string Output text
  6400. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6401. */
  6402. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6403. {
  6404. if ($nboflines == 1) {
  6405. if (dol_textishtml($text)) {
  6406. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6407. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6408. } else {
  6409. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6410. }
  6411. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  6412. } else {
  6413. $ishtml = 0;
  6414. if (dol_textishtml($text)) {
  6415. $text = preg_replace('/\n/', '', $text);
  6416. $ishtml = 1;
  6417. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6418. } else {
  6419. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6420. }
  6421. $text = strtr($text, $repTable);
  6422. if ($charset == 'UTF-8') {
  6423. $pattern = '/(<br[^>]*>)/Uu';
  6424. } else {
  6425. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6426. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6427. }
  6428. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6429. $firstline = '';
  6430. $i = 0;
  6431. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  6432. while (($i < $nba) && ($i < ($nboflines * 2))) {
  6433. if ($i % 2 == 0) {
  6434. $firstline .= $a[$i];
  6435. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  6436. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6437. }
  6438. $i++;
  6439. }
  6440. unset($a);
  6441. return $firstline.(($i < $nba) ? '...' : '');
  6442. }
  6443. }
  6444. /**
  6445. * Replace CRLF in string with a HTML BR tag.
  6446. * 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.
  6447. *
  6448. * @param string $stringtoencode String to encode
  6449. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6450. * @param bool $forxml false=Use <br>, true=Use <br />
  6451. * @return string String encoded
  6452. * @see dol_nboflines(), dolGetFirstLineOfText()
  6453. */
  6454. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6455. {
  6456. if (!$nl2brmode) {
  6457. return nl2br($stringtoencode, $forxml);
  6458. } else {
  6459. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6460. return $ret;
  6461. }
  6462. }
  6463. /**
  6464. * Sanitize a HTML to remove js and dangerous content
  6465. *
  6466. * @param string $stringtoencode String to encode
  6467. * @param int $nouseofiframesandbox Allow use of option MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS for html sanitizing
  6468. * @param string $check 'restricthtml' or 'restricthtmlallowunvalid'
  6469. * @return string HTML sanitized
  6470. */
  6471. function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
  6472. {
  6473. global $conf;
  6474. if (empty($nouseofiframesandbox) && !empty($conf->global->MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS)) {
  6475. // TODO using sandbox on inline html content is not possible yet with current browsers
  6476. //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
  6477. //$s .= $stringtoencode;
  6478. //$s .= '</body></html></iframe>';
  6479. return $stringtoencode;
  6480. } else {
  6481. $out = $stringtoencode;
  6482. do {
  6483. $oldstringtoclean = $out;
  6484. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  6485. try {
  6486. $dom = new DOMDocument;
  6487. // Add a trick to solve pb with text without parent tag
  6488. // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up without the trick into '<h1>Foo<p>bar</p></h1>'
  6489. // like 'abc' that wrongly ends up without the tric into with '<p>abc</p>'
  6490. $out = '<div class="tricktoremove">'.$out.'</div>';
  6491. $dom->loadHTML($out, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6492. $out = trim($dom->saveHTML());
  6493. // Remove the trick added to solve pb with text without parent tag
  6494. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  6495. $out = preg_replace('/<\/div>$/', '', $out);
  6496. } catch (Exception $e) {
  6497. // If error, invalid HTML string with no way to clean it
  6498. //print $e->getMessage();
  6499. $out = 'InvalidHTMLString';
  6500. }
  6501. }
  6502. // Clean some html entities that are useless so text is cleaner
  6503. $out = preg_replace('/&(tab|newline);/i', ' ', $out);
  6504. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  6505. // encoded using text entities) so we can then exclude all numeric entities.
  6506. $out = preg_replace('/&#39;/i', '&apos;', $out);
  6507. // 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).
  6508. // 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
  6509. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  6510. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  6511. return realCharForNumericEntities($m); }, $out);
  6512. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  6513. $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'.
  6514. // Keep only some html tags and remove also some 'javascript:' strings
  6515. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  6516. // We should also exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
  6517. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  6518. // 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.
  6519. $out = dol_string_onlythesehtmlattributes($out);
  6520. }
  6521. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  6522. $out = preg_replace('/&apos;/i', "&#39;", $out);
  6523. } while ($oldstringtoclean != $out);
  6524. // Check the limit of external links in a Rich text content. We count '<img' and 'url('
  6525. $reg = array();
  6526. preg_match_all('/(<img|url\()/i', $out, $reg);
  6527. if (count($reg[0]) > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
  6528. $out = 'TooManyLinksIntoHTMLString';
  6529. }
  6530. return $out;
  6531. }
  6532. }
  6533. /**
  6534. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6535. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6536. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6537. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6538. * For PDF usage, you can show text by 2 ways:
  6539. * - writeHTMLCell -> param must be encoded into HTML.
  6540. * - MultiCell -> param must not be encoded into HTML.
  6541. * Because writeHTMLCell convert also \n into <br>, if function
  6542. * is used to build PDF, nl2brmode must be 1.
  6543. *
  6544. * @param string $stringtoencode String to encode
  6545. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6546. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6547. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6548. * @return string String encoded
  6549. */
  6550. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6551. {
  6552. if (is_null($stringtoencode)) {
  6553. return '';
  6554. }
  6555. $newstring = $stringtoencode;
  6556. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6557. $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.
  6558. if ($removelasteolbr) {
  6559. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6560. }
  6561. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6562. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6563. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6564. } else {
  6565. if ($removelasteolbr) {
  6566. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6567. }
  6568. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6569. }
  6570. // Other substitutions that htmlentities does not do
  6571. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6572. return $newstring;
  6573. }
  6574. /**
  6575. * This function is called to decode a HTML string (it decodes entities and br tags)
  6576. *
  6577. * @param string $stringtodecode String to decode
  6578. * @param string $pagecodeto Page code for result
  6579. * @return string String decoded
  6580. */
  6581. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6582. {
  6583. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6584. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6585. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6586. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6587. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6588. return $ret;
  6589. }
  6590. /**
  6591. * This function remove all ending \n and br at end
  6592. *
  6593. * @param string $stringtodecode String to decode
  6594. * @return string String decoded
  6595. */
  6596. function dol_htmlcleanlastbr($stringtodecode)
  6597. {
  6598. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6599. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6600. return $ret;
  6601. }
  6602. /**
  6603. * Replace html_entity_decode functions to manage errors
  6604. *
  6605. * @param string $a Operand a
  6606. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6607. * @param string $c Operand c
  6608. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6609. * @return string String decoded
  6610. */
  6611. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6612. {
  6613. $newstring = $a;
  6614. if ($keepsomeentities) {
  6615. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6616. }
  6617. $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
  6618. if ($keepsomeentities) {
  6619. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6620. }
  6621. return $newstring;
  6622. }
  6623. /**
  6624. * Replace htmlentities functions.
  6625. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6626. *
  6627. * @param string $string The input string to encode
  6628. * @param int $flags Flags (see PHP doc above)
  6629. * @param string $encoding Encoding page code
  6630. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6631. * @return string $ret Encoded string
  6632. */
  6633. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6634. {
  6635. return htmlentities($string, $flags, $encoding, $double_encode);
  6636. }
  6637. /**
  6638. * Check if a string is a correct iso string
  6639. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6640. * Example, if string contains euro symbol that has ascii code 128
  6641. *
  6642. * @param string $s String to check
  6643. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6644. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6645. */
  6646. function dol_string_is_good_iso($s, $clean = 0)
  6647. {
  6648. $len = dol_strlen($s);
  6649. $out = '';
  6650. $ok = 1;
  6651. for ($scursor = 0; $scursor < $len; $scursor++) {
  6652. $ordchar = ord($s[$scursor]);
  6653. //print $scursor.'-'.$ordchar.'<br>';
  6654. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6655. $ok = 0;
  6656. break;
  6657. } elseif ($ordchar > 126 && $ordchar < 160) {
  6658. $ok = 0;
  6659. break;
  6660. } elseif ($clean) {
  6661. $out .= $s[$scursor];
  6662. }
  6663. }
  6664. if ($clean) {
  6665. return $out;
  6666. }
  6667. return $ok;
  6668. }
  6669. /**
  6670. * Return nb of lines of a clear text
  6671. *
  6672. * @param string $s String to check
  6673. * @param int $maxchar Not yet used
  6674. * @return int Number of lines
  6675. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6676. */
  6677. function dol_nboflines($s, $maxchar = 0)
  6678. {
  6679. if ($s == '') {
  6680. return 0;
  6681. }
  6682. $arraystring = explode("\n", $s);
  6683. $nb = count($arraystring);
  6684. return $nb;
  6685. }
  6686. /**
  6687. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6688. *
  6689. * @param string $text Text
  6690. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6691. * @param string $charset Give the charset used to encode the $text variable in memory.
  6692. * @return int Number of lines
  6693. * @see dol_nboflines(), dolGetFirstLineOfText()
  6694. */
  6695. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6696. {
  6697. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6698. if (dol_textishtml($text)) {
  6699. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6700. }
  6701. $text = strtr($text, $repTable);
  6702. if ($charset == 'UTF-8') {
  6703. $pattern = '/(<br[^>]*>)/Uu';
  6704. } else {
  6705. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6706. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6707. }
  6708. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6709. $nblines = (int) floor((count($a) + 1) / 2);
  6710. // count possible auto line breaks
  6711. if ($maxlinesize) {
  6712. foreach ($a as $line) {
  6713. if (dol_strlen($line) > $maxlinesize) {
  6714. //$line_dec = html_entity_decode(strip_tags($line));
  6715. $line_dec = html_entity_decode($line);
  6716. if (dol_strlen($line_dec) > $maxlinesize) {
  6717. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6718. $nblines += substr_count($line_dec, '\n');
  6719. }
  6720. }
  6721. }
  6722. }
  6723. unset($a);
  6724. return $nblines;
  6725. }
  6726. /**
  6727. * Return if a text is a html content
  6728. *
  6729. * @param string $msg Content to check
  6730. * @param int $option 0=Full detection, 1=Fast check
  6731. * @return boolean true/false
  6732. * @see dol_concatdesc()
  6733. */
  6734. function dol_textishtml($msg, $option = 0)
  6735. {
  6736. if (is_null($msg)) {
  6737. return false;
  6738. }
  6739. if ($option == 1) {
  6740. if (preg_match('/<html/i', $msg)) {
  6741. return true;
  6742. } elseif (preg_match('/<body/i', $msg)) {
  6743. return true;
  6744. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6745. return true;
  6746. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6747. return true;
  6748. } elseif (preg_match('/<br/i', $msg)) {
  6749. return true;
  6750. }
  6751. return false;
  6752. } else {
  6753. // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
  6754. $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
  6755. if (preg_match('/<html/i', $msg)) {
  6756. return true;
  6757. } elseif (preg_match('/<body/i', $msg)) {
  6758. return true;
  6759. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6760. return true;
  6761. } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
  6762. return true;
  6763. } elseif (preg_match('/<br\/>/i', $msg)) {
  6764. return true;
  6765. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6766. return true;
  6767. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6768. return true;
  6769. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6770. return true; // must accept <img src="http://example.com/aaa.png" />
  6771. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6772. return true; // must accept <a href="http://example.com/aaa.png" />
  6773. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6774. return true;
  6775. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6776. // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
  6777. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6778. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6779. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6780. }
  6781. return false;
  6782. }
  6783. }
  6784. /**
  6785. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6786. * text1 html + text2 html => text1 + '<br>' + text2
  6787. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6788. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6789. * text1 txt + text2 txt => text1 + '\n' + text2
  6790. *
  6791. * @param string $text1 Text 1
  6792. * @param string $text2 Text 2
  6793. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6794. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6795. * @return string Text 1 + new line + Text2
  6796. * @see dol_textishtml()
  6797. */
  6798. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6799. {
  6800. if (!empty($invert)) {
  6801. $tmp = $text1;
  6802. $text1 = $text2;
  6803. $text2 = $tmp;
  6804. }
  6805. $ret = '';
  6806. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6807. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6808. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6809. return $ret;
  6810. }
  6811. /**
  6812. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6813. *
  6814. * @param Translate $outputlangs Output language
  6815. * @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)
  6816. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6817. * @param Object $object Object for keys on object
  6818. * @return array Array of substitutions
  6819. * @see setSubstitFromObject()
  6820. */
  6821. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  6822. {
  6823. global $db, $conf, $mysoc, $user, $extrafields;
  6824. $substitutionarray = array();
  6825. if (empty($exclude) || !in_array('user', $exclude)) {
  6826. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6827. // this will include signature content first and then replace var found into content of signature
  6828. //var_dump($onlykey);
  6829. $emailsendersignature = $user->signature; // dy default, we use the signature of current user. We must complete substitution with signature in c_email_senderprofile of array after calling getCommonSubstitutionArray()
  6830. $usersignature = $user->signature;
  6831. $substitutionarray = array_merge($substitutionarray, array(
  6832. '__SENDEREMAIL_SIGNATURE__' => (string) ((empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
  6833. '__USER_SIGNATURE__' => (string) (($usersignature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
  6834. ));
  6835. if (is_object($user)) {
  6836. $substitutionarray = array_merge($substitutionarray, array(
  6837. '__USER_ID__' => (string) $user->id,
  6838. '__USER_LOGIN__' => (string) $user->login,
  6839. '__USER_EMAIL__' => (string) $user->email,
  6840. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone),
  6841. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile),
  6842. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile),
  6843. '__USER_FAX__' => (string) $user->office_fax,
  6844. '__USER_LASTNAME__' => (string) $user->lastname,
  6845. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6846. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6847. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6848. '__USER_JOB__' => (string) $user->job,
  6849. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  6850. ));
  6851. }
  6852. }
  6853. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc)) {
  6854. $substitutionarray = array_merge($substitutionarray, array(
  6855. '__MYCOMPANY_NAME__' => $mysoc->name,
  6856. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  6857. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone),
  6858. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax),
  6859. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  6860. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  6861. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  6862. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  6863. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  6864. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  6865. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  6866. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  6867. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  6868. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  6869. '__MYCOMPANY_TOWN__' => $mysoc->town,
  6870. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  6871. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  6872. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  6873. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  6874. ));
  6875. }
  6876. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude))) {
  6877. if ($onlykey) {
  6878. $substitutionarray['__ID__'] = '__ID__';
  6879. $substitutionarray['__REF__'] = '__REF__';
  6880. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  6881. $substitutionarray['__LABEL__'] = '__LABEL__';
  6882. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  6883. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  6884. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  6885. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  6886. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  6887. if (isModEnabled("societe")) { // Most objects are concerned
  6888. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  6889. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  6890. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  6891. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  6892. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  6893. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  6894. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  6895. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  6896. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  6897. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  6898. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  6899. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  6900. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  6901. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  6902. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  6903. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  6904. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  6905. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  6906. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  6907. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  6908. }
  6909. if (isModEnabled('adherent') && (!is_object($object) || $object->element == 'adherent')) {
  6910. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  6911. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  6912. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  6913. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  6914. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  6915. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  6916. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  6917. }
  6918. // add variables subtitutions ticket
  6919. if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket')) {
  6920. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  6921. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  6922. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  6923. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  6924. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  6925. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  6926. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  6927. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  6928. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  6929. }
  6930. if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature')) {
  6931. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  6932. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  6933. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  6934. }
  6935. if (isModEnabled('project')) { // Most objects
  6936. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  6937. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  6938. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  6939. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  6940. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  6941. }
  6942. if (isModEnabled('contrat') && (!is_object($object) || $object->element == 'contract')) {
  6943. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  6944. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  6945. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  6946. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  6947. }
  6948. if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal')) {
  6949. $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
  6950. }
  6951. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  6952. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  6953. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  6954. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  6955. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  6956. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  6957. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  6958. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  6959. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  6960. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  6961. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  6962. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  6963. if (isModEnabled("expedition") && (!is_object($object) || $object->element == 'shipping')) {
  6964. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  6965. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  6966. }
  6967. if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
  6968. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  6969. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  6970. }
  6971. } else {
  6972. $substitutionarray['__ID__'] = $object->id;
  6973. $substitutionarray['__REF__'] = $object->ref;
  6974. $substitutionarray['__NEWREF__'] = $object->newref;
  6975. $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
  6976. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6977. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6978. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  6979. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  6980. if ($object->element == "shipping") {
  6981. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, 'day', 0, $outputlangs) : '');
  6982. } else {
  6983. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6984. }
  6985. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  6986. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  6987. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  6988. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  6989. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  6990. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  6991. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  6992. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  6993. // For backward compatibility
  6994. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  6995. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  6996. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  6997. $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 : '')) : '');
  6998. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  6999. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  7000. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  7001. if (method_exists($object, 'getCivilityLabel')) {
  7002. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  7003. }
  7004. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  7005. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  7006. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  7007. if (method_exists($object, 'getFullName')) {
  7008. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  7009. }
  7010. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  7011. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  7012. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  7013. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  7014. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  7015. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  7016. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  7017. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  7018. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  7019. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  7020. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  7021. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  7022. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  7023. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  7024. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  7025. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
  7026. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
  7027. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  7028. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  7029. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  7030. }
  7031. if (is_object($object) && $object->element == 'societe') {
  7032. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  7033. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  7034. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  7035. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  7036. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  7037. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  7038. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  7039. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  7040. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  7041. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  7042. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  7043. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  7044. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  7045. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  7046. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  7047. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  7048. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  7049. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  7050. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  7051. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  7052. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  7053. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  7054. } elseif (is_object($object->thirdparty)) {
  7055. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  7056. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  7057. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  7058. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  7059. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  7060. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  7061. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  7062. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  7063. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  7064. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  7065. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  7066. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  7067. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  7068. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  7069. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  7070. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  7071. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  7072. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  7073. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  7074. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  7075. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  7076. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  7077. }
  7078. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  7079. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  7080. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7081. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7082. }
  7083. if (is_object($object->project)) {
  7084. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  7085. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  7086. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  7087. }
  7088. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  7089. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  7090. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  7091. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  7092. }
  7093. if (is_object($object) && $object->element == 'project') {
  7094. $substitutionarray['__PROJECT_NAME__'] = $object->title;
  7095. }
  7096. if (is_object($object) && $object->element == 'shipping') {
  7097. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  7098. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  7099. }
  7100. if (is_object($object) && $object->element == 'reception') {
  7101. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  7102. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  7103. }
  7104. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  7105. $dateplannedstart = '';
  7106. $datenextexpiration = '';
  7107. foreach ($object->lines as $line) {
  7108. if ($line->date_start > $dateplannedstart) {
  7109. $dateplannedstart = $line->date_start;
  7110. }
  7111. if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
  7112. $datenextexpiration = $line->date_end;
  7113. }
  7114. }
  7115. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  7116. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  7117. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  7118. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  7119. }
  7120. // add substition variable for ticket
  7121. if (is_object($object) && $object->element == 'ticket') {
  7122. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  7123. $substitutionarray['__REF__'] = $object->ref;
  7124. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  7125. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  7126. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  7127. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  7128. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  7129. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  7130. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  7131. $userstat = new User($db);
  7132. if ($object->fk_user_assign > 0) {
  7133. $userstat->fetch($object->fk_user_assign);
  7134. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7135. }
  7136. if ($object->fk_user_create > 0) {
  7137. $userstat->fetch($object->fk_user_create);
  7138. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7139. }
  7140. }
  7141. // Create dynamic tags for __EXTRAFIELD_FIELD__
  7142. if ($object->table_element && $object->id > 0) {
  7143. if (!is_object($extrafields)) {
  7144. $extrafields = new ExtraFields($db);
  7145. }
  7146. $extrafields->fetch_name_optionals_label($object->table_element, true);
  7147. if ($object->fetch_optionals() > 0) {
  7148. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  7149. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  7150. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7151. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  7152. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  7153. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  7154. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  7155. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  7156. $datetime = $object->array_options['options_'.$key];
  7157. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  7158. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  7159. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  7160. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  7161. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  7162. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  7163. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  7164. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7165. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  7166. }
  7167. }
  7168. }
  7169. }
  7170. }
  7171. // Complete substitution array with the url to make online payment
  7172. $paymenturl = '';
  7173. if (empty($substitutionarray['__REF__'])) {
  7174. $paymenturl = '';
  7175. } else {
  7176. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  7177. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  7178. $outputlangs->loadLangs(array('paypal', 'other'));
  7179. $typeforonlinepayment = 'free';
  7180. if (is_object($object) && $object->element == 'commande') {
  7181. $typeforonlinepayment = 'order';
  7182. }
  7183. if (is_object($object) && $object->element == 'facture') {
  7184. $typeforonlinepayment = 'invoice';
  7185. }
  7186. if (is_object($object) && $object->element == 'member') {
  7187. $typeforonlinepayment = 'member';
  7188. }
  7189. if (is_object($object) && $object->element == 'contrat') {
  7190. $typeforonlinepayment = 'contract';
  7191. }
  7192. if (is_object($object) && $object->element == 'fichinter') {
  7193. $typeforonlinepayment = 'ficheinter';
  7194. }
  7195. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  7196. $paymenturl = $url;
  7197. }
  7198. if ($object->id > 0) {
  7199. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  7200. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  7201. if (is_object($object) && $object->element == 'propal') {
  7202. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7203. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  7204. }
  7205. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  7206. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7207. } else {
  7208. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  7209. }
  7210. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  7211. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  7212. } else {
  7213. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  7214. }
  7215. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  7216. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  7217. } else {
  7218. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  7219. }
  7220. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  7221. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  7222. } else {
  7223. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  7224. }
  7225. if (!empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'fichinter') {
  7226. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
  7227. } else {
  7228. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
  7229. }
  7230. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  7231. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7232. } else {
  7233. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  7234. }
  7235. if (is_object($object) && $object->element == 'propal') {
  7236. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  7237. }
  7238. if (is_object($object) && $object->element == 'commande') {
  7239. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  7240. }
  7241. if (is_object($object) && $object->element == 'facture') {
  7242. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  7243. }
  7244. if (is_object($object) && $object->element == 'contrat') {
  7245. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  7246. }
  7247. if (is_object($object) && $object->element == 'fichinter') {
  7248. $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT."/fichinter/card.php?id=".$object->id;
  7249. }
  7250. if (is_object($object) && $object->element == 'supplier_proposal') {
  7251. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  7252. }
  7253. if (is_object($object) && $object->element == 'shipping') {
  7254. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  7255. }
  7256. }
  7257. if (is_object($object) && $object->element == 'action') {
  7258. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  7259. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  7260. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  7261. }
  7262. }
  7263. }
  7264. if (empty($exclude) || !in_array('objectamount', $exclude)) {
  7265. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  7266. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  7267. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  7268. $already_payed_all = 0;
  7269. if (is_object($object) && ($object instanceof Facture)) {
  7270. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  7271. }
  7272. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  7273. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  7274. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  7275. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  7276. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? $object->total_ttc - $already_payed_all : '';
  7277. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7278. $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)) : '';
  7279. $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)) : '';
  7280. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7281. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  7282. }
  7283. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7284. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  7285. }
  7286. // Amount keys formated in a currency
  7287. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7288. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7289. $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) : '';
  7290. $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)) : '';
  7291. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7292. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7293. }
  7294. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7295. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7296. }
  7297. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  7298. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  7299. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  7300. // TODO Add other keys for foreign multicurrency
  7301. // For backward compatibility
  7302. if ($onlykey != 2) {
  7303. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  7304. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  7305. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7306. }
  7307. }
  7308. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  7309. if (empty($exclude) || !in_array('date', $exclude)) {
  7310. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  7311. $now = dol_now();
  7312. $tmp = dol_getdate($now, true);
  7313. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7314. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  7315. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7316. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  7317. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  7318. $substitutionarray = array_merge($substitutionarray, array(
  7319. '__NOW_TMS__' => (int) $now,
  7320. '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 0, $outputlangs),
  7321. '__DAY__' => (string) $tmp['mday'],
  7322. '__DAY_TEXT__' => $daytext, // Monday
  7323. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  7324. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  7325. '__MONTH__' => (string) $tmp['mon'],
  7326. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  7327. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  7328. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  7329. '__YEAR__' => (string) $tmp['year'],
  7330. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  7331. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  7332. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  7333. '__NEXT_DAY__' => (string) $tmp4['day'],
  7334. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7335. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7336. ));
  7337. }
  7338. if (isModEnabled('multicompany')) {
  7339. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7340. }
  7341. if (empty($exclude) || !in_array('system', $exclude)) {
  7342. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7343. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7344. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7345. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7346. }
  7347. return $substitutionarray;
  7348. }
  7349. /**
  7350. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7351. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7352. * Example of usage:
  7353. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7354. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7355. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7356. *
  7357. * @param string $text Source string in which we must do substitution
  7358. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7359. * @param Translate $outputlangs Output language
  7360. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7361. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7362. * @return string Output string after substitutions
  7363. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7364. */
  7365. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7366. {
  7367. global $conf, $langs;
  7368. if (!is_array($substitutionarray)) {
  7369. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7370. }
  7371. if (empty($outputlangs)) {
  7372. $outputlangs = $langs;
  7373. }
  7374. // Is initial text HTML or simple text ?
  7375. $msgishtml = 0;
  7376. if (dol_textishtml($text, 1)) {
  7377. $msgishtml = 1;
  7378. }
  7379. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7380. if (is_object($outputlangs)) {
  7381. $reg = array();
  7382. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7383. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7384. $tmp = explode('|', $reg[1]);
  7385. if (!empty($tmp[1])) {
  7386. $outputlangs->load($tmp[1]);
  7387. }
  7388. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7389. if (empty($converttextinhtmlifnecessary)) {
  7390. // convert $newval into HTML is necessary
  7391. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7392. } else {
  7393. if (! $msgishtml) {
  7394. $valueishtml = dol_textishtml($value, 1);
  7395. //var_dump("valueishtml=".$valueishtml);
  7396. if ($valueishtml) {
  7397. $text = dol_htmlentitiesbr($text);
  7398. $msgishtml = 1;
  7399. }
  7400. } else {
  7401. $value = dol_nl2br("$value");
  7402. }
  7403. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7404. }
  7405. }
  7406. }
  7407. // Make substitution for constant keys.
  7408. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7409. $reg = array();
  7410. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7411. $keyfound = $reg[1];
  7412. if (isASecretKey($keyfound)) {
  7413. $value = '*****forbidden*****';
  7414. } else {
  7415. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7416. }
  7417. if (empty($converttextinhtmlifnecessary)) {
  7418. // convert $newval into HTML is necessary
  7419. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7420. } else {
  7421. if (! $msgishtml) {
  7422. $valueishtml = dol_textishtml($value, 1);
  7423. if ($valueishtml) {
  7424. $text = dol_htmlentitiesbr($text);
  7425. $msgishtml = 1;
  7426. }
  7427. } else {
  7428. $value = dol_nl2br("$value");
  7429. }
  7430. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7431. }
  7432. }
  7433. // Make substitution for array $substitutionarray
  7434. foreach ($substitutionarray as $key => $value) {
  7435. if (!isset($value)) {
  7436. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7437. }
  7438. if (($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__') && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  7439. $value = ''; // Protection
  7440. }
  7441. if (empty($converttextinhtmlifnecessary)) {
  7442. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7443. } else {
  7444. if (! $msgishtml) {
  7445. $valueishtml = dol_textishtml($value, 1);
  7446. if ($valueishtml) {
  7447. $text = dol_htmlentitiesbr($text);
  7448. $msgishtml = 1;
  7449. }
  7450. } else {
  7451. $value = dol_nl2br("$value");
  7452. }
  7453. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7454. }
  7455. }
  7456. return $text;
  7457. }
  7458. /**
  7459. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  7460. * In this case, method completesubstitutionarray provided by module is called.
  7461. *
  7462. * @param array $substitutionarray Array substitution old value => new value value
  7463. * @param Translate $outputlangs Output language
  7464. * @param Object $object Source object
  7465. * @param mixed $parameters Add more parameters (useful to pass product lines)
  7466. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  7467. * @return void
  7468. * @see make_substitutions()
  7469. */
  7470. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  7471. {
  7472. global $conf, $user;
  7473. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7474. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7475. // Check if there is external substitution to do, requested by plugins
  7476. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7477. foreach ($dirsubstitutions as $reldir) {
  7478. $dir = dol_buildpath($reldir, 0);
  7479. // Check if directory exists
  7480. if (!dol_is_dir($dir)) {
  7481. continue;
  7482. }
  7483. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7484. foreach ($substitfiles as $substitfile) {
  7485. $reg = array();
  7486. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7487. $module = $reg[1];
  7488. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7489. // Include the user's functions file
  7490. require_once $dir.$substitfile['name'];
  7491. // Call the user's function, and only if it is defined
  7492. $function_name = $module."_".$callfunc;
  7493. if (function_exists($function_name)) {
  7494. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7495. }
  7496. }
  7497. }
  7498. }
  7499. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7500. // to list all tags in odt template
  7501. $tags = '';
  7502. foreach ($substitutionarray as $key => $value) {
  7503. $tags .= '{'.$key.'} => '.$value."\n";
  7504. }
  7505. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7506. }
  7507. }
  7508. /**
  7509. * Format output for start and end date
  7510. *
  7511. * @param int $date_start Start date
  7512. * @param int $date_end End date
  7513. * @param string $format Output format
  7514. * @param Translate $outputlangs Output language
  7515. * @return void
  7516. */
  7517. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7518. {
  7519. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7520. }
  7521. /**
  7522. * Format output for start and end date
  7523. *
  7524. * @param int $date_start Start date
  7525. * @param int $date_end End date
  7526. * @param string $format Output date format ('day', 'dayhour', ...)
  7527. * @param Translate $outputlangs Output language
  7528. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7529. * @return string String
  7530. */
  7531. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7532. {
  7533. global $langs;
  7534. $out = '';
  7535. if (!is_object($outputlangs)) {
  7536. $outputlangs = $langs;
  7537. }
  7538. if ($date_start && $date_end) {
  7539. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7540. }
  7541. if ($date_start && !$date_end) {
  7542. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7543. }
  7544. if (!$date_start && $date_end) {
  7545. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7546. }
  7547. return $out;
  7548. }
  7549. /**
  7550. * Return firstname and lastname in correct order
  7551. *
  7552. * @param string $firstname Firstname
  7553. * @param string $lastname Lastname
  7554. * @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
  7555. * @return string Firstname + lastname or Lastname + firstname
  7556. */
  7557. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7558. {
  7559. global $conf;
  7560. $ret = '';
  7561. // If order not defined, we use the setup
  7562. if ($nameorder < 0) {
  7563. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7564. }
  7565. if ($nameorder == 1) {
  7566. $ret .= $firstname;
  7567. if ($firstname && $lastname) {
  7568. $ret .= ' ';
  7569. }
  7570. $ret .= $lastname;
  7571. } elseif ($nameorder == 2 || $nameorder == 3) {
  7572. $ret .= $firstname;
  7573. if (empty($ret) && $nameorder == 3) {
  7574. $ret .= $lastname;
  7575. }
  7576. } else { // 0, 4 or 5
  7577. $ret .= $lastname;
  7578. if (empty($ret) && $nameorder == 5) {
  7579. $ret .= $firstname;
  7580. }
  7581. if ($nameorder == 0) {
  7582. if ($firstname && $lastname) {
  7583. $ret .= ' ';
  7584. }
  7585. $ret .= $firstname;
  7586. }
  7587. }
  7588. return $ret;
  7589. }
  7590. /**
  7591. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  7592. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7593. * Note: Prefer to use setEventMessages instead.
  7594. *
  7595. * @param string|string[] $mesgs Message string or array
  7596. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7597. * @return void
  7598. * @see dol_htmloutput_events()
  7599. */
  7600. function setEventMessage($mesgs, $style = 'mesgs')
  7601. {
  7602. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  7603. if (!is_array($mesgs)) {
  7604. // If mesgs is a string
  7605. if ($mesgs) {
  7606. $_SESSION['dol_events'][$style][] = $mesgs;
  7607. }
  7608. } else {
  7609. // If mesgs is an array
  7610. foreach ($mesgs as $mesg) {
  7611. if ($mesg) {
  7612. $_SESSION['dol_events'][$style][] = $mesg;
  7613. }
  7614. }
  7615. }
  7616. }
  7617. /**
  7618. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7619. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7620. *
  7621. * @param string $mesg Message string
  7622. * @param array|null $mesgs Message array
  7623. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7624. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7625. * @return void
  7626. * @see dol_htmloutput_events()
  7627. */
  7628. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  7629. {
  7630. if (empty($mesg) && empty($mesgs)) {
  7631. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  7632. } else {
  7633. if ($messagekey) {
  7634. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7635. // TODO
  7636. $mesg .= '';
  7637. }
  7638. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7639. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7640. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7641. }
  7642. if (empty($mesgs)) {
  7643. setEventMessage($mesg, $style);
  7644. } else {
  7645. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7646. setEventMessage($mesg, $style); // Add message string if not already into array
  7647. }
  7648. setEventMessage($mesgs, $style);
  7649. }
  7650. }
  7651. }
  7652. }
  7653. /**
  7654. * Print formated messages to output (Used to show messages on html output).
  7655. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7656. * no need to call it explicitely.
  7657. *
  7658. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7659. * @return void
  7660. * @see dol_htmloutput_mesg()
  7661. */
  7662. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7663. {
  7664. // Show mesgs
  7665. if (isset($_SESSION['dol_events']['mesgs'])) {
  7666. if (empty($disabledoutputofmessages)) {
  7667. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7668. }
  7669. unset($_SESSION['dol_events']['mesgs']);
  7670. }
  7671. // Show errors
  7672. if (isset($_SESSION['dol_events']['errors'])) {
  7673. if (empty($disabledoutputofmessages)) {
  7674. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7675. }
  7676. unset($_SESSION['dol_events']['errors']);
  7677. }
  7678. // Show warnings
  7679. if (isset($_SESSION['dol_events']['warnings'])) {
  7680. if (empty($disabledoutputofmessages)) {
  7681. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7682. }
  7683. unset($_SESSION['dol_events']['warnings']);
  7684. }
  7685. }
  7686. /**
  7687. * Get formated messages to output (Used to show messages on html output).
  7688. * This include also the translation of the message key.
  7689. *
  7690. * @param string $mesgstring Message string or message key
  7691. * @param string[] $mesgarray Array of message strings or message keys
  7692. * @param string $style Style of message output ('ok' or 'error')
  7693. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7694. * @return string Return html output
  7695. *
  7696. * @see dol_print_error()
  7697. * @see dol_htmloutput_errors()
  7698. * @see setEventMessages()
  7699. */
  7700. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7701. {
  7702. global $conf, $langs;
  7703. $ret = 0;
  7704. $return = '';
  7705. $out = '';
  7706. $divstart = $divend = '';
  7707. // If inline message with no format, we add it.
  7708. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7709. $divstart = '<div class="'.$style.' clearboth">';
  7710. $divend = '</div>';
  7711. }
  7712. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7713. $langs->load("errors");
  7714. $out .= $divstart;
  7715. if (is_array($mesgarray) && count($mesgarray)) {
  7716. foreach ($mesgarray as $message) {
  7717. $ret++;
  7718. $out .= $langs->trans($message);
  7719. if ($ret < count($mesgarray)) {
  7720. $out .= "<br>\n";
  7721. }
  7722. }
  7723. }
  7724. if ($mesgstring) {
  7725. $ret++;
  7726. $out .= $langs->trans($mesgstring);
  7727. }
  7728. $out .= $divend;
  7729. }
  7730. if ($out) {
  7731. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7732. $return = '<script>
  7733. $(document).ready(function() {
  7734. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7735. if (block) {
  7736. $.dolEventValid("","'.dol_escape_js($out).'");
  7737. } else {
  7738. /* jnotify(message, preset of message type, keepmessage) */
  7739. $.jnotify("'.dol_escape_js($out).'",
  7740. "'.($style == "ok" ? 3000 : $style).'",
  7741. '.($style == "ok" ? "false" : "true").',
  7742. { remove: function (){} } );
  7743. }
  7744. });
  7745. </script>';
  7746. } else {
  7747. $return = $out;
  7748. }
  7749. }
  7750. return $return;
  7751. }
  7752. /**
  7753. * Get formated error messages to output (Used to show messages on html output).
  7754. *
  7755. * @param string $mesgstring Error message
  7756. * @param array $mesgarray Error messages array
  7757. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7758. * @return string Return html output
  7759. *
  7760. * @see dol_print_error()
  7761. * @see dol_htmloutput_mesg()
  7762. */
  7763. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7764. {
  7765. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7766. }
  7767. /**
  7768. * Print formated messages to output (Used to show messages on html output).
  7769. *
  7770. * @param string $mesgstring Message string or message key
  7771. * @param string[] $mesgarray Array of message strings or message keys
  7772. * @param string $style Which style to use ('ok', 'warning', 'error')
  7773. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7774. * @return void
  7775. *
  7776. * @see dol_print_error()
  7777. * @see dol_htmloutput_errors()
  7778. * @see setEventMessages()
  7779. */
  7780. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7781. {
  7782. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7783. return;
  7784. }
  7785. $iserror = 0;
  7786. $iswarning = 0;
  7787. if (is_array($mesgarray)) {
  7788. foreach ($mesgarray as $val) {
  7789. if ($val && preg_match('/class="error"/i', $val)) {
  7790. $iserror++;
  7791. break;
  7792. }
  7793. if ($val && preg_match('/class="warning"/i', $val)) {
  7794. $iswarning++;
  7795. break;
  7796. }
  7797. }
  7798. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7799. $iserror++;
  7800. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7801. $iswarning++;
  7802. }
  7803. if ($style == 'error') {
  7804. $iserror++;
  7805. }
  7806. if ($style == 'warning') {
  7807. $iswarning++;
  7808. }
  7809. if ($iserror || $iswarning) {
  7810. // Remove div from texts
  7811. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7812. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7813. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7814. // Remove div from texts array
  7815. if (is_array($mesgarray)) {
  7816. $newmesgarray = array();
  7817. foreach ($mesgarray as $val) {
  7818. if (is_string($val)) {
  7819. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7820. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7821. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7822. $newmesgarray[] = $tmpmesgstring;
  7823. } else {
  7824. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7825. }
  7826. }
  7827. $mesgarray = $newmesgarray;
  7828. }
  7829. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  7830. } else {
  7831. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  7832. }
  7833. }
  7834. /**
  7835. * Print formated error messages to output (Used to show messages on html output).
  7836. *
  7837. * @param string $mesgstring Error message
  7838. * @param array $mesgarray Error messages array
  7839. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7840. * @return void
  7841. *
  7842. * @see dol_print_error()
  7843. * @see dol_htmloutput_mesg()
  7844. */
  7845. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7846. {
  7847. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7848. }
  7849. /**
  7850. * Advanced sort array by second index function, which produces ascending (default)
  7851. * or descending output and uses optionally natural case insensitive sorting (which
  7852. * can be optionally case sensitive as well).
  7853. *
  7854. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  7855. * @param string $index Key in array to use for sorting criteria
  7856. * @param int $order Sort order ('asc' or 'desc')
  7857. * @param int $natsort If values are strings (I said value not type): 0=Use alphabetical order, 1=use "natural" sort (natsort)
  7858. * If values are numeric (I said value not type): 0=Use numeric order (even if type is string) so use a "natural" sort, 1=use "natural" sort too (same than 0), -1=Force alphabetical order
  7859. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  7860. * @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.
  7861. * @return array Sorted array
  7862. */
  7863. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  7864. {
  7865. // Clean parameters
  7866. $order = strtolower($order);
  7867. if (is_array($array)) {
  7868. $sizearray = count($array);
  7869. if ($sizearray > 0) {
  7870. $temp = array();
  7871. foreach (array_keys($array) as $key) {
  7872. if (is_object($array[$key])) {
  7873. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  7874. } else {
  7875. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  7876. }
  7877. if ($natsort == -1) {
  7878. $temp[$key] = '___'.$temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
  7879. }
  7880. }
  7881. if (empty($natsort) || $natsort == -1) {
  7882. if ($order == 'asc') {
  7883. asort($temp);
  7884. } else {
  7885. arsort($temp);
  7886. }
  7887. } else {
  7888. if ($case_sensitive) {
  7889. natsort($temp);
  7890. } else {
  7891. natcasesort($temp); // natecasesort is not sensible to case
  7892. }
  7893. if ($order != 'asc') {
  7894. $temp = array_reverse($temp, true);
  7895. }
  7896. }
  7897. $sorted = array();
  7898. foreach (array_keys($temp) as $key) {
  7899. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  7900. }
  7901. return $sorted;
  7902. }
  7903. }
  7904. return $array;
  7905. }
  7906. /**
  7907. * Check if a string is in UTF8
  7908. *
  7909. * @param string $str String to check
  7910. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  7911. */
  7912. function utf8_check($str)
  7913. {
  7914. $str = (string) $str; // Sometimes string is an int.
  7915. // We must use here a binary strlen function (so not dol_strlen)
  7916. $strLength = dol_strlen($str);
  7917. for ($i = 0; $i < $strLength; $i++) {
  7918. if (ord($str[$i]) < 0x80) {
  7919. continue; // 0bbbbbbb
  7920. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  7921. $n = 1; // 110bbbbb
  7922. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  7923. $n = 2; // 1110bbbb
  7924. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  7925. $n = 3; // 11110bbb
  7926. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  7927. $n = 4; // 111110bb
  7928. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  7929. $n = 5; // 1111110b
  7930. } else {
  7931. return false; // Does not match any model
  7932. }
  7933. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  7934. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  7935. return false;
  7936. }
  7937. }
  7938. }
  7939. return true;
  7940. }
  7941. /**
  7942. * Check if a string is in ASCII
  7943. *
  7944. * @param string $str String to check
  7945. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  7946. */
  7947. function ascii_check($str)
  7948. {
  7949. if (function_exists('mb_check_encoding')) {
  7950. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  7951. if (!mb_check_encoding($str, 'ASCII')) {
  7952. return false;
  7953. }
  7954. } else {
  7955. if (preg_match('/[^\x00-\x7f]/', $str)) {
  7956. return false; // Contains a byte > 7f
  7957. }
  7958. }
  7959. return true;
  7960. }
  7961. /**
  7962. * Return a string encoded into OS filesystem encoding. This function is used to define
  7963. * value to pass to filesystem PHP functions.
  7964. *
  7965. * @param string $str String to encode (UTF-8)
  7966. * @return string Encoded string (UTF-8, ISO-8859-1)
  7967. */
  7968. function dol_osencode($str)
  7969. {
  7970. global $conf;
  7971. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  7972. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  7973. $tmp = 'iso-8859-1'; // By default for windows
  7974. }
  7975. if (empty($tmp)) {
  7976. $tmp = 'utf-8'; // By default for other
  7977. }
  7978. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  7979. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  7980. }
  7981. if ($tmp == 'iso-8859-1') {
  7982. return utf8_decode($str);
  7983. }
  7984. return $str;
  7985. }
  7986. /**
  7987. * Return an id or code from a code or id.
  7988. * Store also Code-Id into a cache to speed up next request on same key.
  7989. *
  7990. * @param DoliDB $db Database handler
  7991. * @param string $key Code or Id to get Id or Code
  7992. * @param string $tablename Table name without prefix
  7993. * @param string $fieldkey Field to search the key into
  7994. * @param string $fieldid Field to get
  7995. * @param int $entityfilter Filter by entity
  7996. * @param string $filters Filters to add. WARNING: string must be escaped for SQL and not coming from user input.
  7997. * @return int <0 if KO, Id of code if OK
  7998. * @see $langs->getLabelFromKey
  7999. */
  8000. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '')
  8001. {
  8002. global $cache_codes;
  8003. // If key empty
  8004. if ($key == '') {
  8005. return '';
  8006. }
  8007. // Check in cache
  8008. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  8009. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  8010. }
  8011. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  8012. $sql = "SELECT ".$fieldid." as valuetoget";
  8013. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  8014. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  8015. if (!empty($entityfilter)) {
  8016. $sql .= " AND entity IN (".getEntity($tablename).")";
  8017. }
  8018. if ($filters) {
  8019. $sql .= $filters;
  8020. }
  8021. $resql = $db->query($sql);
  8022. if ($resql) {
  8023. $obj = $db->fetch_object($resql);
  8024. if ($obj) {
  8025. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  8026. } else {
  8027. $cache_codes[$tablename][$key][$fieldid] = '';
  8028. }
  8029. $db->free($resql);
  8030. return $cache_codes[$tablename][$key][$fieldid];
  8031. } else {
  8032. return -1;
  8033. }
  8034. }
  8035. /**
  8036. * Verify if condition in string is ok or not
  8037. *
  8038. * @param string $strToEvaluate String with condition to check
  8039. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  8040. */
  8041. function verifCond($strToEvaluate)
  8042. {
  8043. global $user, $conf, $langs;
  8044. global $leftmenu;
  8045. global $rights; // To export to dol_eval function
  8046. //print $strToEvaluate."<br>\n";
  8047. $rights = true;
  8048. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  8049. //var_dump($strToEvaluate);
  8050. $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
  8051. $rights = $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
  8052. //var_dump($rights);
  8053. }
  8054. return $rights;
  8055. }
  8056. /**
  8057. * Replace eval function to add more security.
  8058. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  8059. *
  8060. * @param string $s String to evaluate
  8061. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  8062. * @param int $hideerrors 1=Hide errors
  8063. * @param string $onlysimplestring '0' (used for computed property of extrafields)=Accept all chars, '1' (most common use)=Accept only simple string with char 'a-z0-9\s^$_+-.*>&|=!?():"\',/@';', '2' (not used)=Accept also ';[]'
  8064. * @return mixed Nothing or return result of eval
  8065. */
  8066. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  8067. {
  8068. // Only global variables can be changed by eval function and returned to caller
  8069. global $db, $langs, $user, $conf, $website, $websitepage;
  8070. global $action, $mainmenu, $leftmenu;
  8071. global $rights;
  8072. global $object;
  8073. global $mysoc;
  8074. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  8075. global $soc; // For backward compatibility
  8076. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  8077. if ($onlysimplestring == '1') {
  8078. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL'
  8079. // We must accept: '$conf->barcode->enabled || preg_match(\'/^AAA/\',$leftmenu)'
  8080. // We must accept: '$user->rights->cabinetmed->read && !$object->canvas=="patient@cabinetmed"'
  8081. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@', '/').']/i', $s)) {
  8082. if ($returnvalue) {
  8083. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8084. } else {
  8085. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8086. return '';
  8087. }
  8088. // TODO
  8089. // We can exclude all parenthesis ( that are not '($db' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match(' and 'isModEnabled('
  8090. // ...
  8091. }
  8092. } elseif ($onlysimplestring == '2') {
  8093. // 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"
  8094. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@;[]', '/').']/i', $s)) {
  8095. if ($returnvalue) {
  8096. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8097. } else {
  8098. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8099. return '';
  8100. }
  8101. }
  8102. }
  8103. if (strpos($s, '::') !== false) {
  8104. if ($returnvalue) {
  8105. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  8106. } else {
  8107. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  8108. return '';
  8109. }
  8110. }
  8111. if (strpos($s, '`') !== false) {
  8112. if ($returnvalue) {
  8113. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  8114. } else {
  8115. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  8116. return '';
  8117. }
  8118. }
  8119. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  8120. if ($returnvalue) {
  8121. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  8122. } else {
  8123. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  8124. return '';
  8125. }
  8126. }
  8127. // We block use of php exec or php file functions
  8128. $forbiddenphpstrings = array('$$');
  8129. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  8130. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI", "verifCond", "base64_decode");
  8131. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  8132. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  8133. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  8134. do {
  8135. $oldstringtoclean = $s;
  8136. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  8137. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  8138. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  8139. } while ($oldstringtoclean != $s);
  8140. if (strpos($s, '__forbiddenstring__') !== false) {
  8141. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  8142. if ($returnvalue) {
  8143. return 'Bad string syntax to evaluate: '.$s;
  8144. } else {
  8145. dol_syslog('Bad string syntax to evaluate: '.$s);
  8146. return '';
  8147. }
  8148. }
  8149. //print $s."<br>\n";
  8150. if ($returnvalue) {
  8151. if ($hideerrors) {
  8152. return @eval('return '.$s.';');
  8153. } else {
  8154. return eval('return '.$s.';');
  8155. }
  8156. } else {
  8157. if ($hideerrors) {
  8158. @eval($s);
  8159. } else {
  8160. eval($s);
  8161. }
  8162. }
  8163. }
  8164. /**
  8165. * Return if var element is ok
  8166. *
  8167. * @param string $element Variable to check
  8168. * @return boolean Return true of variable is not empty
  8169. */
  8170. function dol_validElement($element)
  8171. {
  8172. return (trim($element) != '');
  8173. }
  8174. /**
  8175. * Return img flag of country for a language code or country code.
  8176. *
  8177. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  8178. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  8179. * @param int $notitlealt No title alt
  8180. * @return string HTML img string with flag.
  8181. */
  8182. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  8183. {
  8184. if (empty($codelang)) {
  8185. return '';
  8186. }
  8187. if ($codelang == 'auto') {
  8188. return '<span class="fa fa-language"></span>';
  8189. }
  8190. $langtocountryflag = array(
  8191. 'ar_AR' => '',
  8192. 'ca_ES' => 'catalonia',
  8193. 'da_DA' => 'dk',
  8194. 'fr_CA' => 'mq',
  8195. 'sv_SV' => 'se',
  8196. 'sw_SW' => 'unknown',
  8197. 'AQ' => 'unknown',
  8198. 'CW' => 'unknown',
  8199. 'IM' => 'unknown',
  8200. 'JE' => 'unknown',
  8201. 'MF' => 'unknown',
  8202. 'BL' => 'unknown',
  8203. 'SX' => 'unknown'
  8204. );
  8205. if (isset($langtocountryflag[$codelang])) {
  8206. $flagImage = $langtocountryflag[$codelang];
  8207. } else {
  8208. $tmparray = explode('_', $codelang);
  8209. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  8210. }
  8211. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  8212. }
  8213. /**
  8214. * Return default language from country code.
  8215. * Return null if not found.
  8216. *
  8217. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  8218. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  8219. */
  8220. function getLanguageCodeFromCountryCode($countrycode)
  8221. {
  8222. global $mysoc;
  8223. if (empty($countrycode)) {
  8224. return null;
  8225. }
  8226. if (strtoupper($countrycode) == 'MQ') {
  8227. return 'fr_CA';
  8228. }
  8229. if (strtoupper($countrycode) == 'SE') {
  8230. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  8231. }
  8232. if (strtoupper($countrycode) == 'CH') {
  8233. if ($mysoc->country_code == 'FR') {
  8234. return 'fr_CH';
  8235. }
  8236. if ($mysoc->country_code == 'DE') {
  8237. return 'de_CH';
  8238. }
  8239. if ($mysoc->country_code == 'IT') {
  8240. return 'it_CH';
  8241. }
  8242. }
  8243. // Locale list taken from:
  8244. // http://stackoverflow.com/questions/3191664/
  8245. // list-of-all-locales-and-their-short-codes
  8246. $locales = array(
  8247. 'af-ZA',
  8248. 'am-ET',
  8249. 'ar-AE',
  8250. 'ar-BH',
  8251. 'ar-DZ',
  8252. 'ar-EG',
  8253. 'ar-IQ',
  8254. 'ar-JO',
  8255. 'ar-KW',
  8256. 'ar-LB',
  8257. 'ar-LY',
  8258. 'ar-MA',
  8259. 'ar-OM',
  8260. 'ar-QA',
  8261. 'ar-SA',
  8262. 'ar-SY',
  8263. 'ar-TN',
  8264. 'ar-YE',
  8265. //'as-IN', // Moved after en-IN
  8266. 'ba-RU',
  8267. 'be-BY',
  8268. 'bg-BG',
  8269. 'bn-BD',
  8270. //'bn-IN', // Moved after en-IN
  8271. 'bo-CN',
  8272. 'br-FR',
  8273. 'ca-ES',
  8274. 'co-FR',
  8275. 'cs-CZ',
  8276. 'cy-GB',
  8277. 'da-DK',
  8278. 'de-AT',
  8279. 'de-CH',
  8280. 'de-DE',
  8281. 'de-LI',
  8282. 'de-LU',
  8283. 'dv-MV',
  8284. 'el-GR',
  8285. 'en-AU',
  8286. 'en-BZ',
  8287. 'en-CA',
  8288. 'en-GB',
  8289. 'en-IE',
  8290. 'en-IN',
  8291. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  8292. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  8293. 'en-JM',
  8294. 'en-MY',
  8295. 'en-NZ',
  8296. 'en-PH',
  8297. 'en-SG',
  8298. 'en-TT',
  8299. 'en-US',
  8300. 'en-ZA',
  8301. 'en-ZW',
  8302. 'es-AR',
  8303. 'es-BO',
  8304. 'es-CL',
  8305. 'es-CO',
  8306. 'es-CR',
  8307. 'es-DO',
  8308. 'es-EC',
  8309. 'es-ES',
  8310. 'es-GT',
  8311. 'es-HN',
  8312. 'es-MX',
  8313. 'es-NI',
  8314. 'es-PA',
  8315. 'es-PE',
  8316. 'es-PR',
  8317. 'es-PY',
  8318. 'es-SV',
  8319. 'es-US',
  8320. 'es-UY',
  8321. 'es-VE',
  8322. 'et-EE',
  8323. 'eu-ES',
  8324. 'fa-IR',
  8325. 'fi-FI',
  8326. 'fo-FO',
  8327. 'fr-BE',
  8328. 'fr-CA',
  8329. 'fr-CH',
  8330. 'fr-FR',
  8331. 'fr-LU',
  8332. 'fr-MC',
  8333. 'fy-NL',
  8334. 'ga-IE',
  8335. 'gd-GB',
  8336. 'gl-ES',
  8337. 'gu-IN',
  8338. 'he-IL',
  8339. 'hi-IN',
  8340. 'hr-BA',
  8341. 'hr-HR',
  8342. 'hu-HU',
  8343. 'hy-AM',
  8344. 'id-ID',
  8345. 'ig-NG',
  8346. 'ii-CN',
  8347. 'is-IS',
  8348. 'it-CH',
  8349. 'it-IT',
  8350. 'ja-JP',
  8351. 'ka-GE',
  8352. 'kk-KZ',
  8353. 'kl-GL',
  8354. 'km-KH',
  8355. 'kn-IN',
  8356. 'ko-KR',
  8357. 'ky-KG',
  8358. 'lb-LU',
  8359. 'lo-LA',
  8360. 'lt-LT',
  8361. 'lv-LV',
  8362. 'mi-NZ',
  8363. 'mk-MK',
  8364. 'ml-IN',
  8365. 'mn-MN',
  8366. 'mr-IN',
  8367. 'ms-BN',
  8368. 'ms-MY',
  8369. 'mt-MT',
  8370. 'nb-NO',
  8371. 'ne-NP',
  8372. 'nl-BE',
  8373. 'nl-NL',
  8374. 'nn-NO',
  8375. 'oc-FR',
  8376. 'or-IN',
  8377. 'pa-IN',
  8378. 'pl-PL',
  8379. 'ps-AF',
  8380. 'pt-BR',
  8381. 'pt-PT',
  8382. 'rm-CH',
  8383. 'ro-MD',
  8384. 'ro-RO',
  8385. 'ru-RU',
  8386. 'rw-RW',
  8387. 'sa-IN',
  8388. 'se-FI',
  8389. 'se-NO',
  8390. 'se-SE',
  8391. 'si-LK',
  8392. 'sk-SK',
  8393. 'sl-SI',
  8394. 'sq-AL',
  8395. 'sv-FI',
  8396. 'sv-SE',
  8397. 'sw-KE',
  8398. 'ta-IN',
  8399. 'te-IN',
  8400. 'th-TH',
  8401. 'tk-TM',
  8402. 'tn-ZA',
  8403. 'tr-TR',
  8404. 'tt-RU',
  8405. 'ug-CN',
  8406. 'uk-UA',
  8407. 'ur-PK',
  8408. 'vi-VN',
  8409. 'wo-SN',
  8410. 'xh-ZA',
  8411. 'yo-NG',
  8412. 'zh-CN',
  8413. 'zh-HK',
  8414. 'zh-MO',
  8415. 'zh-SG',
  8416. 'zh-TW',
  8417. 'zu-ZA',
  8418. );
  8419. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  8420. if (in_array($buildprimarykeytotest, $locales)) {
  8421. return strtolower($countrycode).'_'.strtoupper($countrycode);
  8422. }
  8423. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  8424. foreach ($locales as $locale) {
  8425. $locale_language = locale_get_primary_language($locale);
  8426. $locale_region = locale_get_region($locale);
  8427. if (strtoupper($countrycode) == $locale_region) {
  8428. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  8429. return strtolower($locale_language).'_'.strtoupper($locale_region);
  8430. }
  8431. }
  8432. } else {
  8433. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  8434. }
  8435. return null;
  8436. }
  8437. /**
  8438. * Complete or removed entries into a head array (used to build tabs).
  8439. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  8440. * Or by change using hook completeTabsHead
  8441. *
  8442. * @param Conf $conf Object conf
  8443. * @param Translate $langs Object langs
  8444. * @param object|null $object Object object
  8445. * @param array $head Object head
  8446. * @param int $h New position to fill
  8447. * @param string $type Value for object where objectvalue can be
  8448. * 'thirdparty' to add a tab in third party view
  8449. * 'intervention' to add a tab in intervention view
  8450. * 'supplier_order' to add a tab in purchase order view
  8451. * 'supplier_invoice' to add a tab in purchase invoice view
  8452. * 'invoice' to add a tab in sales invoice view
  8453. * 'order' to add a tab in sales order view
  8454. * 'contract' to add a tabl in contract view
  8455. * 'product' to add a tab in product view
  8456. * 'propal' to add a tab in propal view
  8457. * 'user' to add a tab in user view
  8458. * 'group' to add a tab in group view
  8459. * 'member' to add a tab in fundation member view
  8460. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  8461. * 'ecm' to add a tab for another ecm view
  8462. * 'stock' to add a tab for warehouse view
  8463. * @param string $mode 'add' to complete head, 'remove' to remove entries
  8464. * @param string $filterorigmodule Filter on module origin: 'external' will show only external modules. 'core' only core modules. No filter (default) will add both.
  8465. * @return void
  8466. */
  8467. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
  8468. {
  8469. global $hookmanager, $db;
  8470. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  8471. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  8472. $values = explode(':', $value);
  8473. $reg = array();
  8474. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  8475. if (count($values) == 6) {
  8476. // new declaration with permissions:
  8477. // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8478. // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8479. if ($values[0] != $type) {
  8480. continue;
  8481. }
  8482. if (verifCond($values[4])) {
  8483. if ($values[3]) {
  8484. if ($filterorigmodule) { // If a filter of module origin has been requested
  8485. if (strpos($values[3], '@')) { // This is an external module
  8486. if ($filterorigmodule != 'external') {
  8487. continue;
  8488. }
  8489. } else { // This looks a core module
  8490. if ($filterorigmodule != 'core') {
  8491. continue;
  8492. }
  8493. }
  8494. }
  8495. $langs->load($values[3]);
  8496. }
  8497. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8498. // If label is "SUBSTITUION_..."
  8499. $substitutionarray = array();
  8500. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8501. $label = make_substitutions($reg[1], $substitutionarray);
  8502. } else {
  8503. // If label is "Label,Class,File,Method", we call the method to show content inside the badge
  8504. $labeltemp = explode(',', $values[2]);
  8505. $label = $langs->trans($labeltemp[0]);
  8506. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  8507. dol_include_once($labeltemp[2]);
  8508. $classtoload = $labeltemp[1];
  8509. if (class_exists($classtoload)) {
  8510. $obj = new $classtoload($db);
  8511. $function = $labeltemp[3];
  8512. if ($obj && $function && method_exists($obj, $function)) {
  8513. $nbrec = $obj->$function($object->id, $obj);
  8514. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  8515. }
  8516. }
  8517. }
  8518. }
  8519. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  8520. $head[$h][1] = $label;
  8521. $head[$h][2] = str_replace('+', '', $values[1]);
  8522. $h++;
  8523. }
  8524. } elseif (count($values) == 5) { // case deprecated
  8525. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  8526. if ($values[0] != $type) {
  8527. continue;
  8528. }
  8529. if ($values[3]) {
  8530. if ($filterorigmodule) { // If a filter of module origin has been requested
  8531. if (strpos($values[3], '@')) { // This is an external module
  8532. if ($filterorigmodule != 'external') {
  8533. continue;
  8534. }
  8535. } else { // This looks a core module
  8536. if ($filterorigmodule != 'core') {
  8537. continue;
  8538. }
  8539. }
  8540. }
  8541. $langs->load($values[3]);
  8542. }
  8543. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8544. $substitutionarray = array();
  8545. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8546. $label = make_substitutions($reg[1], $substitutionarray);
  8547. } else {
  8548. $label = $langs->trans($values[2]);
  8549. }
  8550. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  8551. $head[$h][1] = $label;
  8552. $head[$h][2] = str_replace('+', '', $values[1]);
  8553. $h++;
  8554. }
  8555. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  8556. if ($values[0] != $type) {
  8557. continue;
  8558. }
  8559. $tabname = str_replace('-', '', $values[1]);
  8560. foreach ($head as $key => $val) {
  8561. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  8562. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  8563. if ($head[$key][2] == $tabname && $condition) {
  8564. unset($head[$key]);
  8565. break;
  8566. }
  8567. }
  8568. }
  8569. }
  8570. }
  8571. // No need to make a return $head. Var is modified as a reference
  8572. if (!empty($hookmanager)) {
  8573. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
  8574. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  8575. if ($reshook > 0) { // Hook ask to replace completely the array
  8576. $head = $hookmanager->resArray;
  8577. } else { // Hook
  8578. $head = array_merge($head, $hookmanager->resArray);
  8579. }
  8580. $h = count($head);
  8581. }
  8582. }
  8583. /**
  8584. * Print common footer :
  8585. * conf->global->MAIN_HTML_FOOTER
  8586. * js for switch of menu hider
  8587. * js for conf->global->MAIN_GOOGLE_AN_ID
  8588. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  8589. * js for conf->logbuffer
  8590. *
  8591. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  8592. * @return void
  8593. */
  8594. function printCommonFooter($zone = 'private')
  8595. {
  8596. global $conf, $hookmanager, $user, $debugbar;
  8597. global $action;
  8598. global $micro_start_time;
  8599. if ($zone == 'private') {
  8600. print "\n".'<!-- Common footer for private page -->'."\n";
  8601. } else {
  8602. print "\n".'<!-- Common footer for public page -->'."\n";
  8603. }
  8604. // A div to store page_y POST parameter so we can read it using javascript
  8605. print "\n<!-- A div to store page_y POST parameter -->\n";
  8606. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  8607. $parameters = array();
  8608. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  8609. if (empty($reshook)) {
  8610. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  8611. print $conf->global->MAIN_HTML_FOOTER."\n";
  8612. }
  8613. print "\n";
  8614. if (!empty($conf->use_javascript_ajax)) {
  8615. print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and madatory fields, tuning info, ... -->\n";
  8616. print '<script>'."\n";
  8617. print 'jQuery(document).ready(function() {'."\n";
  8618. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  8619. print "\n";
  8620. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  8621. print 'jQuery("li.menuhider").click(function(event) {';
  8622. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  8623. print ' console.log("We click on .menuhider");'."\n";
  8624. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  8625. print '});'."\n";
  8626. }
  8627. // Management of focus and mandatory for fields
  8628. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
  8629. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  8630. $relativepathstring = $_SERVER["PHP_SELF"];
  8631. // Clean $relativepathstring
  8632. if (constant('DOL_URL_ROOT')) {
  8633. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  8634. }
  8635. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  8636. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  8637. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  8638. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  8639. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  8640. $qualified = 0;
  8641. if ($defkey != '_noquery_') {
  8642. $tmpqueryarraytohave = explode('&', $defkey);
  8643. $foundintru = 0;
  8644. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8645. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8646. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8647. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8648. $foundintru = 1;
  8649. }
  8650. }
  8651. if (!$foundintru) {
  8652. $qualified = 1;
  8653. }
  8654. //var_dump($defkey.'-'.$qualified);
  8655. } else {
  8656. $qualified = 1;
  8657. }
  8658. if ($qualified) {
  8659. foreach ($defval as $paramkey => $paramval) {
  8660. // Set focus on field
  8661. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  8662. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  8663. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  8664. }
  8665. }
  8666. }
  8667. }
  8668. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  8669. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  8670. $qualified = 0;
  8671. if ($defkey != '_noquery_') {
  8672. $tmpqueryarraytohave = explode('&', $defkey);
  8673. $foundintru = 0;
  8674. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8675. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8676. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8677. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8678. $foundintru = 1;
  8679. }
  8680. }
  8681. if (!$foundintru) {
  8682. $qualified = 1;
  8683. }
  8684. //var_dump($defkey.'-'.$qualified);
  8685. } else {
  8686. $qualified = 1;
  8687. }
  8688. if ($qualified) {
  8689. foreach ($defval as $paramkey => $paramval) {
  8690. // Add property 'required' on input
  8691. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8692. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8693. 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";
  8694. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8695. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  8696. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  8697. // Add 'field required' class on closest td for all input elements : input, textarea and select
  8698. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  8699. }
  8700. }
  8701. }
  8702. }
  8703. }
  8704. print '});'."\n";
  8705. // End of tuning
  8706. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  8707. print "\n";
  8708. print "/* JS CODE TO ENABLE to add memory info */\n";
  8709. print 'window.console && console.log("';
  8710. if (!empty($conf->global->MEMCACHED_SERVER)) {
  8711. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  8712. }
  8713. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  8714. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  8715. $micro_end_time = microtime(true);
  8716. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  8717. }
  8718. if (function_exists("memory_get_usage")) {
  8719. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  8720. }
  8721. if (function_exists("memory_get_peak_usage")) {
  8722. print ' - Real mem peak: '.memory_get_peak_usage(true);
  8723. }
  8724. if (function_exists("zend_loader_file_encoded")) {
  8725. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8726. }
  8727. print '");'."\n";
  8728. }
  8729. print "\n".'</script>'."\n";
  8730. // Google Analytics
  8731. // TODO Add a hook here
  8732. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8733. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8734. foreach ($tmptagarray as $tmptag) {
  8735. print "\n";
  8736. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8737. print "
  8738. <!-- Global site tag (gtag.js) - Google Analytics -->
  8739. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  8740. <script>
  8741. window.dataLayer = window.dataLayer || [];
  8742. function gtag(){dataLayer.push(arguments);}
  8743. gtag('js', new Date());
  8744. gtag('config', '".trim($tmptag)."');
  8745. </script>";
  8746. print "\n";
  8747. }
  8748. }
  8749. }
  8750. // Add Xdebug coverage of code
  8751. if (defined('XDEBUGCOVERAGE')) {
  8752. print_r(xdebug_get_code_coverage());
  8753. }
  8754. // Add DebugBar data
  8755. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8756. $debugbar['time']->stopMeasure('pageaftermaster');
  8757. print '<!-- Output debugbar data -->'."\n";
  8758. $renderer = $debugbar->getRenderer();
  8759. print $debugbar->getRenderer()->render();
  8760. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8761. print "\n";
  8762. print "<!-- Start of log output\n";
  8763. //print '<div class="hidden">'."\n";
  8764. foreach ($conf->logbuffer as $logline) {
  8765. print $logline."<br>\n";
  8766. }
  8767. //print '</div>'."\n";
  8768. print "End of log output -->\n";
  8769. }
  8770. }
  8771. }
  8772. /**
  8773. * Split a string with 2 keys into key array.
  8774. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8775. *
  8776. * @param string $string String to explode
  8777. * @param string $delimiter Delimiter between each couple of data
  8778. * @param string $kv Delimiter between key and value
  8779. * @return array Array of data exploded
  8780. */
  8781. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8782. {
  8783. if ($a = explode($delimiter, $string)) {
  8784. $ka = array();
  8785. foreach ($a as $s) { // each part
  8786. if ($s) {
  8787. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8788. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8789. } else { // key delimiter not found
  8790. $ka[] = trim($s);
  8791. }
  8792. }
  8793. }
  8794. return $ka;
  8795. }
  8796. return array();
  8797. }
  8798. /**
  8799. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  8800. *
  8801. * @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.
  8802. * @return void
  8803. */
  8804. function dol_set_focus($selector)
  8805. {
  8806. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  8807. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  8808. }
  8809. /**
  8810. * Return getmypid() or random PID when function is disabled
  8811. * Some web hosts disable this php function for security reasons
  8812. * and sometimes we can't redeclare function.
  8813. *
  8814. * @return int
  8815. */
  8816. function dol_getmypid()
  8817. {
  8818. if (!function_exists('getmypid')) {
  8819. return mt_rand(99900000, 99965535);
  8820. } else {
  8821. return getmypid(); // May be a number on 64 bits (depending on OS)
  8822. }
  8823. }
  8824. /**
  8825. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  8826. *
  8827. * @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")
  8828. * @param string $value The value to look for.
  8829. * If param $mode is 0, can contains several keywords separated with a space or |
  8830. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  8831. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  8832. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  8833. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  8834. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  8835. * @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')
  8836. * 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'
  8837. * @param integer $nofirstand 1=Do not output the first 'AND'
  8838. * @return string $res The statement to append to the SQL query
  8839. * @see dolSqlDateFilter()
  8840. */
  8841. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  8842. {
  8843. global $db, $langs;
  8844. $value = trim($value);
  8845. if ($mode == 0) {
  8846. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  8847. }
  8848. if ($mode == 1) {
  8849. $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
  8850. }
  8851. $value = preg_replace('/\s*\|\s*/', '|', $value);
  8852. $crits = explode(' ', $value);
  8853. $res = '';
  8854. if (!is_array($fields)) {
  8855. $fields = array($fields);
  8856. }
  8857. $j = 0;
  8858. foreach ($crits as $crit) {
  8859. $crit = trim($crit);
  8860. $i = 0;
  8861. $i2 = 0;
  8862. $newres = '';
  8863. foreach ($fields as $field) {
  8864. if ($mode == 1) {
  8865. $operator = '=';
  8866. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  8867. $reg = array();
  8868. preg_match('/([<>=]+)/', $crit, $reg);
  8869. if (!empty($reg[1])) {
  8870. $operator = $reg[1];
  8871. }
  8872. if ($newcrit != '') {
  8873. $numnewcrit = price2num($newcrit);
  8874. if (is_numeric($numnewcrit)) {
  8875. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  8876. } else {
  8877. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  8878. }
  8879. $i2++; // a criteria was added to string
  8880. }
  8881. } elseif ($mode == 2 || $mode == -2) {
  8882. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  8883. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  8884. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  8885. if ($mode == -2) {
  8886. $newres .= ' OR '.$field.' IS NULL';
  8887. }
  8888. $i2++; // a criteria was added to string
  8889. } elseif ($mode == 3 || $mode == -3) {
  8890. $tmparray = explode(',', $crit);
  8891. if (count($tmparray)) {
  8892. $listofcodes = '';
  8893. foreach ($tmparray as $val) {
  8894. $val = trim($val);
  8895. if ($val) {
  8896. $listofcodes .= ($listofcodes ? ',' : '');
  8897. $listofcodes .= "'".$db->escape($val)."'";
  8898. }
  8899. }
  8900. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  8901. $i2++; // a criteria was added to string
  8902. }
  8903. if ($mode == -3) {
  8904. $newres .= ' OR '.$field.' IS NULL';
  8905. }
  8906. } elseif ($mode == 4) {
  8907. $tmparray = explode(',', $crit);
  8908. if (count($tmparray)) {
  8909. $listofcodes = '';
  8910. foreach ($tmparray as $val) {
  8911. $val = trim($val);
  8912. if ($val) {
  8913. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  8914. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  8915. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  8916. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  8917. $newres .= ')';
  8918. $i2++;
  8919. }
  8920. }
  8921. }
  8922. } else // $mode=0
  8923. {
  8924. $tmpcrits = explode('|', $crit);
  8925. $i3 = 0;
  8926. foreach ($tmpcrits as $tmpcrit) {
  8927. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  8928. continue;
  8929. }
  8930. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  8931. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  8932. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? ((float) trim($tmpcrit)) : '0');
  8933. } else {
  8934. $tmpcrit = trim($tmpcrit);
  8935. $tmpcrit2 = $tmpcrit;
  8936. $tmpbefore = '%';
  8937. $tmpafter = '%';
  8938. if (preg_match('/^!/', $tmpcrit)) {
  8939. $newres .= $field." NOT LIKE '"; // ! as exclude character
  8940. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  8941. } else $newres .= $field." LIKE '";
  8942. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  8943. $tmpbefore = '';
  8944. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  8945. }
  8946. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  8947. $tmpafter = '';
  8948. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  8949. }
  8950. $newres .= $tmpbefore;
  8951. $newres .= $db->escape($tmpcrit2);
  8952. $newres .= $tmpafter;
  8953. $newres .= "'";
  8954. if ($tmpcrit2 == '') {
  8955. $newres .= " OR ".$field." IS NULL";
  8956. }
  8957. }
  8958. $i3++;
  8959. }
  8960. $i2++; // a criteria was added to string
  8961. }
  8962. $i++;
  8963. }
  8964. if ($newres) {
  8965. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  8966. }
  8967. $j++;
  8968. }
  8969. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  8970. //print 'xx'.$res.'yy';
  8971. return $res;
  8972. }
  8973. /**
  8974. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  8975. *
  8976. * @param Object $object Object
  8977. * @return string Url string
  8978. */
  8979. function showDirectDownloadLink($object)
  8980. {
  8981. global $conf, $langs;
  8982. $out = '';
  8983. $url = $object->getLastMainDocLink($object->element);
  8984. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  8985. if ($url) {
  8986. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  8987. $out .= ajax_autoselect("directdownloadlink", 0);
  8988. } else {
  8989. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  8990. }
  8991. return $out;
  8992. }
  8993. /**
  8994. * Return the filename of file to get the thumbs
  8995. *
  8996. * @param string $file Original filename (full or relative path)
  8997. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  8998. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  8999. * @return string New file name (full or relative path, including the thumbs/)
  9000. */
  9001. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  9002. {
  9003. $dirName = dirname($file);
  9004. if ($dirName == '.') {
  9005. $dirName = '';
  9006. }
  9007. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  9008. $fileName = basename($fileName);
  9009. if (empty($extImgTarget)) {
  9010. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  9011. }
  9012. if (empty($extImgTarget)) {
  9013. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  9014. }
  9015. if (empty($extImgTarget)) {
  9016. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  9017. }
  9018. if (empty($extImgTarget)) {
  9019. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  9020. }
  9021. if (empty($extImgTarget)) {
  9022. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  9023. }
  9024. if (empty($extImgTarget)) {
  9025. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  9026. }
  9027. if (!$extImgTarget) {
  9028. return $file;
  9029. }
  9030. $subdir = '';
  9031. if ($extName) {
  9032. $subdir = 'thumbs/';
  9033. }
  9034. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  9035. }
  9036. /**
  9037. * Return URL we can use for advanced preview links
  9038. *
  9039. * @param string $modulepart propal, facture, facture_fourn, ...
  9040. * @param string $relativepath Relative path of docs.
  9041. * @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)
  9042. * @param string $param More param on http links
  9043. * @return string|array Output string with href link or array with all components of link
  9044. */
  9045. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  9046. {
  9047. global $conf, $langs;
  9048. if (empty($conf->use_javascript_ajax)) {
  9049. return '';
  9050. }
  9051. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  9052. if ($alldata == 1) {
  9053. if ($isAllowedForPreview) {
  9054. 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));
  9055. } else {
  9056. return array();
  9057. }
  9058. }
  9059. // old behavior, return a string
  9060. if ($isAllowedForPreview) {
  9061. 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')).'\')';
  9062. } else {
  9063. return '';
  9064. }
  9065. }
  9066. /**
  9067. * Make content of an input box selected when we click into input field.
  9068. *
  9069. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  9070. * @param string $addlink Add a 'link to' after
  9071. * @param string $textonlink Text to show on link or 'image'
  9072. * @return string
  9073. */
  9074. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  9075. {
  9076. global $langs;
  9077. $out = '<script>
  9078. jQuery(document).ready(function () {
  9079. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  9080. });
  9081. </script>';
  9082. if ($addlink) {
  9083. if ($textonlink === 'image') {
  9084. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  9085. } else {
  9086. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  9087. }
  9088. }
  9089. return $out;
  9090. }
  9091. /**
  9092. * Return if a file is qualified for preview
  9093. *
  9094. * @param string $file Filename we looking for information
  9095. * @return int 1 If allowed, 0 otherwise
  9096. * @see dol_mimetype(), image_format_supported() from images.lib.php
  9097. */
  9098. function dolIsAllowedForPreview($file)
  9099. {
  9100. global $conf;
  9101. // Check .noexe extension in filename
  9102. if (preg_match('/\.noexe$/i', $file)) {
  9103. return 0;
  9104. }
  9105. // Check mime types
  9106. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  9107. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  9108. $mime_preview[] = 'svg+xml';
  9109. }
  9110. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  9111. //$mime_preview[]='archive';
  9112. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  9113. if ($num_mime !== false) {
  9114. return 1;
  9115. }
  9116. // By default, not allowed for preview
  9117. return 0;
  9118. }
  9119. /**
  9120. * Return MIME type of a file from its name with extension.
  9121. *
  9122. * @param string $file Filename we looking for MIME type
  9123. * @param string $default Default mime type if extension not found in known list
  9124. * @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
  9125. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  9126. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  9127. */
  9128. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  9129. {
  9130. $mime = $default;
  9131. $imgmime = 'other.png';
  9132. $famime = 'file-o';
  9133. $srclang = '';
  9134. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  9135. // Plain text files
  9136. if (preg_match('/\.txt$/i', $tmpfile)) {
  9137. $mime = 'text/plain';
  9138. $imgmime = 'text.png';
  9139. $famime = 'file-text-o';
  9140. }
  9141. if (preg_match('/\.rtx$/i', $tmpfile)) {
  9142. $mime = 'text/richtext';
  9143. $imgmime = 'text.png';
  9144. $famime = 'file-text-o';
  9145. }
  9146. if (preg_match('/\.csv$/i', $tmpfile)) {
  9147. $mime = 'text/csv';
  9148. $imgmime = 'text.png';
  9149. $famime = 'file-text-o';
  9150. }
  9151. if (preg_match('/\.tsv$/i', $tmpfile)) {
  9152. $mime = 'text/tab-separated-values';
  9153. $imgmime = 'text.png';
  9154. $famime = 'file-text-o';
  9155. }
  9156. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  9157. $mime = 'text/plain';
  9158. $imgmime = 'text.png';
  9159. $famime = 'file-text-o';
  9160. }
  9161. if (preg_match('/\.ini$/i', $tmpfile)) {
  9162. $mime = 'text/plain';
  9163. $imgmime = 'text.png';
  9164. $srclang = 'ini';
  9165. $famime = 'file-text-o';
  9166. }
  9167. if (preg_match('/\.md$/i', $tmpfile)) {
  9168. $mime = 'text/plain';
  9169. $imgmime = 'text.png';
  9170. $srclang = 'md';
  9171. $famime = 'file-text-o';
  9172. }
  9173. if (preg_match('/\.css$/i', $tmpfile)) {
  9174. $mime = 'text/css';
  9175. $imgmime = 'css.png';
  9176. $srclang = 'css';
  9177. $famime = 'file-text-o';
  9178. }
  9179. if (preg_match('/\.lang$/i', $tmpfile)) {
  9180. $mime = 'text/plain';
  9181. $imgmime = 'text.png';
  9182. $srclang = 'lang';
  9183. $famime = 'file-text-o';
  9184. }
  9185. // Certificate files
  9186. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  9187. $mime = 'text/plain';
  9188. $imgmime = 'text.png';
  9189. $famime = 'file-text-o';
  9190. }
  9191. // XML based (HTML/XML/XAML)
  9192. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  9193. $mime = 'text/html';
  9194. $imgmime = 'html.png';
  9195. $srclang = 'html';
  9196. $famime = 'file-text-o';
  9197. }
  9198. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  9199. $mime = 'text/xml';
  9200. $imgmime = 'other.png';
  9201. $srclang = 'xml';
  9202. $famime = 'file-text-o';
  9203. }
  9204. if (preg_match('/\.xaml$/i', $tmpfile)) {
  9205. $mime = 'text/xml';
  9206. $imgmime = 'other.png';
  9207. $srclang = 'xaml';
  9208. $famime = 'file-text-o';
  9209. }
  9210. // Languages
  9211. if (preg_match('/\.bas$/i', $tmpfile)) {
  9212. $mime = 'text/plain';
  9213. $imgmime = 'text.png';
  9214. $srclang = 'bas';
  9215. $famime = 'file-code-o';
  9216. }
  9217. if (preg_match('/\.(c)$/i', $tmpfile)) {
  9218. $mime = 'text/plain';
  9219. $imgmime = 'text.png';
  9220. $srclang = 'c';
  9221. $famime = 'file-code-o';
  9222. }
  9223. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  9224. $mime = 'text/plain';
  9225. $imgmime = 'text.png';
  9226. $srclang = 'cpp';
  9227. $famime = 'file-code-o';
  9228. }
  9229. if (preg_match('/\.cs$/i', $tmpfile)) {
  9230. $mime = 'text/plain';
  9231. $imgmime = 'text.png';
  9232. $srclang = 'cs';
  9233. $famime = 'file-code-o';
  9234. }
  9235. if (preg_match('/\.(h)$/i', $tmpfile)) {
  9236. $mime = 'text/plain';
  9237. $imgmime = 'text.png';
  9238. $srclang = 'h';
  9239. $famime = 'file-code-o';
  9240. }
  9241. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  9242. $mime = 'text/plain';
  9243. $imgmime = 'text.png';
  9244. $srclang = 'java';
  9245. $famime = 'file-code-o';
  9246. }
  9247. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  9248. $mime = 'text/plain';
  9249. $imgmime = 'php.png';
  9250. $srclang = 'php';
  9251. $famime = 'file-code-o';
  9252. }
  9253. if (preg_match('/\.phtml$/i', $tmpfile)) {
  9254. $mime = 'text/plain';
  9255. $imgmime = 'php.png';
  9256. $srclang = 'php';
  9257. $famime = 'file-code-o';
  9258. }
  9259. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  9260. $mime = 'text/plain';
  9261. $imgmime = 'pl.png';
  9262. $srclang = 'perl';
  9263. $famime = 'file-code-o';
  9264. }
  9265. if (preg_match('/\.sql$/i', $tmpfile)) {
  9266. $mime = 'text/plain';
  9267. $imgmime = 'text.png';
  9268. $srclang = 'sql';
  9269. $famime = 'file-code-o';
  9270. }
  9271. if (preg_match('/\.js$/i', $tmpfile)) {
  9272. $mime = 'text/x-javascript';
  9273. $imgmime = 'jscript.png';
  9274. $srclang = 'js';
  9275. $famime = 'file-code-o';
  9276. }
  9277. // Open office
  9278. if (preg_match('/\.odp$/i', $tmpfile)) {
  9279. $mime = 'application/vnd.oasis.opendocument.presentation';
  9280. $imgmime = 'ooffice.png';
  9281. $famime = 'file-powerpoint-o';
  9282. }
  9283. if (preg_match('/\.ods$/i', $tmpfile)) {
  9284. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  9285. $imgmime = 'ooffice.png';
  9286. $famime = 'file-excel-o';
  9287. }
  9288. if (preg_match('/\.odt$/i', $tmpfile)) {
  9289. $mime = 'application/vnd.oasis.opendocument.text';
  9290. $imgmime = 'ooffice.png';
  9291. $famime = 'file-word-o';
  9292. }
  9293. // MS Office
  9294. if (preg_match('/\.mdb$/i', $tmpfile)) {
  9295. $mime = 'application/msaccess';
  9296. $imgmime = 'mdb.png';
  9297. $famime = 'file-o';
  9298. }
  9299. if (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
  9300. $mime = 'application/msword';
  9301. $imgmime = 'doc.png';
  9302. $famime = 'file-word-o';
  9303. }
  9304. if (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
  9305. $mime = 'application/msword';
  9306. $imgmime = 'doc.png';
  9307. $famime = 'file-word-o';
  9308. }
  9309. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  9310. $mime = 'application/vnd.ms-excel';
  9311. $imgmime = 'xls.png';
  9312. $famime = 'file-excel-o';
  9313. }
  9314. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  9315. $mime = 'application/vnd.ms-excel';
  9316. $imgmime = 'xls.png';
  9317. $famime = 'file-excel-o';
  9318. }
  9319. if (preg_match('/\.xls$/i', $tmpfile)) {
  9320. $mime = 'application/vnd.ms-excel';
  9321. $imgmime = 'xls.png';
  9322. $famime = 'file-excel-o';
  9323. }
  9324. if (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
  9325. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  9326. $imgmime = 'xls.png';
  9327. $famime = 'file-excel-o';
  9328. }
  9329. if (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
  9330. $mime = 'application/vnd.ms-powerpoint';
  9331. $imgmime = 'ppt.png';
  9332. $famime = 'file-powerpoint-o';
  9333. }
  9334. if (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
  9335. $mime = 'application/x-mspowerpoint';
  9336. $imgmime = 'ppt.png';
  9337. $famime = 'file-powerpoint-o';
  9338. }
  9339. // Other
  9340. if (preg_match('/\.pdf$/i', $tmpfile)) {
  9341. $mime = 'application/pdf';
  9342. $imgmime = 'pdf.png';
  9343. $famime = 'file-pdf-o';
  9344. }
  9345. // Scripts
  9346. if (preg_match('/\.bat$/i', $tmpfile)) {
  9347. $mime = 'text/x-bat';
  9348. $imgmime = 'script.png';
  9349. $srclang = 'dos';
  9350. $famime = 'file-code-o';
  9351. }
  9352. if (preg_match('/\.sh$/i', $tmpfile)) {
  9353. $mime = 'text/x-sh';
  9354. $imgmime = 'script.png';
  9355. $srclang = 'bash';
  9356. $famime = 'file-code-o';
  9357. }
  9358. if (preg_match('/\.ksh$/i', $tmpfile)) {
  9359. $mime = 'text/x-ksh';
  9360. $imgmime = 'script.png';
  9361. $srclang = 'bash';
  9362. $famime = 'file-code-o';
  9363. }
  9364. if (preg_match('/\.bash$/i', $tmpfile)) {
  9365. $mime = 'text/x-bash';
  9366. $imgmime = 'script.png';
  9367. $srclang = 'bash';
  9368. $famime = 'file-code-o';
  9369. }
  9370. // Images
  9371. if (preg_match('/\.ico$/i', $tmpfile)) {
  9372. $mime = 'image/x-icon';
  9373. $imgmime = 'image.png';
  9374. $famime = 'file-image-o';
  9375. }
  9376. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  9377. $mime = 'image/jpeg';
  9378. $imgmime = 'image.png';
  9379. $famime = 'file-image-o';
  9380. }
  9381. if (preg_match('/\.png$/i', $tmpfile)) {
  9382. $mime = 'image/png';
  9383. $imgmime = 'image.png';
  9384. $famime = 'file-image-o';
  9385. }
  9386. if (preg_match('/\.gif$/i', $tmpfile)) {
  9387. $mime = 'image/gif';
  9388. $imgmime = 'image.png';
  9389. $famime = 'file-image-o';
  9390. }
  9391. if (preg_match('/\.bmp$/i', $tmpfile)) {
  9392. $mime = 'image/bmp';
  9393. $imgmime = 'image.png';
  9394. $famime = 'file-image-o';
  9395. }
  9396. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  9397. $mime = 'image/tiff';
  9398. $imgmime = 'image.png';
  9399. $famime = 'file-image-o';
  9400. }
  9401. if (preg_match('/\.svg$/i', $tmpfile)) {
  9402. $mime = 'image/svg+xml';
  9403. $imgmime = 'image.png';
  9404. $famime = 'file-image-o';
  9405. }
  9406. if (preg_match('/\.webp$/i', $tmpfile)) {
  9407. $mime = 'image/webp';
  9408. $imgmime = 'image.png';
  9409. $famime = 'file-image-o';
  9410. }
  9411. // Calendar
  9412. if (preg_match('/\.vcs$/i', $tmpfile)) {
  9413. $mime = 'text/calendar';
  9414. $imgmime = 'other.png';
  9415. $famime = 'file-text-o';
  9416. }
  9417. if (preg_match('/\.ics$/i', $tmpfile)) {
  9418. $mime = 'text/calendar';
  9419. $imgmime = 'other.png';
  9420. $famime = 'file-text-o';
  9421. }
  9422. // Other
  9423. if (preg_match('/\.torrent$/i', $tmpfile)) {
  9424. $mime = 'application/x-bittorrent';
  9425. $imgmime = 'other.png';
  9426. $famime = 'file-o';
  9427. }
  9428. // Audio
  9429. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  9430. $mime = 'audio';
  9431. $imgmime = 'audio.png';
  9432. $famime = 'file-audio-o';
  9433. }
  9434. // Video
  9435. if (preg_match('/\.mp4$/i', $tmpfile)) {
  9436. $mime = 'video/mp4';
  9437. $imgmime = 'video.png';
  9438. $famime = 'file-video-o';
  9439. }
  9440. if (preg_match('/\.ogv$/i', $tmpfile)) {
  9441. $mime = 'video/ogg';
  9442. $imgmime = 'video.png';
  9443. $famime = 'file-video-o';
  9444. }
  9445. if (preg_match('/\.webm$/i', $tmpfile)) {
  9446. $mime = 'video/webm';
  9447. $imgmime = 'video.png';
  9448. $famime = 'file-video-o';
  9449. }
  9450. if (preg_match('/\.avi$/i', $tmpfile)) {
  9451. $mime = 'video/x-msvideo';
  9452. $imgmime = 'video.png';
  9453. $famime = 'file-video-o';
  9454. }
  9455. if (preg_match('/\.divx$/i', $tmpfile)) {
  9456. $mime = 'video/divx';
  9457. $imgmime = 'video.png';
  9458. $famime = 'file-video-o';
  9459. }
  9460. if (preg_match('/\.xvid$/i', $tmpfile)) {
  9461. $mime = 'video/xvid';
  9462. $imgmime = 'video.png';
  9463. $famime = 'file-video-o';
  9464. }
  9465. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  9466. $mime = 'video';
  9467. $imgmime = 'video.png';
  9468. $famime = 'file-video-o';
  9469. }
  9470. // Archive
  9471. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  9472. $mime = 'archive';
  9473. $imgmime = 'archive.png';
  9474. $famime = 'file-archive-o';
  9475. } // application/xxx where zzz is zip, ...
  9476. // Exe
  9477. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  9478. $mime = 'application/octet-stream';
  9479. $imgmime = 'other.png';
  9480. $famime = 'file-o';
  9481. }
  9482. // Lib
  9483. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  9484. $mime = 'library';
  9485. $imgmime = 'library.png';
  9486. $famime = 'file-o';
  9487. }
  9488. // Err
  9489. if (preg_match('/\.err$/i', $tmpfile)) {
  9490. $mime = 'error';
  9491. $imgmime = 'error.png';
  9492. $famime = 'file-text-o';
  9493. }
  9494. // Return string
  9495. if ($mode == 1) {
  9496. $tmp = explode('/', $mime);
  9497. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  9498. }
  9499. if ($mode == 2) {
  9500. return $imgmime;
  9501. }
  9502. if ($mode == 3) {
  9503. return $srclang;
  9504. }
  9505. if ($mode == 4) {
  9506. return $famime;
  9507. }
  9508. return $mime;
  9509. }
  9510. /**
  9511. * Return the value of a filed into a dictionary for the record $id.
  9512. * This also set all the values into a cache for a next search.
  9513. *
  9514. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  9515. * @param string $field The name of field where to find the value to return
  9516. * @param int $id Id of line record
  9517. * @param bool $checkentity Add filter on entity
  9518. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  9519. * @return string The value of field $field. This also set $dictvalues cache.
  9520. */
  9521. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  9522. {
  9523. global $conf, $db;
  9524. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  9525. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  9526. if (is_null($dictvalues)) {
  9527. $dictvalues = array();
  9528. $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
  9529. if ($checkentity) {
  9530. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  9531. }
  9532. $resql = $db->query($sql);
  9533. if ($resql) {
  9534. while ($obj = $db->fetch_object($resql)) {
  9535. $dictvalues[$obj->{$rowidfield}] = $obj; // $obj is stdClass
  9536. }
  9537. } else {
  9538. dol_print_error($db);
  9539. }
  9540. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  9541. }
  9542. if (!empty($dictvalues[$id])) {
  9543. // Found
  9544. $tmp = $dictvalues[$id];
  9545. return (property_exists($tmp, $field) ? $tmp->$field : '');
  9546. } else {
  9547. // Not found
  9548. return '';
  9549. }
  9550. }
  9551. /**
  9552. * Return true if the color is light
  9553. *
  9554. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  9555. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  9556. */
  9557. function colorIsLight($stringcolor)
  9558. {
  9559. $stringcolor = str_replace('#', '', $stringcolor);
  9560. $res = -1;
  9561. if (!empty($stringcolor)) {
  9562. $res = 0;
  9563. $tmp = explode(',', $stringcolor);
  9564. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  9565. $r = $tmp[0];
  9566. $g = $tmp[1];
  9567. $b = $tmp[2];
  9568. } else {
  9569. $hexr = $stringcolor[0].$stringcolor[1];
  9570. $hexg = $stringcolor[2].$stringcolor[3];
  9571. $hexb = $stringcolor[4].$stringcolor[5];
  9572. $r = hexdec($hexr);
  9573. $g = hexdec($hexg);
  9574. $b = hexdec($hexb);
  9575. }
  9576. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  9577. if ($bright > 0.6) {
  9578. $res = 1;
  9579. }
  9580. }
  9581. return $res;
  9582. }
  9583. /**
  9584. * Function to test if an entry is enabled or not
  9585. *
  9586. * @param string $type_user 0=We test for internal user, 1=We test for external user
  9587. * @param array $menuentry Array for feature entry to test
  9588. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  9589. * @return int 0=Hide, 1=Show, 2=Show gray
  9590. */
  9591. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  9592. {
  9593. global $conf;
  9594. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  9595. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  9596. if (empty($menuentry['enabled'])) {
  9597. return 0; // Entry disabled by condition
  9598. }
  9599. if ($type_user && $menuentry['module']) {
  9600. $tmploops = explode('|', $menuentry['module']);
  9601. $found = 0;
  9602. foreach ($tmploops as $tmploop) {
  9603. if (in_array($tmploop, $listofmodulesforexternal)) {
  9604. $found++;
  9605. break;
  9606. }
  9607. }
  9608. if (!$found) {
  9609. return 0; // Entry is for menus all excluded to external users
  9610. }
  9611. }
  9612. if (!$menuentry['perms'] && $type_user) {
  9613. return 0; // No permissions and user is external
  9614. }
  9615. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  9616. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  9617. }
  9618. if (!$menuentry['perms']) {
  9619. return 2; // No permissions and user is external
  9620. }
  9621. return 1;
  9622. }
  9623. /**
  9624. * Round to next multiple.
  9625. *
  9626. * @param double $n Number to round up
  9627. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  9628. * @return integer Value rounded.
  9629. */
  9630. function roundUpToNextMultiple($n, $x = 5)
  9631. {
  9632. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  9633. }
  9634. /**
  9635. * Function dolGetBadge
  9636. *
  9637. * @param string $label label of badge no html : use in alt attribute for accessibility
  9638. * @param string $html optional : label of badge with html
  9639. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  9640. * @param string $mode default '' , 'pill', 'dot'
  9641. * @param string $url the url for link
  9642. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  9643. * @return string Html badge
  9644. */
  9645. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  9646. {
  9647. $attr = array(
  9648. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  9649. );
  9650. if (empty($html)) {
  9651. $html = $label;
  9652. }
  9653. if (!empty($url)) {
  9654. $attr['href'] = $url;
  9655. }
  9656. if ($mode === 'dot') {
  9657. $attr['class'] .= ' classfortooltip';
  9658. $attr['title'] = $html;
  9659. $attr['aria-label'] = $label;
  9660. $html = '';
  9661. }
  9662. // Override attr
  9663. if (!empty($params['attr']) && is_array($params['attr'])) {
  9664. foreach ($params['attr'] as $key => $value) {
  9665. if ($key == 'class') {
  9666. $attr['class'] .= ' '.$value;
  9667. } elseif ($key == 'classOverride') {
  9668. $attr['class'] = $value;
  9669. } else {
  9670. $attr[$key] = $value;
  9671. }
  9672. }
  9673. }
  9674. // TODO: add hook
  9675. // escape all attribute
  9676. $attr = array_map('dol_escape_htmltag', $attr);
  9677. $TCompiledAttr = array();
  9678. foreach ($attr as $key => $value) {
  9679. $TCompiledAttr[] = $key.'="'.$value.'"';
  9680. }
  9681. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9682. $tag = !empty($url) ? 'a' : 'span';
  9683. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  9684. }
  9685. /**
  9686. * Output the badge of a status.
  9687. *
  9688. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  9689. * @param string $statusLabelShort Short label of badge no html
  9690. * @param string $html Optional : label of badge with html
  9691. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  9692. * @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
  9693. * @param string $url The url for link
  9694. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  9695. * @return string Html status string
  9696. */
  9697. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  9698. {
  9699. global $conf;
  9700. $return = '';
  9701. $dolGetBadgeParams = array();
  9702. if (!empty($params['badgeParams'])) {
  9703. $dolGetBadgeParams = $params['badgeParams'];
  9704. }
  9705. // TODO : add a hook
  9706. if ($displayMode == 0) {
  9707. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  9708. } elseif ($displayMode == 1) {
  9709. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9710. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  9711. // Use status with images (for backward compatibility)
  9712. $return = '';
  9713. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  9714. $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>' : '');
  9715. // For small screen, we always use the short label instead of long label.
  9716. if (!empty($conf->dol_optimize_smallscreen)) {
  9717. if ($displayMode == 0) {
  9718. $displayMode = 1;
  9719. } elseif ($displayMode == 4) {
  9720. $displayMode = 2;
  9721. } elseif ($displayMode == 6) {
  9722. $displayMode = 5;
  9723. }
  9724. }
  9725. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  9726. $statusImg = array(
  9727. 'status0' => 'statut0',
  9728. 'status1' => 'statut1',
  9729. 'status2' => 'statut2',
  9730. 'status3' => 'statut3',
  9731. 'status4' => 'statut4',
  9732. 'status5' => 'statut5',
  9733. 'status6' => 'statut6',
  9734. 'status7' => 'statut7',
  9735. 'status8' => 'statut8',
  9736. 'status9' => 'statut9'
  9737. );
  9738. if (!empty($statusImg[$statusType])) {
  9739. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  9740. } else {
  9741. $htmlImg = img_picto($statusLabel, $statusType);
  9742. }
  9743. if ($displayMode === 2) {
  9744. $return = $htmlImg.' '.$htmlLabelShort;
  9745. } elseif ($displayMode === 3) {
  9746. $return = $htmlImg;
  9747. } elseif ($displayMode === 4) {
  9748. $return = $htmlImg.' '.$htmlLabel;
  9749. } elseif ($displayMode === 5) {
  9750. $return = $htmlLabelShort.' '.$htmlImg;
  9751. } else { // $displayMode >= 6
  9752. $return = $htmlLabel.' '.$htmlImg;
  9753. }
  9754. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9755. // Use new badge
  9756. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9757. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9758. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9759. if ($displayMode == 3) {
  9760. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9761. } elseif ($displayMode === 5) {
  9762. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9763. } else {
  9764. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9765. }
  9766. }
  9767. return $return;
  9768. }
  9769. /**
  9770. * Function dolGetButtonAction
  9771. *
  9772. * @param string $label Label or tooltip of button. Also used as tooltip in title attribute. Can be escaped HTML content or full simple text.
  9773. * @param string $text Optional : short label on button. Can be escaped HTML content or full simple text.
  9774. * @param string $actionType 'default', 'delete', 'danger'
  9775. * @param string $url Url for link
  9776. * @param string $id Attribute id of button
  9777. * @param int|boolean $userRight User action right
  9778. * // phpcs:disable
  9779. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  9780. * 'attr' => [ // to add or override button attributes
  9781. * 'xxxxx' => '', // your xxxxx attribute you want
  9782. * 'class' => 'reposition', // to add more css class to the button class attribute
  9783. * 'classOverride' => '' // to replace class attribute of the button
  9784. * ],
  9785. * 'confirm' => [
  9786. * '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.
  9787. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  9788. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  9789. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  9790. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  9791. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  9792. * 'isDropDrown' => false, // true|false to display dialog as a dropdown (with dark background)
  9793. * ],
  9794. * ]
  9795. * // phpcs:enable
  9796. * @return string html button
  9797. */
  9798. function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  9799. {
  9800. global $hookmanager, $action, $object, $langs;
  9801. //var_dump($params);
  9802. if (!empty($params['isDropdown']))
  9803. $class = "dropdown-item";
  9804. else {
  9805. $class = 'butAction';
  9806. if ($actionType == 'danger' || $actionType == 'delete') {
  9807. $class = 'butActionDelete';
  9808. if (!empty($url) && strpos($url, 'token=') === false) $url .= '&token='.newToken();
  9809. }
  9810. }
  9811. $attr = array(
  9812. 'class' => $class,
  9813. 'href' => empty($url) ? '' : $url,
  9814. 'title' => $label
  9815. );
  9816. if (empty($text)) {
  9817. $text = $label;
  9818. $attr['title'] = ''; // if html not set, leave label on title is redundant
  9819. } else {
  9820. $attr['title'] = $label;
  9821. $attr['aria-label'] = $label;
  9822. }
  9823. if (empty($userRight)) {
  9824. $attr['class'] = 'butActionRefused';
  9825. $attr['href'] = '';
  9826. $attr['title'] = (($label && $text && $label != $text) ? $label : $langs->trans('NotEnoughPermissions'));
  9827. }
  9828. if (!empty($id)) {
  9829. $attr['id'] = $id;
  9830. }
  9831. // Override attr
  9832. if (!empty($params['attr']) && is_array($params['attr'])) {
  9833. foreach ($params['attr'] as $key => $value) {
  9834. if ($key == 'class') {
  9835. $attr['class'] .= ' '.$value;
  9836. } elseif ($key == 'classOverride') {
  9837. $attr['class'] = $value;
  9838. } else {
  9839. $attr[$key] = $value;
  9840. }
  9841. }
  9842. }
  9843. // automatic add tooltip when title is detected
  9844. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  9845. $attr['class'].= ' classfortooltip';
  9846. }
  9847. // Js Confirm button
  9848. if ($userRight && !empty($params['confirm'])) {
  9849. if (!is_array($params['confirm'])) {
  9850. $params['confirm'] = array();
  9851. }
  9852. if (empty($params['confirm']['url'])) {
  9853. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  9854. }
  9855. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  9856. $attr['data-confirm-url'] = $params['confirm']['url'];
  9857. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  9858. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  9859. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  9860. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  9861. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  9862. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  9863. $attr['class'].= ' butActionConfirm';
  9864. }
  9865. if (isset($attr['href']) && empty($attr['href'])) {
  9866. unset($attr['href']);
  9867. }
  9868. // escape all attribute
  9869. $attr = array_map('dol_escape_htmltag', $attr);
  9870. $TCompiledAttr = array();
  9871. foreach ($attr as $key => $value) {
  9872. $TCompiledAttr[] = $key.'= "'.$value.'"';
  9873. }
  9874. $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
  9875. $tag = !empty($attr['href']) ? 'a' : 'span';
  9876. $parameters = array(
  9877. 'TCompiledAttr' => $TCompiledAttr, // array
  9878. 'compiledAttributes' => $compiledAttributes, // string
  9879. 'attr' => $attr,
  9880. 'tag' => $tag,
  9881. 'label' => $label,
  9882. 'html' => $text,
  9883. 'actionType' => $actionType,
  9884. 'url' => $url,
  9885. 'id' => $id,
  9886. 'userRight' => $userRight,
  9887. 'params' => $params
  9888. );
  9889. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  9890. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  9891. if (empty($reshook)) {
  9892. if (dol_textishtml($text)) { // If content already HTML encoded
  9893. return '<' . $tag . ' ' . $compiledAttributes . '>' . $text . '</' . $tag . '>';
  9894. } else {
  9895. return '<' . $tag . ' ' . $compiledAttributes . '>' . dol_escape_htmltag($text) . '</' . $tag . '>';
  9896. }
  9897. } else {
  9898. return $hookmanager->resPrint;
  9899. }
  9900. }
  9901. /**
  9902. * Add space between dolGetButtonTitle
  9903. *
  9904. * @param string $moreClass more css class label
  9905. * @return string html of title separator
  9906. */
  9907. function dolGetButtonTitleSeparator($moreClass = "")
  9908. {
  9909. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  9910. }
  9911. /**
  9912. * get field error icon
  9913. *
  9914. * @param string $fieldValidationErrorMsg message to add in tooltip
  9915. * @return string html output
  9916. */
  9917. function getFieldErrorIcon($fieldValidationErrorMsg)
  9918. {
  9919. $out = '';
  9920. if (!empty($fieldValidationErrorMsg)) {
  9921. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  9922. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  9923. $out.= '</span>';
  9924. }
  9925. return $out;
  9926. }
  9927. /**
  9928. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  9929. *
  9930. * @param string $label label of button
  9931. * @param string $helpText optional : content for help tooltip
  9932. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  9933. * @param string $url the url for link
  9934. * @param string $id attribute id of button
  9935. * @param int $status 0 no user rights, 1 active, 2 current action or selected, -1 Feature Disabled, -2 disable Other reason use param $helpText as tooltip help
  9936. * @param array $params various params for future : recommended rather than adding more function arguments
  9937. * @return string html button
  9938. */
  9939. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  9940. {
  9941. global $langs, $conf, $user;
  9942. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  9943. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  9944. return '';
  9945. }
  9946. $class = 'btnTitle';
  9947. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
  9948. $class .= ' btnTitlePlus';
  9949. }
  9950. $useclassfortooltip = 1;
  9951. if (!empty($params['morecss'])) {
  9952. $class .= ' '.$params['morecss'];
  9953. }
  9954. $attr = array(
  9955. 'class' => $class,
  9956. 'href' => empty($url) ? '' : $url
  9957. );
  9958. if (!empty($helpText)) {
  9959. $attr['title'] = dol_escape_htmltag($helpText);
  9960. } elseif (empty($attr['title']) && $label) {
  9961. $attr['title'] = $label;
  9962. $useclassfortooltip = 0;
  9963. }
  9964. if ($status == 2) {
  9965. $attr['class'] .= ' btnTitleSelected';
  9966. } elseif ($status <= 0) {
  9967. $attr['class'] .= ' refused';
  9968. $attr['href'] = '';
  9969. if ($status == -1) { // disable
  9970. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  9971. } elseif ($status == 0) { // Not enough permissions
  9972. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  9973. }
  9974. }
  9975. if (!empty($attr['title']) && $useclassfortooltip) {
  9976. $attr['class'] .= ' classfortooltip';
  9977. }
  9978. if (!empty($id)) {
  9979. $attr['id'] = $id;
  9980. }
  9981. // Override attr
  9982. if (!empty($params['attr']) && is_array($params['attr'])) {
  9983. foreach ($params['attr'] as $key => $value) {
  9984. if ($key == 'class') {
  9985. $attr['class'] .= ' '.$value;
  9986. } elseif ($key == 'classOverride') {
  9987. $attr['class'] = $value;
  9988. } else {
  9989. $attr[$key] = $value;
  9990. }
  9991. }
  9992. }
  9993. if (isset($attr['href']) && empty($attr['href'])) {
  9994. unset($attr['href']);
  9995. }
  9996. // TODO : add a hook
  9997. // escape all attribute
  9998. $attr = array_map('dol_escape_htmltag', $attr);
  9999. $TCompiledAttr = array();
  10000. foreach ($attr as $key => $value) {
  10001. $TCompiledAttr[] = $key.'="'.$value.'"';
  10002. }
  10003. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  10004. $tag = (empty($attr['href']) ? 'span' : 'a');
  10005. $button = '<'.$tag.' '.$compiledAttributes.'>';
  10006. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  10007. if (!empty($params['forcenohideoftext'])) {
  10008. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  10009. }
  10010. $button .= '</'.$tag.'>';
  10011. return $button;
  10012. }
  10013. /**
  10014. * Get an array with properties of an element.
  10015. * Called by fetchObjectByElement.
  10016. *
  10017. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  10018. * @return array (module, classpath, element, subelement, classfile, classname)
  10019. */
  10020. function getElementProperties($element_type)
  10021. {
  10022. $regs = array();
  10023. $classfile = $classname = $classpath = '';
  10024. // Parse element/subelement (ex: project_task)
  10025. $module = $element_type;
  10026. $element = $element_type;
  10027. $subelement = $element_type;
  10028. // If we ask an resource form external module (instead of default path)
  10029. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  10030. $element = $subelement = $regs[1];
  10031. $module = $regs[2];
  10032. }
  10033. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  10034. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  10035. $module = $element = $regs[1];
  10036. $subelement = $regs[2];
  10037. }
  10038. // For compat
  10039. if ($element_type == "action") {
  10040. $classpath = 'comm/action/class';
  10041. $subelement = 'Actioncomm';
  10042. $module = 'agenda';
  10043. }
  10044. // To work with non standard path
  10045. if ($element_type == 'facture' || $element_type == 'invoice') {
  10046. $classpath = 'compta/facture/class';
  10047. $module = 'facture';
  10048. $subelement = 'facture';
  10049. }
  10050. if ($element_type == 'commande' || $element_type == 'order') {
  10051. $classpath = 'commande/class';
  10052. $module = 'commande';
  10053. $subelement = 'commande';
  10054. }
  10055. if ($element_type == 'propal') {
  10056. $classpath = 'comm/propal/class';
  10057. }
  10058. if ($element_type == 'supplier_proposal') {
  10059. $classpath = 'supplier_proposal/class';
  10060. }
  10061. if ($element_type == 'shipping') {
  10062. $classpath = 'expedition/class';
  10063. $subelement = 'expedition';
  10064. $module = 'expedition_bon';
  10065. }
  10066. if ($element_type == 'delivery') {
  10067. $classpath = 'delivery/class';
  10068. $subelement = 'delivery';
  10069. $module = 'delivery_note';
  10070. }
  10071. if ($element_type == 'contract') {
  10072. $classpath = 'contrat/class';
  10073. $module = 'contrat';
  10074. $subelement = 'contrat';
  10075. }
  10076. if ($element_type == 'member') {
  10077. $classpath = 'adherents/class';
  10078. $module = 'adherent';
  10079. $subelement = 'adherent';
  10080. }
  10081. if ($element_type == 'cabinetmed_cons') {
  10082. $classpath = 'cabinetmed/class';
  10083. $module = 'cabinetmed';
  10084. $subelement = 'cabinetmedcons';
  10085. }
  10086. if ($element_type == 'fichinter') {
  10087. $classpath = 'fichinter/class';
  10088. $module = 'ficheinter';
  10089. $subelement = 'fichinter';
  10090. }
  10091. if ($element_type == 'dolresource' || $element_type == 'resource') {
  10092. $classpath = 'resource/class';
  10093. $module = 'resource';
  10094. $subelement = 'dolresource';
  10095. }
  10096. if ($element_type == 'propaldet') {
  10097. $classpath = 'comm/propal/class';
  10098. $module = 'propal';
  10099. $subelement = 'propaleligne';
  10100. }
  10101. if ($element_type == 'order_supplier') {
  10102. $classpath = 'fourn/class';
  10103. $module = 'fournisseur';
  10104. $subelement = 'commandefournisseur';
  10105. $classfile = 'fournisseur.commande';
  10106. }
  10107. if ($element_type == 'invoice_supplier') {
  10108. $classpath = 'fourn/class';
  10109. $module = 'fournisseur';
  10110. $subelement = 'facturefournisseur';
  10111. $classfile = 'fournisseur.facture';
  10112. }
  10113. if ($element_type == "service") {
  10114. $classpath = 'product/class';
  10115. $subelement = 'product';
  10116. }
  10117. if (empty($classfile)) {
  10118. $classfile = strtolower($subelement);
  10119. }
  10120. if (empty($classname)) {
  10121. $classname = ucfirst($subelement);
  10122. }
  10123. if (empty($classpath)) {
  10124. $classpath = $module.'/class';
  10125. }
  10126. $element_properties = array(
  10127. 'module' => $module,
  10128. 'classpath' => $classpath,
  10129. 'element' => $element,
  10130. 'subelement' => $subelement,
  10131. 'classfile' => $classfile,
  10132. 'classname' => $classname
  10133. );
  10134. return $element_properties;
  10135. }
  10136. /**
  10137. * Fetch an object from its id and element_type
  10138. * Inclusion of classes is automatic
  10139. *
  10140. * @param int $element_id Element id
  10141. * @param string $element_type Element type
  10142. * @param string $element_ref Element ref (Use this or element_id but not both)
  10143. * @return int|object object || 0 || -1 if error
  10144. */
  10145. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  10146. {
  10147. global $conf, $db;
  10148. $element_prop = getElementProperties($element_type);
  10149. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled) {
  10150. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  10151. $objecttmp = new $element_prop['classname']($db);
  10152. $ret = $objecttmp->fetch($element_id, $element_ref);
  10153. if ($ret >= 0) {
  10154. return $objecttmp;
  10155. }
  10156. }
  10157. return 0;
  10158. }
  10159. /**
  10160. * Return if a file can contains executable content
  10161. *
  10162. * @param string $filename File name to test
  10163. * @return boolean True if yes, False if no
  10164. */
  10165. function isAFileWithExecutableContent($filename)
  10166. {
  10167. 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)) {
  10168. return true;
  10169. }
  10170. return false;
  10171. }
  10172. /**
  10173. * Return the value of token currently saved into session with name 'newtoken'.
  10174. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  10175. *
  10176. * @return string
  10177. */
  10178. function newToken()
  10179. {
  10180. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  10181. }
  10182. /**
  10183. * Return the value of token currently saved into session with name 'token'.
  10184. * 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).
  10185. *
  10186. * @return string
  10187. */
  10188. function currentToken()
  10189. {
  10190. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  10191. }
  10192. /**
  10193. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  10194. *
  10195. * @param string $header The first left header of the table (automatic translated)
  10196. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  10197. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  10198. * @param integer $emptyRows (optional) The count of empty rows after the first header
  10199. * @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"
  10200. * @return void
  10201. *
  10202. * @see finishSimpleTable()
  10203. */
  10204. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  10205. {
  10206. global $langs;
  10207. print '<div class="div-table-responsive-no-min">';
  10208. print '<table class="noborder centpercent">';
  10209. print '<tr class="liste_titre">';
  10210. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  10211. print $langs->trans($header);
  10212. // extra space between the first header and the number
  10213. if ($number > -1) {
  10214. print ' ';
  10215. }
  10216. if (!empty($link)) {
  10217. if (!empty($arguments)) {
  10218. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10219. } else {
  10220. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  10221. }
  10222. }
  10223. if ($number > -1) {
  10224. print '<span class="badge">'.$number.'</span>';
  10225. }
  10226. if (!empty($link)) {
  10227. print '</a>';
  10228. }
  10229. print '</th>';
  10230. if ($number < 0 && !empty($link)) {
  10231. print '<th class="right">';
  10232. if (!empty($arguments)) {
  10233. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10234. } else {
  10235. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  10236. }
  10237. print $langs->trans("FullList");
  10238. print '</a>';
  10239. print '</th>';
  10240. }
  10241. print '</tr>';
  10242. }
  10243. /**
  10244. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  10245. *
  10246. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  10247. * @return void
  10248. *
  10249. * @see startSimpleTable()
  10250. */
  10251. function finishSimpleTable($addLineBreak = false)
  10252. {
  10253. print '</table>';
  10254. print '</div>';
  10255. if ($addLineBreak) {
  10256. print '<br>';
  10257. }
  10258. }
  10259. /**
  10260. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  10261. *
  10262. * @param integer $tableColumnCount The complete count columns of the table
  10263. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  10264. * @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)
  10265. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  10266. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  10267. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  10268. * @return void
  10269. */
  10270. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  10271. {
  10272. global $langs;
  10273. if ($num === 0) {
  10274. print '<tr class="oddeven">';
  10275. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  10276. print '</tr>';
  10277. return;
  10278. }
  10279. if ($nbofloop === 0) {
  10280. // don't show a summary line
  10281. return;
  10282. }
  10283. if ($num === 0) {
  10284. $colspan = $tableColumnCount;
  10285. } elseif ($num > $nbofloop) {
  10286. $colspan = $tableColumnCount;
  10287. } else {
  10288. $colspan = $tableColumnCount - 1;
  10289. }
  10290. if ($extraRightColumn) {
  10291. $colspan--;
  10292. }
  10293. print '<tr class="liste_total">';
  10294. if ($nbofloop > 0 && $num > $nbofloop) {
  10295. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  10296. } else {
  10297. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  10298. print '<td class="right" width="100">'.price($total).'</td>';
  10299. }
  10300. if ($extraRightColumn) {
  10301. print '<td></td>';
  10302. }
  10303. print '</tr>';
  10304. }
  10305. /**
  10306. * Return a file on output using a low memory. It can return very large files with no need of memory.
  10307. * WARNING: This close output buffers.
  10308. *
  10309. * @param string $fullpath_original_file_osencoded Full path of file to return.
  10310. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  10311. * @return void
  10312. */
  10313. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  10314. {
  10315. global $conf;
  10316. if ($method == -1) {
  10317. $method = 0;
  10318. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  10319. $method = 1;
  10320. }
  10321. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  10322. $method = 2;
  10323. }
  10324. }
  10325. // Be sure we don't have output buffering enabled to have readfile working correctly
  10326. while (ob_get_level()) {
  10327. ob_end_flush();
  10328. }
  10329. // Solution 0
  10330. if ($method == 0) {
  10331. readfile($fullpath_original_file_osencoded);
  10332. } elseif ($method == 1) {
  10333. // Solution 1
  10334. $handle = fopen($fullpath_original_file_osencoded, "rb");
  10335. while (!feof($handle)) {
  10336. print fread($handle, 8192);
  10337. }
  10338. fclose($handle);
  10339. } elseif ($method == 2) {
  10340. // Solution 2
  10341. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  10342. $handle2 = fopen("php://output", "wb");
  10343. stream_copy_to_stream($handle1, $handle2);
  10344. fclose($handle1);
  10345. fclose($handle2);
  10346. }
  10347. }
  10348. /**
  10349. * Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
  10350. * Code that handle the click is inside core/js/lib_foot.js.php.
  10351. *
  10352. * @param string $valuetocopy The value to print
  10353. * @param int $showonlyonhover Show the copy-paste button only on hover
  10354. * @param string $texttoshow Replace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
  10355. * @return string The string to print for the button
  10356. */
  10357. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  10358. {
  10359. /*
  10360. global $conf;
  10361. if (!empty($conf->dol_no_mouse_hover)) {
  10362. $showonlyonhover = 0;
  10363. }*/
  10364. $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
  10365. if ($texttoshow === 'none') {
  10366. $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>';
  10367. } elseif ($texttoshow) {
  10368. $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>';
  10369. } else {
  10370. $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>';
  10371. }
  10372. return $result;
  10373. }
  10374. /**
  10375. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  10376. *
  10377. * @param string $stringtodecode String to decode (json or serialize coded)
  10378. * @return mixed The decoded object.
  10379. */
  10380. function jsonOrUnserialize($stringtodecode)
  10381. {
  10382. $result = json_decode($stringtodecode);
  10383. if ($result === null) {
  10384. $result = unserialize($stringtodecode);
  10385. }
  10386. return $result;
  10387. }
  10388. /**
  10389. * Return if a $sqlfilters parameter is valid and will pass the preg_replace_callback() to replace Generic filter string with SQL filter string
  10390. * Example of usage:
  10391. * if ($sqlfilters) {
  10392. * $errormessage = '';
  10393. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  10394. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  10395. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  10396. * }
  10397. * }
  10398. *
  10399. * @param string $sqlfilters sqlfilter string
  10400. * @param string $error Error message
  10401. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  10402. */
  10403. function dolCheckFilters($sqlfilters, &$error = '')
  10404. {
  10405. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  10406. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  10407. $tmp = $sqlfilters;
  10408. $i = 0; $nb = strlen($tmp);
  10409. $counter = 0;
  10410. while ($i < $nb) {
  10411. if ($tmp[$i] == '(') {
  10412. $counter++;
  10413. }
  10414. if ($tmp[$i] == ')') {
  10415. $counter--;
  10416. }
  10417. if ($counter < 0) {
  10418. $error = "Bad sqlfilters=".$sqlfilters;
  10419. dol_syslog($error, LOG_WARNING);
  10420. return false;
  10421. }
  10422. $i++;
  10423. }
  10424. return true;
  10425. }
  10426. /**
  10427. * Function to forge a SQL criteria from a Generic filter string.
  10428. * Example of usage:
  10429. * if ($sqlfilters) {
  10430. * $errormessage = '';
  10431. * if (dolCheckFilters($sqlfilters, $errormessage)) {
  10432. * $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^\(\)]+)\)';
  10433. * $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'dolForgeCriteriaCallback', $sqlfilters).")";
  10434. * }
  10435. * }
  10436. *
  10437. * @param array $matches Array of found string by regex search.
  10438. * 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"
  10439. * @return string Forged criteria. Example: "t.field like 'abc%'"
  10440. */
  10441. function dolForgeCriteriaCallback($matches)
  10442. {
  10443. global $db;
  10444. dol_syslog("Convert matches ".$matches[1]);
  10445. if (empty($matches[1])) {
  10446. return '';
  10447. }
  10448. $tmp = explode(':', $matches[1], 3);
  10449. if (count($tmp) < 3) {
  10450. return '';
  10451. }
  10452. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  10453. $operator = strtoupper(preg_replace('/[^a-z<>=]/i', '', trim($tmp[1])));
  10454. if ($operator == 'NOTLIKE') {
  10455. $operator = 'NOT LIKE';
  10456. }
  10457. $tmpescaped = trim($tmp[2]);
  10458. $regbis = array();
  10459. if ($operator == 'IN') {
  10460. $tmpescaped = "(".$db->sanitize($tmpescaped, 1).")";
  10461. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  10462. $tmpescaped = "'".$db->escape($regbis[1])."'";
  10463. } else {
  10464. $tmpescaped = $db->sanitize($db->escape($tmpescaped));
  10465. }
  10466. return $db->escape($operand).' '.$db->escape($operator)." ".$tmpescaped;
  10467. }
  10468. /**
  10469. * Get timeline icon
  10470. * @param ActionComm $actionstatic actioncomm
  10471. * @param array $histo histo
  10472. * @param int $key key
  10473. * @return string
  10474. */
  10475. function getTimelineIcon($actionstatic, &$histo, $key)
  10476. {
  10477. global $conf, $langs;
  10478. $out = '<!-- timeline icon -->'."\n";
  10479. $iconClass = 'fa fa-comments';
  10480. $img_picto = '';
  10481. $colorClass = '';
  10482. $pictoTitle = '';
  10483. if ($histo[$key]['percent'] == -1) {
  10484. $colorClass = 'timeline-icon-not-applicble';
  10485. $pictoTitle = $langs->trans('StatusNotApplicable');
  10486. } elseif ($histo[$key]['percent'] == 0) {
  10487. $colorClass = 'timeline-icon-todo';
  10488. $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
  10489. } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
  10490. $colorClass = 'timeline-icon-in-progress';
  10491. $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
  10492. } elseif ($histo[$key]['percent'] >= 100) {
  10493. $colorClass = 'timeline-icon-done';
  10494. $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
  10495. }
  10496. if ($actionstatic->code == 'AC_TICKET_CREATE') {
  10497. $iconClass = 'fa fa-ticket';
  10498. } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
  10499. $iconClass = 'fa fa-pencilxxx';
  10500. } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  10501. $iconClass = 'fa fa-comments';
  10502. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  10503. $iconClass = 'fa fa-mask';
  10504. } elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  10505. if ($actionstatic->type_picto) {
  10506. $img_picto = img_picto('', $actionstatic->type_picto);
  10507. } else {
  10508. if ($actionstatic->type_code == 'AC_RDV') {
  10509. $iconClass = 'fa fa-handshake';
  10510. } elseif ($actionstatic->type_code == 'AC_TEL') {
  10511. $iconClass = 'fa fa-phone';
  10512. } elseif ($actionstatic->type_code == 'AC_FAX') {
  10513. $iconClass = 'fa fa-fax';
  10514. } elseif ($actionstatic->type_code == 'AC_EMAIL') {
  10515. $iconClass = 'fa fa-envelope';
  10516. } elseif ($actionstatic->type_code == 'AC_INT') {
  10517. $iconClass = 'fa fa-shipping-fast';
  10518. } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
  10519. $iconClass = 'fa fa-robot';
  10520. } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
  10521. $iconClass = 'fa fa-robot';
  10522. }
  10523. }
  10524. }
  10525. $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
  10526. return $out;
  10527. }
  10528. /**
  10529. * getActionCommEcmList
  10530. *
  10531. * @param ActionComm $object Object ActionComm
  10532. * @return array Array of documents in index table
  10533. */
  10534. function getActionCommEcmList($object)
  10535. {
  10536. global $conf, $db;
  10537. $documents = array();
  10538. $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename';
  10539. $sql .= ' FROM '.MAIN_DB_PREFIX.'ecm_files ecm';
  10540. $sql .= " WHERE ecm.filepath = 'agenda/".((int) $object->id)."'";
  10541. //$sql.= " ecm.src_object_type = '".$db->escape($object->element)."' AND ecm.src_object_id = ".((int) $object->id); // Old version didn't add object_type during upload
  10542. $sql .= ' ORDER BY ecm.position ASC';
  10543. $resql = $db->query($sql);
  10544. if ($resql) {
  10545. if ($db->num_rows($resql)) {
  10546. while ($obj = $db->fetch_object($resql)) {
  10547. $documents[$obj->id] = $obj;
  10548. }
  10549. }
  10550. }
  10551. return $documents;
  10552. }
  10553. /**
  10554. * Show html area with actions in messaging format.
  10555. * Note: Global parameter $param must be defined.
  10556. *
  10557. * @param Conf $conf Object conf
  10558. * @param Translate $langs Object langs
  10559. * @param DoliDB $db Object db
  10560. * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object
  10561. * @param Contact $objcon Filter on object contact to filter events on a contact
  10562. * @param int $noprint Return string but does not output it
  10563. * @param string $actioncode Filter on actioncode
  10564. * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all).
  10565. * @param array $filters Filter on other fields
  10566. * @param string $sortfield Sort field
  10567. * @param string $sortorder Sort order
  10568. * @return string|void Return html part or void if noprint is 1
  10569. */
  10570. function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
  10571. {
  10572. global $user, $conf;
  10573. global $form;
  10574. global $param, $massactionbutton;
  10575. dol_include_once('/comm/action/class/actioncomm.class.php');
  10576. // Check parameters
  10577. if (!is_object($filterobj) && !is_object($objcon)) {
  10578. dol_print_error('', 'BadParameter');
  10579. }
  10580. $histo = array();
  10581. $numaction = 0;
  10582. $now = dol_now();
  10583. $sortfield_list = explode(',', $sortfield);
  10584. $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
  10585. $sortfield_new_list = array();
  10586. foreach ($sortfield_list as $sortfield_value) {
  10587. $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
  10588. }
  10589. $sortfield_new = implode(',', $sortfield_new_list);
  10590. if (isModEnabled('agenda')) {
  10591. // Search histo on actioncomm
  10592. if (is_object($objcon) && $objcon->id > 0) {
  10593. $sql = "SELECT DISTINCT a.id, a.label as label,";
  10594. } else {
  10595. $sql = "SELECT a.id, a.label as label,";
  10596. }
  10597. $sql .= " a.datep as dp,";
  10598. $sql .= " a.note as message,";
  10599. $sql .= " a.datep2 as dp2,";
  10600. $sql .= " a.percent as percent, 'action' as type,";
  10601. $sql .= " a.fk_element, a.elementtype,";
  10602. $sql .= " a.fk_contact,";
  10603. $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
  10604. $sql .= " u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname";
  10605. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  10606. $sql .= ", sp.lastname, sp.firstname";
  10607. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  10608. $sql .= ", m.lastname, m.firstname";
  10609. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  10610. $sql .= ", o.ref";
  10611. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  10612. $sql .= ", o.ref";
  10613. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  10614. $sql .= ", o.ref";
  10615. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  10616. $sql .= ", o.ref";
  10617. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  10618. $sql .= ", o.ref";
  10619. }
  10620. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  10621. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
  10622. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
  10623. $force_filter_contact = false;
  10624. if (is_object($objcon) && $objcon->id > 0) {
  10625. $force_filter_contact = true;
  10626. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
  10627. $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
  10628. }
  10629. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  10630. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
  10631. } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
  10632. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
  10633. $sql .= " ON er.resource_type = 'dolresource'";
  10634. $sql .= " AND er.element_id = a.id";
  10635. $sql .= " AND er.resource_id = ".((int) $filterobj->id);
  10636. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  10637. $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
  10638. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  10639. $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
  10640. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  10641. $sql .= ", ".MAIN_DB_PREFIX."product as o";
  10642. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  10643. $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
  10644. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  10645. $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
  10646. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  10647. $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
  10648. }
  10649. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  10650. if ($force_filter_contact === false) {
  10651. if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
  10652. $sql .= " AND a.fk_soc = ".((int) $filterobj->id);
  10653. } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
  10654. $sql .= " AND a.fk_project = ".((int) $filterobj->id);
  10655. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  10656. $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
  10657. if ($filterobj->id) {
  10658. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  10659. }
  10660. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  10661. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
  10662. if ($filterobj->id) {
  10663. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  10664. }
  10665. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  10666. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
  10667. if ($filterobj->id) {
  10668. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  10669. }
  10670. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  10671. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
  10672. if ($filterobj->id) {
  10673. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  10674. }
  10675. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  10676. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
  10677. if ($filterobj->id) {
  10678. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  10679. }
  10680. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  10681. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
  10682. if ($filterobj->id) {
  10683. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  10684. }
  10685. }
  10686. }
  10687. // Condition on actioncode
  10688. if (!empty($actioncode)) {
  10689. if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  10690. if ($actioncode == 'AC_NON_AUTO') {
  10691. $sql .= " AND c.type != 'systemauto'";
  10692. } elseif ($actioncode == 'AC_ALL_AUTO') {
  10693. $sql .= " AND c.type = 'systemauto'";
  10694. } else {
  10695. if ($actioncode == 'AC_OTH') {
  10696. $sql .= " AND c.type != 'systemauto'";
  10697. } elseif ($actioncode == 'AC_OTH_AUTO') {
  10698. $sql .= " AND c.type = 'systemauto'";
  10699. }
  10700. }
  10701. } else {
  10702. if ($actioncode == 'AC_NON_AUTO') {
  10703. $sql .= " AND c.type != 'systemauto'";
  10704. } elseif ($actioncode == 'AC_ALL_AUTO') {
  10705. $sql .= " AND c.type = 'systemauto'";
  10706. } else {
  10707. $sql .= " AND c.code = '".$db->escape($actioncode)."'";
  10708. }
  10709. }
  10710. }
  10711. if ($donetodo == 'todo') {
  10712. $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  10713. } elseif ($donetodo == 'done') {
  10714. $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  10715. }
  10716. if (is_array($filters) && $filters['search_agenda_label']) {
  10717. $sql .= natural_search('a.label', $filters['search_agenda_label']);
  10718. }
  10719. }
  10720. // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
  10721. if (isModEnabled('mailing') && !empty($objcon->email)
  10722. && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
  10723. $langs->load("mails");
  10724. $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type";
  10725. $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
  10726. $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
  10727. $sql2 .= ", u.rowid as user_id, u.login as user_login, u.photo as user_photo, u.firstname as user_firstname, u.lastname as user_lastname"; // User that valid action
  10728. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  10729. $sql2 .= ", '' as lastname, '' as firstname";
  10730. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  10731. $sql2 .= ", '' as lastname, '' as firstname";
  10732. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  10733. $sql2 .= ", '' as ref";
  10734. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  10735. $sql2 .= ", '' as ref";
  10736. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  10737. $sql2 .= ", '' as ref";
  10738. }
  10739. $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
  10740. $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
  10741. $sql2 .= " AND mc.statut = 1";
  10742. $sql2 .= " AND u.rowid = m.fk_user_valid";
  10743. $sql2 .= " AND mc.fk_mailing=m.rowid";
  10744. }
  10745. if (!empty($sql) && !empty($sql2)) {
  10746. $sql = $sql." UNION ".$sql2;
  10747. } elseif (empty($sql) && !empty($sql2)) {
  10748. $sql = $sql2;
  10749. }
  10750. // TODO Add limit in nb of results
  10751. if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too
  10752. $sql .= $db->order($sortfield_new, $sortorder);
  10753. dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
  10754. $resql = $db->query($sql);
  10755. if ($resql) {
  10756. $i = 0;
  10757. $num = $db->num_rows($resql);
  10758. while ($i < $num) {
  10759. $obj = $db->fetch_object($resql);
  10760. if ($obj->type == 'action') {
  10761. $contactaction = new ActionComm($db);
  10762. $contactaction->id = $obj->id;
  10763. $result = $contactaction->fetchResources();
  10764. if ($result < 0) {
  10765. dol_print_error($db);
  10766. setEventMessage("actions.lib::show_actions_messaging Error fetch ressource", 'errors');
  10767. }
  10768. //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  10769. //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  10770. $tododone = '';
  10771. if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
  10772. $tododone = 'todo';
  10773. }
  10774. $histo[$numaction] = array(
  10775. 'type'=>$obj->type,
  10776. 'tododone'=>$tododone,
  10777. 'id'=>$obj->id,
  10778. 'datestart'=>$db->jdate($obj->dp),
  10779. 'dateend'=>$db->jdate($obj->dp2),
  10780. 'note'=>$obj->label,
  10781. 'message'=>$obj->message,
  10782. 'percent'=>$obj->percent,
  10783. 'userid'=>$obj->user_id,
  10784. 'login'=>$obj->user_login,
  10785. 'userfirstname'=>$obj->user_firstname,
  10786. 'userlastname'=>$obj->user_lastname,
  10787. 'userphoto'=>$obj->user_photo,
  10788. 'contact_id'=>$obj->fk_contact,
  10789. 'socpeopleassigned' => $contactaction->socpeopleassigned,
  10790. 'lastname'=>$obj->lastname,
  10791. 'firstname'=>$obj->firstname,
  10792. 'fk_element'=>$obj->fk_element,
  10793. 'elementtype'=>$obj->elementtype,
  10794. // Type of event
  10795. 'acode'=>$obj->acode,
  10796. 'alabel'=>$obj->alabel,
  10797. 'libelle'=>$obj->alabel, // deprecated
  10798. 'apicto'=>$obj->apicto
  10799. );
  10800. } else {
  10801. $histo[$numaction] = array(
  10802. 'type'=>$obj->type,
  10803. 'tododone'=>'done',
  10804. 'id'=>$obj->id,
  10805. 'datestart'=>$db->jdate($obj->dp),
  10806. 'dateend'=>$db->jdate($obj->dp2),
  10807. 'note'=>$obj->label,
  10808. 'message'=>$obj->message,
  10809. 'percent'=>$obj->percent,
  10810. 'acode'=>$obj->acode,
  10811. 'userid'=>$obj->user_id,
  10812. 'login'=>$obj->user_login,
  10813. 'userfirstname'=>$obj->user_firstname,
  10814. 'userlastname'=>$obj->user_lastname,
  10815. 'userphoto'=>$obj->user_photo
  10816. );
  10817. }
  10818. $numaction++;
  10819. $i++;
  10820. }
  10821. } else {
  10822. dol_print_error($db);
  10823. }
  10824. }
  10825. // Set $out to show events
  10826. $out = '';
  10827. if (!isModEnabled('agenda')) {
  10828. $langs->loadLangs(array("admin", "errors"));
  10829. $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
  10830. }
  10831. if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
  10832. $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
  10833. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  10834. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  10835. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  10836. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  10837. $formactions = new FormActions($db);
  10838. $actionstatic = new ActionComm($db);
  10839. $userstatic = new User($db);
  10840. $contactstatic = new Contact($db);
  10841. $userGetNomUrlCache = array();
  10842. $out .= '<div class="filters-container" >';
  10843. $out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  10844. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  10845. if ($objcon && get_class($objcon) == 'Contact' &&
  10846. (is_null($filterobj) || get_class($filterobj) == 'Societe')) {
  10847. $out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
  10848. } else {
  10849. $out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
  10850. }
  10851. if ($filterobj && get_class($filterobj) == 'Societe') {
  10852. $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
  10853. }
  10854. $out .= "\n";
  10855. $out .= '<div class="div-table-responsive-no-min">';
  10856. $out .= '<table class="noborder borderbottom centpercent">';
  10857. $out .= '<tr class="liste_titre">';
  10858. $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n";
  10859. $out .= '<th class="liste_titre"><strong class="hideonsmartphone">'.$langs->trans("Search").' : </strong></th>';
  10860. if ($donetodo) {
  10861. $out .= '<th class="liste_titre"></th>';
  10862. }
  10863. $out .= '<th class="liste_titre">';
  10864. $out .= '<span class="fas fa-square inline-block fawidth30" style=" color: #ddd;" title="'.$langs->trans("ActionType").'"></span>';
  10865. //$out .= img_picto($langs->trans("Type"), 'type');
  10866. $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1, 'minwidth200imp');
  10867. $out .= '</th>';
  10868. $out .= '<th class="liste_titre maxwidth100onsmartphone">';
  10869. $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'" placeholder="'.$langs->trans("Label").'">';
  10870. $out .= '</th>';
  10871. $out .= '<th class="liste_titre width50 middle">';
  10872. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  10873. $out .= $searchpicto;
  10874. $out .= '</th>';
  10875. $out .= '</tr>';
  10876. $out .= '</table>';
  10877. $out .= '</form>';
  10878. $out .= '</div>';
  10879. $out .= "\n";
  10880. $out .= '<ul class="timeline">';
  10881. if ($donetodo) {
  10882. $tmp = '';
  10883. if (get_class($filterobj) == 'Societe') {
  10884. $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
  10885. }
  10886. $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
  10887. $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
  10888. $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
  10889. //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
  10890. if (get_class($filterobj) == 'Societe') {
  10891. $tmp .= '</a>';
  10892. }
  10893. $out .= getTitleFieldOfList($tmp);
  10894. }
  10895. //require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
  10896. //$caction=new CActionComm($db);
  10897. //$arraylist=$caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:0), '', 1);
  10898. $actualCycleDate = false;
  10899. // Loop on each event to show it
  10900. foreach ($histo as $key => $value) {
  10901. $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
  10902. $actionstatic->type_picto = $histo[$key]['apicto'];
  10903. $actionstatic->type_code = $histo[$key]['acode'];
  10904. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
  10905. $tmpa = dol_getdate($histo[$key]['datestart'], false);
  10906. if ($actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
  10907. $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
  10908. $out .= '<!-- timeline time label -->';
  10909. $out .= '<li class="time-label">';
  10910. $out .= '<span class="timeline-badge-date">';
  10911. $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
  10912. $out .= '</span>';
  10913. $out .= '</li>';
  10914. $out .= '<!-- /.timeline-label -->';
  10915. }
  10916. $out .= '<!-- timeline item -->'."\n";
  10917. $out .= '<li class="timeline-code-'.strtolower($actionstatic->code).'">';
  10918. $out .= getTimelineIcon($actionstatic, $histo, $key);
  10919. $out .= '<div class="timeline-item">'."\n";
  10920. $out .= '<span class="timeline-header-action">';
  10921. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
  10922. $out .= '<a class="timeline-btn" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  10923. $out .= $histo[$key]['id'];
  10924. $out .= '</a> ';
  10925. } else {
  10926. $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle').' ';
  10927. }
  10928. if ($user->hasRight('agenda', 'allactions', 'create') ||
  10929. (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && !empty($user->rights->agenda->myactions->create))) {
  10930. $out .= '<a class="timeline-btn" href="'.DOL_MAIN_URL_ROOT.'/comm/action/card.php?action=edit&token='.newToken().'&id='.$actionstatic->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?'.$param).'"><i class="fa fa-pencil" title="'.$langs->trans("Modify").'" ></i></a>';
  10931. }
  10932. $out .= '</span>';
  10933. // Date
  10934. $out .= '<span class="time"><i class="fa fa-clock-o"></i> ';
  10935. $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
  10936. if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
  10937. $tmpa = dol_getdate($histo[$key]['datestart'], true);
  10938. $tmpb = dol_getdate($histo[$key]['dateend'], true);
  10939. if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
  10940. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
  10941. } else {
  10942. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
  10943. }
  10944. }
  10945. $late = 0;
  10946. if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  10947. $late = 1;
  10948. }
  10949. if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  10950. $late = 1;
  10951. }
  10952. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
  10953. $late = 1;
  10954. }
  10955. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  10956. $late = 1;
  10957. }
  10958. if ($late) {
  10959. $out .= img_warning($langs->trans("Late")).' ';
  10960. }
  10961. $out .= "</span>\n";
  10962. // Ref
  10963. $out .= '<h3 class="timeline-header">';
  10964. // Author of event
  10965. $out .= '<span class="messaging-author">';
  10966. if ($histo[$key]['userid'] > 0) {
  10967. if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
  10968. $userstatic->fetch($histo[$key]['userid']);
  10969. $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
  10970. }
  10971. $out .= $userGetNomUrlCache[$histo[$key]['userid']];
  10972. }
  10973. $out .= '</span>';
  10974. // Title
  10975. $out .= ' <span class="messaging-title">';
  10976. if (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  10977. $out .= $langs->trans('TicketNewMessage');
  10978. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  10979. $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
  10980. } else {
  10981. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'action') {
  10982. $transcode = $langs->trans("Action".$histo[$key]['acode']);
  10983. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
  10984. $libelle = $histo[$key]['note'];
  10985. $actionstatic->id = $histo[$key]['id'];
  10986. $out .= dol_trunc($libelle, 120);
  10987. }
  10988. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
  10989. $out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  10990. $transcode = $langs->trans("Action".$histo[$key]['acode']);
  10991. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
  10992. $out .= dol_trunc($libelle, 120);
  10993. }
  10994. }
  10995. $out .= '</span>';
  10996. $out .= '</h3>';
  10997. if (!empty($histo[$key]['message'])
  10998. && $actionstatic->code != 'AC_TICKET_CREATE'
  10999. && $actionstatic->code != 'AC_TICKET_MODIFY'
  11000. ) {
  11001. $out .= '<div class="timeline-body">';
  11002. $out .= $histo[$key]['message'];
  11003. $out .= '</div>';
  11004. }
  11005. // Timeline footer
  11006. $footer = '';
  11007. // Contact for this action
  11008. if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
  11009. $contactList = '';
  11010. foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
  11011. $contact = new Contact($db);
  11012. $result = $contact->fetch($cid);
  11013. if ($result < 0) {
  11014. dol_print_error($db, $contact->error);
  11015. }
  11016. if ($result > 0) {
  11017. $contactList .= !empty($contactList) ? ', ' : '';
  11018. $contactList .= $contact->getNomUrl(1);
  11019. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11020. if (!empty($contact->phone_pro)) {
  11021. $contactList .= '('.dol_print_phone($contact->phone_pro).')';
  11022. }
  11023. }
  11024. }
  11025. }
  11026. $footer .= $langs->trans('ActionOnContact').' : '.$contactList;
  11027. } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
  11028. $contact = new Contact($db);
  11029. $result = $contact->fetch($histo[$key]['contact_id']);
  11030. if ($result < 0) {
  11031. dol_print_error($db, $contact->error);
  11032. }
  11033. if ($result > 0) {
  11034. $footer .= $contact->getNomUrl(1);
  11035. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11036. if (!empty($contact->phone_pro)) {
  11037. $footer .= '('.dol_print_phone($contact->phone_pro).')';
  11038. }
  11039. }
  11040. }
  11041. }
  11042. $documents = getActionCommEcmList($actionstatic);
  11043. if (!empty($documents)) {
  11044. $footer .= '<div class="timeline-documents-container">';
  11045. foreach ($documents as $doc) {
  11046. $footer .= '<span id="document_'.$doc->id.'" class="timeline-documents" ';
  11047. $footer .= ' data-id="'.$doc->id.'" ';
  11048. $footer .= ' data-path="'.$doc->filepath.'"';
  11049. $footer .= ' data-filename="'.dol_escape_htmltag($doc->filename).'" ';
  11050. $footer .= '>';
  11051. $filePath = DOL_DATA_ROOT.'/'.$doc->filepath.'/'.$doc->filename;
  11052. $mime = dol_mimetype($filePath);
  11053. $file = $actionstatic->id.'/'.$doc->filename;
  11054. $thumb = $actionstatic->id.'/thumbs/'.substr($doc->filename, 0, strrpos($doc->filename, '.')).'_mini'.substr($doc->filename, strrpos($doc->filename, '.'));
  11055. $doclink = dol_buildpath('document.php', 1).'?modulepart=actions&attachment=0&file='.urlencode($file).'&entity='.$conf->entity;
  11056. $viewlink = dol_buildpath('viewimage.php', 1).'?modulepart=actions&file='.urlencode($thumb).'&entity='.$conf->entity;
  11057. $mimeAttr = ' mime="'.$mime.'" ';
  11058. $class = '';
  11059. if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
  11060. $class .= ' documentpreview';
  11061. }
  11062. $footer .= '<a href="'.$doclink.'" class="btn-link '.$class.'" target="_blank" rel="noopener noreferrer" '.$mimeAttr.' >';
  11063. $footer .= img_mime($filePath).' '.$doc->filename;
  11064. $footer .= '</a>';
  11065. $footer .= '</span>';
  11066. }
  11067. $footer .= '</div>';
  11068. }
  11069. if (!empty($footer)) {
  11070. $out .= '<div class="timeline-footer">'.$footer.'</div>';
  11071. }
  11072. $out .= '</div>'."\n"; // end timeline-item
  11073. $out .= '</li>';
  11074. $out .= '<!-- END timeline item -->';
  11075. $i++;
  11076. }
  11077. $out .= "</ul>\n";
  11078. if (empty($histo)) {
  11079. $out .= '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
  11080. }
  11081. }
  11082. if ($noprint) {
  11083. return $out;
  11084. } else {
  11085. print $out;
  11086. }
  11087. }