functions.lib.php 518 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798
  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-2023 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019-2023 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. * Copyright (C) 2023 Joachim Kueter <git-jk@bloxera.com>
  24. *
  25. * This program is free software; you can redistribute it and/or modify
  26. * it under the terms of the GNU General Public License as published by
  27. * the Free Software Foundation; either version 3 of the License, or
  28. * (at your option) any later version.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU General Public License
  36. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  37. * or see https://www.gnu.org/
  38. */
  39. /**
  40. * \file htdocs/core/lib/functions.lib.php
  41. * \brief A set of functions for Dolibarr
  42. * This file contains all frequently used functions.
  43. */
  44. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  45. if (!function_exists('utf8_encode')) {
  46. /**
  47. * Implement utf8_encode for PHP that does not support it.
  48. *
  49. * @param mixed $elements PHP Object to json encode
  50. * @return string Json encoded string
  51. */
  52. function utf8_encode($elements)
  53. {
  54. return mb_convert_encoding($elements, 'UTF-8', 'ISO-8859-1');
  55. }
  56. }
  57. if (!function_exists('utf8_decode')) {
  58. /**
  59. * Implement utf8_decode for PHP that does not support it.
  60. *
  61. * @param mixed $elements PHP Object to json encode
  62. * @return string Json encoded string
  63. */
  64. function utf8_decode($elements)
  65. {
  66. return mb_convert_encoding($elements, 'ISO-8859-1', 'UTF-8');
  67. }
  68. }
  69. /**
  70. * Return the full path of the directory where a module (or an object of a module) stores its files. Path may depends on the entity if a multicompany module is enabled.
  71. *
  72. * @param CommonObject $object Dolibarr common object
  73. * @param string $module Override object element, for example to use 'mycompany' instead of 'societe'
  74. * @return string|void The path of the relative directory of the module
  75. * @since Dolibarr V18
  76. */
  77. function getMultidirOutput($object, $module = '')
  78. {
  79. global $conf;
  80. if (!is_object($object) && empty($module)) {
  81. return null;
  82. }
  83. if (empty($module) && !empty($object->element)) {
  84. $module = $object->element;
  85. }
  86. return $conf->$module->multidir_output[(!empty($object->entity) ? $object->entity : $conf->entity)];
  87. }
  88. /**
  89. * Return dolibarr global constant string value
  90. *
  91. * @param string $key key to return value, return '' if not set
  92. * @param string $default value to return
  93. * @return string
  94. */
  95. function getDolGlobalString($key, $default = '')
  96. {
  97. global $conf;
  98. // return $conf->global->$key ?? $default;
  99. return (string) (isset($conf->global->$key) ? $conf->global->$key : $default);
  100. }
  101. /**
  102. * Return dolibarr global constant int value
  103. *
  104. * @param string $key key to return value, return 0 if not set
  105. * @param int $default value to return
  106. * @return int
  107. */
  108. function getDolGlobalInt($key, $default = 0)
  109. {
  110. global $conf;
  111. // return $conf->global->$key ?? $default;
  112. return (int) (isset($conf->global->$key) ? $conf->global->$key : $default);
  113. }
  114. /**
  115. * Return Dolibarr user constant string value
  116. *
  117. * @param string $key key to return value, return '' if not set
  118. * @param string $default value to return
  119. * @param User $tmpuser To get another user than current user
  120. * @return string
  121. */
  122. function getDolUserString($key, $default = '', $tmpuser = null)
  123. {
  124. if (empty($tmpuser)) {
  125. global $user;
  126. $tmpuser = $user;
  127. }
  128. // return $conf->global->$key ?? $default;
  129. return (string) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  130. }
  131. /**
  132. * Return Dolibarr user constant int value
  133. *
  134. * @param string $key key to return value, return 0 if not set
  135. * @param int $default value to return
  136. * @param User $tmpuser To get another user than current user
  137. * @return int
  138. */
  139. function getDolUserInt($key, $default = 0, $tmpuser = null)
  140. {
  141. if (empty($tmpuser)) {
  142. global $user;
  143. $tmpuser = $user;
  144. }
  145. // return $conf->global->$key ?? $default;
  146. return (int) (empty($tmpuser->conf->$key) ? $default : $tmpuser->conf->$key);
  147. }
  148. /**
  149. * Is Dolibarr module enabled
  150. *
  151. * @param string $module Module name to check
  152. * @return boolean True if module is enabled
  153. */
  154. function isModEnabled($module)
  155. {
  156. global $conf;
  157. // Fix special cases
  158. $arrayconv = array(
  159. 'project' => 'projet',
  160. 'contract' => 'contrat'
  161. );
  162. if (empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) {
  163. $arrayconv['supplier_order'] = 'fournisseur';
  164. $arrayconv['supplier_invoice'] = 'fournisseur';
  165. }
  166. if (!empty($arrayconv[$module])) {
  167. $module = $arrayconv[$module];
  168. }
  169. return !empty($conf->modules[$module]);
  170. //return !empty($conf->$module->enabled);
  171. }
  172. /**
  173. * Return a DoliDB instance (database handler).
  174. *
  175. * @param string $type Type of database (mysql, pgsql...)
  176. * @param string $host Address of database server
  177. * @param string $user Authorized username
  178. * @param string $pass Password
  179. * @param string $name Name of database
  180. * @param int $port Port of database server
  181. * @return DoliDB A DoliDB instance
  182. */
  183. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  184. {
  185. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  186. $class = 'DoliDB'.ucfirst($type);
  187. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  188. return $dolidb;
  189. }
  190. /**
  191. * Get list of entity id to use.
  192. *
  193. * @param string $element Current element
  194. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  195. * 'product', 'productprice', 'stock', 'bom', 'mo',
  196. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  197. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  198. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  199. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  200. * 'email_template', 'event', 'donation'
  201. * 'c_paiement', 'c_payment_term', ...
  202. * @param int $shared 0=Return id of current entity only,
  203. * 1=Return id of current entity + shared entities (default)
  204. * @param object $currentobject Current object if needed
  205. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  206. */
  207. function getEntity($element, $shared = 1, $currentobject = null)
  208. {
  209. global $conf, $mc, $hookmanager, $object, $action, $db;
  210. if (!is_object($hookmanager)) {
  211. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  212. $hookmanager = new HookManager($db);
  213. }
  214. // fix different element names (France to English)
  215. switch ($element) {
  216. case 'contrat':
  217. $element = 'contract';
  218. break; // "/contrat/class/contrat.class.php"
  219. case 'order_supplier':
  220. $element = 'supplier_order';
  221. break; // "/fourn/class/fournisseur.commande.class.php"
  222. case 'invoice_supplier':
  223. $element = 'supplier_invoice';
  224. break; // "/fourn/class/fournisseur.facture.class.php"
  225. }
  226. if (is_object($mc)) {
  227. $out = $mc->getEntity($element, $shared, $currentobject);
  228. } else {
  229. $out = '';
  230. $addzero = array('user', 'usergroup', 'cronjob', 'c_email_templates', 'email_template', 'default_values');
  231. if (in_array($element, $addzero)) {
  232. $out .= '0,';
  233. }
  234. $out .= ((int) $conf->entity);
  235. }
  236. // Manipulate entities to query on the fly
  237. $parameters = array(
  238. 'element' => $element,
  239. 'shared' => $shared,
  240. 'object' => $object,
  241. 'currentobject' => $currentobject,
  242. 'out' => $out
  243. );
  244. $reshook = $hookmanager->executeHooks('hookGetEntity', $parameters, $currentobject, $action); // Note that $action and $object may have been modified by some hooks
  245. if (is_numeric($reshook)) {
  246. if ($reshook == 0 && !empty($hookmanager->resPrint)) {
  247. $out .= ','.$hookmanager->resPrint; // add
  248. } elseif ($reshook == 1) {
  249. $out = $hookmanager->resPrint; // replace
  250. }
  251. }
  252. return $out;
  253. }
  254. /**
  255. * Set entity id to use when to create an object
  256. *
  257. * @param object $currentobject Current object
  258. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  259. */
  260. function setEntity($currentobject)
  261. {
  262. global $conf, $mc;
  263. if (is_object($mc) && method_exists($mc, 'setEntity')) {
  264. return $mc->setEntity($currentobject);
  265. } else {
  266. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  267. }
  268. }
  269. /**
  270. * Return if string has a name dedicated to store a secret
  271. *
  272. * @param string $keyname Name of key to test
  273. * @return boolean True if key is used to store a secret
  274. */
  275. function isASecretKey($keyname)
  276. {
  277. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  278. }
  279. /**
  280. * Return a numeric value into an Excel like column number. So 0 return 'A', 1 returns 'B'..., 26 return 'AA'
  281. *
  282. * @param int|string $n Numeric value
  283. * @return string Column in Excel format
  284. */
  285. function num2Alpha($n)
  286. {
  287. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1)
  288. $r = chr($n % 26 + 0x41) . $r;
  289. return $r;
  290. }
  291. /**
  292. * Return information about user browser
  293. *
  294. * Returns array with the following format:
  295. * array(
  296. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  297. * 'browserversion' => Browser version. Empty if unknown
  298. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  299. * 'layout' => (tablet|phone|classic)
  300. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  301. * 'tablet' => true/false
  302. * )
  303. *
  304. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  305. * @return array Check function documentation
  306. */
  307. function getBrowserInfo($user_agent)
  308. {
  309. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  310. $name = 'unknown';
  311. $version = '';
  312. $os = 'unknown';
  313. $phone = '';
  314. $user_agent = substr($user_agent, 0, 512); // Avoid to process too large user agent
  315. $detectmobile = new Mobile_Detect(null, $user_agent);
  316. $tablet = $detectmobile->isTablet();
  317. if ($detectmobile->isMobile()) {
  318. $phone = 'unknown';
  319. // If phone/smartphone, we set phone os name.
  320. if ($detectmobile->is('AndroidOS')) {
  321. $os = $phone = 'android';
  322. } elseif ($detectmobile->is('BlackBerryOS')) {
  323. $os = $phone = 'blackberry';
  324. } elseif ($detectmobile->is('iOS')) {
  325. $os = 'ios';
  326. $phone = 'iphone';
  327. } elseif ($detectmobile->is('PalmOS')) {
  328. $os = $phone = 'palm';
  329. } elseif ($detectmobile->is('SymbianOS')) {
  330. $os = 'symbian';
  331. } elseif ($detectmobile->is('webOS')) {
  332. $os = 'webos';
  333. } elseif ($detectmobile->is('MaemoOS')) {
  334. $os = 'maemo';
  335. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  336. $os = 'windows';
  337. }
  338. }
  339. // OS
  340. if (preg_match('/linux/i', $user_agent)) {
  341. $os = 'linux';
  342. } elseif (preg_match('/macintosh/i', $user_agent)) {
  343. $os = 'macintosh';
  344. } elseif (preg_match('/windows/i', $user_agent)) {
  345. $os = 'windows';
  346. }
  347. // Name
  348. $reg = array();
  349. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  350. $name = 'firefox';
  351. $version = empty($reg[2]) ? '' : $reg[2];
  352. } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  353. $name = 'edge';
  354. $version = empty($reg[2]) ? '' : $reg[2];
  355. } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
  356. $name = 'chrome';
  357. $version = empty($reg[2]) ? '' : $reg[2];
  358. } elseif (preg_match('/chrome/i', $user_agent, $reg)) {
  359. // we can have 'chrome (Mozilla...) chrome x.y' in one string
  360. $name = 'chrome';
  361. } elseif (preg_match('/iceweasel/i', $user_agent)) {
  362. $name = 'iceweasel';
  363. } elseif (preg_match('/epiphany/i', $user_agent)) {
  364. $name = 'epiphany';
  365. } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  366. $name = 'safari';
  367. $version = empty($reg[2]) ? '' : $reg[2];
  368. } elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
  369. // Safari is often present in string for mobile but its not.
  370. $name = 'opera';
  371. $version = empty($reg[2]) ? '' : $reg[2];
  372. } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  373. $name = 'ie';
  374. $version = end($reg);
  375. } elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
  376. // MS products at end
  377. $name = 'ie';
  378. $version = end($reg);
  379. } elseif (preg_match('/l[iy]n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
  380. // MS products at end
  381. $name = 'lynxlinks';
  382. $version = empty($reg[3]) ? '' : $reg[3];
  383. }
  384. if ($tablet) {
  385. $layout = 'tablet';
  386. } elseif ($phone) {
  387. $layout = 'phone';
  388. } else {
  389. $layout = 'classic';
  390. }
  391. return array(
  392. 'browsername' => $name,
  393. 'browserversion' => $version,
  394. 'browseros' => $os,
  395. 'layout' => $layout,
  396. 'phone' => $phone,
  397. 'tablet' => $tablet
  398. );
  399. }
  400. /**
  401. * Function called at end of web php process
  402. *
  403. * @return void
  404. */
  405. function dol_shutdown()
  406. {
  407. global $conf, $user, $langs, $db;
  408. $disconnectdone = false;
  409. $depth = 0;
  410. if (is_object($db) && !empty($db->connected)) {
  411. $depth = $db->transaction_opened;
  412. $disconnectdone = $db->close();
  413. }
  414. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
  415. }
  416. /**
  417. * Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
  418. * Warning:
  419. * For action=add, use: $var = GETPOST('var'); // No GETPOSTISSET, so GETPOST always called and default value is retreived if not a form POST, and value of form is retreived if it is a form POST.
  420. * For action=update, use: $var = GETPOSTISSET('var') ? GETPOST('var') : $object->var;
  421. *
  422. * @param string $paramname Name or parameter to test
  423. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  424. */
  425. function GETPOSTISSET($paramname)
  426. {
  427. $isset = false;
  428. $relativepathstring = $_SERVER["PHP_SELF"];
  429. // Clean $relativepathstring
  430. if (constant('DOL_URL_ROOT')) {
  431. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  432. }
  433. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  434. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  435. //var_dump($relativepathstring);
  436. //var_dump($user->default_values);
  437. // Code for search criteria persistence.
  438. // Retrieve values if restore_lastsearch_values
  439. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  440. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  441. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  442. if (is_array($tmp)) {
  443. foreach ($tmp as $key => $val) {
  444. if ($key == $paramname) { // We are on the requested parameter
  445. $isset = true;
  446. break;
  447. }
  448. }
  449. }
  450. }
  451. // If there is saved contextpage, limit, page or mode
  452. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  453. $isset = true;
  454. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  455. $isset = true;
  456. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  457. $isset = true;
  458. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  459. $isset = true;
  460. }
  461. } else {
  462. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  463. }
  464. return $isset;
  465. }
  466. /**
  467. * Return true if the parameter $paramname is submit from a POST OR GET as an array.
  468. * Can be used before GETPOST to know if the $check param of GETPOST need to check an array or a string
  469. *
  470. * @param string $paramname Name or parameter to test
  471. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  472. * @return bool True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  473. */
  474. function GETPOSTISARRAY($paramname, $method = 0)
  475. {
  476. // for $method test need return the same $val as GETPOST
  477. if (empty($method)) {
  478. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  479. } elseif ($method == 1) {
  480. $val = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  481. } elseif ($method == 2) {
  482. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  483. } elseif ($method == 3) {
  484. $val = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  485. } else {
  486. $val = 'BadFirstParameterForGETPOST';
  487. }
  488. return is_array($val);
  489. }
  490. /**
  491. * Return value of a param into GET or POST supervariable.
  492. * Use the property $user->default_values[path]['createform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  493. * Note: The property $user->default_values is loaded by main.php when loading the user.
  494. *
  495. * @param string $paramname Name of parameter to found
  496. * @param string $check Type of check
  497. * ''=no check (deprecated)
  498. * 'none'=no check (only for param that should have very rich content like passwords)
  499. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  500. * 'int'=check it's numeric (integer or float)
  501. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  502. * 'alpha'=Same than alphanohtml since v13
  503. * 'alphawithlgt'=alpha with lgt
  504. * 'alphanohtml'=check there is no html content and no " and no ../
  505. * 'aZ'=check it's a-z only
  506. * 'aZ09'=check it's simple alpha string (recommended for keys)
  507. * 'aZ09arobase'=check it's a string for an element type
  508. * 'aZ09comma'=check it's a string for a sortfield or sortorder
  509. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  510. * 'nohtml'=check there is no html content
  511. * 'restricthtml'=check html content is restricted to some tags only
  512. * 'custom'= custom filter specify $filter and $options)
  513. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  514. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  515. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  516. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  517. * @return string|array Value found (string or array), or '' if check fails
  518. */
  519. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  520. {
  521. global $mysoc, $user, $conf;
  522. if (empty($paramname)) {
  523. return 'BadFirstParameterForGETPOST';
  524. }
  525. if (empty($check)) {
  526. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  527. // Enable this line to know who call the GETPOST with '' $check parameter.
  528. //var_dump(debug_backtrace()[0]);
  529. }
  530. if (empty($method)) {
  531. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  532. } elseif ($method == 1) {
  533. $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  534. } elseif ($method == 2) {
  535. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  536. } elseif ($method == 3) {
  537. $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  538. } else {
  539. return 'BadThirdParameterForGETPOST';
  540. }
  541. if (empty($method) || $method == 3 || $method == 4) {
  542. $relativepathstring = $_SERVER["PHP_SELF"];
  543. // Clean $relativepathstring
  544. if (constant('DOL_URL_ROOT')) {
  545. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  546. }
  547. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  548. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  549. //var_dump($relativepathstring);
  550. //var_dump($user->default_values);
  551. // Code for search criteria persistence.
  552. // Retrieve values if restore_lastsearch_values
  553. if (!empty($_GET['restore_lastsearch_values'])) { // Use $_GET here and not GETPOST
  554. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
  555. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  556. if (is_array($tmp)) {
  557. foreach ($tmp as $key => $val) {
  558. if ($key == $paramname) { // We are on the requested parameter
  559. $out = $val;
  560. break;
  561. }
  562. }
  563. }
  564. }
  565. // If there is saved contextpage, page or limit
  566. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
  567. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  568. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
  569. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  570. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
  571. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  572. } elseif ($paramname == 'mode' && !empty($_SESSION['lastsearch_mode_'.$relativepathstring])) {
  573. $out = $_SESSION['lastsearch_mode_'.$relativepathstring];
  574. }
  575. } elseif (!isset($_GET['sortfield'])) {
  576. // Else, retrieve default values if we are not doing a sort
  577. // 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
  578. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  579. // Search default value from $object->field
  580. global $object;
  581. if (is_object($object) && isset($object->fields[$paramname]['default'])) {
  582. $out = $object->fields[$paramname]['default'];
  583. }
  584. }
  585. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
  586. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  587. // Now search in setup to overwrite default values
  588. if (!empty($user->default_values)) { // $user->default_values defined from menu 'Setup - Default values'
  589. if (isset($user->default_values[$relativepathstring]['createform'])) {
  590. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
  591. $qualified = 0;
  592. if ($defkey != '_noquery_') {
  593. $tmpqueryarraytohave = explode('&', $defkey);
  594. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  595. $foundintru = 0;
  596. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  597. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  598. $foundintru = 1;
  599. }
  600. }
  601. if (!$foundintru) {
  602. $qualified = 1;
  603. }
  604. //var_dump($defkey.'-'.$qualified);
  605. } else {
  606. $qualified = 1;
  607. }
  608. if ($qualified) {
  609. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
  610. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  611. break;
  612. }
  613. }
  614. }
  615. }
  616. }
  617. } elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
  618. // Management of default search_filters and sort order
  619. if (!empty($user->default_values)) {
  620. // $user->default_values defined from menu 'Setup - Default values'
  621. //var_dump($user->default_values[$relativepathstring]);
  622. if ($paramname == 'sortfield' || $paramname == 'sortorder') {
  623. // Sorted on which fields ? ASC or DESC ?
  624. if (isset($user->default_values[$relativepathstring]['sortorder'])) {
  625. // Even if paramname is sortfield, data are stored into ['sortorder...']
  626. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
  627. $qualified = 0;
  628. if ($defkey != '_noquery_') {
  629. $tmpqueryarraytohave = explode('&', $defkey);
  630. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  631. $foundintru = 0;
  632. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  633. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  634. $foundintru = 1;
  635. }
  636. }
  637. if (!$foundintru) {
  638. $qualified = 1;
  639. }
  640. //var_dump($defkey.'-'.$qualified);
  641. } else {
  642. $qualified = 1;
  643. }
  644. if ($qualified) {
  645. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  646. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
  647. if ($out) {
  648. $out .= ', ';
  649. }
  650. if ($paramname == 'sortfield') {
  651. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  652. }
  653. if ($paramname == 'sortorder') {
  654. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  655. }
  656. }
  657. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  658. }
  659. }
  660. }
  661. } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
  662. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  663. if (!empty($_GET['disabledefaultvalues'])) { // If set of default values has been disabled by a request parameter
  664. continue;
  665. }
  666. $qualified = 0;
  667. if ($defkey != '_noquery_') {
  668. $tmpqueryarraytohave = explode('&', $defkey);
  669. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  670. $foundintru = 0;
  671. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  672. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
  673. $foundintru = 1;
  674. }
  675. }
  676. if (!$foundintru) {
  677. $qualified = 1;
  678. }
  679. //var_dump($defkey.'-'.$qualified);
  680. } else {
  681. $qualified = 1;
  682. }
  683. if ($qualified && isset($user->default_values[$relativepathstring]['filters'][$defkey][$paramname])) {
  684. // We must keep $_POST and $_GET here
  685. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
  686. // We made a search from quick search menu, do we still use default filter ?
  687. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
  688. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  689. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  690. }
  691. } else {
  692. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  693. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  694. }
  695. break;
  696. }
  697. }
  698. }
  699. }
  700. }
  701. }
  702. }
  703. }
  704. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  705. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  706. // 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.
  707. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
  708. $reg = array();
  709. $maxloop = 20;
  710. $loopnb = 0; // Protection against infinite loop
  711. 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.
  712. $loopnb++;
  713. $newout = '';
  714. if ($reg[1] == 'DAY') {
  715. $tmp = dol_getdate(dol_now(), true);
  716. $newout = $tmp['mday'];
  717. } elseif ($reg[1] == 'MONTH') {
  718. $tmp = dol_getdate(dol_now(), true);
  719. $newout = $tmp['mon'];
  720. } elseif ($reg[1] == 'YEAR') {
  721. $tmp = dol_getdate(dol_now(), true);
  722. $newout = $tmp['year'];
  723. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  724. $tmp = dol_getdate(dol_now(), true);
  725. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  726. $newout = $tmp2['day'];
  727. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  728. $tmp = dol_getdate(dol_now(), true);
  729. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  730. $newout = $tmp2['month'];
  731. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  732. $tmp = dol_getdate(dol_now(), true);
  733. $newout = ($tmp['year'] - 1);
  734. } elseif ($reg[1] == 'NEXT_DAY') {
  735. $tmp = dol_getdate(dol_now(), true);
  736. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  737. $newout = $tmp2['day'];
  738. } elseif ($reg[1] == 'NEXT_MONTH') {
  739. $tmp = dol_getdate(dol_now(), true);
  740. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  741. $newout = $tmp2['month'];
  742. } elseif ($reg[1] == 'NEXT_YEAR') {
  743. $tmp = dol_getdate(dol_now(), true);
  744. $newout = ($tmp['year'] + 1);
  745. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  746. $newout = $mysoc->country_id;
  747. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  748. $newout = $user->id;
  749. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  750. $newout = $user->fk_user;
  751. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  752. $newout = $conf->entity;
  753. } else {
  754. $newout = ''; // Key not found, we replace with empty string
  755. }
  756. //var_dump('__'.$reg[1].'__ -> '.$newout);
  757. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  758. }
  759. }
  760. // Check rule
  761. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09' or 'array:intcomma'
  762. if (!is_array($out) || empty($out)) {
  763. $out = array();
  764. } else {
  765. $tmparray = explode(':', $check);
  766. if (!empty($tmparray[1])) {
  767. $tmpcheck = $tmparray[1];
  768. } else {
  769. $tmpcheck = 'alphanohtml';
  770. }
  771. foreach ($out as $outkey => $outval) {
  772. $out[$outkey] = sanitizeVal($outval, $tmpcheck, $filter, $options);
  773. }
  774. }
  775. } else {
  776. // If field name is 'search_xxx' then we force the add of space after each < and > (when following char is numeric) because it means
  777. // we use the < or > to make a search on a numeric value to do higher or lower so we can add a space to break html tags
  778. if (strpos($paramname, 'search_') === 0) {
  779. $out = preg_replace('/([<>])([-+]?\d)/', '\1 \2', $out);
  780. }
  781. $out = sanitizeVal($out, $check, $filter, $options);
  782. }
  783. // Sanitizing for special parameters.
  784. // Note: There is no reason to allow the backtopage, backtolist or backtourl parameter to contains an external URL. Only relative URLs are allowed.
  785. if ($paramname == 'backtopage' || $paramname == 'backtolist' || $paramname == 'backtourl') {
  786. $out = str_replace('\\', '/', $out); // Can be before the loop because only 1 char is replaced. No risk to get it after other replacements.
  787. $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.
  788. do {
  789. $oldstringtoclean = $out;
  790. $out = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $out);
  791. $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'
  792. $out = preg_replace(array('/^[a-z]*\/\s*\/+/i'), '', $out); // We remove schema*// to remove external URL
  793. } while ($oldstringtoclean != $out);
  794. }
  795. // Code for search criteria persistence.
  796. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  797. if (empty($method) || $method == 3 || $method == 4) {
  798. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
  799. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  800. // We save search key only if $out not empty that means:
  801. // - posted value not empty, or
  802. // - 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).
  803. if ($out != '' && isset($user)) {// $out = '0' or 'abc', it is a search criteria to keep
  804. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  805. }
  806. }
  807. }
  808. return $out;
  809. }
  810. /**
  811. * Return value of a param into GET or POST supervariable.
  812. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  813. * Note: The property $user->default_values is loaded by main.php when loading the user.
  814. *
  815. * @param string $paramname Name of parameter to found
  816. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  817. * @return int Value found (int)
  818. */
  819. function GETPOSTINT($paramname, $method = 0)
  820. {
  821. return (int) GETPOST($paramname, 'int', $method, null, null, 0);
  822. }
  823. /**
  824. * Return a sanitized or empty value after checking value against a rule.
  825. *
  826. * @deprecated
  827. * @param string|array $out Value to check/clear.
  828. * @param string $check Type of check/sanitizing
  829. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  830. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  831. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  832. */
  833. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  834. {
  835. return sanitizeVal($out, $check, $filter, $options);
  836. }
  837. /**
  838. * Return a sanitized or empty value after checking value against a rule.
  839. *
  840. * @param string|array $out Value to check/clear.
  841. * @param string $check Type of check/sanitizing
  842. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  843. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  844. * @return string|array Value sanitized (string or array). It may be '' if format check fails.
  845. */
  846. function sanitizeVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  847. {
  848. global $conf;
  849. // TODO : use class "Validate" to perform tests (and add missing tests) if needed for factorize
  850. // Check is done after replacement
  851. switch ($check) {
  852. case 'none':
  853. break;
  854. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  855. if (!is_numeric($out)) {
  856. $out = '';
  857. }
  858. break;
  859. case 'intcomma':
  860. if (preg_match('/[^0-9,-]+/i', $out)) {
  861. $out = '';
  862. }
  863. break;
  864. case 'san_alpha':
  865. $out = filter_var($out, FILTER_SANITIZE_STRING);
  866. break;
  867. case 'email':
  868. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  869. break;
  870. case 'aZ':
  871. if (!is_array($out)) {
  872. $out = trim($out);
  873. if (preg_match('/[^a-z]+/i', $out)) {
  874. $out = '';
  875. }
  876. }
  877. break;
  878. case 'aZ09':
  879. if (!is_array($out)) {
  880. $out = trim($out);
  881. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
  882. $out = '';
  883. }
  884. }
  885. break;
  886. case 'aZ09arobase': // great to sanitize $objecttype parameter
  887. if (!is_array($out)) {
  888. $out = trim($out);
  889. if (preg_match('/[^a-z0-9_\-\.@]+/i', $out)) {
  890. $out = '';
  891. }
  892. }
  893. break;
  894. case 'aZ09comma': // great to sanitize $sortfield or $sortorder params that can be 't.abc,t.def_gh'
  895. if (!is_array($out)) {
  896. $out = trim($out);
  897. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
  898. $out = '';
  899. }
  900. }
  901. break;
  902. case 'alpha': // No html and no ../ and "
  903. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  904. if (!is_array($out)) {
  905. $out = trim($out);
  906. do {
  907. $oldstringtoclean = $out;
  908. // Remove html tags
  909. $out = dol_string_nohtmltag($out, 0);
  910. // Remove also other dangerous string sequences
  911. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  912. // '../' or '..\' is dangerous because it allows dir transversals
  913. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  914. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  915. } while ($oldstringtoclean != $out);
  916. // keep lines feed
  917. }
  918. break;
  919. 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'
  920. if (!is_array($out)) {
  921. $out = trim($out);
  922. do {
  923. $oldstringtoclean = $out;
  924. // Remove html tags
  925. $out = dol_html_entity_decode($out, ENT_COMPAT | ENT_HTML5, 'UTF-8');
  926. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  927. // '../' or '..\' is dangerous because it allows dir transversals
  928. // Note &#38, '&#0000038', '&#x26'... is a simple char like '&' alone but there is no reason to accept such way to encode input data.
  929. $out = str_ireplace(array('&#38', '&#0000038', '&#x26', '&quot', '&#34', '&#0000034', '&#x22', '"', '&#47', '&#0000047', '&#92', '&#0000092', '&#x2F', '../', '..\\'), '', $out);
  930. } while ($oldstringtoclean != $out);
  931. }
  932. break;
  933. case 'nohtml': // No html
  934. $out = dol_string_nohtmltag($out, 0);
  935. break;
  936. case 'restricthtml': // Recommended for most html textarea
  937. case 'restricthtmlnolink':
  938. case 'restricthtmlallowunvalid':
  939. $out = dol_htmlwithnojs($out, 1, $check);
  940. break;
  941. case 'custom':
  942. if (!empty($out)) {
  943. if (empty($filter)) {
  944. return 'BadParameterForGETPOST - Param 3 of sanitizeVal()';
  945. }
  946. /*if (empty($options)) {
  947. return 'BadParameterForGETPOST - Param 4 of sanitizeVal()';
  948. }*/
  949. $out = filter_var($out, $filter, $options);
  950. }
  951. break;
  952. }
  953. return $out;
  954. }
  955. if (!function_exists('dol_getprefix')) {
  956. /**
  957. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  958. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  959. * or two instances in same virtual servers.
  960. * This function must not use dol_hash (that is used for password hash) and need to have all context $conf loaded.
  961. *
  962. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  963. * @return string A calculated prefix
  964. */
  965. function dol_getprefix($mode = '')
  966. {
  967. // If prefix is for email (we need to have $conf already loaded for this case)
  968. if ($mode == 'email') {
  969. global $conf;
  970. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) { // If MAIL_PREFIX_FOR_EMAIL_ID is set
  971. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
  972. return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  973. } elseif (isset($_SERVER["SERVER_NAME"])) { // If MAIL_PREFIX_FOR_EMAIL_ID is set to 'SERVER_NAME'
  974. return $_SERVER["SERVER_NAME"];
  975. }
  976. }
  977. // The recommended value if MAIL_PREFIX_FOR_EMAIL_ID is not defined (may be not defined for old versions)
  978. if (!empty($conf->file->instance_unique_id)) {
  979. return sha1('dolibarr'.$conf->file->instance_unique_id);
  980. }
  981. // For backward compatibility when instance_unique_id is not set
  982. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  983. }
  984. // If prefix is for session (no need to have $conf loaded)
  985. global $dolibarr_main_instance_unique_id, $dolibarr_main_cookie_cryptkey; // This is loaded by filefunc.inc.php
  986. $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
  987. // The recommended value (may be not defined for old versions)
  988. if (!empty($tmp_instance_unique_id)) {
  989. return sha1('dolibarr'.$tmp_instance_unique_id);
  990. }
  991. // For backward compatibility when instance_unique_id is not set
  992. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
  993. return sha1($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  994. } else {
  995. return sha1(DOL_DOCUMENT_ROOT.DOL_URL_ROOT);
  996. }
  997. }
  998. }
  999. /**
  1000. * Make an include_once using default root and alternate root if it fails.
  1001. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  1002. * To link to a module file from a module file, use include './mymodulefile';
  1003. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  1004. *
  1005. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  1006. * @param string $classname Class name (deprecated)
  1007. * @return bool True if load is a success, False if it fails
  1008. */
  1009. function dol_include_once($relpath, $classname = '')
  1010. {
  1011. 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']
  1012. $fullpath = dol_buildpath($relpath);
  1013. if (!file_exists($fullpath)) {
  1014. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  1015. return false;
  1016. }
  1017. if (!empty($classname) && !class_exists($classname)) {
  1018. return include $fullpath;
  1019. } else {
  1020. return include_once $fullpath;
  1021. }
  1022. }
  1023. /**
  1024. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  1025. *
  1026. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  1027. * @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)
  1028. * @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)
  1029. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  1030. * 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
  1031. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  1032. */
  1033. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  1034. {
  1035. global $conf;
  1036. $path = preg_replace('/^\//', '', $path);
  1037. if (empty($type)) { // For a filesystem path
  1038. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  1039. if (is_array($conf->file->dol_document_root)) {
  1040. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  1041. if ($key == 'main') {
  1042. continue;
  1043. }
  1044. if (file_exists($dirroot.'/'.$path)) {
  1045. $res = $dirroot.'/'.$path;
  1046. return $res;
  1047. }
  1048. }
  1049. }
  1050. if ($returnemptyifnotfound) {
  1051. // Not found into alternate dir
  1052. if ($returnemptyifnotfound == 1 || !file_exists($res)) {
  1053. return '';
  1054. }
  1055. }
  1056. } else {
  1057. // For an url path
  1058. // We try to get local path of file on filesystem from url
  1059. // Note that trying to know if a file on disk exist by forging path on disk from url
  1060. // works only for some web server and some setup. This is bugged when
  1061. // using proxy, rewriting, virtual path, etc...
  1062. $res = '';
  1063. if ($type == 1) {
  1064. $res = DOL_URL_ROOT.'/'.$path; // Standard value
  1065. }
  1066. if ($type == 2) {
  1067. $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  1068. }
  1069. if ($type == 3) {
  1070. $res = DOL_URL_ROOT.'/'.$path;
  1071. }
  1072. foreach ($conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  1073. if ($key == 'main') {
  1074. if ($type == 3) {
  1075. global $dolibarr_main_url_root;
  1076. // Define $urlwithroot
  1077. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1078. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1079. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1080. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  1081. }
  1082. continue;
  1083. }
  1084. $regs = array();
  1085. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  1086. if (!empty($regs[1])) {
  1087. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  1088. if (file_exists($dirroot.'/'.$regs[1])) {
  1089. if ($type == 1) {
  1090. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1091. }
  1092. if ($type == 2) {
  1093. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  1094. }
  1095. if ($type == 3) {
  1096. global $dolibarr_main_url_root;
  1097. // Define $urlwithroot
  1098. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  1099. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  1100. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  1101. $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
  1102. }
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. }
  1108. return $res;
  1109. }
  1110. /**
  1111. * Create a clone of instance of object (new instance with same value for each properties)
  1112. * 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.
  1113. * 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.
  1114. * 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.
  1115. *
  1116. * @param object $object Object to clone
  1117. * @param int $native 0=Full isolation method, 1=Native PHP method, 2=Full isolation method keeping only scalar and array properties (recommended)
  1118. * @return object Clone object
  1119. * @see https://php.net/manual/language.oop5.cloning.php
  1120. */
  1121. function dol_clone($object, $native = 0)
  1122. {
  1123. if ($native == 0) {
  1124. // deprecated method, use the method with native = 2 instead
  1125. $tmpsavdb = null;
  1126. if (isset($object->db) && isset($object->db->db) && is_object($object->db->db) && get_class($object->db->db) == 'PgSql\Connection') {
  1127. $tmpsavdb = $object->db;
  1128. unset($object->db); // Such property can not be serialized with pgsl (when object->db->db = 'PgSql\Connection')
  1129. }
  1130. $myclone = unserialize(serialize($object)); // serialize then unserialize is a hack to be sure to have a new object for all fields
  1131. if (!empty($tmpsavdb)) {
  1132. $object->db = $tmpsavdb;
  1133. }
  1134. } elseif ($native == 2) {
  1135. // recommended method to have a full isolated cloned object
  1136. $myclone = new stdClass();
  1137. $tmparray = get_object_vars($object); // return only public properties
  1138. if (is_array($tmparray)) {
  1139. foreach ($tmparray as $propertykey => $propertyval) {
  1140. if (is_scalar($propertyval) || is_array($propertyval)) {
  1141. $myclone->$propertykey = $propertyval;
  1142. }
  1143. }
  1144. }
  1145. } else {
  1146. $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)
  1147. }
  1148. return $myclone;
  1149. }
  1150. /**
  1151. * Optimize a size for some browsers (phone, smarphone, ...)
  1152. *
  1153. * @param int $size Size we want
  1154. * @param string $type Type of optimizing:
  1155. * '' = function used to define a size for truncation
  1156. * 'width' = function is used to define a width
  1157. * @return int New size after optimizing
  1158. */
  1159. function dol_size($size, $type = '')
  1160. {
  1161. global $conf;
  1162. if (empty($conf->dol_optimize_smallscreen)) {
  1163. return $size;
  1164. }
  1165. if ($type == 'width' && $size > 250) {
  1166. return 250;
  1167. } else {
  1168. return 10;
  1169. }
  1170. }
  1171. /**
  1172. * Clean a string to use it as a file name.
  1173. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1174. *
  1175. * @param string $str String to clean
  1176. * @param string $newstr String to replace bad chars with.
  1177. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1178. * @return string String cleaned (a-zA-Z_)
  1179. *
  1180. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  1181. */
  1182. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  1183. {
  1184. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1185. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1186. // Char '/' and '\' are file delimiters.
  1187. // 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
  1188. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  1189. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1190. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1191. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1192. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1193. $tmp = str_replace('..', '', $tmp);
  1194. return $tmp;
  1195. }
  1196. /**
  1197. * Clean a string to use it as a path name.
  1198. * Replace also '--' and ' -' strings, they are used for parameters separation (Note: ' - ' is allowed).
  1199. *
  1200. * @param string $str String to clean
  1201. * @param string $newstr String to replace bad chars with
  1202. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  1203. * @return string String cleaned (a-zA-Z_)
  1204. *
  1205. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  1206. */
  1207. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  1208. {
  1209. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  1210. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  1211. // 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
  1212. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°', '$', ';');
  1213. $tmp = dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  1214. $tmp = preg_replace('/\-\-+/', '_', $tmp);
  1215. $tmp = preg_replace('/\s+\-([^\s])/', ' _$1', $tmp);
  1216. $tmp = preg_replace('/\s+\-$/', '', $tmp);
  1217. $tmp = str_replace('..', '', $tmp);
  1218. return $tmp;
  1219. }
  1220. /**
  1221. * Clean a string to use it as an URL (into a href or src attribute)
  1222. *
  1223. * @param string $stringtoclean String to clean
  1224. * @param int $type 0=Accept all Url, 1=Clean external Url (keep only relative Url)
  1225. * @return string Escaped string.
  1226. */
  1227. function dol_sanitizeUrl($stringtoclean, $type = 1)
  1228. {
  1229. // 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)
  1230. // We should use dol_string_nounprintableascii but function may not be yet loaded/available
  1231. $stringtoclean = preg_replace('/[\x00-\x1F\x7F]/u', '', $stringtoclean); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1232. // We clean html comments because some hacks try to obfuscate evil strings by inserting HTML comments. Example: on<!-- -->error=alert(1)
  1233. $stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  1234. $stringtoclean = str_replace('\\', '/', $stringtoclean);
  1235. if ($type == 1) {
  1236. // removing : should disable links to external url like http:aaa)
  1237. // removing ';' should disable "named" html entities encode into an url (we should not have this into an url)
  1238. $stringtoclean = str_replace(array(':', ';', '@'), '', $stringtoclean);
  1239. }
  1240. do {
  1241. $oldstringtoclean = $stringtoclean;
  1242. // removing '&colon' should disable links to external url like http:aaa)
  1243. // removing '&#' should disable "numeric" html entities encode into an url (we should not have this into an url)
  1244. $stringtoclean = str_ireplace(array('javascript', 'vbscript', '&colon', '&#'), '', $stringtoclean);
  1245. } while ($oldstringtoclean != $stringtoclean);
  1246. if ($type == 1) {
  1247. // removing '//' should disable links to external url like //aaa or http//)
  1248. $stringtoclean = preg_replace(array('/^[a-z]*\/\/+/i'), '', $stringtoclean);
  1249. }
  1250. return $stringtoclean;
  1251. }
  1252. /**
  1253. * Clean a string to use it as an Email.
  1254. *
  1255. * @param string $stringtoclean String to clean. Example 'abc@mycompany.com <My name>'
  1256. * @return string Escaped string.
  1257. */
  1258. function dol_sanitizeEmail($stringtoclean)
  1259. {
  1260. do {
  1261. $oldstringtoclean = $stringtoclean;
  1262. $stringtoclean = str_ireplace(array('"', ':', '[', ']',"\n", "\r", '\\', '\/'), '', $stringtoclean);
  1263. } while ($oldstringtoclean != $stringtoclean);
  1264. return $stringtoclean;
  1265. }
  1266. /**
  1267. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  1268. *
  1269. * @param string $str String to clean
  1270. * @return string Cleaned string
  1271. *
  1272. * @see dol_sanitizeFilename(), dol_string_nospecial()
  1273. */
  1274. function dol_string_unaccent($str)
  1275. {
  1276. global $conf;
  1277. if (is_null($str)) {
  1278. return '';
  1279. }
  1280. if (utf8_check($str)) {
  1281. if (extension_loaded('intl') && !empty($conf->global->MAIN_UNACCENT_USE_TRANSLITERATOR)) {
  1282. $transliterator = Transliterator::createFromRules(':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD);
  1283. return $transliterator->transliterate($str);
  1284. }
  1285. // See http://www.utf8-chartable.de/
  1286. $string = rawurlencode($str);
  1287. $replacements = array(
  1288. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  1289. '%C3%87' => 'C',
  1290. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  1291. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  1292. '%C3%91' => 'N',
  1293. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  1294. '%C5%A0' => 'S',
  1295. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  1296. '%C3%9D' => 'Y', '%C5%B8' => 'y',
  1297. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  1298. '%C3%A7' => 'c',
  1299. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  1300. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  1301. '%C3%B1' => 'n',
  1302. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  1303. '%C5%A1' => 's',
  1304. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  1305. '%C3%BD' => 'y', '%C3%BF' => 'y'
  1306. );
  1307. $string = strtr($string, $replacements);
  1308. return rawurldecode($string);
  1309. } else {
  1310. // See http://www.ascii-code.com/
  1311. $string = strtr(
  1312. $str,
  1313. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  1314. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  1315. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  1316. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  1317. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  1318. \xF9\xFA\xFB\xFC\xFD\xFF",
  1319. "AAAAAAC
  1320. EEEEIIIIDN
  1321. OOOOOUUUY
  1322. aaaaaaceeee
  1323. iiiidnooooo
  1324. uuuuyy"
  1325. );
  1326. $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"));
  1327. return $string;
  1328. }
  1329. }
  1330. /**
  1331. * Clean a string from all punctuation characters to use it as a ref or login.
  1332. * This is a more complete function than dol_sanitizeFileName().
  1333. *
  1334. * @param string $str String to clean
  1335. * @param string $newstr String to replace forbidden chars with
  1336. * @param array|string $badcharstoreplace Array of forbidden characters to replace. Use '' to keep default list.
  1337. * @param array|string $badcharstoremove Array of forbidden characters to remove. Use '' to keep default list.
  1338. * @param int $keepspaces 1=Do not treat space as a special char to replace or remove
  1339. * @return string Cleaned string
  1340. *
  1341. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  1342. */
  1343. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '', $badcharstoremove = '', $keepspaces = 0)
  1344. {
  1345. $forbidden_chars_to_replace = array("'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°', '$', ';'); // more complete than dol_sanitizeFileName
  1346. if (empty($keepspaces)) {
  1347. $forbidden_chars_to_replace[] = " ";
  1348. }
  1349. $forbidden_chars_to_remove = array();
  1350. //$forbidden_chars_to_remove=array("(",")");
  1351. if (is_array($badcharstoreplace)) {
  1352. $forbidden_chars_to_replace = $badcharstoreplace;
  1353. }
  1354. if (is_array($badcharstoremove)) {
  1355. $forbidden_chars_to_remove = $badcharstoremove;
  1356. }
  1357. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  1358. }
  1359. /**
  1360. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  1361. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  1362. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  1363. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  1364. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  1365. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  1366. * @param string $str String to clean
  1367. * @param int $removetabcrlf Remove also CR-LF
  1368. * @return string Cleaned string
  1369. *
  1370. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  1371. */
  1372. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  1373. {
  1374. if ($removetabcrlf) {
  1375. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  1376. } else {
  1377. 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
  1378. }
  1379. }
  1380. /**
  1381. * Returns text escaped for inclusion into javascript code
  1382. *
  1383. * @param string $stringtoescape String to escape
  1384. * @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 \
  1385. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  1386. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  1387. */
  1388. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  1389. {
  1390. if (is_null($stringtoescape)) {
  1391. return '';
  1392. }
  1393. // escape quotes and backslashes, newlines, etc.
  1394. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  1395. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  1396. if (empty($noescapebackslashn)) {
  1397. $substitjs["\n"] = '\\n';
  1398. $substitjs['\\'] = '\\\\';
  1399. }
  1400. if (empty($mode)) {
  1401. $substitjs["'"] = "\\'";
  1402. $substitjs['"'] = "\\'";
  1403. } elseif ($mode == 1) {
  1404. $substitjs["'"] = "\\'";
  1405. } elseif ($mode == 2) {
  1406. $substitjs['"'] = '\\"';
  1407. } elseif ($mode == 3) {
  1408. $substitjs["'"] = "\\'";
  1409. $substitjs['"'] = "\\\"";
  1410. }
  1411. return strtr($stringtoescape, $substitjs);
  1412. }
  1413. /**
  1414. * Returns text escaped for inclusion into javascript code
  1415. *
  1416. * @param string $stringtoescape String to escape
  1417. * @return string Escaped string for json content.
  1418. */
  1419. function dol_escape_json($stringtoescape)
  1420. {
  1421. return str_replace('"', '\"', $stringtoescape);
  1422. }
  1423. /**
  1424. * Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input fields.
  1425. *
  1426. * @param string $stringtoescape String to escape
  1427. * @param int $keepb 1=Keep b tags, 0=remove them completely
  1428. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  1429. * @param string $noescapetags '' or 'common' or list of tags to not escape. TODO Does not works yet when there is attributes into tag.
  1430. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1431. * @return string Escaped string
  1432. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent(), dol_htmlentitiesbr()
  1433. */
  1434. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $noescapetags = '', $escapeonlyhtmltags = 0)
  1435. {
  1436. if ($noescapetags == 'common') {
  1437. $noescapetags = 'html,body,a,b,em,hr,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1438. }
  1439. // escape quotes and backslashes, newlines, etc.
  1440. if ($escapeonlyhtmltags) {
  1441. $tmp = htmlspecialchars_decode((string) $stringtoescape, ENT_COMPAT);
  1442. } else {
  1443. $tmp = html_entity_decode((string) $stringtoescape, ENT_COMPAT, 'UTF-8');
  1444. }
  1445. if (!$keepb) {
  1446. $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1447. }
  1448. if (!$keepn) {
  1449. $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1450. }
  1451. if ($escapeonlyhtmltags) {
  1452. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1453. } else {
  1454. // Escape tags to keep
  1455. // TODO Does not works yet when there is attributes into tag
  1456. $tmparrayoftags = array();
  1457. if ($noescapetags) {
  1458. $tmparrayoftags = explode(',', $noescapetags);
  1459. }
  1460. if (count($tmparrayoftags)) {
  1461. foreach ($tmparrayoftags as $tagtoreplace) {
  1462. $tmp = str_ireplace('<'.$tagtoreplace.'>', '__BEGINTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1463. $tmp = str_ireplace('</'.$tagtoreplace.'>', '__ENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1464. $tmp = str_ireplace('<'.$tagtoreplace.' />', '__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', $tmp);
  1465. }
  1466. }
  1467. $result = htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1468. if (count($tmparrayoftags)) {
  1469. foreach ($tmparrayoftags as $tagtoreplace) {
  1470. $result = str_ireplace('__BEGINTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.'>', $result);
  1471. $result = str_ireplace('__ENDTAGTOREPLACE'.$tagtoreplace.'__', '</'.$tagtoreplace.'>', $result);
  1472. $result = str_ireplace('__BEGINENDTAGTOREPLACE'.$tagtoreplace.'__', '<'.$tagtoreplace.' />', $result);
  1473. }
  1474. }
  1475. return $result;
  1476. }
  1477. }
  1478. /**
  1479. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1480. *
  1481. * @param string $string String to encode
  1482. * @param string $encoding Character set encoding
  1483. * @return string String converted
  1484. */
  1485. function dol_strtolower($string, $encoding = "UTF-8")
  1486. {
  1487. if (function_exists('mb_strtolower')) {
  1488. return mb_strtolower($string, $encoding);
  1489. } else {
  1490. return strtolower($string);
  1491. }
  1492. }
  1493. /**
  1494. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1495. *
  1496. * @param string $string String to encode
  1497. * @param string $encoding Character set encoding
  1498. * @return string String converted
  1499. * @see dol_ucfirst(), dol_ucwords()
  1500. */
  1501. function dol_strtoupper($string, $encoding = "UTF-8")
  1502. {
  1503. if (function_exists('mb_strtoupper')) {
  1504. return mb_strtoupper($string, $encoding);
  1505. } else {
  1506. return strtoupper($string);
  1507. }
  1508. }
  1509. /**
  1510. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1511. *
  1512. * @param string $string String to encode
  1513. * @param string $encoding Character set encodign
  1514. * @return string String converted
  1515. * @see dol_strtoupper(), dol_ucwords()
  1516. */
  1517. function dol_ucfirst($string, $encoding = "UTF-8")
  1518. {
  1519. if (function_exists('mb_substr')) {
  1520. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1521. } else {
  1522. return ucfirst($string);
  1523. }
  1524. }
  1525. /**
  1526. * Convert first character of all the words of a string to upper.
  1527. *
  1528. * @param string $string String to encode
  1529. * @param string $encoding Character set encodign
  1530. * @return string String converted
  1531. * @see dol_strtoupper(), dol_ucfirst()
  1532. */
  1533. function dol_ucwords($string, $encoding = "UTF-8")
  1534. {
  1535. if (function_exists('mb_convert_case')) {
  1536. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1537. } else {
  1538. return ucwords($string);
  1539. }
  1540. }
  1541. /**
  1542. * Write log message into outputs. Possible outputs can be:
  1543. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1544. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1545. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1546. * this, use logging to files instead of syslog (see setup of module).
  1547. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1548. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1549. * This function works only if syslog module is enabled.
  1550. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1551. *
  1552. * @param string $message Line to log. ''=Show nothing
  1553. * @param int $level Log level
  1554. * 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
  1555. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_NOTICE=5, LOG_INFO=6, LOG_DEBUG=7
  1556. * @param int $ident 1=Increase ident of 1 (after log), -1=Decrease ident of 1 (before log)
  1557. * @param string $suffixinfilename When output is a file, append this suffix into default log filename. Example '_stripe', '_mail'
  1558. * @param string $restricttologhandler Force output of log only to this log handler
  1559. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1560. * @return void
  1561. */
  1562. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1563. {
  1564. global $conf, $user, $debugbar;
  1565. // If syslog module enabled
  1566. if (!isModEnabled('syslog')) {
  1567. return;
  1568. }
  1569. // Check if we are into execution of code of a website
  1570. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1571. global $website, $websitekey;
  1572. if (is_object($website) && !empty($website->ref)) {
  1573. $suffixinfilename .= '_website_'.$website->ref;
  1574. } elseif (!empty($websitekey)) {
  1575. $suffixinfilename .= '_website_'.$websitekey;
  1576. }
  1577. }
  1578. // Check if we have a forced suffix
  1579. if (defined('USESUFFIXINLOG')) {
  1580. $suffixinfilename .= constant('USESUFFIXINLOG');
  1581. }
  1582. if ($ident < 0) {
  1583. foreach ($conf->loghandlers as $loghandlerinstance) {
  1584. $loghandlerinstance->setIdent($ident);
  1585. }
  1586. }
  1587. if (!empty($message)) {
  1588. // Test log level
  1589. $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');
  1590. if (!array_key_exists($level, $logLevels)) {
  1591. throw new Exception('Incorrect log level');
  1592. }
  1593. if ($level > getDolGlobalInt('SYSLOG_LEVEL')) {
  1594. return;
  1595. }
  1596. if (empty($conf->global->MAIN_SHOW_PASSWORD_INTO_LOG)) {
  1597. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1598. }
  1599. // If adding log inside HTML page is required
  1600. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1601. || (!empty($user->rights->debugbar->read) && is_object($debugbar))) {
  1602. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1603. }
  1604. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1605. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1606. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
  1607. print "\n\n<!-- Log start\n";
  1608. print dol_escape_htmltag($message)."\n";
  1609. print "Log end -->\n";
  1610. }
  1611. $data = array(
  1612. 'message' => $message,
  1613. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1614. 'level' => $level,
  1615. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1616. 'ip' => false
  1617. );
  1618. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1619. if (!empty($remoteip)) {
  1620. $data['ip'] = $remoteip;
  1621. // This is when server run behind a reverse proxy
  1622. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) {
  1623. $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1624. } elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) {
  1625. $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1626. }
  1627. } elseif (!empty($_SERVER['SERVER_ADDR'])) {
  1628. // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1629. $data['ip'] = $_SERVER['SERVER_ADDR'];
  1630. } elseif (!empty($_SERVER['COMPUTERNAME'])) {
  1631. // 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).
  1632. $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1633. } elseif (!empty($_SERVER['LOGNAME'])) {
  1634. // 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).
  1635. $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1636. }
  1637. // Loop on each log handler and send output
  1638. foreach ($conf->loghandlers as $loghandlerinstance) {
  1639. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
  1640. continue;
  1641. }
  1642. $loghandlerinstance->export($data, $suffixinfilename);
  1643. }
  1644. unset($data);
  1645. }
  1646. if ($ident > 0) {
  1647. foreach ($conf->loghandlers as $loghandlerinstance) {
  1648. $loghandlerinstance->setIdent($ident);
  1649. }
  1650. }
  1651. }
  1652. /**
  1653. * Return HTML code to output a button to open a dialog popup box.
  1654. * Such buttons must be included inside a HTML form.
  1655. *
  1656. * @param string $name A name for the html component
  1657. * @param string $label Label shown in Popup title top bar
  1658. * @param string $buttonstring button string (HTML text we can click on)
  1659. * @param string $url Relative Url to open. For example '/project/card.php'
  1660. * @param string $disabled Disabled text
  1661. * @param string $morecss More CSS
  1662. * @param string $jsonopen Some JS code to execute on click/open of popup
  1663. * @param string $backtopagejsfields The back to page must be managed using javascript instead of a redirect.
  1664. * Value is 'keyforpopupid:Name_of_html_component_to_set_with id,Name_of_html_component_to_set_with_label'
  1665. * @param string $accesskey A key to use shortcut
  1666. * @return string HTML component with button
  1667. */
  1668. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '', $morecss = 'classlink button bordertransp', $jsonopen = '', $backtopagejsfields = '', $accesskey = '')
  1669. {
  1670. global $conf;
  1671. if (strpos($url, '?') > 0) {
  1672. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1673. } else {
  1674. $url .= '?dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup='.urlencode($name);
  1675. }
  1676. $out = '';
  1677. $backtopagejsfieldsid = ''; $backtopagejsfieldslabel = '';
  1678. if ($backtopagejsfields) {
  1679. $tmpbacktopagejsfields = explode(':', $backtopagejsfields);
  1680. if (empty($tmpbacktopagejsfields[1])) { // If the part 'keyforpopupid:' is missing, we add $name for it.
  1681. $backtopagejsfields = $name.":".$backtopagejsfields;
  1682. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[0]);
  1683. } else {
  1684. $tmp2backtopagejsfields = explode(',', $tmpbacktopagejsfields[1]);
  1685. }
  1686. $backtopagejsfieldsid = empty($tmp2backtopagejsfields[0]) ? '' : $tmp2backtopagejsfields[0];
  1687. $backtopagejsfieldslabel = empty($tmp2backtopagejsfields[1]) ? '' : $tmp2backtopagejsfields[1];
  1688. $url .= '&backtopagejsfields='.urlencode($backtopagejsfields);
  1689. }
  1690. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1691. $out .= '<!-- a link for button to open url into a dialog popup with backtopagejsfields = '.$backtopagejsfields.' -->';
  1692. $out .= '<a '.($accesskey ? ' accesskey="'.$accesskey.'"' : '').' class="cursorpointer reposition button_'.$name.($morecss ? ' '.$morecss : '').'"'.$disabled.' title="'.dol_escape_htmltag($label).'"';
  1693. if (empty($conf->use_javascript_ajax)) {
  1694. $out .= ' href="'.DOL_URL_ROOT.$url.'" target="_blank"';
  1695. } elseif ($jsonopen) {
  1696. $out .= ' href="#" onclick="'.$jsonopen.'"';
  1697. } else {
  1698. $out .= ' href="#"';
  1699. }
  1700. $out .= '>'.$buttonstring.'</a>';
  1701. if (!empty($conf->use_javascript_ajax)) {
  1702. // Add code to open url using the popup. Add also hidden field to retreive the returned variables
  1703. $out .= '<!-- code to open popup and variables to retreive returned variables -->';
  1704. $out .= '<div id="idfordialog'.$name.'" class="hidden">div for dialog</div>';
  1705. $out .= '<div id="varforreturndialogid'.$name.'" class="hidden">div for returned id</div>';
  1706. $out .= '<div id="varforreturndialoglabel'.$name.'" class="hidden">div for returned label</div>';
  1707. $out .= '<!-- Add js code to open dialog popup on dialog -->';
  1708. $out .= '<script nonce="'.getNonce().'" type="text/javascript">
  1709. jQuery(document).ready(function () {
  1710. jQuery(".button_'.$name.'").click(function () {
  1711. console.log(\'Open popup with jQuery(...).dialog() on URL '.dol_escape_js(DOL_URL_ROOT.$url).'\');
  1712. var $tmpdialog = $(\'#idfordialog'.$name.'\');
  1713. $tmpdialog.html(\'<iframe class="iframedialog" id="iframedialog'.$name.'" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\');
  1714. $tmpdialog.dialog({
  1715. autoOpen: false,
  1716. modal: true,
  1717. height: (window.innerHeight - 150),
  1718. width: \'80%\',
  1719. title: \''.dol_escape_js($label).'\',
  1720. open: function (event, ui) {
  1721. console.log("open popup name='.$name.', backtopagejsfields='.$backtopagejsfields.'");
  1722. },
  1723. close: function (event, ui) {
  1724. var returnedid = jQuery("#varforreturndialogid'.$name.'").text();
  1725. var returnedlabel = jQuery("#varforreturndialoglabel'.$name.'").text();
  1726. console.log("popup has been closed. returnedid (js var defined into parent page)="+returnedid+" returnedlabel="+returnedlabel);
  1727. if (returnedid != "" && returnedid != "div for returned id") {
  1728. jQuery("#'.(empty($backtopagejsfieldsid)?"none":$backtopagejsfieldsid).'").val(returnedid);
  1729. }
  1730. if (returnedlabel != "" && returnedlabel != "div for returned label") {
  1731. jQuery("#'.(empty($backtopagejsfieldslabel)?"none":$backtopagejsfieldslabel).'").val(returnedlabel);
  1732. }
  1733. }
  1734. });
  1735. $tmpdialog.dialog(\'open\');
  1736. return false;
  1737. });
  1738. });
  1739. </script>';
  1740. }
  1741. return $out;
  1742. }
  1743. /**
  1744. * Show tab header of a card
  1745. *
  1746. * @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.
  1747. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1748. * @param string $title Title
  1749. * @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
  1750. * @param string $picto Add a picto on tab title
  1751. * @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.
  1752. * @param string $morehtmlright Add more html content on right of tabs title
  1753. * @param string $morecss More Css
  1754. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1755. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1756. * @return void
  1757. * @deprecated Use print dol_get_fiche_head() instead
  1758. */
  1759. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1760. {
  1761. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1762. }
  1763. /**
  1764. * Show tabs of a record
  1765. *
  1766. * @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.
  1767. * @param string $active Active tab name
  1768. * @param string $title Title
  1769. * @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'
  1770. * @param string $picto Add a picto on tab title
  1771. * @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.
  1772. * @param string $morehtmlright Add more html content on right of tabs title
  1773. * @param string $morecss More CSS on the link <a>
  1774. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1775. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1776. * @param int $dragdropfile 0 (default) or 1. 1 enable a drop zone for file to be upload, 0 disable it
  1777. * @return string
  1778. */
  1779. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '', $dragdropfile = 0)
  1780. {
  1781. global $conf, $langs, $hookmanager;
  1782. // Show title
  1783. $showtitle = 1;
  1784. if (!empty($conf->dol_optimize_smallscreen)) {
  1785. $showtitle = 0;
  1786. }
  1787. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1788. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1789. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1790. }
  1791. // Show right part
  1792. if ($morehtmlright) {
  1793. $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.
  1794. }
  1795. // Show title
  1796. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1797. $limittitle = 30;
  1798. $out .= '<a class="tabTitle">';
  1799. if ($picto) {
  1800. $noprefix = $pictoisfullpath;
  1801. if (strpos($picto, 'fontawesome_') !== false) {
  1802. $noprefix = 1;
  1803. }
  1804. $out .= img_picto($title, ($noprefix ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1805. }
  1806. $out .= '<span class="tabTitleText">'.dol_escape_htmltag(dol_trunc($title, $limittitle)).'</span>';
  1807. $out .= '</a>';
  1808. }
  1809. // Show tabs
  1810. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1811. $maxkey = -1;
  1812. if (is_array($links) && !empty($links)) {
  1813. $keys = array_keys($links);
  1814. if (count($keys)) {
  1815. $maxkey = max($keys);
  1816. }
  1817. }
  1818. // Show tabs
  1819. // if =0 we don't use the feature
  1820. if (empty($limittoshow)) {
  1821. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1822. }
  1823. if (!empty($conf->dol_optimize_smallscreen)) {
  1824. $limittoshow = 2;
  1825. }
  1826. $displaytab = 0;
  1827. $nbintab = 0;
  1828. $popuptab = 0;
  1829. $outmore = '';
  1830. for ($i = 0; $i <= $maxkey; $i++) {
  1831. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1832. // If active tab is already present
  1833. if ($i >= $limittoshow) {
  1834. $limittoshow--;
  1835. }
  1836. }
  1837. }
  1838. for ($i = 0; $i <= $maxkey; $i++) {
  1839. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1840. $isactive = true;
  1841. } else {
  1842. $isactive = false;
  1843. }
  1844. if ($i < $limittoshow || $isactive) {
  1845. // Output entry with a visible tab
  1846. $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])).' -->';
  1847. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1848. if (!empty($links[$i][0])) {
  1849. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1850. } else {
  1851. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1852. }
  1853. } elseif (!empty($links[$i][1])) {
  1854. //print "x $i $active ".$links[$i][2]." z";
  1855. $out .= '<div class="tab tab'.($isactive?'active':'unactive').'" style="margin: 0 !important">';
  1856. if (!empty($links[$i][0])) {
  1857. $titletoshow = preg_replace('/<.*$/', '', $links[$i][1]);
  1858. $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).'">';
  1859. }
  1860. $out .= $links[$i][1];
  1861. if (!empty($links[$i][0])) {
  1862. $out .= '</a>'."\n";
  1863. }
  1864. $out .= empty($links[$i][4]) ? '' : $links[$i][4];
  1865. $out .= '</div>';
  1866. }
  1867. $out .= '</div>';
  1868. } else {
  1869. // Add entry into the combo popup with the other tabs
  1870. if (!$popuptab) {
  1871. $popuptab = 1;
  1872. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1873. }
  1874. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1875. if (isset($links[$i][2]) && $links[$i][2] == 'image') {
  1876. if (!empty($links[$i][0])) {
  1877. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1878. } else {
  1879. $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1880. }
  1881. } elseif (!empty($links[$i][1])) {
  1882. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1883. $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.
  1884. $outmore .= '</a>'."\n";
  1885. }
  1886. $outmore .= '</div>';
  1887. $nbintab++;
  1888. }
  1889. $displaytab = $i;
  1890. }
  1891. if ($popuptab) {
  1892. $outmore .= '</div>';
  1893. }
  1894. if ($popuptab) { // If there is some tabs not shown
  1895. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1896. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1897. $widthofpopup = 200;
  1898. $tabsname = $moretabssuffix;
  1899. if (empty($tabsname)) {
  1900. $tabsname = str_replace("@", "", $picto);
  1901. }
  1902. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem valignmiddle">';
  1903. $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".
  1904. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1905. $out .= $outmore;
  1906. $out .= '</div>';
  1907. $out .= '<div></div>';
  1908. $out .= "</div>\n";
  1909. $out .= '<script nonce="'.getNonce().'">';
  1910. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1911. var x = this.offsetLeft, y = this.offsetTop;
  1912. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1913. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1914. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1915. }
  1916. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1917. });
  1918. ";
  1919. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1920. $out .= "</script>";
  1921. }
  1922. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1923. $out .= "</div>\n";
  1924. }
  1925. if (!$notab || $notab == -1 || $notab == -2 || $notab == -3) {
  1926. $out .= "\n".'<div id="dragDropAreaTabBar" class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : (($notab == -3 ? ' noborderbottom' : '').' tabBarWithBottom'))).'">'."\n";
  1927. }
  1928. if (!empty($dragdropfile)) {
  1929. $out .= dragAndDropFileUpload("dragDropAreaTabBar");
  1930. }
  1931. $parameters = array('tabname' => $active, 'out' => $out);
  1932. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1933. if ($reshook > 0) {
  1934. $out = $hookmanager->resPrint;
  1935. }
  1936. return $out;
  1937. }
  1938. /**
  1939. * Show tab footer of a card
  1940. *
  1941. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1942. * @return void
  1943. * @deprecated Use print dol_get_fiche_end() instead
  1944. */
  1945. function dol_fiche_end($notab = 0)
  1946. {
  1947. print dol_get_fiche_end($notab);
  1948. }
  1949. /**
  1950. * Return tab footer of a card
  1951. *
  1952. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1953. * @return string
  1954. */
  1955. function dol_get_fiche_end($notab = 0)
  1956. {
  1957. if (!$notab || $notab == -1) {
  1958. return "\n</div>\n";
  1959. } else {
  1960. return '';
  1961. }
  1962. }
  1963. /**
  1964. * Show tab footer of a card.
  1965. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1966. *
  1967. * @param Object $object Object to show
  1968. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1969. * @param string $morehtml More html content to output just before the nav bar
  1970. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1971. * @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.
  1972. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1973. * @param string $morehtmlref More html to show after the ref (see $morehtmlleft for before)
  1974. * @param string $moreparam More param to add in nav link url.
  1975. * @param int $nodbprefix Do not include DB prefix to forge table name
  1976. * @param string $morehtmlleft More html code to show before the ref (see $morehtmlref for after)
  1977. * @param string $morehtmlstatus More html code to show under navigation arrows
  1978. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1979. * @param string $morehtmlright More html code to show before navigation arrows
  1980. * @return void
  1981. */
  1982. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1983. {
  1984. global $conf, $form, $user, $langs, $hookmanager, $action;
  1985. $error = 0;
  1986. $maxvisiblephotos = 1;
  1987. $showimage = 1;
  1988. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1989. $showbarcode = empty($conf->barcode->enabled) ? 0 : (empty($object->barcode) ? 0 : 1);
  1990. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
  1991. $showbarcode = 0;
  1992. }
  1993. $modulepart = 'unknown';
  1994. if ($object->element == 'societe' || $object->element == 'contact' || $object->element == 'product' || $object->element == 'ticket') {
  1995. $modulepart = $object->element;
  1996. } elseif ($object->element == 'member') {
  1997. $modulepart = 'memberphoto';
  1998. } elseif ($object->element == 'user') {
  1999. $modulepart = 'userphoto';
  2000. }
  2001. if (class_exists("Imagick")) {
  2002. if ($object->element == 'expensereport' || $object->element == 'propal' || $object->element == 'commande' || $object->element == 'facture' || $object->element == 'supplier_proposal') {
  2003. $modulepart = $object->element;
  2004. } elseif ($object->element == 'fichinter') {
  2005. $modulepart = 'ficheinter';
  2006. } elseif ($object->element == 'contrat') {
  2007. $modulepart = 'contract';
  2008. } elseif ($object->element == 'order_supplier') {
  2009. $modulepart = 'supplier_order';
  2010. } elseif ($object->element == 'invoice_supplier') {
  2011. $modulepart = 'supplier_invoice';
  2012. }
  2013. }
  2014. if ($object->element == 'product') {
  2015. $width = 80;
  2016. $cssclass = 'photowithmargin photoref';
  2017. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  2018. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  2019. if ($conf->browser->layout == 'phone') {
  2020. $maxvisiblephotos = 1;
  2021. }
  2022. if ($showimage) {
  2023. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, 0, $width, 0, '').'</div>';
  2024. } else {
  2025. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  2026. $nophoto = '';
  2027. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2028. } else { // Show no photo link
  2029. $nophoto = '/public/theme/common/nophoto.png';
  2030. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" title="'.dol_escape_htmltag($langs->trans("UploadAnImageToSeeAPhotoHere", $langs->transnoentitiesnoconv("Documents"))).'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  2031. }
  2032. }
  2033. } elseif ($object->element == 'ticket') {
  2034. $width = 80;
  2035. $cssclass = 'photoref';
  2036. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  2037. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  2038. if ($conf->browser->layout == 'phone') {
  2039. $maxvisiblephotos = 1;
  2040. }
  2041. if ($showimage) {
  2042. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  2043. if ($object->nbphoto > 0) {
  2044. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  2045. } else {
  2046. $showimage = 0;
  2047. }
  2048. }
  2049. if (!$showimage) {
  2050. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  2051. $nophoto = '';
  2052. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  2053. } else { // Show no photo link
  2054. $nophoto = img_picto('No photo', 'object_ticket');
  2055. $morehtmlleft .= '<!-- No photo to show -->';
  2056. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2057. $morehtmlleft .= $nophoto;
  2058. $morehtmlleft .= '</div></div>';
  2059. }
  2060. }
  2061. } else {
  2062. if ($showimage) {
  2063. if ($modulepart != 'unknown') {
  2064. $phototoshow = '';
  2065. // Check if a preview file is available
  2066. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
  2067. $objectref = dol_sanitizeFileName($object->ref);
  2068. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  2069. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
  2070. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  2071. $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
  2072. } else {
  2073. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  2074. }
  2075. if (empty($subdir)) {
  2076. $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  2077. }
  2078. $filepath = $dir_output.$subdir."/";
  2079. $filepdf = $filepath.$objectref.".pdf";
  2080. $relativepath = $subdir.'/'.$objectref.'.pdf';
  2081. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  2082. $fileimage = $filepdf.'_preview.png';
  2083. $relativepathimage = $relativepath.'_preview.png';
  2084. $pdfexists = file_exists($filepdf);
  2085. // If PDF file exists
  2086. if ($pdfexists) {
  2087. // Conversion du PDF en image png si fichier png non existant
  2088. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) {
  2089. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  2090. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2091. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  2092. if ($ret < 0) {
  2093. $error++;
  2094. }
  2095. }
  2096. }
  2097. }
  2098. if ($pdfexists && !$error) {
  2099. $heightforphotref = 80;
  2100. if (!empty($conf->dol_optimize_smallscreen)) {
  2101. $heightforphotref = 60;
  2102. }
  2103. // If the preview file is found
  2104. if (file_exists($fileimage)) {
  2105. $phototoshow = '<div class="photoref">';
  2106. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  2107. $phototoshow .= '</div>';
  2108. }
  2109. }
  2110. } elseif (!$phototoshow) { // example if modulepart = 'societe' or 'photo'
  2111. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, $maxvisiblephotos);
  2112. }
  2113. if ($phototoshow) {
  2114. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  2115. $morehtmlleft .= $phototoshow;
  2116. $morehtmlleft .= '</div>';
  2117. }
  2118. }
  2119. if (empty($phototoshow)) { // Show No photo link (picto of object)
  2120. if ($object->element == 'action') {
  2121. $width = 80;
  2122. $cssclass = 'photorefcenter';
  2123. $nophoto = img_picto('No photo', 'title_agenda');
  2124. } else {
  2125. $width = 14;
  2126. $cssclass = 'photorefcenter';
  2127. $picto = $object->picto;
  2128. $prefix = 'object_';
  2129. if ($object->element == 'project' && !$object->public) {
  2130. $picto = 'project'; // instead of projectpub
  2131. }
  2132. if (strpos($picto, 'fontawesome_') !== false) {
  2133. $prefix = '';
  2134. }
  2135. $nophoto = img_picto('No photo', $prefix.$picto);
  2136. }
  2137. $morehtmlleft .= '<!-- No photo to show -->';
  2138. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  2139. $morehtmlleft .= $nophoto;
  2140. $morehtmlleft .= '</div></div>';
  2141. }
  2142. }
  2143. }
  2144. // Show barcode
  2145. if ($showbarcode) {
  2146. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object, 100, 'photoref valignmiddle').'</div>';
  2147. }
  2148. if ($object->element == 'societe') {
  2149. if (!empty($conf->use_javascript_ajax) && $user->hasRight('societe', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2150. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  2151. } else {
  2152. $morehtmlstatus .= $object->getLibStatut(6);
  2153. }
  2154. } elseif ($object->element == 'product') {
  2155. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  2156. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2157. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  2158. } else {
  2159. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  2160. }
  2161. $morehtmlstatus .= ' &nbsp; ';
  2162. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  2163. if (!empty($conf->use_javascript_ajax) && $user->hasRight('produit', 'creer') && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  2164. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  2165. } else {
  2166. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  2167. }
  2168. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan', 'tva', 'salary'))) {
  2169. $tmptxt = $object->getLibStatut(6, $object->totalpaid);
  2170. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2171. $tmptxt = $object->getLibStatut(5, $object->totalpaid);
  2172. }
  2173. $morehtmlstatus .= $tmptxt;
  2174. } elseif ($object->element == 'contrat' || $object->element == 'contract') {
  2175. if ($object->statut == 0) {
  2176. $morehtmlstatus .= $object->getLibStatut(5);
  2177. } else {
  2178. $morehtmlstatus .= $object->getLibStatut(4);
  2179. }
  2180. } elseif ($object->element == 'facturerec') {
  2181. if ($object->frequency == 0) {
  2182. $morehtmlstatus .= $object->getLibStatut(2);
  2183. } else {
  2184. $morehtmlstatus .= $object->getLibStatut(5);
  2185. }
  2186. } elseif ($object->element == 'project_task') {
  2187. $object->fk_statut = 1;
  2188. if ($object->progress > 0) {
  2189. $object->fk_statut = 2;
  2190. }
  2191. if ($object->progress >= 100) {
  2192. $object->fk_statut = 3;
  2193. }
  2194. $tmptxt = $object->getLibStatut(5);
  2195. $morehtmlstatus .= $tmptxt; // No status on task
  2196. } elseif (method_exists($object, 'getLibStatut')) { // Generic case
  2197. $tmptxt = $object->getLibStatut(6);
  2198. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) {
  2199. $tmptxt = $object->getLibStatut(5);
  2200. }
  2201. $morehtmlstatus .= $tmptxt;
  2202. }
  2203. // Add if object was dispatched "into accountancy"
  2204. if (isModEnabled('accounting') && in_array($object->element, array('bank', 'paiementcharge', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various'))) {
  2205. // Note: For 'chargesociales', 'salaries'... this is the payments that are dispatched (so element = 'bank')
  2206. if (method_exists($object, 'getVentilExportCompta')) {
  2207. $accounted = $object->getVentilExportCompta();
  2208. $langs->load("accountancy");
  2209. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  2210. }
  2211. }
  2212. // Add alias for thirdparty
  2213. if (!empty($object->name_alias)) {
  2214. $morehtmlref .= '<div class="refidno opacitymedium">'.dol_escape_htmltag($object->name_alias).'</div>';
  2215. }
  2216. // Add label
  2217. if (in_array($object->element, array('product', 'bank_account', 'project_task'))) {
  2218. if (!empty($object->label)) {
  2219. $morehtmlref .= '<div class="refidno opacitymedium">'.$object->label.'</div>';
  2220. }
  2221. }
  2222. // Show address and email
  2223. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files'))) {
  2224. $moreaddress = $object->getBannerAddress('refaddress', $object);
  2225. if ($moreaddress) {
  2226. $morehtmlref .= '<div class="refidno refaddress">';
  2227. $morehtmlref .= $moreaddress;
  2228. $morehtmlref .= '</div>';
  2229. }
  2230. }
  2231. 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)) {
  2232. $morehtmlref .= '<div style="clear: both;"></div>';
  2233. $morehtmlref .= '<div class="refidno opacitymedium">';
  2234. $morehtmlref .= $langs->trans("TechnicalID").': '.((int) $object->id);
  2235. $morehtmlref .= '</div>';
  2236. }
  2237. $parameters=array('morehtmlref'=>$morehtmlref);
  2238. $reshook = $hookmanager->executeHooks('formDolBanner', $parameters, $object, $action);
  2239. if ($reshook < 0) {
  2240. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2241. } elseif (empty($reshook)) {
  2242. $morehtmlref .= $hookmanager->resPrint;
  2243. } elseif ($reshook > 0) {
  2244. $morehtmlref = $hookmanager->resPrint;
  2245. }
  2246. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  2247. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  2248. print '</div>';
  2249. print '<div class="underrefbanner clearboth"></div>';
  2250. }
  2251. /**
  2252. * Show a string with the label tag dedicated to the HTML edit field.
  2253. *
  2254. * @param string $langkey Translation key
  2255. * @param string $fieldkey Key of the html select field the text refers to
  2256. * @param int $fieldrequired 1=Field is mandatory
  2257. * @return string
  2258. * @deprecated Form::editfieldkey
  2259. */
  2260. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  2261. {
  2262. global $langs;
  2263. $ret = '';
  2264. if ($fieldrequired) {
  2265. $ret .= '<span class="fieldrequired">';
  2266. }
  2267. $ret .= '<label for="'.$fieldkey.'">';
  2268. $ret .= $langs->trans($langkey);
  2269. $ret .= '</label>';
  2270. if ($fieldrequired) {
  2271. $ret .= '</span>';
  2272. }
  2273. return $ret;
  2274. }
  2275. /**
  2276. * Return string to add class property on html element with pair/impair.
  2277. *
  2278. * @param string $var 0 or 1
  2279. * @param string $moreclass More class to add
  2280. * @return string String to add class onto HTML element
  2281. */
  2282. function dol_bc($var, $moreclass = '')
  2283. {
  2284. global $bc;
  2285. $ret = ' '.$bc[$var];
  2286. if ($moreclass) {
  2287. $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  2288. }
  2289. return $ret;
  2290. }
  2291. /**
  2292. * Return a formated address (part address/zip/town/state) according to country rules.
  2293. * See https://en.wikipedia.org/wiki/Address
  2294. *
  2295. * @param Object $object A company or contact object
  2296. * @param int $withcountry 1=Add country into address string
  2297. * @param string $sep Separator to use to build string
  2298. * @param Translate $outputlangs Object lang that contains language for text translation.
  2299. * @param int $mode 0=Standard output, 1=Remove address
  2300. * @param string $extralangcode User extralanguage $langcode as values for address, town
  2301. * @return string Formated string
  2302. * @see dol_print_address()
  2303. */
  2304. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  2305. {
  2306. global $conf, $langs, $hookmanager;
  2307. $ret = '';
  2308. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR', 'CN'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  2309. // See format of addresses on https://en.wikipedia.org/wiki/Address
  2310. // Address
  2311. if (empty($mode)) {
  2312. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : (empty($object->address) ? '' : $object->address));
  2313. }
  2314. // Zip/Town/State
  2315. if (isset($object->country_code) && in_array($object->country_code, array('AU', 'CA', 'US', 'CN')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {
  2316. // US: title firstname name \n address lines \n town, state, zip \n country
  2317. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2318. $ret .= (($ret && $town) ? $sep : '').$town;
  2319. if (!empty($object->state)) {
  2320. $ret .= ($ret ? ($town ? ", " : $sep) : '').$object->state;
  2321. }
  2322. if (!empty($object->zip)) {
  2323. $ret .= ($ret ? (($town || $object->state) ? ", " : $sep) : '').$object->zip;
  2324. }
  2325. } elseif (isset($object->country_code) && in_array($object->country_code, array('GB', 'UK'))) {
  2326. // UK: title firstname name \n address lines \n town state \n zip \n country
  2327. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2328. $ret .= ($ret ? $sep : '').$town;
  2329. if (!empty($object->state)) {
  2330. $ret .= ($ret ? ", " : '').$object->state;
  2331. }
  2332. if (!empty($object->zip)) {
  2333. $ret .= ($ret ? $sep : '').$object->zip;
  2334. }
  2335. } elseif (isset($object->country_code) && in_array($object->country_code, array('ES', 'TR'))) {
  2336. // ES: title firstname name \n address lines \n zip town \n state \n country
  2337. $ret .= ($ret ? $sep : '').$object->zip;
  2338. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2339. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2340. if (!empty($object->state)) {
  2341. $ret .= "\n".$object->state;
  2342. }
  2343. } elseif (isset($object->country_code) && in_array($object->country_code, array('JP'))) {
  2344. // JP: In romaji, title firstname name\n address lines \n [state,] town zip \n country
  2345. // See https://www.sljfaq.org/afaq/addresses.html
  2346. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2347. $ret .= ($ret ? $sep : '').($object->state ? $object->state.', ' : '').$town.($object->zip ? ' ' : '').$object->zip;
  2348. } elseif (isset($object->country_code) && in_array($object->country_code, array('IT'))) {
  2349. // IT: title firstname name\n address lines \n zip town state_code \n country
  2350. $ret .= ($ret ? $sep : '').$object->zip;
  2351. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2352. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  2353. $ret .= (empty($object->state_code) ? '' : (' '.$object->state_code));
  2354. } else {
  2355. // Other: title firstname name \n address lines \n zip town[, state] \n country
  2356. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : (empty($object->town) ? '' : $object->town));
  2357. $ret .= !empty($object->zip) ? (($ret ? $sep : '').$object->zip) : '';
  2358. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  2359. if (!empty($object->state) && in_array($object->country_code, $countriesusingstate)) {
  2360. $ret .= ($ret ? ", " : '').$object->state;
  2361. }
  2362. }
  2363. if (!is_object($outputlangs)) {
  2364. $outputlangs = $langs;
  2365. }
  2366. if ($withcountry) {
  2367. $langs->load("dict");
  2368. $ret .= (empty($object->country_code) ? '' : ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)));
  2369. }
  2370. if ($hookmanager) {
  2371. $parameters = array('withcountry' => $withcountry, 'sep' => $sep, 'outputlangs' => $outputlangs,'mode' => $mode, 'extralangcode' => $extralangcode);
  2372. $reshook = $hookmanager->executeHooks('formatAddress', $parameters, $object);
  2373. if ($reshook > 0) {
  2374. $ret = '';
  2375. }
  2376. $ret .= $hookmanager->resPrint;
  2377. }
  2378. return $ret;
  2379. }
  2380. /**
  2381. * Format a string.
  2382. *
  2383. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  2384. * @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)
  2385. * @param int $is_gmt See comment of timestamp parameter
  2386. * @return string A formatted string
  2387. */
  2388. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  2389. {
  2390. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  2391. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  2392. } else {
  2393. return 'Error date into a not supported range';
  2394. }
  2395. }
  2396. /**
  2397. * Output date in a string format according to outputlangs (or langs if not defined).
  2398. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  2399. *
  2400. * @param int $time GM Timestamps date
  2401. * @param string $format Output date format (tag of strftime function)
  2402. * "%d %b %Y",
  2403. * "%d/%m/%Y %H:%M",
  2404. * "%d/%m/%Y %H:%M:%S",
  2405. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  2406. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...inputnoreduce", "...reduceformat"
  2407. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  2408. * false or 'tzserver' => output string is for local PHP server TZ usage
  2409. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  2410. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position)
  2411. * @param Translate $outputlangs Object lang that contains language for text translation.
  2412. * @param boolean $encodetooutput false=no convert into output pagecode
  2413. * @return string Formated date or '' if time is null
  2414. *
  2415. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  2416. */
  2417. function dol_print_date($time, $format = '', $tzoutput = 'auto', $outputlangs = '', $encodetooutput = false)
  2418. {
  2419. global $conf, $langs;
  2420. // If date undefined or "", we return ""
  2421. if (dol_strlen($time) == 0) {
  2422. return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  2423. }
  2424. if ($tzoutput === 'auto') {
  2425. $tzoutput = (empty($conf) ? 'tzserver' : (isset($conf->tzuserinputkey) ? $conf->tzuserinputkey : 'tzserver'));
  2426. }
  2427. // Clean parameters
  2428. $to_gmt = false;
  2429. $offsettz = $offsetdst = 0;
  2430. if ($tzoutput) {
  2431. $to_gmt = true; // For backward compatibility
  2432. if (is_string($tzoutput)) {
  2433. if ($tzoutput == 'tzserver') {
  2434. $to_gmt = false;
  2435. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2436. $offsettz = 0; // Timezone offset with server timezone (because to_gmt is false), so 0
  2437. $offsetdst = 0; // Dst offset with server timezone (because to_gmt is false), so 0
  2438. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
  2439. $to_gmt = true;
  2440. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  2441. if (class_exists('DateTimeZone')) {
  2442. $user_date_tz = new DateTimeZone($offsettzstring);
  2443. $user_dt = new DateTime();
  2444. $user_dt->setTimezone($user_date_tz);
  2445. $user_dt->setTimestamp($tzoutput == 'tzuser' ? dol_now() : (int) $time);
  2446. $offsettz = $user_dt->getOffset(); // should include dst ?
  2447. } else { // with old method (The 'tzuser' was processed like the 'tzuserrel')
  2448. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  2449. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  2450. }
  2451. }
  2452. }
  2453. }
  2454. if (!is_object($outputlangs)) {
  2455. $outputlangs = $langs;
  2456. }
  2457. if (!$format) {
  2458. $format = 'daytextshort';
  2459. }
  2460. // Do we have to reduce the length of date (year on 2 chars) to save space.
  2461. // Note: dayinputnoreduce is same than day but no reduction of year length will be done
  2462. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0; // Test on original $format param.
  2463. $format = preg_replace('/inputnoreduce/', '', $format); // so format 'dayinputnoreduce' is processed like day
  2464. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  2465. if ($formatwithoutreduce != $format) {
  2466. $format = $formatwithoutreduce;
  2467. $reduceformat = 1;
  2468. } // so format 'dayreduceformat' is processed like day
  2469. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  2470. // TODO Add format daysmallyear and dayhoursmallyear
  2471. if ($format == 'day') {
  2472. $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  2473. } elseif ($format == 'hour') {
  2474. $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  2475. } elseif ($format == 'hourduration') {
  2476. $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  2477. } elseif ($format == 'daytext') {
  2478. $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  2479. } elseif ($format == 'daytextshort') {
  2480. $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  2481. } elseif ($format == 'dayhour') {
  2482. $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  2483. } elseif ($format == 'dayhoursec') {
  2484. $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  2485. } elseif ($format == 'dayhourtext') {
  2486. $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  2487. } elseif ($format == 'dayhourtextshort') {
  2488. $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  2489. } elseif ($format == 'dayhourlog') {
  2490. // Format not sensitive to language
  2491. $format = '%Y%m%d%H%M%S';
  2492. } elseif ($format == 'dayhourlogsmall') {
  2493. // Format not sensitive to language
  2494. $format = '%y%m%d%H%M';
  2495. } elseif ($format == 'dayhourldap') {
  2496. $format = '%Y%m%d%H%M%SZ';
  2497. } elseif ($format == 'dayhourxcard') {
  2498. $format = '%Y%m%dT%H%M%SZ';
  2499. } elseif ($format == 'dayxcard') {
  2500. $format = '%Y%m%d';
  2501. } elseif ($format == 'dayrfc') {
  2502. $format = '%Y-%m-%d'; // DATE_RFC3339
  2503. } elseif ($format == 'dayhourrfc') {
  2504. $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  2505. } elseif ($format == 'standard') {
  2506. $format = '%Y-%m-%d %H:%M:%S';
  2507. }
  2508. if ($reduceformat) {
  2509. $format = str_replace('%Y', '%y', $format);
  2510. $format = str_replace('yyyy', 'yy', $format);
  2511. }
  2512. // Clean format
  2513. if (preg_match('/%b/i', $format)) { // There is some text to translate
  2514. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2515. $format = str_replace('%b', '__b__', $format);
  2516. $format = str_replace('%B', '__B__', $format);
  2517. }
  2518. if (preg_match('/%a/i', $format)) { // There is some text to translate
  2519. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  2520. $format = str_replace('%a', '__a__', $format);
  2521. $format = str_replace('%A', '__A__', $format);
  2522. }
  2523. // Analyze date
  2524. $reg = array();
  2525. 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
  2526. dol_print_error('', "Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  2527. return '';
  2528. } 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
  2529. // This part of code should not be used anymore.
  2530. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  2531. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  2532. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  2533. $syear = (!empty($reg[1]) ? $reg[1] : '');
  2534. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  2535. $sday = (!empty($reg[3]) ? $reg[3] : '');
  2536. $shour = (!empty($reg[4]) ? $reg[4] : '');
  2537. $smin = (!empty($reg[5]) ? $reg[5] : '');
  2538. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  2539. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  2540. if ($to_gmt) {
  2541. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2542. } else {
  2543. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2544. }
  2545. $dtts = new DateTime();
  2546. $dtts->setTimestamp($time);
  2547. $dtts->setTimezone($tzo);
  2548. $newformat = str_replace(
  2549. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2550. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2551. $format);
  2552. $ret = $dtts->format($newformat);
  2553. $ret = str_replace(
  2554. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2555. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2556. $ret
  2557. );
  2558. } else {
  2559. // Date is a timestamps
  2560. if ($time < 100000000000) { // Protection against bad date values
  2561. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2562. if ($to_gmt) {
  2563. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2564. } else {
  2565. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2566. }
  2567. $dtts = new DateTime();
  2568. $dtts->setTimestamp($timetouse);
  2569. $dtts->setTimezone($tzo);
  2570. $newformat = str_replace(
  2571. array('%Y', '%y', '%m', '%d', '%H', '%I', '%M', '%S', '%p', '%w', 'T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2572. array('Y', 'y', 'm', 'd', 'H', 'h', 'i', 's', 'A', 'w', '__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2573. $format);
  2574. $ret = $dtts->format($newformat);
  2575. $ret = str_replace(
  2576. array('__£__', '__$__', '__{__', '__}__', '__[__', '__]__'),
  2577. array('T', 'Z', '__a__', '__A__', '__b__', '__B__'),
  2578. $ret
  2579. );
  2580. //var_dump($ret);exit;
  2581. } else {
  2582. $ret = 'Bad value '.$time.' for date';
  2583. }
  2584. }
  2585. if (preg_match('/__b__/i', $format)) {
  2586. $timetouse = $time + $offsettz + $offsetdst; // TODO We could be able to disable use of offsettz and offsetdst to use only offsettzstring.
  2587. if ($to_gmt) {
  2588. $tzo = new DateTimeZone('UTC'); // when to_gmt is true, base for offsettz and offsetdst (so timetouse) is UTC
  2589. } else {
  2590. $tzo = new DateTimeZone(date_default_timezone_get()); // when to_gmt is false, base for offsettz and offsetdst (so timetouse) is PHP server
  2591. }
  2592. $dtts = new DateTime();
  2593. $dtts->setTimestamp($timetouse);
  2594. $dtts->setTimezone($tzo);
  2595. $month = $dtts->format("m");
  2596. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  2597. if ($encodetooutput) {
  2598. $monthtext = $outputlangs->transnoentities('Month'.$month);
  2599. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  2600. } else {
  2601. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  2602. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  2603. }
  2604. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  2605. $ret = str_replace('__b__', $monthtextshort, $ret);
  2606. $ret = str_replace('__B__', $monthtext, $ret);
  2607. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  2608. //return $ret;
  2609. }
  2610. if (preg_match('/__a__/i', $format)) {
  2611. //print "time=$time offsettz=$offsettz offsetdst=$offsetdst offsettzstring=$offsettzstring";
  2612. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  2613. if ($to_gmt) {
  2614. $tzo = new DateTimeZone('UTC');
  2615. } else {
  2616. $tzo = new DateTimeZone(date_default_timezone_get());
  2617. }
  2618. $dtts = new DateTime();
  2619. $dtts->setTimestamp($timetouse);
  2620. $dtts->setTimezone($tzo);
  2621. $w = $dtts->format("w");
  2622. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  2623. $ret = str_replace('__A__', $dayweek, $ret);
  2624. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  2625. }
  2626. return $ret;
  2627. }
  2628. /**
  2629. * Return an array with locale date info.
  2630. * WARNING: This function use PHP server timezone by default to return locale informations.
  2631. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  2632. *
  2633. * @param int $timestamp Timestamp
  2634. * @param boolean $fast Fast mode. deprecated.
  2635. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'gmt', 'Europe/Paris' or '+0200' to force timezone.
  2636. * @return array Array of informations
  2637. * 'seconds' => $secs,
  2638. * 'minutes' => $min,
  2639. * 'hours' => $hour,
  2640. * 'mday' => $day,
  2641. * 'wday' => $dow, 0=sunday, 6=saturday
  2642. * 'mon' => $month,
  2643. * 'year' => $year,
  2644. * 'yday' => floor($secsInYear/$_day_power)
  2645. * '0' => original timestamp
  2646. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  2647. */
  2648. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  2649. {
  2650. $datetimeobj = new DateTime();
  2651. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  2652. if ($forcetimezone) {
  2653. $datetimeobj->setTimezone(new DateTimeZone($forcetimezone == 'gmt' ? 'UTC' : $forcetimezone)); // (add timezone relative to the date entered)
  2654. }
  2655. $arrayinfo = array(
  2656. 'year'=>((int) date_format($datetimeobj, 'Y')),
  2657. 'mon'=>((int) date_format($datetimeobj, 'm')),
  2658. 'mday'=>((int) date_format($datetimeobj, 'd')),
  2659. 'wday'=>((int) date_format($datetimeobj, 'w')),
  2660. 'yday'=>((int) date_format($datetimeobj, 'z')),
  2661. 'hours'=>((int) date_format($datetimeobj, 'H')),
  2662. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  2663. 'seconds'=>((int) date_format($datetimeobj, 's')),
  2664. '0'=>$timestamp
  2665. );
  2666. return $arrayinfo;
  2667. }
  2668. /**
  2669. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2670. * Replace function mktime not available under Windows if year < 1970
  2671. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2672. *
  2673. * @param int $hour Hour (can be -1 for undefined)
  2674. * @param int $minute Minute (can be -1 for undefined)
  2675. * @param int $second Second (can be -1 for undefined)
  2676. * @param int $month Month (1 to 12)
  2677. * @param int $day Day (1 to 31)
  2678. * @param int $year Year
  2679. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2680. * False or 0 or 'tzserver' = local to server TZ
  2681. * 'auto'
  2682. * 'tzuser' = local to user TZ taking dst into account at the current date. Not yet implemented.
  2683. * '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.
  2684. * 'tz,TimeZone' = use specified timezone
  2685. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2686. * @return int|string Date as a timestamp, '' or false if error
  2687. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2688. */
  2689. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = 'auto', $check = 1)
  2690. {
  2691. global $conf;
  2692. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2693. if ($gm === 'auto') {
  2694. $gm = (empty($conf) ? 'tzserver' : $conf->tzuserinputkey);
  2695. }
  2696. //print 'gm:'.$gm.' gm === auto:'.($gm === 'auto').'<br>';exit;
  2697. // Clean parameters
  2698. if ($hour == -1 || empty($hour)) {
  2699. $hour = 0;
  2700. }
  2701. if ($minute == -1 || empty($minute)) {
  2702. $minute = 0;
  2703. }
  2704. if ($second == -1 || empty($second)) {
  2705. $second = 0;
  2706. }
  2707. // Check parameters
  2708. if ($check) {
  2709. if (!$month || !$day) {
  2710. return '';
  2711. }
  2712. if ($day > 31) {
  2713. return '';
  2714. }
  2715. if ($month > 12) {
  2716. return '';
  2717. }
  2718. if ($hour < 0 || $hour > 24) {
  2719. return '';
  2720. }
  2721. if ($minute < 0 || $minute > 60) {
  2722. return '';
  2723. }
  2724. if ($second < 0 || $second > 60) {
  2725. return '';
  2726. }
  2727. }
  2728. if (empty($gm) || ($gm === 'server' || $gm === 'tzserver')) {
  2729. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2730. $localtz = new DateTimeZone($default_timezone);
  2731. } elseif ($gm === 'user' || $gm === 'tzuser' || $gm === 'tzuserrel') {
  2732. // We use dol_tz_string first because it is more reliable.
  2733. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2734. try {
  2735. $localtz = new DateTimeZone($default_timezone);
  2736. } catch (Exception $e) {
  2737. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2738. $default_timezone = @date_default_timezone_get();
  2739. }
  2740. } elseif (strrpos($gm, "tz,") !== false) {
  2741. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2742. try {
  2743. $localtz = new DateTimeZone($timezone);
  2744. } catch (Exception $e) {
  2745. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2746. }
  2747. }
  2748. if (empty($localtz)) {
  2749. $localtz = new DateTimeZone('UTC');
  2750. }
  2751. //var_dump($localtz);
  2752. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2753. $dt = new DateTime('now', $localtz);
  2754. $dt->setDate((int) $year, (int) $month, (int) $day);
  2755. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2756. $date = $dt->getTimestamp(); // should include daylight saving time
  2757. //var_dump($date);
  2758. return $date;
  2759. }
  2760. /**
  2761. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2762. *
  2763. * @param string $mode 'auto' => for backward compatibility (avoid this),
  2764. * 'gmt' => we return GMT timestamp,
  2765. * 'tzserver' => we add the PHP server timezone
  2766. * 'tzref' => we add the company timezone. Not implemented.
  2767. * 'tzuser' or 'tzuserrel' => we add the user timezone
  2768. * @return int $date Timestamp
  2769. */
  2770. function dol_now($mode = 'auto')
  2771. {
  2772. $ret = 0;
  2773. if ($mode === 'auto') {
  2774. $mode = 'gmt';
  2775. }
  2776. if ($mode == 'gmt') {
  2777. $ret = time(); // Time for now at greenwich.
  2778. } elseif ($mode == 'tzserver') { // Time for now with PHP server timezone added
  2779. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2780. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2781. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2782. //} elseif ($mode == 'tzref') {// Time for now with parent company timezone is added
  2783. // require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2784. // $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2785. // $ret=dol_now('gmt')+($tzsecond*3600);
  2786. //}
  2787. } elseif ($mode == 'tzuser' || $mode == 'tzuserrel') {
  2788. // Time for now with user timezone added
  2789. //print 'time: '.time();
  2790. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2791. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2792. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2793. }
  2794. return $ret;
  2795. }
  2796. /**
  2797. * Return string with formated size
  2798. *
  2799. * @param int $size Size to print
  2800. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2801. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2802. * @return string Link
  2803. */
  2804. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2805. {
  2806. global $conf, $langs;
  2807. $level = 1024;
  2808. if (!empty($conf->dol_optimize_smallscreen)) {
  2809. $shortunit = 1;
  2810. }
  2811. // Set value text
  2812. if (empty($shortvalue) || $size < ($level * 10)) {
  2813. $ret = $size;
  2814. $textunitshort = $langs->trans("b");
  2815. $textunitlong = $langs->trans("Bytes");
  2816. } else {
  2817. $ret = round($size / $level, 0);
  2818. $textunitshort = $langs->trans("Kb");
  2819. $textunitlong = $langs->trans("KiloBytes");
  2820. }
  2821. // Use long or short text unit
  2822. if (empty($shortunit)) {
  2823. $ret .= ' '.$textunitlong;
  2824. } else {
  2825. $ret .= ' '.$textunitshort;
  2826. }
  2827. return $ret;
  2828. }
  2829. /**
  2830. * Show Url link
  2831. *
  2832. * @param string $url Url to show
  2833. * @param string $target Target for link
  2834. * @param int $max Max number of characters to show
  2835. * @param int $withpicto With picto
  2836. * @param string $morecss More CSS
  2837. * @return string HTML Link
  2838. */
  2839. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0, $morecss = 'float')
  2840. {
  2841. global $langs;
  2842. if (empty($url)) {
  2843. return '';
  2844. }
  2845. $link = '<a href="';
  2846. if (!preg_match('/^http/i', $url)) {
  2847. $link .= 'http://';
  2848. }
  2849. $link .= $url;
  2850. $link .= '"';
  2851. if ($target) {
  2852. $link .= ' target="'.$target.'"';
  2853. }
  2854. $link .= '>';
  2855. if (!preg_match('/^http/i', $url)) {
  2856. $link .= 'http://';
  2857. }
  2858. $link .= dol_trunc($url, $max);
  2859. $link .= '</a>';
  2860. if ($morecss == 'float') {
  2861. return '<div class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2862. } else {
  2863. return '<span class="nospan'.($morecss ? ' '.$morecss : '').'" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</span>';
  2864. }
  2865. }
  2866. /**
  2867. * Show EMail link formatted for HTML output.
  2868. *
  2869. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2870. * @param int $cid Id of contact if known
  2871. * @param int $socid Id of third party if known
  2872. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2873. * @param int $max Max number of characters to show
  2874. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2875. * @param int|string $withpicto Show picto
  2876. * @return string HTML Link
  2877. */
  2878. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2879. {
  2880. global $conf, $user, $langs, $hookmanager;
  2881. $newemail = dol_escape_htmltag($email);
  2882. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) {
  2883. $withpicto = 0;
  2884. }
  2885. if (empty($email)) {
  2886. return '&nbsp;';
  2887. }
  2888. if (!empty($addlink)) {
  2889. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2890. if (!preg_match('/^mailto:/i', $email)) {
  2891. $newemail .= 'mailto:';
  2892. }
  2893. $newemail .= $email;
  2894. $newemail .= '">';
  2895. $newemail .= dol_trunc($email, $max);
  2896. $newemail .= '</a>';
  2897. if ($showinvalid && !isValidEmail($email)) {
  2898. $langs->load("errors");
  2899. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2900. }
  2901. if (($cid || $socid) && isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  2902. $type = 'AC_EMAIL';
  2903. $link = '';
  2904. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) {
  2905. $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>';
  2906. }
  2907. if ($link) {
  2908. $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2909. }
  2910. }
  2911. } else {
  2912. if ($showinvalid && !isValidEmail($email)) {
  2913. $langs->load("errors");
  2914. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2915. }
  2916. }
  2917. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2918. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, (is_numeric($withpicto) ? 'email' : $withpicto)).' ' : '').$newemail;
  2919. //$rep .= '</div>';
  2920. if ($hookmanager) {
  2921. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2922. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2923. if ($reshook > 0) {
  2924. $rep = '';
  2925. }
  2926. $rep .= $hookmanager->resPrint;
  2927. }
  2928. return $rep;
  2929. }
  2930. /**
  2931. * Get array of social network dictionary
  2932. *
  2933. * @return array Array of Social Networks Dictionary
  2934. */
  2935. function getArrayOfSocialNetworks()
  2936. {
  2937. global $conf, $db;
  2938. $socialnetworks = array();
  2939. // Enable caching of array
  2940. require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php';
  2941. $cachekey = 'socialnetworks_' . $conf->entity;
  2942. $dataretrieved = dol_getcache($cachekey);
  2943. if (!is_null($dataretrieved)) {
  2944. $socialnetworks = $dataretrieved;
  2945. } else {
  2946. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2947. $sql .= " WHERE entity=".$conf->entity;
  2948. $resql = $db->query($sql);
  2949. if ($resql) {
  2950. while ($obj = $db->fetch_object($resql)) {
  2951. $socialnetworks[$obj->code] = array(
  2952. 'rowid' => $obj->rowid,
  2953. 'label' => $obj->label,
  2954. 'url' => $obj->url,
  2955. 'icon' => $obj->icon,
  2956. 'active' => $obj->active,
  2957. );
  2958. }
  2959. }
  2960. dol_setcache($cachekey, $socialnetworks); // If setting cache fails, this is not a problem, so we do not test result.
  2961. }
  2962. return $socialnetworks;
  2963. }
  2964. /**
  2965. * Show social network link
  2966. *
  2967. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2968. * @param int $cid Id of contact if known
  2969. * @param int $socid Id of third party if known
  2970. * @param string $type 'skype','facebook',...
  2971. * @param array $dictsocialnetworks socialnetworks availables
  2972. * @return string HTML Link
  2973. */
  2974. function dol_print_socialnetworks($value, $cid, $socid, $type, $dictsocialnetworks = array())
  2975. {
  2976. global $conf, $user, $langs;
  2977. $htmllink = $value;
  2978. if (empty($value)) {
  2979. return '&nbsp;';
  2980. }
  2981. if (!empty($type)) {
  2982. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2983. // Use dictionary definition for picto $dictsocialnetworks[$type]['icon']
  2984. $htmllink .= '<span class="fa pictofixedwidth '.($dictsocialnetworks[$type]['icon'] ? $dictsocialnetworks[$type]['icon'] : 'fa-link').'"></span>';
  2985. if ($type == 'skype') {
  2986. $htmllink .= dol_escape_htmltag($value);
  2987. $htmllink .= '&nbsp; <a href="skype:';
  2988. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2989. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Call").' '.$value).'">';
  2990. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2991. $htmllink .= '</a><a href="skype:';
  2992. $htmllink .= dol_string_nospecial($value, '_', '', array('@'));
  2993. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.dol_escape_htmltag($langs->trans("Chat").' '.$value).'">';
  2994. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2995. $htmllink .= '</a>';
  2996. if (($cid || $socid) && isModEnabled('agenda') && $user->rights->agenda->myactions->create) {
  2997. $addlink = 'AC_SKYPE';
  2998. $link = '';
  2999. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) {
  3000. $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>';
  3001. }
  3002. $htmllink .= ($link ? ' '.$link : '');
  3003. }
  3004. } else {
  3005. if (!empty($dictsocialnetworks[$type]['url'])) {
  3006. $tmpvirginurl = preg_replace('/\/?{socialid}/', '', $dictsocialnetworks[$type]['url']);
  3007. if ($tmpvirginurl) {
  3008. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3009. $value = preg_replace('/^'.preg_quote($tmpvirginurl, '/').'\/?/', '', $value);
  3010. $tmpvirginurl3 = preg_replace('/^https:\/\//i', 'https://www.', $tmpvirginurl);
  3011. if ($tmpvirginurl3) {
  3012. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3013. $value = preg_replace('/^'.preg_quote($tmpvirginurl3, '/').'\/?/', '', $value);
  3014. }
  3015. $tmpvirginurl2 = preg_replace('/^https?:\/\//i', '', $tmpvirginurl);
  3016. if ($tmpvirginurl2) {
  3017. $value = preg_replace('/^www\.'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3018. $value = preg_replace('/^'.preg_quote($tmpvirginurl2, '/').'\/?/', '', $value);
  3019. }
  3020. }
  3021. $link = str_replace('{socialid}', $value, $dictsocialnetworks[$type]['url']);
  3022. if (preg_match('/^https?:\/\//i', $link)) {
  3023. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 0).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3024. } else {
  3025. $htmllink .= '<a href="'.dol_sanitizeUrl($link, 1).'" target="_blank" rel="noopener noreferrer">'.dol_escape_htmltag($value).'</a>';
  3026. }
  3027. } else {
  3028. $htmllink .= dol_escape_htmltag($value);
  3029. }
  3030. }
  3031. $htmllink .= '</div>';
  3032. } else {
  3033. $langs->load("errors");
  3034. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  3035. }
  3036. return $htmllink;
  3037. }
  3038. /**
  3039. * Format profIDs according to country
  3040. *
  3041. * @param string $profID Value of profID to format
  3042. * @param string $profIDtype Type of profID to format ('1', '2', '3', '4', '5', '6' or 'VAT')
  3043. * @param string $countrycode Country code to use for formatting
  3044. * @param int $addcpButton Add button to copy to clipboard (1 => show only on hoover ; 2 => always display )
  3045. * @param string $separ Separation between numbers for a better visibility example : xxx xxx xxx xxxxx
  3046. * @return string Formated profID
  3047. */
  3048. function dol_print_profids($profID, $profIDtype, $countrycode = '', $addcpButton = 1, $separ = '&nbsp;')
  3049. {
  3050. global $mysoc;
  3051. if (empty($profID) || empty($profIDtype)) {
  3052. return '';
  3053. }
  3054. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  3055. $newProfID = $profID;
  3056. $id = substr($profIDtype, -1);
  3057. $ret = '';
  3058. if (strtoupper($countrycode) == 'FR') {
  3059. // France
  3060. if ($id == 1 && dol_strlen($newProfID) == 9) $newProfID = substr($newProfID, 0, 3).$separ.substr($newProfID, 3, 3).$separ.substr($newProfID, 6, 3);
  3061. 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);
  3062. 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);
  3063. }
  3064. if (!empty($addcpButton)) $ret = showValueWithClipboardCPButton(dol_escape_htmltag($profID), ($addcpButton == 1 ? 1 : 0), $newProfID);
  3065. else $ret = $newProfID;
  3066. return $ret;
  3067. }
  3068. /**
  3069. * Format phone numbers according to country
  3070. *
  3071. * @param string $phone Phone number to format
  3072. * @param string $countrycode Country code to use for formatting
  3073. * @param int $cid Id of contact if known
  3074. * @param int $socid Id of third party if known
  3075. * @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), 'tel'=Force "tel:..." link
  3076. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  3077. * @param string $withpicto Show picto ('fax', 'phone', 'mobile')
  3078. * @param string $titlealt Text to show on alt
  3079. * @param int $adddivfloat Add div float around phone.
  3080. * @return string Formated phone number
  3081. */
  3082. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  3083. {
  3084. global $conf, $user, $langs, $mysoc, $hookmanager;
  3085. // Clean phone parameter
  3086. $phone = is_null($phone) ? '' : preg_replace("/[\s.-]/", "", trim($phone));
  3087. if (empty($phone)) {
  3088. return '';
  3089. }
  3090. if (!empty($conf->global->MAIN_PHONE_SEPAR)) {
  3091. $separ = $conf->global->MAIN_PHONE_SEPAR;
  3092. }
  3093. if (empty($countrycode) && is_object($mysoc)) {
  3094. $countrycode = $mysoc->country_code;
  3095. }
  3096. // Short format for small screens
  3097. if ($conf->dol_optimize_smallscreen) {
  3098. $separ = '';
  3099. }
  3100. $newphone = $phone;
  3101. if (strtoupper($countrycode) == "FR") {
  3102. // France
  3103. if (dol_strlen($phone) == 10) {
  3104. $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);
  3105. } elseif (dol_strlen($phone) == 7) {
  3106. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  3107. } elseif (dol_strlen($phone) == 9) {
  3108. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  3109. } elseif (dol_strlen($phone) == 11) {
  3110. $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);
  3111. } elseif (dol_strlen($phone) == 12) {
  3112. $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);
  3113. } elseif (dol_strlen($phone) == 13) {
  3114. $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);
  3115. }
  3116. } elseif (strtoupper($countrycode) == "CA") {
  3117. if (dol_strlen($phone) == 10) {
  3118. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  3119. }
  3120. } elseif (strtoupper($countrycode) == "PT") {//Portugal
  3121. if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
  3122. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3123. }
  3124. } elseif (strtoupper($countrycode) == "SR") {//Suriname
  3125. if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
  3126. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  3127. } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
  3128. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  3129. }
  3130. } elseif (strtoupper($countrycode) == "DE") {//Allemagne
  3131. if (dol_strlen($phone) == 14) {//ex: +49_ABCD_EFGH_IJK
  3132. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  3133. } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
  3134. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  3135. }
  3136. } elseif (strtoupper($countrycode) == "ES") {//Espagne
  3137. if (dol_strlen($phone) == 12) {//ex: +34_ABC_DEF_GHI
  3138. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3139. }
  3140. } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
  3141. if (dol_strlen($phone) == 12) {//ex : +22 A BC_DE_FG_HI
  3142. $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);
  3143. }
  3144. } elseif (strtoupper($countrycode) == "RO") {// Roumanie
  3145. if (dol_strlen($phone) == 12) {//ex : +40 AB_CDE_FG_HI
  3146. $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);
  3147. }
  3148. } elseif (strtoupper($countrycode) == "TR") {//Turquie
  3149. if (dol_strlen($phone) == 13) {//ex : +90 ABC_DEF_GHIJ
  3150. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3151. }
  3152. } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
  3153. if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
  3154. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3155. }
  3156. } elseif (strtoupper($countrycode) == "MX") {//Mexique
  3157. if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
  3158. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3159. } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
  3160. $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);
  3161. } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
  3162. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  3163. }
  3164. } elseif (strtoupper($countrycode) == "ML") {//Mali
  3165. if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
  3166. $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);
  3167. }
  3168. } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
  3169. if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
  3170. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3171. } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
  3172. $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);
  3173. }
  3174. } elseif (strtoupper($countrycode) == "MU") {
  3175. //Maurice
  3176. if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
  3177. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  3178. } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
  3179. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  3180. }
  3181. } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
  3182. if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
  3183. $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);
  3184. }
  3185. } elseif (strtoupper($countrycode) == "SY") {//Syrie
  3186. if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
  3187. $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);
  3188. } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
  3189. $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);
  3190. }
  3191. } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
  3192. if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
  3193. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  3194. } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
  3195. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3196. } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
  3197. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  3198. }
  3199. } elseif (strtoupper($countrycode) == "DZ") {//Algérie
  3200. if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
  3201. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3202. }
  3203. } elseif (strtoupper($countrycode) == "BE") {//Belgique
  3204. if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
  3205. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  3206. } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
  3207. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3208. }
  3209. } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
  3210. if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
  3211. $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);
  3212. }
  3213. } elseif (strtoupper($countrycode) == "CO") {//Colombie
  3214. if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
  3215. $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);
  3216. }
  3217. } elseif (strtoupper($countrycode) == "JO") {//Jordanie
  3218. if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
  3219. $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);
  3220. }
  3221. } elseif (strtoupper($countrycode) == "JM") {//Jamaïque
  3222. if (dol_strlen($newphone) == 12) {//ex: +1867_ABC_DEFG
  3223. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  3224. }
  3225. } elseif (strtoupper($countrycode) == "MG") {//Madagascar
  3226. if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EFG_HI
  3227. $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);
  3228. }
  3229. } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
  3230. if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
  3231. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  3232. }
  3233. } elseif (strtoupper($countrycode) == "CH") {//Suisse
  3234. if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
  3235. $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);
  3236. } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
  3237. $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);
  3238. }
  3239. } elseif (strtoupper($countrycode) == "TN") {//Tunisie
  3240. if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
  3241. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3242. }
  3243. } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
  3244. if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  3245. $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);
  3246. }
  3247. } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
  3248. if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  3249. $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);
  3250. }
  3251. } elseif (strtoupper($countrycode) == "MQ") {//Martinique
  3252. if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  3253. $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);
  3254. }
  3255. } elseif (strtoupper($countrycode) == "IT") {//Italie
  3256. if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
  3257. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  3258. } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
  3259. $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);
  3260. }
  3261. } elseif (strtoupper($countrycode) == "AU") {
  3262. //Australie
  3263. if (dol_strlen($phone) == 12) {
  3264. //ex: +61_A_BCDE_FGHI
  3265. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  3266. }
  3267. } elseif (strtoupper($countrycode) == "LU") {
  3268. // Luxembourg
  3269. if (dol_strlen($phone) == 10) {// fixe 6 chiffres +352_AA_BB_CC
  3270. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
  3271. } elseif (dol_strlen($phone) == 11) {// fixe 7 chiffres +352_AA_BB_CC_D
  3272. $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);
  3273. } elseif (dol_strlen($phone) == 12) {// fixe 8 chiffres +352_AA_BB_CC_DD
  3274. $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);
  3275. } elseif (dol_strlen($phone) == 13) {// mobile +352_AAA_BB_CC_DD
  3276. $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);
  3277. }
  3278. }
  3279. if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  3280. if ($addlink == 'tel' || $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
  3281. $newphoneform = $newphone;
  3282. $newphone = '<a href="tel:'.$phone.'"';
  3283. $newphone .= '>'.$newphoneform.'</a>';
  3284. } elseif (isModEnabled('clicktodial') && $addlink == 'AC_TEL') { // If click to dial, we use click to dial url
  3285. if (empty($user->clicktodial_loaded)) {
  3286. $user->fetch_clicktodial();
  3287. }
  3288. // Define urlmask
  3289. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  3290. if (!empty($conf->global->CLICKTODIAL_URL)) {
  3291. $urlmask = $conf->global->CLICKTODIAL_URL;
  3292. }
  3293. if (!empty($user->clicktodial_url)) {
  3294. $urlmask = $user->clicktodial_url;
  3295. }
  3296. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  3297. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  3298. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  3299. // This line is for backward compatibility
  3300. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  3301. // Thoose lines are for substitution
  3302. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  3303. '__PHONETO__'=>urlencode($phone),
  3304. '__LOGIN__'=>$clicktodial_login,
  3305. '__PASS__'=>$clicktodial_password);
  3306. $url = make_substitutions($url, $substitarray);
  3307. $newphonesav = $newphone;
  3308. if (empty($conf->global->CLICKTODIAL_DO_NOT_USE_AJAX_CALL)) {
  3309. // Default and recommended: New method using ajax without submiting a page making a javascript history.go(-1) back
  3310. $newphone = '<a href="'.$url.'" class="cssforclicktodial"'; // Call of ajax is handled by the lib_foot.js.php on class 'cssforclicktodial'
  3311. $newphone .= '>'.$newphonesav.'</a>';
  3312. } else {
  3313. // Old method
  3314. $newphone = '<a href="'.$url.'"';
  3315. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) {
  3316. $newphone .= ' target="_blank" rel="noopener noreferrer"';
  3317. }
  3318. $newphone .= '>'.$newphonesav.'</a>';
  3319. }
  3320. }
  3321. //if (($cid || $socid) && isModEnabled('agenda') && $user->rights->agenda->myactions->create)
  3322. if (isModEnabled('agenda') && $user->hasRight("agenda", "myactions", "create")) {
  3323. $type = 'AC_TEL';
  3324. $link = '';
  3325. if ($addlink == 'AC_FAX') {
  3326. $type = 'AC_FAX';
  3327. }
  3328. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) {
  3329. $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage='. urlencode($_SERVER['REQUEST_URI']) .'&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  3330. }
  3331. if ($link) {
  3332. $newphone = '<div>'.$newphone.' '.$link.'</div>';
  3333. }
  3334. }
  3335. }
  3336. if (empty($titlealt)) {
  3337. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  3338. }
  3339. $rep = '';
  3340. if ($hookmanager) {
  3341. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  3342. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  3343. $rep .= $hookmanager->resPrint;
  3344. }
  3345. if (empty($reshook)) {
  3346. $picto = '';
  3347. if ($withpicto) {
  3348. if ($withpicto == 'fax') {
  3349. $picto = 'phoning_fax';
  3350. } elseif ($withpicto == 'phone') {
  3351. $picto = 'phoning';
  3352. } elseif ($withpicto == 'mobile') {
  3353. $picto = 'phoning_mobile';
  3354. } else {
  3355. $picto = '';
  3356. }
  3357. }
  3358. if ($adddivfloat == 1) {
  3359. $rep .= '<div class="nospan float" style="margin-right: 10px">';
  3360. } elseif (empty($adddivfloat)) {
  3361. $rep .= '<span style="margin-right: 10px;">';
  3362. }
  3363. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  3364. if ($adddivfloat == 1) {
  3365. $rep .= '</div>';
  3366. } elseif (empty($adddivfloat)) {
  3367. $rep .= '</span>';
  3368. }
  3369. }
  3370. return $rep;
  3371. }
  3372. /**
  3373. * Return an IP formated to be shown on screen
  3374. *
  3375. * @param string $ip IP
  3376. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  3377. * @return string Formated IP, with country if GeoIP module is enabled
  3378. */
  3379. function dol_print_ip($ip, $mode = 0)
  3380. {
  3381. global $conf, $langs;
  3382. $ret = '';
  3383. if (empty($mode)) {
  3384. $ret .= $ip;
  3385. }
  3386. if ($mode != 2) {
  3387. $countrycode = dolGetCountryCodeFromIp($ip);
  3388. if ($countrycode) { // If success, countrycode is us, fr, ...
  3389. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png')) {
  3390. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  3391. } else {
  3392. $ret .= ' ('.$countrycode.')';
  3393. }
  3394. } else {
  3395. // Nothing
  3396. }
  3397. }
  3398. return $ret;
  3399. }
  3400. /**
  3401. * Return the IP of remote user.
  3402. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  3403. * Then HTTP_CLIENT_IP if defined (rare)
  3404. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  3405. *
  3406. * @return string Ip of remote user.
  3407. */
  3408. function getUserRemoteIP()
  3409. {
  3410. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  3411. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  3412. if (empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  3413. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']); // value may have been the IP of the proxy and not the client
  3414. } else {
  3415. $ip = $_SERVER["HTTP_CF_CONNECTING_IP"]; // value here may have been forged by client
  3416. }
  3417. } else {
  3418. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here but may have been forged by proxy
  3419. }
  3420. } else {
  3421. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here but may have been forged by proxy
  3422. }
  3423. return $ip;
  3424. }
  3425. /**
  3426. * Return if we are using a HTTPS connexion
  3427. * Check HTTPS (no way to be modified by user but may be empty or wrong if user is using a proxy)
  3428. * Take HTTP_X_FORWARDED_PROTO (defined when using proxy)
  3429. * Then HTTP_X_FORWARDED_SSL
  3430. *
  3431. * @return boolean True if user is using HTTPS
  3432. */
  3433. function isHTTPS()
  3434. {
  3435. $isSecure = false;
  3436. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  3437. $isSecure = true;
  3438. } 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') {
  3439. $isSecure = true;
  3440. }
  3441. return $isSecure;
  3442. }
  3443. /**
  3444. * Return a country code from IP. Empty string if not found.
  3445. *
  3446. * @param string $ip IP
  3447. * @return string Country code ('us', 'fr', ...)
  3448. */
  3449. function dolGetCountryCodeFromIp($ip)
  3450. {
  3451. global $conf;
  3452. $countrycode = '';
  3453. if (!empty($conf->geoipmaxmind->enabled)) {
  3454. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3455. //$ip='24.24.24.24';
  3456. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  3457. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3458. $geoip = new DolGeoIP('country', $datafile);
  3459. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  3460. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3461. }
  3462. return $countrycode;
  3463. }
  3464. /**
  3465. * Return country code for current user.
  3466. * If software is used inside a local network, detection may fails (we need a public ip)
  3467. *
  3468. * @return string Country code (fr, es, it, us, ...)
  3469. */
  3470. function dol_user_country()
  3471. {
  3472. global $conf, $langs, $user;
  3473. //$ret=$user->xxx;
  3474. $ret = '';
  3475. if (!empty($conf->geoipmaxmind->enabled)) {
  3476. $ip = getUserRemoteIP();
  3477. $datafile = getDolGlobalString('GEOIPMAXMIND_COUNTRY_DATAFILE');
  3478. //$ip='24.24.24.24';
  3479. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  3480. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  3481. $geoip = new DolGeoIP('country', $datafile);
  3482. $countrycode = $geoip->getCountryCodeFromIP($ip);
  3483. $ret = $countrycode;
  3484. }
  3485. return $ret;
  3486. }
  3487. /**
  3488. * Format address string
  3489. *
  3490. * @param string $address Address string, already formatted with dol_format_address()
  3491. * @param int $htmlid Html ID (for example 'gmap')
  3492. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  3493. * @param int $id Id of object
  3494. * @param int $noprint No output. Result is the function return
  3495. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  3496. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  3497. * @see dol_format_address()
  3498. */
  3499. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  3500. {
  3501. global $conf, $user, $langs, $hookmanager;
  3502. $out = '';
  3503. if ($address) {
  3504. if ($hookmanager) {
  3505. $parameters = array('element' => $element, 'id' => $id);
  3506. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  3507. $out .= $hookmanager->resPrint;
  3508. }
  3509. if (empty($reshook)) {
  3510. if (empty($charfornl)) {
  3511. $out .= nl2br($address);
  3512. } else {
  3513. $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  3514. }
  3515. // TODO Remove this block, we can add this using the hook now
  3516. $showgmap = $showomap = 0;
  3517. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) {
  3518. $showgmap = 1;
  3519. }
  3520. if ($element == 'contact' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
  3521. $showgmap = 1;
  3522. }
  3523. if ($element == 'member' && isModEnabled('google') && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
  3524. $showgmap = 1;
  3525. }
  3526. if (($element == 'thirdparty' || $element == 'societe') && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
  3527. $showomap = 1;
  3528. }
  3529. if ($element == 'contact' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
  3530. $showomap = 1;
  3531. }
  3532. if ($element == 'member' && isModEnabled('openstreetmap') && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
  3533. $showomap = 1;
  3534. }
  3535. if ($showgmap) {
  3536. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  3537. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3538. }
  3539. if ($showomap) {
  3540. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  3541. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  3542. }
  3543. }
  3544. }
  3545. if ($noprint) {
  3546. return $out;
  3547. } else {
  3548. print $out;
  3549. }
  3550. }
  3551. /**
  3552. * Return true if email syntax is ok.
  3553. *
  3554. * @param string $address email (Ex: "toto@examle.com". Long form "John Do <johndo@example.com>" will be false)
  3555. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  3556. * @param int $acceptuserkey If 1, the special string '__USER_EMAIL__' is also accepted as valid
  3557. * @return boolean true if email syntax is OK, false if KO or empty string
  3558. * @see isValidMXRecord()
  3559. */
  3560. function isValidEmail($address, $acceptsupervisorkey = 0, $acceptuserkey = 0)
  3561. {
  3562. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
  3563. return true;
  3564. }
  3565. if ($acceptuserkey && $address == '__USER_EMAIL__') {
  3566. return true;
  3567. }
  3568. if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
  3569. return true;
  3570. }
  3571. return false;
  3572. }
  3573. /**
  3574. * Return if the domain name has a valid MX record.
  3575. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  3576. *
  3577. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  3578. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  3579. * @see isValidEmail()
  3580. */
  3581. function isValidMXRecord($domain)
  3582. {
  3583. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr')) {
  3584. if (!checkdnsrr(idn_to_ascii($domain), 'MX')) {
  3585. return 0;
  3586. }
  3587. if (function_exists('getmxrr')) {
  3588. $mxhosts = array();
  3589. $weight = array();
  3590. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  3591. if (count($mxhosts) > 1) {
  3592. return 1;
  3593. }
  3594. if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
  3595. return 1;
  3596. }
  3597. return 0;
  3598. }
  3599. }
  3600. // function idn_to_ascii or checkdnsrr or getmxrr does not exists
  3601. return -1;
  3602. }
  3603. /**
  3604. * Return true if phone number syntax is ok
  3605. * TODO Decide what to do with this
  3606. *
  3607. * @param string $phone phone (Ex: "0601010101")
  3608. * @return boolean true if phone syntax is OK, false if KO or empty string
  3609. */
  3610. function isValidPhone($phone)
  3611. {
  3612. return true;
  3613. }
  3614. /**
  3615. * Return first letters of a strings.
  3616. * Example with nbofchar=1: 'ghi' will return 'g' but 'abc def' will return 'ad'
  3617. * Example with nbofchar=2: 'ghi' will return 'gh' but 'abc def' will return 'abde'
  3618. *
  3619. * @param string $s String to truncate
  3620. * @param int $nbofchar Nb of characters to keep
  3621. * @return string Return first chars.
  3622. */
  3623. function dolGetFirstLetters($s, $nbofchar = 1)
  3624. {
  3625. $ret = '';
  3626. $tmparray = explode(' ', $s);
  3627. foreach ($tmparray as $tmps) {
  3628. $ret .= dol_substr($tmps, 0, $nbofchar);
  3629. }
  3630. return $ret;
  3631. }
  3632. /**
  3633. * Make a strlen call. Works even if mbstring module not enabled
  3634. *
  3635. * @param string $string String to calculate length
  3636. * @param string $stringencoding Encoding of string
  3637. * @return int Length of string
  3638. */
  3639. function dol_strlen($string, $stringencoding = 'UTF-8')
  3640. {
  3641. if (is_null($string)) {
  3642. return 0;
  3643. }
  3644. if (function_exists('mb_strlen')) {
  3645. return mb_strlen($string, $stringencoding);
  3646. } else {
  3647. return strlen($string);
  3648. }
  3649. }
  3650. /**
  3651. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  3652. *
  3653. * @param string $string String to scan
  3654. * @param string $start Start position
  3655. * @param int|null $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  3656. * @param string $stringencoding Page code used for input string encoding
  3657. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  3658. * @return string substring
  3659. */
  3660. function dol_substr($string, $start, $length = null, $stringencoding = '', $trunconbytes = 0)
  3661. {
  3662. global $langs;
  3663. if (empty($stringencoding)) {
  3664. $stringencoding = $langs->charset_output;
  3665. }
  3666. $ret = '';
  3667. if (empty($trunconbytes)) {
  3668. if (function_exists('mb_substr')) {
  3669. $ret = mb_substr($string, $start, $length, $stringencoding);
  3670. } else {
  3671. $ret = substr($string, $start, $length);
  3672. }
  3673. } else {
  3674. if (function_exists('mb_strcut')) {
  3675. $ret = mb_strcut($string, $start, $length, $stringencoding);
  3676. } else {
  3677. $ret = substr($string, $start, $length);
  3678. }
  3679. }
  3680. return $ret;
  3681. }
  3682. /**
  3683. * Truncate a string to a particular length adding '…' if string larger than length.
  3684. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '…'.
  3685. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  3686. *
  3687. * @param string $string String to truncate
  3688. * @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 ...)
  3689. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  3690. * @param string $stringencoding Tell what is source string encoding
  3691. * @param int $nodot Truncation do not add … after truncation. So it's an exact truncation.
  3692. * @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)
  3693. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  3694. */
  3695. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  3696. {
  3697. global $conf;
  3698. if (empty($size) || !empty($conf->global->MAIN_DISABLE_TRUNC)) {
  3699. return $string;
  3700. }
  3701. if (empty($stringencoding)) {
  3702. $stringencoding = 'UTF-8';
  3703. }
  3704. // reduce for small screen
  3705. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) {
  3706. $size = round($size / 3);
  3707. }
  3708. // We go always here
  3709. if ($trunc == 'right') {
  3710. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3711. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3712. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3713. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '…');
  3714. } else {
  3715. //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  3716. return $string;
  3717. }
  3718. } elseif ($trunc == 'middle') {
  3719. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3720. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3721. $size1 = round($size / 2);
  3722. $size2 = round($size / 2);
  3723. return dol_substr($newstring, 0, $size1, $stringencoding).'…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  3724. } else {
  3725. return $string;
  3726. }
  3727. } elseif ($trunc == 'left') {
  3728. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3729. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 1))) {
  3730. // If nodot is 0 and size is 1 chars more, we don't trunc and don't add …
  3731. return '…'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  3732. } else {
  3733. return $string;
  3734. }
  3735. } elseif ($trunc == 'wrap') {
  3736. $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
  3737. if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
  3738. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  3739. } else {
  3740. return $string;
  3741. }
  3742. } else {
  3743. return 'BadParam3CallingDolTrunc';
  3744. }
  3745. }
  3746. /**
  3747. * Show picto whatever it's its name (generic function)
  3748. *
  3749. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  3750. * @param string $picto Name of image file to show ('filenew', ...).
  3751. * For font awesome icon (example 'user'), you can use picto_nocolor to not have the color of picto forced.
  3752. * If no extension provided and it is not a font awesome icon, we use '.png'. Image must be stored into theme/xxx/img directory.
  3753. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3754. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3755. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3756. * 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)
  3757. * @param string $moreatt Add more attribute on img tag (For example 'class="pictofixedwidth"')
  3758. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  3759. * @param int $srconly Return only content of the src attribute of img.
  3760. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3761. * @param string $alt Force alt for bind people
  3762. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  3763. * @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.
  3764. * @return string Return img tag
  3765. * @see img_object(), img_picto_common()
  3766. */
  3767. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  3768. {
  3769. global $conf, $langs;
  3770. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  3771. $url = DOL_URL_ROOT;
  3772. $theme = isset($conf->theme) ? $conf->theme : null;
  3773. $path = 'theme/'.$theme;
  3774. // Define fullpathpicto to use into src
  3775. if ($pictoisfullpath) {
  3776. // Clean parameters
  3777. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3778. $picto .= '.png';
  3779. }
  3780. $fullpathpicto = $picto;
  3781. $reg = array();
  3782. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3783. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3784. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3785. }
  3786. } else {
  3787. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  3788. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3789. $pictowithouttext = str_replace('_nocolor', '', $pictowithouttext);
  3790. if (strpos($pictowithouttext, 'fontawesome_') !== false || preg_match('/^fa-/', $pictowithouttext)) {
  3791. // This is a font awesome image 'fonwtawesome_xxx' or 'fa-xxx'
  3792. $pictowithouttext = str_replace('fontawesome_', '', $pictowithouttext);
  3793. $pictowithouttext = str_replace('fa-', '', $pictowithouttext);
  3794. $pictowithouttextarray = explode('_', $pictowithouttext);
  3795. $marginleftonlyshort = 0;
  3796. if (!empty($pictowithouttextarray[1])) {
  3797. // Syntax is 'fontawesome_fakey_faprefix_facolor_fasize' or 'fa-fakey_faprefix_facolor_fasize'
  3798. $fakey = 'fa-'.$pictowithouttextarray[0];
  3799. $fa = empty($pictowithouttextarray[1]) ? 'fa' : $pictowithouttextarray[1];
  3800. $facolor = empty($pictowithouttextarray[2]) ? '' : $pictowithouttextarray[2];
  3801. $fasize = empty($pictowithouttextarray[3]) ? '' : $pictowithouttextarray[3];
  3802. } else {
  3803. $fakey = 'fa-'.$pictowithouttext;
  3804. $fa = 'fa';
  3805. $facolor = '';
  3806. $fasize = '';
  3807. }
  3808. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3809. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3810. $morestyle = '';
  3811. $reg = array();
  3812. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3813. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3814. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3815. }
  3816. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3817. $morestyle = $reg[1];
  3818. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3819. }
  3820. $moreatt = trim($moreatt);
  3821. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3822. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3823. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3824. $enabledisablehtml .= $titlealt;
  3825. }*/
  3826. $enabledisablehtml .= '</span>';
  3827. return $enabledisablehtml;
  3828. }
  3829. if (empty($srconly) && in_array($pictowithouttext, array(
  3830. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  3831. 'accountancy', 'accounting_account', 'account', 'accountline', 'action', 'add', 'address', 'angle-double-down', 'angle-double-up', 'asset',
  3832. 'bank_account', 'barcode', 'bank', 'bell', 'bill', 'billa', 'billr', 'billd', 'birthday-cake', 'bookmark', 'bom', 'briefcase-medical', 'bug', 'building',
  3833. 'card', 'calendarlist', 'calendar', 'calendarmonth', 'calendarweek', 'calendarday', 'calendarperuser', 'calendarpertype',
  3834. 'cash-register', 'category', 'chart', 'check', 'clock', 'close_title', 'cog', 'collab', 'company', 'contact', 'country', 'contract', 'conversation', 'cron', 'cross', 'cubes',
  3835. 'currency', 'multicurrency',
  3836. 'delete', 'dolly', 'dollyrevert', 'donation', 'download', 'dynamicprice',
  3837. 'edit', 'ellipsis-h', 'email', 'entity', 'envelope', 'eraser', 'establishment', 'expensereport', 'external-link-alt', 'external-link-square-alt', 'eye',
  3838. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'autofill', 'folder', 'folder-open', 'folder-plus',
  3839. 'gears', 'generate', 'globe', 'globe-americas', 'graph', 'grip', 'grip_title', 'group',
  3840. 'hands-helping', 'help', 'holiday',
  3841. 'id-card', 'images', 'incoterm', 'info', 'intervention', 'inventory', 'intracommreport', 'jobprofile',
  3842. 'knowledgemanagement',
  3843. 'label', 'language', 'line', 'link', 'list', 'list-alt', 'listlight', 'loan', 'lock', 'lot', 'long-arrow-alt-right',
  3844. 'margin', 'map-marker-alt', 'member', 'meeting', 'money-bill-alt', 'movement', 'mrp', 'note', 'next',
  3845. 'off', 'on', 'order',
  3846. 'paiment', 'paragraph', 'play', 'pdf', 'phone', 'phoning', 'phoning_mobile', 'phoning_fax', 'playdisabled', 'previous', 'poll', 'pos', 'printer', 'product', 'propal', 'proposal', 'puce',
  3847. 'stock', 'resize', 'service', 'stats', 'trip',
  3848. 'security', 'setup', 'share-alt', 'sign-out', 'split', 'stripe', 'stripe-s', 'switch_off', 'switch_on', 'switch_on_warning', 'switch_on_red', 'tools', 'unlink', 'uparrow', 'user', 'user-tie', 'vcard', 'wrench',
  3849. 'github', 'google', 'jabber', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  3850. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  3851. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  3852. 'partnership', 'payment', 'payment_vat', 'pencil-ruler', 'pictoconfirm', 'preview', 'project', 'projectpub', 'projecttask', 'question', 'refresh', 'region',
  3853. 'salary', 'shipment', 'state', 'supplier_invoice', 'supplier_invoicea', 'supplier_invoicer', 'supplier_invoiced',
  3854. 'technic', 'ticket',
  3855. 'error', 'warning',
  3856. 'recent', 'reception', 'recruitmentcandidature', 'recruitmentjobposition', 'replacement', 'resource', 'recurring','rss',
  3857. 'shapes', 'skill', 'square', 'stop-circle', 'supplier', 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  3858. 'timespent', 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda',
  3859. 'uncheck', 'url', 'user-cog', 'user-injured', 'user-md', 'vat', 'website', 'workstation', 'webhook', 'world', 'private',
  3860. 'conferenceorbooth', 'eventorganization',
  3861. 'stamp', 'signature'
  3862. ))) {
  3863. $fakey = $pictowithouttext;
  3864. $facolor = '';
  3865. $fasize = '';
  3866. $fa = 'fas';
  3867. 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'))) {
  3868. $fa = 'far';
  3869. }
  3870. if (in_array($pictowithouttext, array('black-tie', 'github', 'google', 'microsoft', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3871. $fa = 'fab';
  3872. }
  3873. $arrayconvpictotofa = array(
  3874. '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',
  3875. 'bank_account'=>'university',
  3876. 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'billr'=>'file-invoice-dollar', 'billd'=>'file-medical',
  3877. 'supplier_invoice'=>'file-invoice-dollar', 'supplier_invoicea'=>'file-excel', 'supplier_invoicer'=>'file-invoice-dollar', 'supplier_invoiced'=>'file-medical',
  3878. 'bom'=>'shapes',
  3879. 'card'=>'address-card', 'chart'=>'chart-line', 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'collab'=>'people-arrows', 'conversation'=>'comments', 'country'=>'globe-americas', 'cron'=>'business-time', 'cross'=>'times',
  3880. 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3881. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3882. 'accounting'=>'search-dollar', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3883. 'generate'=>'plus-square', 'hrm'=>'user-tie', 'incoterm'=>'truck-loading',
  3884. 'margin'=>'calculator', 'members'=>'user-friends', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3885. 'email'=>'at', 'establishment'=>'building', 'edit'=>'pencil-alt', 'entity'=>'globe',
  3886. 'graph'=>'chart-line', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3887. 'generic'=>'file', 'holiday'=>'umbrella-beach',
  3888. 'info'=>'info-circle', 'inventory'=>'boxes', 'intracommreport'=>'globe-europe', 'jobprofile'=>'cogs',
  3889. 'knowledgemanagement'=>'ticket-alt', 'label'=>'layer-group', 'line'=>'bars', 'loan'=>'money-bill-alt',
  3890. 'member'=>'user-alt', 'meeting'=>'chalkboard-teacher', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3891. 'trip'=>'wallet', 'expensereport'=>'wallet', 'group'=>'users', 'movement'=>'people-carry',
  3892. 'sign-out'=>'sign-out-alt',
  3893. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'switch_on_warning'=>'toggle-on', 'switch_on_red'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star',
  3894. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'filter'=>'filter',
  3895. 'list-alt'=>'list-alt', 'calendarlist'=>'bars', 'calendar'=>'calendar-alt', 'calendarmonth'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3896. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'currency'=>'dollar-sign', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3897. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3898. 'other'=>'square',
  3899. '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',
  3900. 'partnership'=>'handshake', 'payment'=>'money-check-alt', 'payment_vat'=>'money-check-alt', 'pictoconfirm'=>'check-square', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'puce'=>'angle-right',
  3901. 'recent' => 'check-square', 'reception'=>'dolly', 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3902. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3903. 'refresh'=>'redo', 'region'=>'map-marked', 'replacement'=>'exchange-alt', 'resource'=>'laptop-house', 'recurring'=>'history',
  3904. 'service'=>'concierge-bell',
  3905. 'skill'=>'shapes', 'state'=>'map-marked-alt', 'security'=>'key', 'salary'=>'wallet', 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'stripe'=>'stripe-s',
  3906. 'supplier'=>'building', 'technic'=>'cogs',
  3907. 'timespent'=>'clock', 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3908. 'title_agenda'=>'calendar-alt',
  3909. 'uncheck'=>'times', 'uparrow'=>'share', 'url'=>'external-link-alt', 'vat'=>'money-check-alt', 'vcard'=>'arrow-alt-circle-down',
  3910. 'jabber'=>'comment-o',
  3911. 'website'=>'globe-americas', 'workstation'=>'pallet', 'webhook'=>'bullseye', 'world'=>'globe', 'private'=>'user-lock',
  3912. 'conferenceorbooth'=>'chalkboard-teacher', 'eventorganization'=>'project-diagram'
  3913. );
  3914. if ($pictowithouttext == 'off') {
  3915. $fakey = 'fa-square';
  3916. $fasize = '1.3em';
  3917. } elseif ($pictowithouttext == 'on') {
  3918. $fakey = 'fa-check-square';
  3919. $fasize = '1.3em';
  3920. } elseif ($pictowithouttext == 'listlight') {
  3921. $fakey = 'fa-download';
  3922. $marginleftonlyshort = 1;
  3923. } elseif ($pictowithouttext == 'printer') {
  3924. $fakey = 'fa-print';
  3925. $fasize = '1.2em';
  3926. } elseif ($pictowithouttext == 'note') {
  3927. $fakey = 'fa-sticky-note';
  3928. $marginleftonlyshort = 1;
  3929. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3930. $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');
  3931. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3932. if (preg_match('/selected/', $pictowithouttext)) {
  3933. $facolor = '#888';
  3934. }
  3935. $marginleftonlyshort = 1;
  3936. } elseif (!empty($arrayconvpictotofa[$pictowithouttext])) {
  3937. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3938. } else {
  3939. $fakey = 'fa-'.$pictowithouttext;
  3940. }
  3941. if (in_array($pictowithouttext, array('dollyrevert', 'member', 'members', 'contract', 'group', 'resource', 'shipment'))) {
  3942. $morecss .= ' em092';
  3943. }
  3944. if (in_array($pictowithouttext, array('conferenceorbooth', 'collab', 'eventorganization', 'holiday', 'info', 'project', 'workstation'))) {
  3945. $morecss .= ' em088';
  3946. }
  3947. if (in_array($pictowithouttext, array('asset', 'intervention', 'payment', 'loan', 'partnership', 'stock', 'technic'))) {
  3948. $morecss .= ' em080';
  3949. }
  3950. // Define $marginleftonlyshort
  3951. $arrayconvpictotomarginleftonly = array(
  3952. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3953. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_on_red', 'switch_off',
  3954. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3955. );
  3956. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3957. $marginleftonlyshort = 0;
  3958. }
  3959. // Add CSS
  3960. $arrayconvpictotomorcess = array(
  3961. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accounting_account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account', 'asset'=>'infobox-bank_account',
  3962. 'bank_account'=>'infobox-bank_account',
  3963. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billr'=>'infobox-commande', 'billd'=>'infobox-commande',
  3964. 'margin'=>'infobox-bank_account', 'conferenceorbooth'=>'infobox-project',
  3965. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'collab'=>'infobox-action', 'conversation'=>'infobox-contrat',
  3966. 'donation'=>'infobox-commande', 'dolly'=>'infobox-commande', 'dollyrevert'=>'flip infobox-order_supplier',
  3967. 'ecm'=>'infobox-action', 'eventorganization'=>'infobox-project',
  3968. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3969. 'incoterm'=>'infobox-supplier_proposal',
  3970. 'currency'=>'infobox-bank_account', 'multicurrency'=>'infobox-bank_account',
  3971. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3972. 'order'=>'infobox-commande',
  3973. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3974. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4', 'switch_on_warning'=>'font-status4 warning', 'switch_on_red'=>'font-status8',
  3975. 'holiday'=>'infobox-holiday', 'info'=>'opacityhigh', 'invoice'=>'infobox-commande',
  3976. 'knowledgemanagement'=>'infobox-contrat rotate90', 'loan'=>'infobox-bank_account',
  3977. 'payment'=>'infobox-bank_account', 'payment_vat'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'pos'=>'infobox-bank_account', 'project'=>'infobox-project', 'projecttask'=>'infobox-project',
  3978. 'propal'=>'infobox-propal', 'proposal'=>'infobox-propal','private'=>'infobox-project',
  3979. 'reception'=>'flip', 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3980. 'resource'=>'infobox-action',
  3981. 'salary'=>'infobox-bank_account', 'shipment'=>'infobox-commande', 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3982. 'supplier'=>'infobox-order_supplier', 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3983. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'expensereport'=>'infobox-expensereport', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3984. 'vat'=>'infobox-bank_account',
  3985. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3986. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3987. );
  3988. if (!empty($arrayconvpictotomorcess[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  3989. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3990. }
  3991. // Define $color
  3992. $arrayconvpictotocolor = array(
  3993. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3994. 'cog'=>'#999', 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#6c6aa8', 'cron'=>'#555',
  3995. 'dynamicprice'=>'#a69944',
  3996. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999', 'language'=>'#555',
  3997. //'dolly'=>'#a69944', 'dollyrevert'=>'#a69944',
  3998. 'lock'=>'#ddd', 'lot'=>'#a69944',
  3999. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'inventory'=>'#a69944', 'stock'=>'#a69944', 'movement'=>'#a69944',
  4000. 'other'=>'#ddd', 'world'=>'#986c6a',
  4001. 'partnership'=>'#6c6aa8', 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'reception'=>'#a69944', 'resize'=>'#444', 'rss'=>'#cba',
  4002. //'shipment'=>'#a69944',
  4003. 'security'=>'#999', 'square'=>'#888', 'stop-circle'=>'#888', 'stats'=>'#444', 'switch_off'=>'#999', 'technic'=>'#999', 'timespent'=>'#555',
  4004. 'uncheck'=>'#800', 'uparrow'=>'#555', 'user-cog'=>'#999', 'country'=>'#aaa', 'globe-americas'=>'#aaa', 'region'=>'#aaa', 'state'=>'#aaa',
  4005. 'website'=>'#304', 'workstation'=>'#a69944'
  4006. );
  4007. if (isset($arrayconvpictotocolor[$pictowithouttext]) && strpos($picto, '_nocolor') === false) {
  4008. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  4009. }
  4010. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  4011. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  4012. $morestyle = '';
  4013. $reg = array();
  4014. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  4015. $morecss .= ($morecss ? ' ' : '').$reg[1];
  4016. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  4017. }
  4018. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  4019. $morestyle = $reg[1];
  4020. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  4021. }
  4022. $moreatt = trim($moreatt);
  4023. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  4024. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  4025. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4026. $enabledisablehtml .= $titlealt;
  4027. }*/
  4028. $enabledisablehtml .= '</span>';
  4029. return $enabledisablehtml;
  4030. }
  4031. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  4032. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  4033. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  4034. $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
  4035. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  4036. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  4037. }
  4038. // If we ask an image into $url/$mymodule/img (instead of default path)
  4039. $regs = array();
  4040. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  4041. $picto = $regs[1];
  4042. $path = $regs[2]; // $path is $mymodule
  4043. }
  4044. // Clean parameters
  4045. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  4046. $picto .= '.png';
  4047. }
  4048. // If alt path are defined, define url where img file is, according to physical path
  4049. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  4050. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  4051. if ($type == 'main') {
  4052. continue;
  4053. }
  4054. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  4055. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  4056. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  4057. break;
  4058. }
  4059. }
  4060. // $url is '' or '/custom', $path is current theme or
  4061. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  4062. }
  4063. if ($srconly) {
  4064. return $fullpathpicto;
  4065. }
  4066. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  4067. 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
  4068. }
  4069. /**
  4070. * Show a picto called object_picto (generic function)
  4071. *
  4072. * @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.
  4073. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  4074. * For external modules use imagename@mymodule to search into directory "img" of module.
  4075. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  4076. * @param int $pictoisfullpath If 1, image path is a full path
  4077. * @param int $srconly Return only content of the src attribute of img.
  4078. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4079. * @return string Return img tag
  4080. * @see img_picto(), img_picto_common()
  4081. */
  4082. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  4083. {
  4084. if (strpos($picto, '^') === 0) {
  4085. return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  4086. } else {
  4087. return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  4088. }
  4089. }
  4090. /**
  4091. * Show weather picto
  4092. *
  4093. * @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.
  4094. * @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).
  4095. * @param string $moreatt Add more attribute on img tag
  4096. * @param int $pictoisfullpath If 1, image path is a full path
  4097. * @param string $morecss More CSS
  4098. * @return string Return img tag
  4099. * @see img_object(), img_picto()
  4100. */
  4101. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  4102. {
  4103. global $conf;
  4104. if (is_numeric($picto)) {
  4105. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  4106. //$picto = $leveltopicto[$picto];
  4107. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  4108. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4109. $picto .= '.png';
  4110. }
  4111. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  4112. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  4113. }
  4114. /**
  4115. * Show picto (generic function)
  4116. *
  4117. * @param string $titlealt Text on alt and title of image. Alt only if param notitle is set to 1. If text is "TextA:TextB", use Text A on alt and Text B on title.
  4118. * @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.
  4119. * @param string $moreatt Add more attribute on img tag
  4120. * @param int $pictoisfullpath If 1, image path is a full path
  4121. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  4122. * @return string Return img tag
  4123. * @see img_object(), img_picto()
  4124. */
  4125. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $notitle = 0)
  4126. {
  4127. global $conf;
  4128. if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  4129. $picto .= '.png';
  4130. }
  4131. if ($pictoisfullpath) {
  4132. $path = $picto;
  4133. } else {
  4134. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  4135. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
  4136. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  4137. if (file_exists($themepath)) {
  4138. $path = $themepath;
  4139. }
  4140. }
  4141. }
  4142. return img_picto($titlealt, $path, $moreatt, 1, 0, $notitle);
  4143. }
  4144. /**
  4145. * Show logo action
  4146. *
  4147. * @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.
  4148. * @param string $numaction Action id or code to show
  4149. * @param string $picto Name of image file to show ('filenew', ...)
  4150. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  4151. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4152. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4153. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4154. * @param string $moreatt More attributes
  4155. * @return string Return an img tag
  4156. */
  4157. function img_action($titlealt, $numaction, $picto = '', $moreatt = '')
  4158. {
  4159. global $langs;
  4160. if (empty($titlealt) || $titlealt == 'default') {
  4161. if ($numaction == '-1' || $numaction == 'ST_NO') {
  4162. $numaction = -1;
  4163. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  4164. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  4165. $numaction = 0;
  4166. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  4167. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  4168. $numaction = 1;
  4169. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  4170. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  4171. $numaction = 2;
  4172. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  4173. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  4174. $numaction = 3;
  4175. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  4176. } else {
  4177. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  4178. $numaction = 0;
  4179. }
  4180. }
  4181. if (!is_numeric($numaction)) {
  4182. $numaction = 0;
  4183. }
  4184. return img_picto($titlealt, (empty($picto) ? 'stcomm'.$numaction.'.png' : $picto), $moreatt);
  4185. }
  4186. /**
  4187. * Show pdf logo
  4188. *
  4189. * @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.
  4190. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  4191. * @return string Retourne tag img
  4192. */
  4193. function img_pdf($titlealt = 'default', $size = 3)
  4194. {
  4195. global $langs;
  4196. if ($titlealt == 'default') {
  4197. $titlealt = $langs->trans('Show');
  4198. }
  4199. return img_picto($titlealt, 'pdf'.$size.'.png');
  4200. }
  4201. /**
  4202. * Show logo +
  4203. *
  4204. * @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.
  4205. * @param string $other Add more attributes on img
  4206. * @return string Return tag img
  4207. */
  4208. function img_edit_add($titlealt = 'default', $other = '')
  4209. {
  4210. global $langs;
  4211. if ($titlealt == 'default') {
  4212. $titlealt = $langs->trans('Add');
  4213. }
  4214. return img_picto($titlealt, 'edit_add.png', $other);
  4215. }
  4216. /**
  4217. * Show logo -
  4218. *
  4219. * @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.
  4220. * @param string $other Add more attributes on img
  4221. * @return string Return tag img
  4222. */
  4223. function img_edit_remove($titlealt = 'default', $other = '')
  4224. {
  4225. global $langs;
  4226. if ($titlealt == 'default') {
  4227. $titlealt = $langs->trans('Remove');
  4228. }
  4229. return img_picto($titlealt, 'edit_remove.png', $other);
  4230. }
  4231. /**
  4232. * Show logo editer/modifier fiche
  4233. *
  4234. * @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.
  4235. * @param integer $float If you have to put the style "float: right"
  4236. * @param string $other Add more attributes on img
  4237. * @return string Return tag img
  4238. */
  4239. function img_edit($titlealt = 'default', $float = 0, $other = '')
  4240. {
  4241. global $langs;
  4242. if ($titlealt == 'default') {
  4243. $titlealt = $langs->trans('Modify');
  4244. }
  4245. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  4246. }
  4247. /**
  4248. * Show logo view card
  4249. *
  4250. * @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.
  4251. * @param integer $float If you have to put the style "float: right"
  4252. * @param string $other Add more attributes on img
  4253. * @return string Return tag img
  4254. */
  4255. function img_view($titlealt = 'default', $float = 0, $other = 'class="valignmiddle"')
  4256. {
  4257. global $langs;
  4258. if ($titlealt == 'default') {
  4259. $titlealt = $langs->trans('View');
  4260. }
  4261. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  4262. return img_picto($titlealt, 'eye', $moreatt);
  4263. }
  4264. /**
  4265. * Show delete logo
  4266. *
  4267. * @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.
  4268. * @param string $other Add more attributes on img
  4269. * @param string $morecss More CSS
  4270. * @return string Retourne tag img
  4271. */
  4272. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  4273. {
  4274. global $langs;
  4275. if ($titlealt == 'default') {
  4276. $titlealt = $langs->trans('Delete');
  4277. }
  4278. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  4279. }
  4280. /**
  4281. * Show printer logo
  4282. *
  4283. * @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.
  4284. * @param string $other Add more attributes on img
  4285. * @return string Retourne tag img
  4286. */
  4287. function img_printer($titlealt = "default", $other = '')
  4288. {
  4289. global $langs;
  4290. if ($titlealt == "default") {
  4291. $titlealt = $langs->trans("Print");
  4292. }
  4293. return img_picto($titlealt, 'printer.png', $other);
  4294. }
  4295. /**
  4296. * Show split logo
  4297. *
  4298. * @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.
  4299. * @param string $other Add more attributes on img
  4300. * @return string Retourne tag img
  4301. */
  4302. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  4303. {
  4304. global $langs;
  4305. if ($titlealt == 'default') {
  4306. $titlealt = $langs->trans('Split');
  4307. }
  4308. return img_picto($titlealt, 'split.png', $other);
  4309. }
  4310. /**
  4311. * Show help logo with cursor "?"
  4312. *
  4313. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  4314. * @param int|string $usealttitle Text to use as alt title
  4315. * @return string Return tag img
  4316. */
  4317. function img_help($usehelpcursor = 1, $usealttitle = 1)
  4318. {
  4319. global $langs;
  4320. if ($usealttitle) {
  4321. if (is_string($usealttitle)) {
  4322. $usealttitle = dol_escape_htmltag($usealttitle);
  4323. } else {
  4324. $usealttitle = $langs->trans('Info');
  4325. }
  4326. }
  4327. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  4328. }
  4329. /**
  4330. * Show info 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. * @return string Return img tag
  4334. */
  4335. function img_info($titlealt = 'default')
  4336. {
  4337. global $langs;
  4338. if ($titlealt == 'default') {
  4339. $titlealt = $langs->trans('Informations');
  4340. }
  4341. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  4342. }
  4343. /**
  4344. * Show warning logo
  4345. *
  4346. * @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.
  4347. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  4348. * @param string $morecss Add more CSS
  4349. * @return string Return img tag
  4350. */
  4351. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  4352. {
  4353. global $langs;
  4354. if ($titlealt == 'default') {
  4355. $titlealt = $langs->trans('Warning');
  4356. }
  4357. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  4358. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  4359. }
  4360. /**
  4361. * Show error logo
  4362. *
  4363. * @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.
  4364. * @return string Return img tag
  4365. */
  4366. function img_error($titlealt = 'default')
  4367. {
  4368. global $langs;
  4369. if ($titlealt == 'default') {
  4370. $titlealt = $langs->trans('Error');
  4371. }
  4372. return img_picto($titlealt, 'error.png');
  4373. }
  4374. /**
  4375. * Show next logo
  4376. *
  4377. * @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.
  4378. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4379. * @return string Return img tag
  4380. */
  4381. function img_next($titlealt = 'default', $moreatt = '')
  4382. {
  4383. global $langs;
  4384. if ($titlealt == 'default') {
  4385. $titlealt = $langs->trans('Next');
  4386. }
  4387. //return img_picto($titlealt, 'next.png', $moreatt);
  4388. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4389. }
  4390. /**
  4391. * Show previous logo
  4392. *
  4393. * @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.
  4394. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4395. * @return string Return img tag
  4396. */
  4397. function img_previous($titlealt = 'default', $moreatt = '')
  4398. {
  4399. global $langs;
  4400. if ($titlealt == 'default') {
  4401. $titlealt = $langs->trans('Previous');
  4402. }
  4403. //return img_picto($titlealt, 'previous.png', $moreatt);
  4404. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  4405. }
  4406. /**
  4407. * Show down arrow logo
  4408. *
  4409. * @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.
  4410. * @param int $selected Selected
  4411. * @param string $moreclass Add more CSS classes
  4412. * @return string Return img tag
  4413. */
  4414. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  4415. {
  4416. global $langs;
  4417. if ($titlealt == 'default') {
  4418. $titlealt = $langs->trans('Down');
  4419. }
  4420. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  4421. }
  4422. /**
  4423. * Show top arrow logo
  4424. *
  4425. * @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.
  4426. * @param int $selected Selected
  4427. * @param string $moreclass Add more CSS classes
  4428. * @return string Return img tag
  4429. */
  4430. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  4431. {
  4432. global $langs;
  4433. if ($titlealt == 'default') {
  4434. $titlealt = $langs->trans('Up');
  4435. }
  4436. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  4437. }
  4438. /**
  4439. * Show left arrow logo
  4440. *
  4441. * @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.
  4442. * @param int $selected Selected
  4443. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4444. * @return string Return img tag
  4445. */
  4446. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  4447. {
  4448. global $langs;
  4449. if ($titlealt == 'default') {
  4450. $titlealt = $langs->trans('Left');
  4451. }
  4452. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  4453. }
  4454. /**
  4455. * Show right arrow logo
  4456. *
  4457. * @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.
  4458. * @param int $selected Selected
  4459. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  4460. * @return string Return img tag
  4461. */
  4462. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  4463. {
  4464. global $langs;
  4465. if ($titlealt == 'default') {
  4466. $titlealt = $langs->trans('Right');
  4467. }
  4468. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  4469. }
  4470. /**
  4471. * Show tick logo if allowed
  4472. *
  4473. * @param string $allow Allow
  4474. * @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.
  4475. * @return string Return img tag
  4476. */
  4477. function img_allow($allow, $titlealt = 'default')
  4478. {
  4479. global $langs;
  4480. if ($titlealt == 'default') {
  4481. $titlealt = $langs->trans('Active');
  4482. }
  4483. if ($allow == 1) {
  4484. return img_picto($titlealt, 'tick.png');
  4485. }
  4486. return '-';
  4487. }
  4488. /**
  4489. * Return image of a credit card according to its brand name
  4490. *
  4491. * @param string $brand Brand name of credit card
  4492. * @param string $morecss More CSS
  4493. * @return string Return img tag
  4494. */
  4495. function img_credit_card($brand, $morecss = null)
  4496. {
  4497. if (is_null($morecss)) {
  4498. $morecss = 'fa-2x';
  4499. }
  4500. if ($brand == 'visa' || $brand == 'Visa') {
  4501. $brand = 'cc-visa';
  4502. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  4503. $brand = 'cc-mastercard';
  4504. } elseif ($brand == 'amex' || $brand == 'American Express') {
  4505. $brand = 'cc-amex';
  4506. } elseif ($brand == 'discover' || $brand == 'Discover') {
  4507. $brand = 'cc-discover';
  4508. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  4509. $brand = 'cc-jcb';
  4510. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  4511. $brand = 'cc-diners-club';
  4512. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  4513. $brand = 'credit-card';
  4514. }
  4515. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  4516. }
  4517. /**
  4518. * Show MIME img of a file
  4519. *
  4520. * @param string $file Filename
  4521. * @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.
  4522. * @param string $morecss More css
  4523. * @return string Return img tag
  4524. */
  4525. function img_mime($file, $titlealt = '', $morecss = '')
  4526. {
  4527. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4528. $mimetype = dol_mimetype($file, '', 1);
  4529. $mimeimg = dol_mimetype($file, '', 2);
  4530. $mimefa = dol_mimetype($file, '', 4);
  4531. if (empty($titlealt)) {
  4532. $titlealt = 'Mime type: '.$mimetype;
  4533. }
  4534. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  4535. return '<i class="fa fa-'.$mimefa.' paddingright'.($morecss ? ' '.$morecss : '').'"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  4536. }
  4537. /**
  4538. * Show search logo
  4539. *
  4540. * @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.
  4541. * @param string $other Add more attributes on img
  4542. * @return string Retourne tag img
  4543. */
  4544. function img_search($titlealt = 'default', $other = '')
  4545. {
  4546. global $conf, $langs;
  4547. if ($titlealt == 'default') {
  4548. $titlealt = $langs->trans('Search');
  4549. }
  4550. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  4551. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  4552. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4553. return $input;
  4554. }
  4555. /**
  4556. * Show search logo
  4557. *
  4558. * @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.
  4559. * @param string $other Add more attributes on img
  4560. * @return string Retourne tag img
  4561. */
  4562. function img_searchclear($titlealt = 'default', $other = '')
  4563. {
  4564. global $conf, $langs;
  4565. if ($titlealt == 'default') {
  4566. $titlealt = $langs->trans('Search');
  4567. }
  4568. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  4569. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  4570. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  4571. return $input;
  4572. }
  4573. /**
  4574. * Show information for admin users or standard users
  4575. *
  4576. * @param string $text Text info
  4577. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  4578. * @param int $nodiv No div
  4579. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error', 'warning', 'xxx'=Other
  4580. * @param string $morecss More CSS ('', 'warning', 'error')
  4581. * @param string $textfordropdown Show a text to click to dropdown the info box.
  4582. * @return string String with info text
  4583. */
  4584. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = 'hideonsmartphone', $textfordropdown = '')
  4585. {
  4586. global $conf, $langs;
  4587. if ($infoonimgalt) {
  4588. $result = img_picto($text, 'info', 'class="'.($morecss ? ' '.$morecss : '').'"');
  4589. } else {
  4590. if (empty($conf->use_javascript_ajax)) {
  4591. $textfordropdown = '';
  4592. }
  4593. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  4594. $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>');
  4595. if ($textfordropdown) {
  4596. $tmpresult = '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  4597. $tmpresult .= '<script nonce="'.getNonce().'" type="text/javascript">
  4598. jQuery(document).ready(function() {
  4599. jQuery(".'.$class.'text").click(function() {
  4600. console.log("toggle text");
  4601. jQuery(".'.$class.'").toggle();
  4602. });
  4603. });
  4604. </script>';
  4605. $result = $tmpresult.$result;
  4606. }
  4607. }
  4608. return $result;
  4609. }
  4610. /**
  4611. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  4612. * This function must be called when a blocking technical error is encountered.
  4613. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  4614. *
  4615. * @param DoliDB|string $db Database handler
  4616. * @param string|string[] $error String or array of errors strings to show
  4617. * @param array $errors Array of errors
  4618. * @return void
  4619. * @see dol_htmloutput_errors()
  4620. */
  4621. function dol_print_error($db = '', $error = '', $errors = null)
  4622. {
  4623. global $conf, $langs, $argv;
  4624. global $dolibarr_main_prod;
  4625. $out = '';
  4626. $syslog = '';
  4627. // If error occurs before the $lang object was loaded
  4628. if (!$langs) {
  4629. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  4630. $langs = new Translate('', $conf);
  4631. $langs->load("main");
  4632. }
  4633. // Load translation files required by the error messages
  4634. $langs->loadLangs(array('main', 'errors'));
  4635. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4636. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  4637. if (getDolGlobalInt('MAIN_FEATURES_LEVEL') > 0) {
  4638. $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";
  4639. }
  4640. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  4641. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  4642. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  4643. if (isset($conf->global->MAIN_FEATURES_LEVEL)) {
  4644. $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".getDolGlobalInt('MAIN_FEATURES_LEVEL')."<br>\n";
  4645. }
  4646. if (function_exists("phpversion")) {
  4647. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  4648. }
  4649. $out .= "<b>".$langs->trans("Server").":</b> ".(isset($_SERVER["SERVER_SOFTWARE"]) ? dol_htmlentities($_SERVER["SERVER_SOFTWARE"], ENT_COMPAT) : '')."<br>\n";
  4650. if (function_exists("php_uname")) {
  4651. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  4652. }
  4653. $out .= "<b>".$langs->trans("UserAgent").":</b> ".(isset($_SERVER["HTTP_USER_AGENT"]) ? dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT) : '')."<br>\n";
  4654. $out .= "<br>\n";
  4655. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT)."<br>\n";
  4656. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT) : '')."<br>\n";
  4657. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu, ENT_COMPAT) : '')."<br>\n";
  4658. $out .= "<br>\n";
  4659. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  4660. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  4661. } else { // Mode CLI
  4662. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  4663. $syslog .= "pid=".dol_getmypid();
  4664. }
  4665. if (!empty($conf->modules)) {
  4666. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  4667. }
  4668. if (is_object($db)) {
  4669. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4670. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  4671. $lastqueryerror = $db->lastqueryerror();
  4672. if (!utf8_check($lastqueryerror)) {
  4673. $lastqueryerror = "SQL error string is not a valid UTF8 string. We can't show it.";
  4674. }
  4675. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($lastqueryerror ? dol_escape_htmltag($lastqueryerror) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4676. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4677. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  4678. $out .= "<br>\n";
  4679. } else { // Mode CLI
  4680. // No dol_escape_htmltag for output, we are in CLI mode
  4681. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  4682. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4683. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4684. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  4685. }
  4686. $syslog .= ", sql=".$db->lastquery();
  4687. $syslog .= ", db_error=".$db->lasterror();
  4688. }
  4689. if ($error || $errors) {
  4690. $langs->load("errors");
  4691. // Merge all into $errors array
  4692. if (is_array($error) && is_array($errors)) {
  4693. $errors = array_merge($error, $errors);
  4694. } elseif (is_array($error)) {
  4695. $errors = $error;
  4696. } elseif (is_array($errors)) {
  4697. $errors = array_merge(array($error), $errors);
  4698. } else {
  4699. $errors = array_merge(array($error), array($errors));
  4700. }
  4701. foreach ($errors as $msg) {
  4702. if (empty($msg)) {
  4703. continue;
  4704. }
  4705. if ($_SERVER['DOCUMENT_ROOT']) { // Mode web
  4706. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  4707. } else // Mode CLI
  4708. {
  4709. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  4710. }
  4711. $syslog .= ", msg=".$msg;
  4712. }
  4713. }
  4714. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
  4715. xdebug_print_function_stack();
  4716. $out .= '<b>XDebug informations:</b>'."<br>\n";
  4717. $out .= 'File: '.xdebug_call_file()."<br>\n";
  4718. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  4719. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  4720. $out .= "<br>\n";
  4721. }
  4722. // Return a http header with error code if possible
  4723. if (!headers_sent()) {
  4724. if (function_exists('top_httphead')) { // In CLI context, the method does not exists
  4725. top_httphead();
  4726. }
  4727. http_response_code(500);
  4728. }
  4729. if (empty($dolibarr_main_prod)) {
  4730. print $out;
  4731. } else {
  4732. if (empty($langs->defaultlang)) {
  4733. $langs->setDefaultLang();
  4734. }
  4735. $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.
  4736. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  4737. 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";
  4738. print $langs->trans("DolibarrHasDetectedError").'. ';
  4739. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  4740. define("MAIN_CORE_ERROR", 1);
  4741. }
  4742. dol_syslog("Error ".$syslog, LOG_ERR);
  4743. }
  4744. /**
  4745. * Show a public email and error code to contact if technical error
  4746. *
  4747. * @param string $prefixcode Prefix of public error code
  4748. * @param string $errormessage Complete error message
  4749. * @param array $errormessages Array of error messages
  4750. * @param string $morecss More css
  4751. * @param string $email Email
  4752. * @return void
  4753. */
  4754. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  4755. {
  4756. global $langs, $conf;
  4757. if (empty($email)) {
  4758. $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  4759. }
  4760. $langs->load("errors");
  4761. $now = dol_now();
  4762. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  4763. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  4764. if ($errormessage) {
  4765. print '<br><br>'.$errormessage;
  4766. }
  4767. if (is_array($errormessages) && count($errormessages)) {
  4768. foreach ($errormessages as $mesgtoshow) {
  4769. print '<br><br>'.$mesgtoshow;
  4770. }
  4771. }
  4772. print '</div></div>';
  4773. }
  4774. /**
  4775. * Show title line of an array
  4776. *
  4777. * @param string $name Label of field
  4778. * @param string $file Url used when we click on sort picto
  4779. * @param string $field Field to use for new sorting
  4780. * @param string $begin ("" by defaut)
  4781. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4782. * @param string $moreattrib Options of attribute td ("" by defaut)
  4783. * @param string $sortfield Current field used to sort
  4784. * @param string $sortorder Current sort order
  4785. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4786. * @param string $tooltip Tooltip
  4787. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4788. * @return void
  4789. */
  4790. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "", $forcenowrapcolumntitle = 0)
  4791. {
  4792. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip, $forcenowrapcolumntitle);
  4793. }
  4794. /**
  4795. * Get title line of an array
  4796. *
  4797. * @param string $name Translation key of field to show or complete HTML string to show
  4798. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  4799. * @param string $file Url used when we click on sort picto
  4800. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  4801. * @param string $begin ("" by defaut)
  4802. * @param string $moreparam Add more parameters on sort url links ("" by default)
  4803. * @param string $moreattrib Add more attributes on th ("" by defaut). To add more css class, use param $prefix.
  4804. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  4805. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  4806. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  4807. * @param string $disablesortlink 1=Disable sort link
  4808. * @param string $tooltip Tooltip
  4809. * @param string $forcenowrapcolumntitle No need for use 'wrapcolumntitle' css style
  4810. * @return string
  4811. */
  4812. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '', $forcenowrapcolumntitle = 0)
  4813. {
  4814. global $conf, $langs, $form;
  4815. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  4816. if ($moreattrib == 'class="right"') {
  4817. $prefix .= 'right '; // For backward compatibility
  4818. }
  4819. $sortorder = strtoupper($sortorder);
  4820. $out = '';
  4821. $sortimg = '';
  4822. $tag = 'th';
  4823. if ($thead == 2) {
  4824. $tag = 'div';
  4825. }
  4826. $tmpsortfield = explode(',', $sortfield);
  4827. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  4828. $tmpfield = explode(',', $field);
  4829. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  4830. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle)) {
  4831. $prefix = 'wrapcolumntitle '.$prefix;
  4832. }
  4833. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  4834. // If field is used as sort criteria we use a specific css class liste_titre_sel
  4835. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  4836. $liste_titre = 'liste_titre';
  4837. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  4838. $liste_titre = 'liste_titre_sel';
  4839. }
  4840. $tagstart = '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  4841. //$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)).'"' : '');
  4842. $tagstart .= ($name && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) && empty($forcenowrapcolumntitle) && !dol_textishtml($name)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '';
  4843. $tagstart .= '>';
  4844. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4845. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4846. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4847. $options = preg_replace('/&+/i', '&', $options);
  4848. if (!preg_match('/^&/', $options)) {
  4849. $options = '&'.$options;
  4850. }
  4851. $sortordertouseinlink = '';
  4852. if ($field1 != $sortfield1) { // We are on another field than current sorted field
  4853. if (preg_match('/^DESC/i', $sortorder)) {
  4854. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4855. } else { // We reverse the var $sortordertouseinlink
  4856. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4857. }
  4858. } else { // We are on field that is the first current sorting criteria
  4859. if (preg_match('/^ASC/i', $sortorder)) { // We reverse the var $sortordertouseinlink
  4860. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  4861. } else {
  4862. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  4863. }
  4864. }
  4865. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  4866. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  4867. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  4868. $out .= '>';
  4869. }
  4870. if ($tooltip) {
  4871. // You can also use 'TranslationString:keyfortooltiponclick' for a tooltip on click.
  4872. if (preg_match('/:\w+$/', $tooltip)) {
  4873. $tmptooltip = explode(':', $tooltip);
  4874. } else {
  4875. $tmptooltip = array($tooltip);
  4876. }
  4877. $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tmptooltip[0]), 1, 'help', '', 0, 3, (empty($tmptooltip[1]) ? '' : 'extra_'.str_replace('.', '_', $field).'_'.$tmptooltip[1]));
  4878. } else {
  4879. $out .= $langs->trans($name);
  4880. }
  4881. if (empty($thead) && $field && empty($disablesortlink)) { // If this is a sort field
  4882. $out .= '</a>';
  4883. }
  4884. if (empty($thead) && $field) { // If this is a sort field
  4885. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  4886. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  4887. $options = preg_replace('/&+/i', '&', $options);
  4888. if (!preg_match('/^&/', $options)) {
  4889. $options = '&'.$options;
  4890. }
  4891. if (!$sortorder || ($field1 != $sortfield1)) {
  4892. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4893. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4894. } else {
  4895. if (preg_match('/^DESC/', $sortorder)) {
  4896. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  4897. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  4898. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingright').'</span>';
  4899. }
  4900. if (preg_match('/^ASC/', $sortorder)) {
  4901. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  4902. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  4903. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingright').'</span>';
  4904. }
  4905. }
  4906. }
  4907. $tagend = '</'.$tag.'>';
  4908. $out = $tagstart.$sortimg.$out.$tagend;
  4909. return $out;
  4910. }
  4911. /**
  4912. * Show a title.
  4913. *
  4914. * @param string $title Title to show
  4915. * @return void
  4916. * @deprecated Use load_fiche_titre instead
  4917. * @see load_fiche_titre()
  4918. */
  4919. function print_titre($title)
  4920. {
  4921. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  4922. print '<div class="titre">'.$title.'</div>';
  4923. }
  4924. /**
  4925. * Show a title with picto
  4926. *
  4927. * @param string $title Title to show
  4928. * @param string $mesg Added message to show on right
  4929. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4930. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4931. * @param int $id To force an id on html objects
  4932. * @return void
  4933. * @deprecated Use print load_fiche_titre instead
  4934. */
  4935. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  4936. {
  4937. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  4938. }
  4939. /**
  4940. * Load a title with picto
  4941. *
  4942. * @param string $titre Title to show
  4943. * @param string $morehtmlright Added message to show on right
  4944. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4945. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4946. * @param string $id To force an id on html objects
  4947. * @param string $morecssontable More css on table
  4948. * @param string $morehtmlcenter Added message to show on center
  4949. * @return string
  4950. * @see print_barre_liste()
  4951. */
  4952. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  4953. {
  4954. global $conf;
  4955. $return = '';
  4956. if ($picto == 'setup') {
  4957. $picto = 'generic';
  4958. }
  4959. $return .= "\n";
  4960. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  4961. $return .= '<tr class="titre">';
  4962. if ($picto) {
  4963. $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  4964. }
  4965. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  4966. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  4967. $return .= '</td>';
  4968. if (dol_strlen($morehtmlcenter)) {
  4969. $return .= '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  4970. }
  4971. if (dol_strlen($morehtmlright)) {
  4972. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle col-right">'.$morehtmlright.'</td>';
  4973. }
  4974. $return .= '</tr></table>'."\n";
  4975. return $return;
  4976. }
  4977. /**
  4978. * Print a title with navigation controls for pagination
  4979. *
  4980. * @param string $titre Title to show (required)
  4981. * @param int|null $page Numero of page to show in navigation links (required)
  4982. * @param string $file Url of page (required)
  4983. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4984. * @param string $sortfield Field to sort on ('' by default)
  4985. * @param string $sortorder Order to sort ('' by default)
  4986. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4987. * @param int $num Number of records found by select with limit+1
  4988. * @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.
  4989. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4990. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4991. * @param string $morehtmlright More html to show (after arrows)
  4992. * @param string $morecss More css to the table
  4993. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4994. * @param int $hideselectlimit Force to hide select limit
  4995. * @param int $hidenavigation Force to hide the arrows and page for navigation
  4996. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4997. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4998. * @return void
  4999. */
  5000. 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 = '')
  5001. {
  5002. global $conf, $langs;
  5003. $savlimit = $limit;
  5004. $savtotalnboflines = $totalnboflines;
  5005. $totalnboflines = abs((int) $totalnboflines);
  5006. $page = (int) $page;
  5007. if ($picto == 'setup') {
  5008. $picto = 'title_setup.png';
  5009. }
  5010. if (($conf->browser->name == 'ie') && $picto == 'generic') {
  5011. $picto = 'title.gif';
  5012. }
  5013. if ($limit < 0) {
  5014. $limit = $conf->liste_limit;
  5015. }
  5016. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
  5017. $nextpage = 1;
  5018. } else {
  5019. $nextpage = 0;
  5020. }
  5021. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage.'-hideselectlimit='.$hideselectlimit.'-hidenavigation='.$hidenavigation;
  5022. print "\n";
  5023. print "<!-- Begin title -->\n";
  5024. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  5025. // Left
  5026. if ($picto && $titre) {
  5027. print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  5028. }
  5029. print '<td class="nobordernopadding valignmiddle col-title">';
  5030. print '<div class="titre inline-block">'.$titre;
  5031. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
  5032. print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  5033. }
  5034. print '</div></td>';
  5035. // Center
  5036. if ($morehtmlcenter && empty($conf->dol_optimize_smallscreen)) {
  5037. print '<td class="nobordernopadding center valignmiddle col-center">'.$morehtmlcenter.'</td>';
  5038. }
  5039. // Right
  5040. print '<td class="nobordernopadding valignmiddle right col-right">';
  5041. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  5042. if ($sortfield) {
  5043. $options .= "&sortfield=".urlencode($sortfield);
  5044. }
  5045. if ($sortorder) {
  5046. $options .= "&sortorder=".urlencode($sortorder);
  5047. }
  5048. // Show navigation bar
  5049. $pagelist = '';
  5050. if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
  5051. if ($totalnboflines) { // If we know total nb of lines
  5052. // Define nb of extra page links before and after selected page + ... + first or last
  5053. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  5054. if ($limit > 0) {
  5055. $nbpages = ceil($totalnboflines / $limit);
  5056. } else {
  5057. $nbpages = 1;
  5058. }
  5059. $cpt = ($page - $maxnbofpage);
  5060. if ($cpt < 0) {
  5061. $cpt = 0;
  5062. }
  5063. if ($cpt >= 1) {
  5064. if (empty($pagenavastextinput)) {
  5065. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  5066. if ($cpt > 2) {
  5067. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5068. } elseif ($cpt == 2) {
  5069. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  5070. }
  5071. }
  5072. }
  5073. do {
  5074. if ($pagenavastextinput) {
  5075. if ($cpt == $page) {
  5076. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  5077. $pagelist .= '/';
  5078. }
  5079. } else {
  5080. if ($cpt == $page) {
  5081. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  5082. } else {
  5083. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  5084. }
  5085. }
  5086. $cpt++;
  5087. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  5088. if (empty($pagenavastextinput)) {
  5089. if ($cpt < $nbpages) {
  5090. if ($cpt < $nbpages - 2) {
  5091. $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  5092. } elseif ($cpt == $nbpages - 2) {
  5093. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  5094. }
  5095. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5096. }
  5097. } else {
  5098. //var_dump($page.' '.$cpt.' '.$nbpages);
  5099. $pagelist .= '<li class="pagination paginationlastpage"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  5100. }
  5101. } else {
  5102. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  5103. }
  5104. }
  5105. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  5106. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow, $hidenavigation); // output the div and ul for previous/last completed with page numbers into $pagelist
  5107. }
  5108. // js to autoselect page field on focus
  5109. if ($pagenavastextinput) {
  5110. print ajax_autoselect('.pageplusone');
  5111. }
  5112. print '</td>';
  5113. print '</tr>';
  5114. print '</table>'."\n";
  5115. // Center
  5116. if ($morehtmlcenter && !empty($conf->dol_optimize_smallscreen)) {
  5117. print '<div class="nobordernopadding marginbottomonly center valignmiddle col-center centpercent">'.$morehtmlcenter.'</div>';
  5118. }
  5119. print "<!-- End title -->\n\n";
  5120. }
  5121. /**
  5122. * Function to show navigation arrows into lists
  5123. *
  5124. * @param int $page Number of page
  5125. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  5126. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  5127. * @param integer $nextpage Do we show a next page button
  5128. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  5129. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  5130. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  5131. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  5132. * @param int $hideselectlimit Force to hide select limit
  5133. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  5134. * @param int $hidenavigation Force to hide the switch mode view and the navigation tool (select limit, arrows $betweenarrows and $afterarrows but not $beforearrows)
  5135. * @return void
  5136. */
  5137. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '', $hidenavigation = 0)
  5138. {
  5139. global $conf, $langs;
  5140. print '<div class="pagination"><ul>';
  5141. if ($beforearrows) {
  5142. print '<li class="paginationbeforearrows">';
  5143. print $beforearrows;
  5144. print '</li>';
  5145. }
  5146. if (empty($hidenavigation)) {
  5147. if ((int) $limit > 0 && empty($hideselectlimit)) {
  5148. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000';
  5149. $pagesizechoices .= ',5000:5000,10000:10000,20000:20000';
  5150. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  5151. //$pagesizechoices.=',2:2';
  5152. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) {
  5153. $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  5154. }
  5155. print '<li class="pagination">';
  5156. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  5157. $tmpchoice = explode(',', $pagesizechoices);
  5158. $tmpkey = $limit.':'.$limit;
  5159. if (!in_array($tmpkey, $tmpchoice)) {
  5160. $tmpchoice[] = $tmpkey;
  5161. }
  5162. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  5163. if (!in_array($tmpkey, $tmpchoice)) {
  5164. $tmpchoice[] = $tmpkey;
  5165. }
  5166. asort($tmpchoice, SORT_NUMERIC);
  5167. foreach ($tmpchoice as $val) {
  5168. $selected = '';
  5169. $tmp = explode(':', $val);
  5170. $key = $tmp[0];
  5171. $val = $tmp[1];
  5172. if ($key != '' && $val != '') {
  5173. if ((int) $key == (int) $limit) {
  5174. $selected = ' selected="selected"';
  5175. }
  5176. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  5177. }
  5178. }
  5179. print '</select>';
  5180. if ($conf->use_javascript_ajax) {
  5181. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  5182. <script>
  5183. jQuery(document).ready(function () {
  5184. jQuery(".selectlimit").change(function() {
  5185. console.log("Change limit. Send submit");
  5186. $(this).parents(\'form:first\').submit();
  5187. });
  5188. });
  5189. </script>
  5190. ';
  5191. }
  5192. print '</li>';
  5193. }
  5194. if ($page > 0) {
  5195. 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>';
  5196. }
  5197. if ($betweenarrows) {
  5198. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  5199. print $betweenarrows;
  5200. print '<!--</div>-->';
  5201. }
  5202. if ($nextpage > 0) {
  5203. 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>';
  5204. }
  5205. if ($afterarrows) {
  5206. print '<li class="paginationafterarrows">';
  5207. print $afterarrows;
  5208. print '</li>';
  5209. }
  5210. }
  5211. print '</ul></div>'."\n";
  5212. }
  5213. /**
  5214. * Return a string with VAT rate label formated for view output
  5215. * Used into pdf and HTML pages
  5216. *
  5217. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  5218. * @param boolean $addpercent Add a percent % sign in output
  5219. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  5220. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  5221. * @param int $html Used for html output
  5222. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  5223. */
  5224. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0, $html = 0)
  5225. {
  5226. $morelabel = '';
  5227. if (preg_match('/%/', $rate)) {
  5228. $rate = str_replace('%', '', $rate);
  5229. $addpercent = true;
  5230. }
  5231. $reg = array();
  5232. if (preg_match('/\((.*)\)/', $rate, $reg)) {
  5233. $morelabel = ' ('.$reg[1].')';
  5234. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  5235. $morelabel = ' '.($html ? '<span class="opacitymedium">' : '').'('.$reg[1].')'.($html ? '</span>' : '');
  5236. }
  5237. if (preg_match('/\*/', $rate)) {
  5238. $rate = str_replace('*', '', $rate);
  5239. $info_bits |= 1;
  5240. }
  5241. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  5242. if (!preg_match('/\//', $rate)) {
  5243. $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  5244. } else {
  5245. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  5246. $ret = $rate.($addpercent ? '%' : '');
  5247. }
  5248. if (($info_bits & 1) && $usestarfornpr >= 0) {
  5249. $ret .= ' *';
  5250. }
  5251. $ret .= $morelabel;
  5252. return $ret;
  5253. }
  5254. /**
  5255. * Function to format a value into an amount for visual output
  5256. * Function used into PDF and HTML pages
  5257. *
  5258. * @param float $amount Amount to format
  5259. * @param integer $form Type of format, HTML or not (not by default)
  5260. * @param Translate|string $outlangs Object langs for output. '' use default lang. 'none' use international separators.
  5261. * @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.
  5262. * @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)
  5263. * @param int|string $forcerounding MAXIMUM number 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
  5264. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  5265. * @return string String with formated amount
  5266. *
  5267. * @see price2num() Revert function of price
  5268. */
  5269. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  5270. {
  5271. global $langs, $conf;
  5272. // Clean parameters
  5273. if (empty($amount)) {
  5274. $amount = 0; // To have a numeric value if amount not defined or = ''
  5275. }
  5276. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  5277. if ($rounding == -1) {
  5278. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  5279. }
  5280. $nbdecimal = $rounding;
  5281. if ($outlangs === 'none') {
  5282. // Use international separators
  5283. $dec = '.';
  5284. $thousand = '';
  5285. } else {
  5286. // Output separators by default (french)
  5287. $dec = ',';
  5288. $thousand = ' ';
  5289. // If $outlangs not forced, we use use language
  5290. if (!is_object($outlangs)) {
  5291. $outlangs = $langs;
  5292. }
  5293. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5294. $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  5295. }
  5296. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5297. $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  5298. }
  5299. if ($thousand == 'None') {
  5300. $thousand = '';
  5301. } elseif ($thousand == 'Space') {
  5302. $thousand = ' ';
  5303. }
  5304. }
  5305. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5306. //print "amount=".$amount."-";
  5307. $amount = str_replace(',', '.', $amount); // should be useless
  5308. //print $amount."-";
  5309. $datas = explode('.', $amount);
  5310. $decpart = isset($datas[1]) ? $datas[1] : '';
  5311. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  5312. //print "decpart=".$decpart."<br>";
  5313. $end = '';
  5314. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  5315. if (dol_strlen($decpart) > $nbdecimal) {
  5316. $nbdecimal = dol_strlen($decpart);
  5317. }
  5318. // Si on depasse max
  5319. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN) {
  5320. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  5321. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
  5322. // Si un affichage est tronque, on montre des ...
  5323. $end = '...';
  5324. }
  5325. }
  5326. // If force rounding
  5327. if ((string) $forcerounding != '-1') {
  5328. if ($forcerounding === 'MU') {
  5329. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5330. } elseif ($forcerounding === 'MT') {
  5331. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5332. } elseif ($forcerounding >= 0) {
  5333. $nbdecimal = $forcerounding;
  5334. }
  5335. }
  5336. // Format number
  5337. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  5338. if ($form) {
  5339. $output = preg_replace('/\s/', '&nbsp;', $output);
  5340. $output = preg_replace('/\'/', '&#039;', $output);
  5341. }
  5342. // Add symbol of currency if requested
  5343. $cursymbolbefore = $cursymbolafter = '';
  5344. if ($currency_code && is_object($outlangs)) {
  5345. if ($currency_code == 'auto') {
  5346. $currency_code = $conf->currency;
  5347. }
  5348. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD', 'CRC');
  5349. $listoflanguagesbefore = array('nl_NL');
  5350. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore)) {
  5351. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  5352. } else {
  5353. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  5354. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  5355. }
  5356. }
  5357. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  5358. return $output;
  5359. }
  5360. /**
  5361. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  5362. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  5363. * should be roundtext2num().
  5364. *
  5365. * @param string|float $amount Amount to convert/clean or round
  5366. * @param string|int $rounding ''=No rounding
  5367. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  5368. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  5369. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  5370. * 'CU'=Round to Max unit price of foreign currency accuracy
  5371. * 'CT'=Round to Max for totals with Tax of foreign currency accuracy
  5372. * Numeric = Nb of digits for rounding (For example 2 for a percentage)
  5373. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  5374. * Put 2 if you know that number is a user input (so we know we have to fix decimal separator).
  5375. * @return string Amount with universal numeric format (Example: '99.99999').
  5376. * If conversion fails to return a numeric, it returns:
  5377. * - text unchanged or partial if ($rounding = ''): price2num('W9ç', '', 0) => '9ç', price2num('W9ç', '', 1) => 'W9ç', price2num('W9ç', '', 2) => '9ç'
  5378. * - '0' if ($rounding is defined): price2num('W9ç', 'MT', 0) => '9', price2num('W9ç', 'MT', 1) => '0', price2num('W9ç', 'MT', 2) => '9'
  5379. * Note: The best way to guarantee a numeric value is to add a cast (float) before the price2num().
  5380. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined.
  5381. *
  5382. * @see price() Opposite function of price2num
  5383. */
  5384. function price2num($amount, $rounding = '', $option = 0)
  5385. {
  5386. global $langs, $conf;
  5387. // Clean parameters
  5388. if (is_null($amount)) {
  5389. $amount = '';
  5390. }
  5391. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  5392. // Numbers must be '1234.56'
  5393. // Decimal delimiter for PHP and database SQL requests must be '.'
  5394. $dec = ',';
  5395. $thousand = ' ';
  5396. if (is_null($langs)) { // $langs is not defined, we use english values.
  5397. $dec = '.';
  5398. $thousand = ',';
  5399. } else {
  5400. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
  5401. $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  5402. }
  5403. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
  5404. $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  5405. }
  5406. }
  5407. if ($thousand == 'None') {
  5408. $thousand = '';
  5409. } elseif ($thousand == 'Space') {
  5410. $thousand = ' ';
  5411. }
  5412. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  5413. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  5414. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  5415. //print "\n".'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  5416. if (!is_numeric($amount)) {
  5417. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\_]/', '', $amount);
  5418. }
  5419. 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
  5420. $amount = str_replace($thousand, '', $amount);
  5421. }
  5422. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5423. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  5424. // So if number was already a good number, it is converted into local Dolibarr setup.
  5425. if (is_numeric($amount)) {
  5426. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5427. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5428. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5429. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5430. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  5431. }
  5432. //print "QQ".$amount."<br>\n";
  5433. // Now make replace (the main goal of function)
  5434. if ($thousand != ',' && $thousand != '.') {
  5435. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5436. }
  5437. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5438. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5439. $amount = str_replace($dec, '.', $amount);
  5440. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5441. }
  5442. //print ' XX'.$amount.' '.$rounding;
  5443. // Now, $amount is a real PHP float number. We make a rounding if required.
  5444. if ($rounding) {
  5445. $nbofdectoround = '';
  5446. if ($rounding == 'MU') {
  5447. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  5448. } elseif ($rounding == 'MT') {
  5449. $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  5450. } elseif ($rounding == 'MS') {
  5451. $nbofdectoround = isset($conf->global->MAIN_MAX_DECIMALS_STOCK) ? $conf->global->MAIN_MAX_DECIMALS_STOCK : 5;
  5452. } elseif ($rounding == 'CU') {
  5453. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_UNIT, 8); // TODO Use param of currency
  5454. } elseif ($rounding == 'CT') {
  5455. $nbofdectoround = max($conf->global->MAIN_MAX_DECIMALS_TOT, 8); // TODO Use param of currency
  5456. } elseif (is_numeric($rounding)) {
  5457. $nbofdectoround = (int) $rounding;
  5458. }
  5459. //print " RR".$amount.' - '.$nbofdectoround.'<br>';
  5460. if (dol_strlen($nbofdectoround)) {
  5461. $amount = round(is_string($amount) ? (float) $amount : $amount, $nbofdectoround); // $nbofdectoround can be 0.
  5462. } else {
  5463. return 'ErrorBadParameterProvidedToFunction';
  5464. }
  5465. //print ' SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  5466. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  5467. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  5468. if (is_numeric($amount)) {
  5469. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  5470. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  5471. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  5472. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  5473. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  5474. }
  5475. //print "TT".$amount.'<br>';
  5476. // Always make replace because each math function (like round) replace
  5477. // with local values and we want a number that has a SQL string format x.y
  5478. if ($thousand != ',' && $thousand != '.') {
  5479. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  5480. }
  5481. $amount = str_replace(' ', '', $amount); // To avoid spaces
  5482. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  5483. $amount = str_replace($dec, '.', $amount);
  5484. $amount = preg_replace('/[^0-9\-\.]/', '', $amount); // Clean non numeric chars (so it clean some UTF8 spaces for example.
  5485. }
  5486. return $amount;
  5487. }
  5488. /**
  5489. * Output a dimension with best unit
  5490. *
  5491. * @param float $dimension Dimension
  5492. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  5493. * @param string $type 'weight', 'volume', ...
  5494. * @param Translate $outputlangs Translate language object
  5495. * @param int $round -1 = non rounding, x = number of decimal
  5496. * @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)
  5497. * @param int $use_short_label 1=Use short label ('g' instead of 'gram'). Short labels are not translated.
  5498. * @return string String to show dimensions
  5499. */
  5500. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no', $use_short_label = 0)
  5501. {
  5502. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  5503. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
  5504. $dimension = $dimension * 1000000;
  5505. $unit = $unit - 6;
  5506. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3)) {
  5507. $dimension = $dimension * 1000;
  5508. $unit = $unit - 3;
  5509. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6)) {
  5510. $dimension = $dimension / 1000000;
  5511. $unit = $unit + 6;
  5512. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3)) {
  5513. $dimension = $dimension / 1000;
  5514. $unit = $unit + 3;
  5515. }
  5516. // Special case when we want output unit into pound or ounce
  5517. /* TODO
  5518. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  5519. {
  5520. $dimension = // convert dimension from standard unit into ounce or pound
  5521. $unit = $forceunitoutput;
  5522. }
  5523. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  5524. {
  5525. $dimension = // convert dimension from standard unit into ounce or pound
  5526. $unit = $forceunitoutput;
  5527. }*/
  5528. $ret = price($dimension, 0, $outputlangs, 0, 0, $round);
  5529. $ret .= ' '.measuringUnitString(0, $type, $unit, $use_short_label, $outputlangs);
  5530. return $ret;
  5531. }
  5532. /**
  5533. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  5534. * Note: This function applies same rules than get_default_tva
  5535. *
  5536. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  5537. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  5538. * @param Societe $thirdparty_buyer Object of buying third party
  5539. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  5540. * @param int $vatnpr If vat rate is NPR or not
  5541. * @return mixed 0 if not found, localtax rate if found
  5542. * @see get_default_tva()
  5543. */
  5544. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  5545. {
  5546. global $db, $conf, $mysoc;
  5547. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
  5548. $thirdparty_seller = $mysoc;
  5549. }
  5550. 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);
  5551. $vatratecleaned = $vatrate;
  5552. $reg = array();
  5553. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5554. $vatratecleaned = trim($reg[1]);
  5555. $vatratecode = $reg[2];
  5556. }
  5557. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  5558. {
  5559. return 0;
  5560. }*/
  5561. // Some test to guess with no need to make database access
  5562. if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  5563. if ($local == 1) {
  5564. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
  5565. return 0;
  5566. }
  5567. if ($thirdparty_seller->id == $mysoc->id) {
  5568. if (!$thirdparty_buyer->localtax1_assuj) {
  5569. return 0;
  5570. }
  5571. } else {
  5572. if (!$thirdparty_seller->localtax1_assuj) {
  5573. return 0;
  5574. }
  5575. }
  5576. }
  5577. if ($local == 2) {
  5578. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  5579. if (!$mysoc->localtax2_assuj) {
  5580. return 0; // If main vat is 0, IRPF may be different than 0.
  5581. }
  5582. if ($thirdparty_seller->id == $mysoc->id) {
  5583. if (!$thirdparty_buyer->localtax2_assuj) {
  5584. return 0;
  5585. }
  5586. } else {
  5587. if (!$thirdparty_seller->localtax2_assuj) {
  5588. return 0;
  5589. }
  5590. }
  5591. }
  5592. } else {
  5593. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
  5594. return 0;
  5595. }
  5596. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
  5597. return 0;
  5598. }
  5599. }
  5600. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  5601. if (in_array($mysoc->country_code, array('ES'))) {
  5602. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  5603. }
  5604. // Search local taxes
  5605. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY)) {
  5606. if ($local == 1) {
  5607. if ($thirdparty_seller != $mysoc) {
  5608. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5609. return $thirdparty_seller->localtax1_value;
  5610. }
  5611. } else { // i am the seller
  5612. if (!isOnlyOneLocalTax($local)) { // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  5613. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  5614. }
  5615. }
  5616. }
  5617. if ($local == 2) {
  5618. if ($thirdparty_seller != $mysoc) {
  5619. if (!isOnlyOneLocalTax($local)) { // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  5620. // TODO We should also return value defined on thirdparty only if defined
  5621. return $thirdparty_seller->localtax2_value;
  5622. }
  5623. } else { // i am the seller
  5624. if (in_array($mysoc->country_code, array('ES'))) {
  5625. return $thirdparty_buyer->localtax2_value;
  5626. } else {
  5627. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  5628. }
  5629. }
  5630. }
  5631. }
  5632. // By default, search value of local tax on line of common tax
  5633. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  5634. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5635. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  5636. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5637. if (!empty($vatratecode)) {
  5638. $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  5639. } else {
  5640. $sql .= " AND t.recuperableonly = '".$db->escape($vatnpr)."'";
  5641. }
  5642. $resql = $db->query($sql);
  5643. if ($resql) {
  5644. $obj = $db->fetch_object($resql);
  5645. if ($obj) {
  5646. if ($local == 1) {
  5647. return $obj->localtax1;
  5648. } elseif ($local == 2) {
  5649. return $obj->localtax2;
  5650. }
  5651. }
  5652. }
  5653. return 0;
  5654. }
  5655. /**
  5656. * Return true if LocalTax (1 or 2) is unique.
  5657. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  5658. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  5659. *
  5660. * @param int $local Local tax to test (1 or 2)
  5661. * @return boolean True if LocalTax have multiple values, False if not
  5662. */
  5663. function isOnlyOneLocalTax($local)
  5664. {
  5665. $tax = get_localtax_by_third($local);
  5666. $valors = explode(":", $tax);
  5667. if (count($valors) > 1) {
  5668. return false;
  5669. } else {
  5670. return true;
  5671. }
  5672. }
  5673. /**
  5674. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  5675. *
  5676. * @param int $local LocalTax to get
  5677. * @return string Values of localtax (Can be '20', '-19:-15:-9') or 'Error'
  5678. */
  5679. function get_localtax_by_third($local)
  5680. {
  5681. global $db, $mysoc;
  5682. $sql = " SELECT t.localtax".$local." as localtax";
  5683. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t INNER JOIN ".MAIN_DB_PREFIX."c_country as c ON c.rowid = t.fk_pays";
  5684. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux = (";
  5685. $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";
  5686. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1)";
  5687. $sql .= " AND t.localtax".$local."_type <> '0'";
  5688. $sql .= " ORDER BY t.rowid DESC";
  5689. $resql = $db->query($sql);
  5690. if ($resql) {
  5691. $obj = $db->fetch_object($resql);
  5692. if ($obj) {
  5693. return $obj->localtax;
  5694. } else {
  5695. return '0';
  5696. }
  5697. }
  5698. return 'Error';
  5699. }
  5700. /**
  5701. * Get tax (VAT) main information from Id.
  5702. * You can also call getLocalTaxesFromRate() after to get only localtax fields.
  5703. *
  5704. * @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.
  5705. * @param Societe $buyer Company object
  5706. * @param Societe $seller Company object
  5707. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  5708. * @return array array('rowid'=> , 'code'=> ...)
  5709. * @see getLocalTaxesFromRate()
  5710. */
  5711. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  5712. {
  5713. global $db, $mysoc;
  5714. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  5715. // Search local taxes
  5716. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy,";
  5717. $sql .= " t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type";
  5718. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5719. if ($firstparamisid) {
  5720. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5721. } else {
  5722. $vatratecleaned = $vatrate;
  5723. $vatratecode = '';
  5724. $reg = array();
  5725. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "xx (yy)"
  5726. $vatratecleaned = $reg[1];
  5727. $vatratecode = $reg[2];
  5728. }
  5729. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5730. /*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 ??
  5731. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  5732. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  5733. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5734. if ($vatratecode) {
  5735. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5736. }
  5737. }
  5738. $resql = $db->query($sql);
  5739. if ($resql) {
  5740. $obj = $db->fetch_object($resql);
  5741. if ($obj) {
  5742. return array(
  5743. 'rowid'=>$obj->rowid,
  5744. 'code'=>$obj->code,
  5745. 'rate'=>$obj->rate,
  5746. 'localtax1'=>$obj->localtax1,
  5747. 'localtax1_type'=>$obj->localtax1_type,
  5748. 'localtax2'=>$obj->localtax2,
  5749. 'localtax2_type'=>$obj->localtax2_type,
  5750. 'npr'=>$obj->npr,
  5751. 'accountancy_code_sell'=>$obj->accountancy_code_sell,
  5752. 'accountancy_code_buy'=>$obj->accountancy_code_buy
  5753. );
  5754. } else {
  5755. return array();
  5756. }
  5757. } else {
  5758. dol_print_error($db);
  5759. }
  5760. return array();
  5761. }
  5762. /**
  5763. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  5764. * This does not take into account the seller setup if subject to vat or not, only country.
  5765. *
  5766. * TODO This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  5767. * Instead this function must be called when adding a line to get the array of possible values for localtax and type, and then
  5768. * provide the selected value to the function calcul_price_total.
  5769. *
  5770. * @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.
  5771. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  5772. * @param Societe $buyer Company object
  5773. * @param Societe $seller Company object
  5774. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  5775. * @return array array(localtax_type1(1-6 or 0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  5776. * @see getTaxesFromId()
  5777. */
  5778. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  5779. {
  5780. global $db, $mysoc;
  5781. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  5782. // Search local taxes
  5783. $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";
  5784. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  5785. if ($firstparamisid) {
  5786. $sql .= " WHERE t.rowid = ".(int) $vatrate;
  5787. } else {
  5788. $vatratecleaned = $vatrate;
  5789. $vatratecode = '';
  5790. $reg = array();
  5791. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) { // If vat is "x.x (yy)"
  5792. $vatratecleaned = $reg[1];
  5793. $vatratecode = $reg[2];
  5794. }
  5795. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  5796. if (!empty($mysoc) && $mysoc->country_code == 'ES') {
  5797. $countrycodetouse = ((empty($buyer) || empty($buyer->country_code)) ? $mysoc->country_code : $buyer->country_code);
  5798. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'"; // local tax in spain use the buyer country ??
  5799. } else {
  5800. $countrycodetouse = ((empty($seller) || empty($seller->country_code)) ? $mysoc->country_code : $seller->country_code);
  5801. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($countrycodetouse)."'";
  5802. }
  5803. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  5804. if ($vatratecode) {
  5805. $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  5806. }
  5807. }
  5808. $resql = $db->query($sql);
  5809. if ($resql) {
  5810. $obj = $db->fetch_object($resql);
  5811. if ($obj) {
  5812. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  5813. if ($local == 1) {
  5814. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5815. } elseif ($local == 2) {
  5816. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  5817. } else {
  5818. 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);
  5819. }
  5820. }
  5821. }
  5822. return array();
  5823. }
  5824. /**
  5825. * Return vat rate of a product in a particular country, or default country vat if product is unknown.
  5826. * Function called by get_default_tva().
  5827. *
  5828. * @param int $idprod Id of product or 0 if not a predefined product
  5829. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5830. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  5831. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  5832. * @see get_product_localtax_for_country()
  5833. */
  5834. function get_product_vat_for_country($idprod, $thirdpartytouse, $idprodfournprice = 0)
  5835. {
  5836. global $db, $conf, $mysoc;
  5837. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5838. $ret = 0;
  5839. $found = 0;
  5840. if ($idprod > 0) {
  5841. // Load product
  5842. $product = new Product($db);
  5843. $product->fetch($idprod);
  5844. if ($mysoc->country_code == $thirdpartytouse->country_code) {
  5845. // If country to consider is ours
  5846. if ($idprodfournprice > 0) { // We want vat for product for a "supplier" object
  5847. $result = $product->get_buyprice($idprodfournprice, 0, 0, 0);
  5848. if ($result > 0) {
  5849. $ret = $product->vatrate_supplier;
  5850. if ($product->default_vat_code_supplier) {
  5851. $ret .= ' ('.$product->default_vat_code_supplier.')';
  5852. }
  5853. $found = 1;
  5854. }
  5855. }
  5856. if (!$found) {
  5857. $ret = $product->tva_tx; // Default sales vat of product
  5858. if ($product->default_vat_code) {
  5859. $ret .= ' ('.$product->default_vat_code.')';
  5860. }
  5861. $found = 1;
  5862. }
  5863. } else {
  5864. // TODO Read default product vat according to product and another countrycode.
  5865. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5866. }
  5867. }
  5868. if (!$found) {
  5869. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
  5870. // 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).
  5871. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  5872. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5873. $sql .= " WHERE t.active = 1 AND t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdpartytouse->country_code)."'";
  5874. $sql .= " ORDER BY t.use_default DESC, t.taux DESC, t.code ASC, t.recuperableonly ASC";
  5875. $sql .= $db->plimit(1);
  5876. $resql = $db->query($sql);
  5877. if ($resql) {
  5878. $obj = $db->fetch_object($resql);
  5879. if ($obj) {
  5880. $ret = $obj->vat_rate;
  5881. if ($obj->default_vat_code) {
  5882. $ret .= ' ('.$obj->default_vat_code.')';
  5883. }
  5884. }
  5885. $db->free($resql);
  5886. } else {
  5887. dol_print_error($db);
  5888. }
  5889. } else {
  5890. // Forced value if autodetect fails. MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS can be
  5891. // '1.23'
  5892. // or '1.23 (CODE)'
  5893. $defaulttx = '';
  5894. if ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS != 'none') {
  5895. $defaulttx = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
  5896. }
  5897. /*if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
  5898. $defaultcode = $reg[1];
  5899. $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
  5900. }*/
  5901. $ret = $defaulttx;
  5902. }
  5903. }
  5904. dol_syslog("get_product_vat_for_country: ret=".$ret);
  5905. return $ret;
  5906. }
  5907. /**
  5908. * Return localtax vat rate of a product in a particular country or default country vat if product is unknown
  5909. *
  5910. * @param int $idprod Id of product
  5911. * @param int $local 1 for localtax1, 2 for localtax 2
  5912. * @param Societe $thirdpartytouse Thirdparty with a ->country_code defined (FR, US, IT, ...)
  5913. * @return int <0 if KO, Vat rate if OK
  5914. * @see get_product_vat_for_country()
  5915. */
  5916. function get_product_localtax_for_country($idprod, $local, $thirdpartytouse)
  5917. {
  5918. global $db, $mysoc;
  5919. if (!class_exists('Product')) {
  5920. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  5921. }
  5922. $ret = 0;
  5923. $found = 0;
  5924. if ($idprod > 0) {
  5925. // Load product
  5926. $product = new Product($db);
  5927. $result = $product->fetch($idprod);
  5928. if ($mysoc->country_code == $thirdpartytouse->country_code) { // If selling country is ours
  5929. /* Not defined yet, so we don't use this
  5930. if ($local==1) $ret=$product->localtax1_tx;
  5931. elseif ($local==2) $ret=$product->localtax2_tx;
  5932. $found=1;
  5933. */
  5934. } else {
  5935. // TODO Read default product vat according to product and another countrycode.
  5936. // Vat for couple anothercountrycode/product is data that is not managed and store yet, so we will fallback on next rule.
  5937. }
  5938. }
  5939. if (!$found) {
  5940. // If vat of product for the country not found or not defined, we return higher vat of country.
  5941. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  5942. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  5943. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdpartytouse->country_code)."'";
  5944. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  5945. $sql .= $db->plimit(1);
  5946. $resql = $db->query($sql);
  5947. if ($resql) {
  5948. $obj = $db->fetch_object($resql);
  5949. if ($obj) {
  5950. if ($local == 1) {
  5951. $ret = $obj->localtax1;
  5952. } elseif ($local == 2) {
  5953. $ret = $obj->localtax2;
  5954. }
  5955. }
  5956. } else {
  5957. dol_print_error($db);
  5958. }
  5959. }
  5960. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  5961. return $ret;
  5962. }
  5963. /**
  5964. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  5965. * VATRULE 1: If seller does not use VAT, default VAT is 0. End of rule.
  5966. * VATRULE 2: If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  5967. * VATRULE 3: If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  5968. * VATRULE 4: If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  5969. * VATRULE 5: If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  5970. * VATRULE 6: Otherwise the VAT proposed by default=0. End of rule.
  5971. *
  5972. * @param Societe $thirdparty_seller Objet societe vendeuse
  5973. * @param Societe $thirdparty_buyer Objet societe acheteuse
  5974. * @param int $idprod Id product
  5975. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  5976. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  5977. * @see get_default_npr(), get_default_localtax()
  5978. */
  5979. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  5980. {
  5981. global $conf;
  5982. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  5983. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  5984. $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;
  5985. $seller_country_code = $thirdparty_seller->country_code;
  5986. $seller_in_cee = isInEEC($thirdparty_seller);
  5987. $buyer_country_code = $thirdparty_buyer->country_code;
  5988. $buyer_in_cee = isInEEC($thirdparty_buyer);
  5989. 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 : ''));
  5990. // 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)
  5991. // we use the buyer VAT.
  5992. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
  5993. if ($seller_in_cee && $buyer_in_cee) {
  5994. $isacompany = $thirdparty_buyer->isACompany();
  5995. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  5996. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  5997. if (!isValidVATID($thirdparty_buyer)) {
  5998. $isacompany = 0;
  5999. }
  6000. }
  6001. if (!$isacompany) {
  6002. //print 'VATRULE 0';
  6003. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  6004. }
  6005. }
  6006. }
  6007. // If seller does not use VAT, default VAT is 0. End of rule.
  6008. if (!$seller_use_vat) {
  6009. //print 'VATRULE 1';
  6010. return 0;
  6011. }
  6012. // If the (seller country = buyer country) then the default VAT = VAT of the product sold. End of rule.
  6013. if (($seller_country_code == $buyer_country_code)
  6014. || (in_array($seller_country_code, array('FR', 'MC')) && in_array($buyer_country_code, array('FR', 'MC')))) { // Warning ->country_code not always defined
  6015. //print 'VATRULE 2';
  6016. $tmpvat = get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6017. if ($seller_country_code == 'IN' && getDolGlobalString('MAIN_SALETAX_AUTOSWITCH_I_CS_FOR_INDIA')) {
  6018. // Special case for india.
  6019. //print 'VATRULE 2b';
  6020. $reg = array();
  6021. if (preg_match('/C+S-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id != $thirdparty_buyer->state_id) {
  6022. // we must revert the C+S into I
  6023. $tmpvat = str_replace("C+S", "I", $tmpvat);
  6024. } elseif (preg_match('/I-(\d+)/', $tmpvat, $reg) && $thirdparty_seller->state_id == $thirdparty_buyer->state_id) {
  6025. // we must revert the I into C+S
  6026. $tmpvat = str_replace("I", "C+S", $tmpvat);
  6027. }
  6028. }
  6029. return $tmpvat;
  6030. }
  6031. // If (seller and buyer in the European Community) and (property sold = new means of transport such as car, boat, plane) then VAT by default = 0 (VAT must be paid by the buyer to the tax center of his country and not to the seller). End of rule.
  6032. // 'VATRULE 3' - Not supported
  6033. // If (seller and buyer in the European Community) and (buyer = individual) then VAT by default = VAT of the product sold. End of rule
  6034. // If (seller and buyer in European Community) and (buyer = company) then VAT by default=0. End of rule
  6035. if (($seller_in_cee && $buyer_in_cee)) {
  6036. $isacompany = $thirdparty_buyer->isACompany();
  6037. if ($isacompany && getDolGlobalString('MAIN_USE_VAT_COMPANIES_IN_EEC_WITH_INVALID_VAT_ID_ARE_INDIVIDUAL')) {
  6038. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  6039. if (!isValidVATID($thirdparty_buyer)) {
  6040. $isacompany = 0;
  6041. }
  6042. }
  6043. if (!$isacompany) {
  6044. //print 'VATRULE 4';
  6045. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6046. } else {
  6047. //print 'VATRULE 5';
  6048. return 0;
  6049. }
  6050. }
  6051. // If (seller in the European Community and buyer outside the European Community and private buyer) then VAT by default = VAT of the product sold. End of rule
  6052. // I don't see any use case that need this rule.
  6053. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee)) {
  6054. $isacompany = $thirdparty_buyer->isACompany();
  6055. if (!$isacompany) {
  6056. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  6057. //print 'VATRULE extra';
  6058. }
  6059. }
  6060. // Otherwise the VAT proposed by default=0. End of rule.
  6061. // Rem: This means that at least one of the 2 is outside the European Community and the country differs
  6062. //print 'VATRULE 6';
  6063. return 0;
  6064. }
  6065. /**
  6066. * Function that returns whether VAT must be recoverable collected VAT (e.g.: VAT NPR in France)
  6067. *
  6068. * @param Societe $thirdparty_seller Thirdparty seller
  6069. * @param Societe $thirdparty_buyer Thirdparty buyer
  6070. * @param int $idprod Id product
  6071. * @param int $idprodfournprice Id supplier price for product
  6072. * @return float 0 or 1
  6073. * @see get_default_tva(), get_default_localtax()
  6074. */
  6075. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  6076. {
  6077. global $db;
  6078. if ($idprodfournprice > 0) {
  6079. if (!class_exists('ProductFournisseur')) {
  6080. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  6081. }
  6082. $prodprice = new ProductFournisseur($db);
  6083. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  6084. return $prodprice->fourn_tva_npr;
  6085. } elseif ($idprod > 0) {
  6086. if (!class_exists('Product')) {
  6087. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  6088. }
  6089. $prod = new Product($db);
  6090. $prod->fetch($idprod);
  6091. return $prod->tva_npr;
  6092. }
  6093. return 0;
  6094. }
  6095. /**
  6096. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  6097. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  6098. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  6099. * Sinon TVA proposee par defaut=0. Fin de regle.
  6100. *
  6101. * @param Societe $thirdparty_seller Thirdparty seller
  6102. * @param Societe $thirdparty_buyer Thirdparty buyer
  6103. * @param int $local Localtax to process (1 or 2)
  6104. * @param int $idprod Id product
  6105. * @return integer localtax, -1 si ne peut etre determine
  6106. * @see get_default_tva(), get_default_npr()
  6107. */
  6108. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  6109. {
  6110. global $mysoc;
  6111. if (!is_object($thirdparty_seller)) {
  6112. return -1;
  6113. }
  6114. if (!is_object($thirdparty_buyer)) {
  6115. return -1;
  6116. }
  6117. if ($local == 1) { // Localtax 1
  6118. if ($mysoc->country_code == 'ES') {
  6119. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
  6120. return 0;
  6121. }
  6122. } else {
  6123. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  6124. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
  6125. return 0;
  6126. }
  6127. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
  6128. return 0;
  6129. }
  6130. }
  6131. } elseif ($local == 2) { //I Localtax 2
  6132. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  6133. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
  6134. return 0;
  6135. }
  6136. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
  6137. return 0;
  6138. }
  6139. }
  6140. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
  6141. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  6142. }
  6143. return 0;
  6144. }
  6145. /**
  6146. * Return yes or no in current language
  6147. *
  6148. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  6149. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  6150. * @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.
  6151. * @return string HTML string
  6152. */
  6153. function yn($yesno, $case = 1, $color = 0)
  6154. {
  6155. global $langs;
  6156. $result = 'unknown';
  6157. $classname = '';
  6158. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') { // A mettre avant test sur no a cause du == 0
  6159. $result = $langs->trans('yes');
  6160. if ($case == 1 || $case == 3) {
  6161. $result = $langs->trans("Yes");
  6162. }
  6163. if ($case == 2) {
  6164. $result = '<input type="checkbox" value="1" checked disabled>';
  6165. }
  6166. if ($case == 3) {
  6167. $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  6168. }
  6169. $classname = 'ok';
  6170. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
  6171. $result = $langs->trans("no");
  6172. if ($case == 1 || $case == 3) {
  6173. $result = $langs->trans("No");
  6174. }
  6175. if ($case == 2) {
  6176. $result = '<input type="checkbox" value="0" disabled>';
  6177. }
  6178. if ($case == 3) {
  6179. $result = '<input type="checkbox" value="0" disabled> '.$result;
  6180. }
  6181. if ($color == 2) {
  6182. $classname = 'ok';
  6183. } else {
  6184. $classname = 'error';
  6185. }
  6186. }
  6187. if ($color) {
  6188. return '<span class="'.$classname.'">'.$result.'</span>';
  6189. }
  6190. return $result;
  6191. }
  6192. /**
  6193. * Return a path to have a the directory according to object where files are stored.
  6194. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '').'/'
  6195. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, '') if multidir_output not defined.
  6196. * Example out with new usage: $object is invoice -> 'INYYMM-ABCD'
  6197. * 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/"
  6198. *
  6199. * @param string|int $num Id of object (deprecated, $object will be used in future)
  6200. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  6201. * @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)
  6202. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  6203. * @param Object $object Object to use to get ref to forge the path.
  6204. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  6205. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  6206. */
  6207. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  6208. {
  6209. global $conf;
  6210. if (empty($modulepart) && !empty($object->module)) {
  6211. $modulepart = $object->module;
  6212. }
  6213. $path = '';
  6214. $arrayforoldpath = array('cheque', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  6215. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  6216. $arrayforoldpath[] = 'product';
  6217. }
  6218. if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
  6219. // This part should be removed once all code is using "get_exdir" to forge path, with parameter $object and $modulepart provided.
  6220. if (empty($alpha)) {
  6221. $num = preg_replace('/([^0-9])/i', '', $num);
  6222. } else {
  6223. $num = preg_replace('/^.*\-/i', '', $num);
  6224. }
  6225. $num = substr("000".$num, -$level);
  6226. if ($level == 1) {
  6227. $path = substr($num, 0, 1);
  6228. }
  6229. if ($level == 2) {
  6230. $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  6231. }
  6232. if ($level == 3) {
  6233. $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  6234. }
  6235. } else {
  6236. // We will enhance here a common way of forging path for document storage.
  6237. // In a future, we may distribute directories on several levels depending on setup and object.
  6238. // Here, $object->id, $object->ref and $modulepart are required.
  6239. //var_dump($modulepart);
  6240. $path = dol_sanitizeFileName(empty($object->ref) ? (string) $object->id : $object->ref);
  6241. }
  6242. if (empty($withoutslash) && !empty($path)) {
  6243. $path .= '/';
  6244. }
  6245. return $path;
  6246. }
  6247. /**
  6248. * Creation of a directory (this can create recursive subdir)
  6249. *
  6250. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  6251. * @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)
  6252. * @param string $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  6253. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  6254. */
  6255. function dol_mkdir($dir, $dataroot = '', $newmask = '')
  6256. {
  6257. global $conf;
  6258. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  6259. $dir_osencoded = dol_osencode($dir);
  6260. if (@is_dir($dir_osencoded)) {
  6261. return 0;
  6262. }
  6263. $nberr = 0;
  6264. $nbcreated = 0;
  6265. $ccdir = '';
  6266. if (!empty($dataroot)) {
  6267. // Remove data root from loop
  6268. $dir = str_replace($dataroot.'/', '', $dir);
  6269. $ccdir = $dataroot.'/';
  6270. }
  6271. $cdir = explode("/", $dir);
  6272. $num = count($cdir);
  6273. for ($i = 0; $i < $num; $i++) {
  6274. if ($i > 0) {
  6275. $ccdir .= '/'.$cdir[$i];
  6276. } else {
  6277. $ccdir .= $cdir[$i];
  6278. }
  6279. if (preg_match("/^.:$/", $ccdir, $regs)) {
  6280. continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  6281. }
  6282. // Attention, le is_dir() peut echouer bien que le rep existe.
  6283. // (ex selon config de open_basedir)
  6284. if ($ccdir) {
  6285. $ccdir_osencoded = dol_osencode($ccdir);
  6286. if (!@is_dir($ccdir_osencoded)) {
  6287. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  6288. umask(0);
  6289. $dirmaskdec = octdec((string) $newmask);
  6290. if (empty($newmask)) {
  6291. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  6292. }
  6293. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  6294. if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
  6295. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  6296. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  6297. $nberr++;
  6298. } else {
  6299. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  6300. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  6301. $nbcreated++;
  6302. }
  6303. } else {
  6304. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  6305. }
  6306. }
  6307. }
  6308. return ($nberr ? -$nberr : $nbcreated);
  6309. }
  6310. /**
  6311. * Change mod of a file
  6312. *
  6313. * @param string $filepath Full file path
  6314. * @param string $newmask Force new mask. For example '0644'
  6315. * @return void
  6316. */
  6317. function dolChmod($filepath, $newmask = '')
  6318. {
  6319. global $conf;
  6320. if (!empty($newmask)) {
  6321. @chmod($filepath, octdec($newmask));
  6322. } elseif (!empty($conf->global->MAIN_UMASK)) {
  6323. @chmod($filepath, octdec($conf->global->MAIN_UMASK));
  6324. }
  6325. }
  6326. /**
  6327. * Return picto saying a field is required
  6328. *
  6329. * @return string Chaine avec picto obligatoire
  6330. */
  6331. function picto_required()
  6332. {
  6333. return '<span class="fieldrequired">*</span>';
  6334. }
  6335. /**
  6336. * Clean a string from all HTML tags and entities.
  6337. * This function differs from strip_tags because:
  6338. * - <br> are replaced with \n if removelinefeed=0 or 1
  6339. * - if entities are found, they are decoded BEFORE the strip
  6340. * - you can decide to convert line feed into a space
  6341. *
  6342. * @param string $stringtoclean String to clean
  6343. * @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..."
  6344. * @param string $pagecodeto Encoding of input/output string
  6345. * @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')
  6346. * @param integer $removedoublespaces Replace double space into one space
  6347. * @return string String cleaned
  6348. *
  6349. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  6350. */
  6351. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  6352. {
  6353. if (is_null($stringtoclean)) {
  6354. return '';
  6355. }
  6356. if ($removelinefeed == 2) {
  6357. $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  6358. }
  6359. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  6360. // 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)
  6361. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6362. $temp = str_replace('< ', '__ltspace__', $temp);
  6363. if ($strip_tags) {
  6364. $temp = strip_tags($temp);
  6365. } else {
  6366. // 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).
  6367. $pattern = "/<[^<>]+>/";
  6368. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  6369. // pass 1 - $temp after pass 1: <a href="/myurl" title="A title">0000-021
  6370. // pass 2 - $temp after pass 2: 0000-021
  6371. $tempbis = $temp;
  6372. do {
  6373. $temp = $tempbis;
  6374. $tempbis = str_replace('<>', '', $temp); // No reason to have this into a text, except if value is to try bypass the next html cleaning
  6375. $tempbis = preg_replace($pattern, '', $tempbis);
  6376. //$idowhile++; print $temp.'-'.$tempbis."\n"; if ($idowhile > 100) break;
  6377. } while ($tempbis != $temp);
  6378. $temp = $tempbis;
  6379. // 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).
  6380. $temp = preg_replace('/<+([a-z]+)/i', '\1', $temp);
  6381. }
  6382. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  6383. // Remove also carriage returns
  6384. if ($removelinefeed == 1) {
  6385. $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  6386. }
  6387. // And double quotes
  6388. if ($removedoublespaces) {
  6389. while (strpos($temp, " ")) {
  6390. $temp = str_replace(" ", " ", $temp);
  6391. }
  6392. }
  6393. $temp = str_replace('__ltspace__', '< ', $temp);
  6394. return trim($temp);
  6395. }
  6396. /**
  6397. * Clean a string to keep only desirable HTML tags.
  6398. * WARNING: This also clean HTML comments (because they can be used to obfuscate tag name).
  6399. *
  6400. * @param string $stringtoclean String to clean
  6401. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  6402. * @param int $removeclassattribute 1=Remove the class attribute from tags
  6403. * @param int $cleanalsojavascript Remove also occurence of 'javascript:'.
  6404. * @param int $allowiframe Allow iframe tags.
  6405. * @param array $allowed_tags List of allowed tags to replace the default list
  6406. * @return string String cleaned
  6407. *
  6408. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  6409. */
  6410. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0, $allowiframe = 0, $allowed_tags = array())
  6411. {
  6412. if (empty($allowed_tags)) {
  6413. $allowed_tags = array(
  6414. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  6415. "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"
  6416. );
  6417. }
  6418. $allowed_tags[] = "comment"; // this tags is added to manage comment <!--...--> that are replaced into <comment>...</comment>
  6419. if ($allowiframe) {
  6420. $allowed_tags[] = "iframe";
  6421. }
  6422. $allowed_tags_string = join("><", $allowed_tags);
  6423. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  6424. $stringtoclean = str_replace('<!DOCTYPE html>', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags
  6425. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  6426. //$stringtoclean = preg_replace('/<!--[^>]*-->/', '', $stringtoclean);
  6427. $stringtoclean = preg_replace('/<!--([^>]*)-->/', '<comment>\1</comment>', $stringtoclean);
  6428. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  6429. $stringtoclean = preg_replace('/&#58;|&#0+58|&#x3A/i', '', $stringtoclean); // refused string ':' encoded (no reason to have a : encoded like this) to disable 'javascript:...'
  6430. $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
  6431. if ($cleanalsosomestyles) { // Clean for remaining html tags
  6432. $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
  6433. }
  6434. if ($removeclassattribute) { // Clean for remaining html tags
  6435. $temp = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  6436. }
  6437. // Remove 'javascript:' that we should not find into a text with
  6438. // 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)).
  6439. if ($cleanalsojavascript) {
  6440. $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);
  6441. }
  6442. $temp = str_replace('__!DOCTYPE_HTML__', '<!DOCTYPE html>', $temp); // Restore the DOCTYPE
  6443. $temp = preg_replace('/<comment>([^>]*)<\/comment>/', '<!--\1-->', $temp); // Restore html comments
  6444. return $temp;
  6445. }
  6446. /**
  6447. * Clean a string from some undesirable HTML tags.
  6448. * Note: Complementary to dol_string_onlythesehtmltags().
  6449. * This method is used for example when option MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES is set to 1.
  6450. *
  6451. * @param string $stringtoclean String to clean
  6452. * @param array $allowed_attributes Array of tags not allowed
  6453. * @return string String cleaned
  6454. *
  6455. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags()
  6456. */
  6457. 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"))
  6458. {
  6459. if (class_exists('DOMDocument') && !empty($stringtoclean)) {
  6460. $stringtoclean = '<?xml encoding="UTF-8"><html><body>'.$stringtoclean.'</body></html>';
  6461. $dom = new DOMDocument(null, 'UTF-8');
  6462. $dom->loadHTML($stringtoclean, LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6463. if (is_object($dom)) {
  6464. for ($els = $dom->getElementsByTagname('*'), $i = $els->length - 1; $i >= 0; $i--) {
  6465. for ($attrs = $els->item($i)->attributes, $ii = $attrs->length - 1; $ii >= 0; $ii--) {
  6466. //var_dump($attrs->item($ii));
  6467. if (!empty($attrs->item($ii)->name)) {
  6468. if (! in_array($attrs->item($ii)->name, $allowed_attributes)) {
  6469. // Delete attribute if not into allowed_attributes
  6470. $els->item($i)->removeAttribute($attrs->item($ii)->name);
  6471. } elseif (in_array($attrs->item($ii)->name, array('style'))) {
  6472. // If attribute is 'style'
  6473. $valuetoclean = $attrs->item($ii)->value;
  6474. if (isset($valuetoclean)) {
  6475. do {
  6476. $oldvaluetoclean = $valuetoclean;
  6477. $valuetoclean = preg_replace('/\/\*.*\*\//m', '', $valuetoclean); // clean css comments
  6478. $valuetoclean = preg_replace('/position\s*:\s*[a-z]+/mi', '', $valuetoclean);
  6479. if ($els->item($i)->tagName == 'a') { // more paranoiac cleaning for clickable tags.
  6480. $valuetoclean = preg_replace('/display\s*:/mi', '', $valuetoclean);
  6481. $valuetoclean = preg_replace('/z-index\s*:/mi', '', $valuetoclean);
  6482. $valuetoclean = preg_replace('/\s+(top|left|right|bottom)\s*:/mi', '', $valuetoclean);
  6483. }
  6484. // We do not allow logout|passwordforgotten.php and action= into the content of a "style" tag
  6485. $valuetoclean = preg_replace('/(logout|passwordforgotten)\.php/mi', '', $valuetoclean);
  6486. $valuetoclean = preg_replace('/action=/mi', '', $valuetoclean);
  6487. } while ($oldvaluetoclean != $valuetoclean);
  6488. }
  6489. $attrs->item($ii)->value = $valuetoclean;
  6490. }
  6491. }
  6492. }
  6493. }
  6494. }
  6495. $return = $dom->saveHTML();
  6496. //$return = '<html><body>aaaa</p>bb<p>ssdd</p>'."\n<p>aaa</p>aa<p>bb</p>";
  6497. $return = preg_replace('/^'.preg_quote('<?xml encoding="UTF-8">', '/').'/', '', $return);
  6498. $return = preg_replace('/^'.preg_quote('<html><body>', '/').'/', '', $return);
  6499. $return = preg_replace('/'.preg_quote('</body></html>', '/').'$/', '', $return);
  6500. return trim($return);
  6501. } else {
  6502. return $stringtoclean;
  6503. }
  6504. }
  6505. /**
  6506. * Clean a string from some undesirable HTML tags.
  6507. * Note. Not as secured as dol_string_onlythesehtmltags().
  6508. *
  6509. * @param string $stringtoclean String to clean
  6510. * @param array $disallowed_tags Array of tags not allowed
  6511. * @param string $cleanalsosomestyles Clean also some tags
  6512. * @return string String cleaned
  6513. *
  6514. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags() dol_string_onlythesehtmlattributes()
  6515. */
  6516. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  6517. {
  6518. $temp = $stringtoclean;
  6519. foreach ($disallowed_tags as $tagtoremove) {
  6520. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  6521. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  6522. }
  6523. if ($cleanalsosomestyles) {
  6524. $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
  6525. }
  6526. return $temp;
  6527. }
  6528. /**
  6529. * Return first line of text. Cut will depends if content is HTML or not.
  6530. *
  6531. * @param string $text Input text
  6532. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  6533. * @param string $charset Charset of $text string (UTF-8 by default)
  6534. * @return string Output text
  6535. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  6536. */
  6537. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  6538. {
  6539. if ($nboflines == 1) {
  6540. if (dol_textishtml($text)) {
  6541. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  6542. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  6543. } else {
  6544. $firstline = preg_replace('/[\n\r].*/', '', $text);
  6545. }
  6546. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  6547. } else {
  6548. $ishtml = 0;
  6549. if (dol_textishtml($text)) {
  6550. $text = preg_replace('/\n/', '', $text);
  6551. $ishtml = 1;
  6552. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6553. } else {
  6554. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6555. }
  6556. $text = strtr($text, $repTable);
  6557. if ($charset == 'UTF-8') {
  6558. $pattern = '/(<br[^>]*>)/Uu';
  6559. } else {
  6560. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6561. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6562. }
  6563. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6564. $firstline = '';
  6565. $i = 0;
  6566. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  6567. while (($i < $nba) && ($i < ($nboflines * 2))) {
  6568. if ($i % 2 == 0) {
  6569. $firstline .= $a[$i];
  6570. } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
  6571. $firstline .= ($ishtml ? "<br>\n" : "\n");
  6572. }
  6573. $i++;
  6574. }
  6575. unset($a);
  6576. return $firstline.(($i < $nba) ? '...' : '');
  6577. }
  6578. }
  6579. /**
  6580. * Replace CRLF in string with a HTML BR tag.
  6581. * 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.
  6582. *
  6583. * @param string $stringtoencode String to encode
  6584. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  6585. * @param bool $forxml false=Use <br>, true=Use <br />
  6586. * @return string String encoded
  6587. * @see dol_nboflines(), dolGetFirstLineOfText()
  6588. */
  6589. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  6590. {
  6591. if (is_null($stringtoencode)) {
  6592. return '';
  6593. }
  6594. if (!$nl2brmode) {
  6595. return nl2br($stringtoencode, $forxml);
  6596. } else {
  6597. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  6598. return $ret;
  6599. }
  6600. }
  6601. /**
  6602. * Sanitize a HTML to remove js and dangerous content
  6603. *
  6604. * @param string $stringtoencode String to encode
  6605. * @param int $nouseofiframesandbox Allow use of option MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS for html sanitizing
  6606. * @param string $check 'restricthtmlnolink' or 'restricthtml' or 'restricthtmlallowunvalid'
  6607. * @return string HTML sanitized
  6608. */
  6609. function dol_htmlwithnojs($stringtoencode, $nouseofiframesandbox = 0, $check = 'restricthtml')
  6610. {
  6611. global $conf;
  6612. if (empty($nouseofiframesandbox) && !empty($conf->global->MAIN_SECURITY_USE_SANDBOX_FOR_HTMLWITHNOJS)) {
  6613. // TODO using sandbox on inline html content is not possible yet with current browsers
  6614. //$s = '<iframe class="iframewithsandbox" sandbox><html><body>';
  6615. //$s .= $stringtoencode;
  6616. //$s .= '</body></html></iframe>';
  6617. return $stringtoencode;
  6618. } else {
  6619. $out = $stringtoencode;
  6620. do {
  6621. $oldstringtoclean = $out;
  6622. libxml_use_internal_errors(false); // Avoid to fill memory with xml errors
  6623. if (!empty($out) && !empty($conf->global->MAIN_RESTRICTHTML_ONLY_VALID_HTML) && $check != 'restricthtmlallowunvalid') {
  6624. try {
  6625. $dom = new DOMDocument;
  6626. // Add a trick to solve pb with text without parent tag
  6627. // like '<h1>Foo</h1><p>bar</p>' that wrongly ends up, without the trick, with '<h1>Foo<p>bar</p></h1>'
  6628. // like 'abc' that wrongly ends up, without the trick, with '<p>abc</p>'
  6629. $out = '<div class="tricktoremove">'.$out.'</div>';
  6630. $dom->loadHTML($out, LIBXML_HTML_NODEFDTD|LIBXML_ERR_NONE|LIBXML_HTML_NOIMPLIED|LIBXML_NONET|LIBXML_NOWARNING|LIBXML_NOXMLDECL);
  6631. $out = trim($dom->saveHTML());
  6632. // Remove the trick added to solve pb with text without parent tag
  6633. $out = preg_replace('/^<div class="tricktoremove">/', '', $out);
  6634. $out = preg_replace('/<\/div>$/', '', $out);
  6635. } catch (Exception $e) {
  6636. // If error, invalid HTML string with no way to clean it
  6637. //print $e->getMessage();
  6638. $out = 'InvalidHTMLString';
  6639. }
  6640. }
  6641. // Clean some html entities that are useless so text is cleaner
  6642. $out = preg_replace('/&(tab|newline);/i', ' ', $out);
  6643. // Ckeditor use the numeric entitic for apostrophe so we force it to text entity (all other special chars are
  6644. // encoded using text entities) so we can then exclude all numeric entities.
  6645. $out = preg_replace('/&#39;/i', '&apos;', $out);
  6646. // 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).
  6647. // 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
  6648. // using a non coventionnel way to be encoded, to not have them sanitized just after)
  6649. $out = preg_replace_callback('/&#(x?[0-9][0-9a-f]+;?)/i', function ($m) {
  6650. return realCharForNumericEntities($m); }, $out);
  6651. // Now we remove all remaining HTML entities starting with a number. We don't want such entities.
  6652. $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'.
  6653. // Keep only some html tags and remove also some 'javascript:' strings
  6654. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  6655. // We should also exclude non expected HTML attributes and clean content of some attributes (keep only alt=, title=...).
  6656. if (!empty($conf->global->MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES)) {
  6657. // 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.
  6658. $out = dol_string_onlythesehtmlattributes($out);
  6659. }
  6660. // Restore entity &apos; into &#39; (restricthtml is for html content so we can use html entity)
  6661. $out = preg_replace('/&apos;/i', "&#39;", $out);
  6662. } while ($oldstringtoclean != $out);
  6663. // Check the limit of external links in a Rich text content. We count '<img' and 'url('
  6664. $reg = array();
  6665. preg_match_all('/(<img|url\()/i', $out, $reg);
  6666. $nbextlink = count($reg[0]);
  6667. if ($nbextlink > getDolGlobalInt("MAIN_SECURITY_MAX_IMG_IN_HTML_CONTENT", 1000)) {
  6668. $out = 'TooManyLinksIntoHTMLString';
  6669. }
  6670. //
  6671. if (!empty($conf->global->MAIN_DISALLOW_EXT_URL_INTO_DESCRIPTIONS) || $check == 'restricthtmlnolink') {
  6672. if ($nbextlink > 0) {
  6673. $out = 'ExternalLinksNotAllowed';
  6674. }
  6675. }
  6676. return $out;
  6677. }
  6678. }
  6679. /**
  6680. * This function is called to encode a string into a HTML string but differs from htmlentities because
  6681. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  6682. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  6683. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  6684. * For PDF usage, you can show text by 2 ways:
  6685. * - writeHTMLCell -> param must be encoded into HTML.
  6686. * - MultiCell -> param must not be encoded into HTML.
  6687. * Because writeHTMLCell convert also \n into <br>, if function
  6688. * is used to build PDF, nl2brmode must be 1.
  6689. *
  6690. * @param string $stringtoencode String to encode
  6691. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  6692. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  6693. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  6694. * @return string String encoded
  6695. * @see dolGetFirstLineOfText()
  6696. */
  6697. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  6698. {
  6699. if (is_null($stringtoencode)) {
  6700. return '';
  6701. }
  6702. $newstring = $stringtoencode;
  6703. if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
  6704. $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.
  6705. if ($removelasteolbr) {
  6706. $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  6707. }
  6708. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  6709. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  6710. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  6711. } else {
  6712. if ($removelasteolbr) {
  6713. $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  6714. }
  6715. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  6716. }
  6717. // Other substitutions that htmlentities does not do
  6718. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  6719. return $newstring;
  6720. }
  6721. /**
  6722. * This function is called to decode a HTML string (it decodes entities and br tags)
  6723. *
  6724. * @param string $stringtodecode String to decode
  6725. * @param string $pagecodeto Page code for result
  6726. * @return string String decoded
  6727. */
  6728. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  6729. {
  6730. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  6731. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  6732. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  6733. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  6734. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  6735. return $ret;
  6736. }
  6737. /**
  6738. * This function remove all ending \n and br at end
  6739. *
  6740. * @param string $stringtodecode String to decode
  6741. * @return string String decoded
  6742. */
  6743. function dol_htmlcleanlastbr($stringtodecode)
  6744. {
  6745. $ret = preg_replace('/&nbsp;$/i', "", $stringtodecode); // Because wysiwyg editor may add a &nbsp; at end of last line
  6746. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $ret);
  6747. return $ret;
  6748. }
  6749. /**
  6750. * Replace html_entity_decode functions to manage errors
  6751. *
  6752. * @param string $a Operand a
  6753. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  6754. * @param string $c Operand c
  6755. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  6756. * @return string String decoded
  6757. */
  6758. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  6759. {
  6760. $newstring = $a;
  6761. if ($keepsomeentities) {
  6762. $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  6763. }
  6764. $newstring = html_entity_decode((string) $newstring, (int) $b, (string) $c);
  6765. if ($keepsomeentities) {
  6766. $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  6767. }
  6768. return $newstring;
  6769. }
  6770. /**
  6771. * Replace htmlentities functions.
  6772. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  6773. *
  6774. * @param string $string The input string to encode
  6775. * @param int $flags Flags (see PHP doc above)
  6776. * @param string $encoding Encoding page code
  6777. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  6778. * @return string $ret Encoded string
  6779. */
  6780. function dol_htmlentities($string, $flags = ENT_QUOTES|ENT_SUBSTITUTE, $encoding = 'UTF-8', $double_encode = false)
  6781. {
  6782. return htmlentities($string, $flags, $encoding, $double_encode);
  6783. }
  6784. /**
  6785. * Check if a string is a correct iso string
  6786. * If not, it will we considered not HTML encoded even if it is by FPDF.
  6787. * Example, if string contains euro symbol that has ascii code 128
  6788. *
  6789. * @param string $s String to check
  6790. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  6791. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  6792. */
  6793. function dol_string_is_good_iso($s, $clean = 0)
  6794. {
  6795. $len = dol_strlen($s);
  6796. $out = '';
  6797. $ok = 1;
  6798. for ($scursor = 0; $scursor < $len; $scursor++) {
  6799. $ordchar = ord($s[$scursor]);
  6800. //print $scursor.'-'.$ordchar.'<br>';
  6801. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) {
  6802. $ok = 0;
  6803. break;
  6804. } elseif ($ordchar > 126 && $ordchar < 160) {
  6805. $ok = 0;
  6806. break;
  6807. } elseif ($clean) {
  6808. $out .= $s[$scursor];
  6809. }
  6810. }
  6811. if ($clean) {
  6812. return $out;
  6813. }
  6814. return $ok;
  6815. }
  6816. /**
  6817. * Return nb of lines of a clear text
  6818. *
  6819. * @param string $s String to check
  6820. * @param int $maxchar Not yet used
  6821. * @return int Number of lines
  6822. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  6823. */
  6824. function dol_nboflines($s, $maxchar = 0)
  6825. {
  6826. if ($s == '') {
  6827. return 0;
  6828. }
  6829. $arraystring = explode("\n", $s);
  6830. $nb = count($arraystring);
  6831. return $nb;
  6832. }
  6833. /**
  6834. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  6835. *
  6836. * @param string $text Text
  6837. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  6838. * @param string $charset Give the charset used to encode the $text variable in memory.
  6839. * @return int Number of lines
  6840. * @see dol_nboflines(), dolGetFirstLineOfText()
  6841. */
  6842. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  6843. {
  6844. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6845. if (dol_textishtml($text)) {
  6846. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  6847. }
  6848. $text = strtr($text, $repTable);
  6849. if ($charset == 'UTF-8') {
  6850. $pattern = '/(<br[^>]*>)/Uu';
  6851. } else {
  6852. // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  6853. $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  6854. }
  6855. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  6856. $nblines = (int) floor((count($a) + 1) / 2);
  6857. // count possible auto line breaks
  6858. if ($maxlinesize) {
  6859. foreach ($a as $line) {
  6860. if (dol_strlen($line) > $maxlinesize) {
  6861. //$line_dec = html_entity_decode(strip_tags($line));
  6862. $line_dec = html_entity_decode($line);
  6863. if (dol_strlen($line_dec) > $maxlinesize) {
  6864. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  6865. $nblines += substr_count($line_dec, '\n');
  6866. }
  6867. }
  6868. }
  6869. }
  6870. unset($a);
  6871. return $nblines;
  6872. }
  6873. /**
  6874. * Return if a text is a html content
  6875. *
  6876. * @param string $msg Content to check
  6877. * @param int $option 0=Full detection, 1=Fast check
  6878. * @return boolean true/false
  6879. * @see dol_concatdesc()
  6880. */
  6881. function dol_textishtml($msg, $option = 0)
  6882. {
  6883. if (is_null($msg)) {
  6884. return false;
  6885. }
  6886. if ($option == 1) {
  6887. if (preg_match('/<html/i', $msg)) {
  6888. return true;
  6889. } elseif (preg_match('/<body/i', $msg)) {
  6890. return true;
  6891. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6892. return true;
  6893. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  6894. return true;
  6895. } elseif (preg_match('/<br/i', $msg)) {
  6896. return true;
  6897. }
  6898. return false;
  6899. } else {
  6900. // Remove all urls because 'http://aa?param1=abc&amp;param2=def' must not be used inside detection
  6901. $msg = preg_replace('/https?:\/\/[^"\'\s]+/i', '', $msg);
  6902. if (preg_match('/<html/i', $msg)) {
  6903. return true;
  6904. } elseif (preg_match('/<body/i', $msg)) {
  6905. return true;
  6906. } elseif (preg_match('/<\/textarea/i', $msg)) {
  6907. return true;
  6908. } elseif (preg_match('/<(b|em|i|u)(\s+[^>]+)?>/i', $msg)) {
  6909. return true;
  6910. } elseif (preg_match('/<br\/>/i', $msg)) {
  6911. return true;
  6912. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
  6913. return true;
  6914. } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/?>/i', $msg)) {
  6915. return true;
  6916. } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
  6917. return true; // must accept <img src="http://example.com/aaa.png" />
  6918. } elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
  6919. return true; // must accept <a href="http://example.com/aaa.png" />
  6920. } elseif (preg_match('/<h[0-9]>/i', $msg)) {
  6921. return true;
  6922. } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
  6923. // TODO If content is 'A link https://aaa?param=abc&amp;param2=def', it return true but must be false
  6924. return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  6925. } elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
  6926. return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  6927. }
  6928. return false;
  6929. }
  6930. }
  6931. /**
  6932. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  6933. * text1 html + text2 html => text1 + '<br>' + text2
  6934. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  6935. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  6936. * text1 txt + text2 txt => text1 + '\n' + text2
  6937. *
  6938. * @param string $text1 Text 1
  6939. * @param string $text2 Text 2
  6940. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  6941. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  6942. * @return string Text 1 + new line + Text2
  6943. * @see dol_textishtml()
  6944. */
  6945. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  6946. {
  6947. if (!empty($invert)) {
  6948. $tmp = $text1;
  6949. $text1 = $text2;
  6950. $text2 = $tmp;
  6951. }
  6952. $ret = '';
  6953. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  6954. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  6955. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  6956. return $ret;
  6957. }
  6958. /**
  6959. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  6960. *
  6961. * @param Translate $outputlangs Output language
  6962. * @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)
  6963. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6964. * @param Object $object Object for keys on object
  6965. * @param array $include Array of family keys we want to include. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  6966. * @return array Array of substitutions
  6967. * @see setSubstitFromObject()
  6968. */
  6969. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null, $include = null)
  6970. {
  6971. global $db, $conf, $mysoc, $user, $extrafields;
  6972. $substitutionarray = array();
  6973. if ((empty($exclude) || !in_array('user', $exclude)) && (empty($include) || in_array('user', $include))) {
  6974. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  6975. // this will include signature content first and then replace var found into content of signature
  6976. //var_dump($onlykey);
  6977. $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()
  6978. $usersignature = $user->signature;
  6979. $substitutionarray = array_merge($substitutionarray, array(
  6980. '__SENDEREMAIL_SIGNATURE__' => (string) ((empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc('SignatureFromTheSelectedSenderProfile', 30) : $emailsendersignature) : ''),
  6981. '__USER_SIGNATURE__' => (string) (($usersignature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($usersignature), 30) : $usersignature) : '')
  6982. ));
  6983. if (is_object($user)) {
  6984. $substitutionarray = array_merge($substitutionarray, array(
  6985. '__USER_ID__' => (string) $user->id,
  6986. '__USER_LOGIN__' => (string) $user->login,
  6987. '__USER_EMAIL__' => (string) $user->email,
  6988. '__USER_PHONE__' => (string) dol_print_phone($user->office_phone, '', 0, 0, '', " ", '', '', -1),
  6989. '__USER_PHONEPRO__' => (string) dol_print_phone($user->user_mobile, '', 0, 0, '', " ", '', '', -1),
  6990. '__USER_PHONEMOBILE__' => (string) dol_print_phone($user->personal_mobile, '', 0, 0, '', " ", '', '', -1),
  6991. '__USER_FAX__' => (string) $user->office_fax,
  6992. '__USER_LASTNAME__' => (string) $user->lastname,
  6993. '__USER_FIRSTNAME__' => (string) $user->firstname,
  6994. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  6995. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  6996. '__USER_JOB__' => (string) $user->job,
  6997. '__USER_REMOTE_IP__' => (string) getUserRemoteIP(),
  6998. '__USER_VCARD_URL__' => (string) $user->getOnlineVirtualCardUrl('', 'external')
  6999. ));
  7000. }
  7001. }
  7002. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc) && (empty($include) || in_array('mycompany', $include))) {
  7003. $substitutionarray = array_merge($substitutionarray, array(
  7004. '__MYCOMPANY_NAME__' => $mysoc->name,
  7005. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  7006. '__MYCOMPANY_PHONE__' => dol_print_phone($mysoc->phone, '', 0, 0, '', " ", '', '', -1),
  7007. '__MYCOMPANY_FAX__' => dol_print_phone($mysoc->fax, '', 0, 0, '', " ", '', '', -1),
  7008. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  7009. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  7010. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  7011. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  7012. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  7013. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  7014. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  7015. '__MYCOMPANY_FULLADDRESS__' => (method_exists($mysoc, 'getFullAddress') ? $mysoc->getFullAddress(1, ', ') : ''), // $mysoc may be stdClass
  7016. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  7017. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  7018. '__MYCOMPANY_TOWN__' => $mysoc->town,
  7019. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  7020. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  7021. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  7022. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  7023. ));
  7024. }
  7025. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)) && (empty($include) || in_array('object', $include))) {
  7026. if ($onlykey) {
  7027. $substitutionarray['__ID__'] = '__ID__';
  7028. $substitutionarray['__REF__'] = '__REF__';
  7029. $substitutionarray['__NEWREF__'] = '__NEWREF__';
  7030. $substitutionarray['__LABEL__'] = '__LABEL__';
  7031. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  7032. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  7033. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  7034. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  7035. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  7036. if (isModEnabled("societe")) { // Most objects are concerned
  7037. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  7038. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  7039. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  7040. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  7041. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  7042. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  7043. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  7044. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  7045. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  7046. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  7047. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  7048. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  7049. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  7050. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  7051. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  7052. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  7053. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  7054. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  7055. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  7056. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  7057. }
  7058. if (isModEnabled('adherent') && (!is_object($object) || $object->element == 'adherent') && (empty($exclude) || !in_array('member', $exclude)) && (empty($include) || in_array('member', $include))) {
  7059. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  7060. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  7061. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  7062. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  7063. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = 'Login and pass of the external user account';
  7064. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  7065. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  7066. }
  7067. // add variables subtitutions ticket
  7068. if (isModEnabled('ticket') && (!is_object($object) || $object->element == 'ticket') && (empty($exclude) || !in_array('ticket', $exclude)) && (empty($include) || in_array('ticket', $include))) {
  7069. $substitutionarray['__TICKET_TRACKID__'] = '__TICKET_TRACKID__';
  7070. $substitutionarray['__TICKET_SUBJECT__'] = '__TICKET_SUBJECT__';
  7071. $substitutionarray['__TICKET_TYPE__'] = '__TICKET_TYPE__';
  7072. $substitutionarray['__TICKET_SEVERITY__'] = '__TICKET_SEVERITY__';
  7073. $substitutionarray['__TICKET_CATEGORY__'] = '__TICKET_CATEGORY__';
  7074. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = '__TICKET_ANALYTIC_CODE__';
  7075. $substitutionarray['__TICKET_MESSAGE__'] = '__TICKET_MESSAGE__';
  7076. $substitutionarray['__TICKET_PROGRESSION__'] = '__TICKET_PROGRESSION__';
  7077. $substitutionarray['__TICKET_USER_ASSIGN__'] = '__TICKET_USER_ASSIGN__';
  7078. }
  7079. if (isModEnabled('recruitment') && (!is_object($object) || $object->element == 'recruitmentcandidature') && (empty($exclude) || !in_array('recruitment', $exclude)) && (empty($include) || in_array('recruitment', $include))) {
  7080. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  7081. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  7082. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  7083. }
  7084. if (isModEnabled('project') && (empty($exclude) || !in_array('project', $exclude)) && (empty($include) || in_array('project', $include))) { // Most objects
  7085. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  7086. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  7087. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  7088. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  7089. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  7090. }
  7091. if (isModEnabled('contrat') && (!is_object($object) || $object->element == 'contract') && (empty($exclude) || !in_array('contract', $exclude)) && (empty($include) || in_array('contract', $include))) {
  7092. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  7093. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  7094. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  7095. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  7096. }
  7097. if (isModEnabled("propal") && (!is_object($object) || $object->element == 'propal') && (empty($exclude) || !in_array('propal', $exclude)) && (empty($include) || in_array('propal', $include))) {
  7098. $substitutionarray['__ONLINE_SIGN_URL__'] = 'ToOfferALinkForOnlineSignature';
  7099. }
  7100. if (isModEnabled("ficheinter") && (!is_object($object) || $object->element == 'fichinter') && (empty($exclude) || !in_array('intervention', $exclude)) && (empty($include) || in_array('intervention', $include))) {
  7101. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = 'ToOfferALinkForOnlineSignature';
  7102. }
  7103. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  7104. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  7105. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  7106. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  7107. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  7108. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  7109. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a service of a contract';
  7110. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  7111. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  7112. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  7113. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = 'Direct download url of a contract';
  7114. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = 'Direct download url of a supplier proposal';
  7115. if (isModEnabled("expedition") && (!is_object($object) || $object->element == 'shipping')) {
  7116. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  7117. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  7118. }
  7119. if (isModEnabled("reception") && (!is_object($object) || $object->element == 'reception')) {
  7120. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  7121. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  7122. }
  7123. } else {
  7124. $substitutionarray['__ID__'] = $object->id;
  7125. $substitutionarray['__REF__'] = $object->ref;
  7126. $substitutionarray['__NEWREF__'] = $object->newref;
  7127. $substitutionarray['__LABEL__'] = (isset($object->label) ? $object->label : (isset($object->title) ? $object->title : null));
  7128. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7129. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7130. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  7131. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  7132. if ($object->element == "shipping") {
  7133. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_delivery) ? dol_print_date($object->date_delivery, 'day', 0, $outputlangs) : '');
  7134. } else {
  7135. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  7136. }
  7137. $substitutionarray['__DATE_DELIVERY_DAY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%d") : '');
  7138. $substitutionarray['__DATE_DELIVERY_DAY_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%A") : '');
  7139. $substitutionarray['__DATE_DELIVERY_MON__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%m") : '');
  7140. $substitutionarray['__DATE_DELIVERY_MON_TEXT__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%b") : '');
  7141. $substitutionarray['__DATE_DELIVERY_YEAR__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%Y") : '');
  7142. $substitutionarray['__DATE_DELIVERY_HH__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%H") : '');
  7143. $substitutionarray['__DATE_DELIVERY_MM__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%M") : '');
  7144. $substitutionarray['__DATE_DELIVERY_SS__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, "%S") : '');
  7145. // For backward compatibility (deprecated)
  7146. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  7147. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  7148. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  7149. $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 : '')) : '');
  7150. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0) {
  7151. $birthday = (empty($object->birth) ? '' : dol_print_date($object->birth, 'day'));
  7152. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  7153. if (method_exists($object, 'getCivilityLabel')) {
  7154. $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  7155. }
  7156. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  7157. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  7158. $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = '';
  7159. if (method_exists($object, 'getFullName')) {
  7160. $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  7161. }
  7162. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  7163. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  7164. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  7165. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  7166. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  7167. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  7168. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  7169. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  7170. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  7171. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  7172. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? dol_print_phone($object->phone) : '');
  7173. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? dol_print_phone($object->phone_perso) : '');
  7174. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? dol_print_phone($object->phone_mobile) : '');
  7175. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  7176. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  7177. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = (isset($object->first_subscription_date_start) ? dol_print_date($object->first_subscription_date_start, 'dayrfc') : '');
  7178. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = (isset($object->first_subscription_date_end) ? dol_print_date($object->first_subscription_date_end, 'dayrfc') : '');
  7179. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  7180. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  7181. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  7182. }
  7183. if (is_object($object) && $object->element == 'societe') {
  7184. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  7185. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  7186. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  7187. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  7188. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  7189. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  7190. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? dol_print_phone($object->phone) : '');
  7191. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? dol_print_phone($object->fax) : '');
  7192. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  7193. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  7194. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  7195. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  7196. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  7197. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  7198. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  7199. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  7200. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  7201. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  7202. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  7203. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  7204. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  7205. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  7206. } elseif (is_object($object->thirdparty)) {
  7207. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  7208. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  7209. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  7210. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  7211. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  7212. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  7213. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->phone) : '');
  7214. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? dol_print_phone($object->thirdparty->fax) : '');
  7215. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  7216. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  7217. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  7218. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  7219. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  7220. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  7221. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  7222. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  7223. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  7224. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  7225. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  7226. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  7227. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  7228. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  7229. }
  7230. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  7231. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  7232. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7233. $substitutionarray['__CANDIDATE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7234. }
  7235. if (is_object($object) && $object->element == 'conferenceorboothattendee') {
  7236. $substitutionarray['__ATTENDEE_FULLNAME__'] = $object->getFullName($outputlangs);
  7237. $substitutionarray['__ATTENDEE_FIRSTNAME__'] = isset($object->firstname) ? $object->firstname : '';
  7238. $substitutionarray['__ATTENDEE_LASTNAME__'] = isset($object->lastname) ? $object->lastname : '';
  7239. }
  7240. if (is_object($object->project)) {
  7241. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  7242. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  7243. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  7244. }
  7245. if (is_object($object->projet)) { // Deprecated, for backward compatibility
  7246. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  7247. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  7248. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  7249. }
  7250. if (is_object($object) && $object->element == 'project') {
  7251. $substitutionarray['__PROJECT_NAME__'] = $object->title;
  7252. }
  7253. if (is_object($object) && $object->element == 'shipping') {
  7254. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  7255. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  7256. }
  7257. if (is_object($object) && $object->element == 'reception') {
  7258. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  7259. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  7260. }
  7261. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines)) {
  7262. $dateplannedstart = '';
  7263. $datenextexpiration = '';
  7264. foreach ($object->lines as $line) {
  7265. if ($line->date_start > $dateplannedstart) {
  7266. $dateplannedstart = $line->date_start;
  7267. }
  7268. if ($line->statut == 4 && $line->date_end && (!$datenextexpiration || $line->date_end < $datenextexpiration)) {
  7269. $datenextexpiration = $line->date_end;
  7270. }
  7271. }
  7272. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  7273. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  7274. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  7275. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  7276. }
  7277. // add substition variable for ticket
  7278. if (is_object($object) && $object->element == 'ticket') {
  7279. $substitutionarray['__TICKET_TRACKID__'] = $object->track_id;
  7280. $substitutionarray['__REF__'] = $object->ref;
  7281. $substitutionarray['__TICKET_SUBJECT__'] = $object->subject;
  7282. $substitutionarray['__TICKET_TYPE__'] = $object->type_code;
  7283. $substitutionarray['__TICKET_SEVERITY__'] = $object->severity_code;
  7284. $substitutionarray['__TICKET_CATEGORY__'] = $object->category_code; // For backward compatibility
  7285. $substitutionarray['__TICKET_ANALYTIC_CODE__'] = $object->category_code;
  7286. $substitutionarray['__TICKET_MESSAGE__'] = $object->message;
  7287. $substitutionarray['__TICKET_PROGRESSION__'] = $object->progress;
  7288. $userstat = new User($db);
  7289. if ($object->fk_user_assign > 0) {
  7290. $userstat->fetch($object->fk_user_assign);
  7291. $substitutionarray['__TICKET_USER_ASSIGN__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7292. }
  7293. if ($object->fk_user_create > 0) {
  7294. $userstat->fetch($object->fk_user_create);
  7295. $substitutionarray['__USER_CREATE__'] = dolGetFirstLastname($userstat->firstname, $userstat->lastname);
  7296. }
  7297. }
  7298. // Create dynamic tags for __EXTRAFIELD_FIELD__
  7299. if ($object->table_element && $object->id > 0) {
  7300. if (!is_object($extrafields)) {
  7301. $extrafields = new ExtraFields($db);
  7302. }
  7303. $extrafields->fetch_name_optionals_label($object->table_element, true);
  7304. if ($object->fetch_optionals() > 0) {
  7305. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
  7306. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  7307. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  7308. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  7309. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  7310. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  7311. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  7312. $datetime = $object->array_options['options_'.$key];
  7313. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  7314. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  7315. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  7316. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  7317. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'phone') {
  7318. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_phone($object->array_options['options_'.$key]);
  7319. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'price') {
  7320. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7321. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_FORMATED__'] = price($object->array_options['options_'.$key]);
  7322. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] != 'separator') {
  7323. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  7324. }
  7325. }
  7326. }
  7327. }
  7328. }
  7329. // Complete substitution array with the url to make online payment
  7330. $paymenturl = '';
  7331. if (empty($substitutionarray['__REF__'])) {
  7332. $paymenturl = '';
  7333. } else {
  7334. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  7335. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  7336. $outputlangs->loadLangs(array('paypal', 'other'));
  7337. $amounttouse = 0;
  7338. $typeforonlinepayment = 'free';
  7339. if (is_object($object) && $object->element == 'commande') {
  7340. $typeforonlinepayment = 'order';
  7341. }
  7342. if (is_object($object) && $object->element == 'facture') {
  7343. $typeforonlinepayment = 'invoice';
  7344. }
  7345. if (is_object($object) && $object->element == 'member') {
  7346. $typeforonlinepayment = 'member';
  7347. if (!empty($object->last_subscription_amount)) {
  7348. $amounttouse = $object->last_subscription_amount;
  7349. }
  7350. }
  7351. if (is_object($object) && $object->element == 'contrat') {
  7352. $typeforonlinepayment = 'contract';
  7353. }
  7354. if (is_object($object) && $object->element == 'fichinter') {
  7355. $typeforonlinepayment = 'ficheinter';
  7356. }
  7357. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__'], $amounttouse);
  7358. $paymenturl = $url;
  7359. }
  7360. if ($object->id > 0) {
  7361. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  7362. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  7363. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
  7364. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7365. } else {
  7366. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  7367. }
  7368. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
  7369. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  7370. } else {
  7371. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  7372. }
  7373. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
  7374. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  7375. } else {
  7376. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  7377. }
  7378. if (!empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'contrat') {
  7379. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = $object->getLastMainDocLink($object->element);
  7380. } else {
  7381. $substitutionarray['__DIRECTDOWNLOAD_URL_CONTRACT__'] = '';
  7382. }
  7383. if (!empty($conf->global->FICHINTER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'fichinter') {
  7384. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = $object->getLastMainDocLink($object->element);
  7385. } else {
  7386. $substitutionarray['__DIRECTDOWNLOAD_URL_FICHINTER__'] = '';
  7387. }
  7388. if (!empty($conf->global->SUPPLIER_PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'supplier_proposal') {
  7389. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  7390. } else {
  7391. $substitutionarray['__DIRECTDOWNLOAD_URL_SUPPLIER_PROPOSAL__'] = '';
  7392. }
  7393. if (is_object($object) && $object->element == 'propal') {
  7394. $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  7395. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7396. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'proposal', $object->ref);
  7397. }
  7398. if (is_object($object) && $object->element == 'commande') {
  7399. $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  7400. }
  7401. if (is_object($object) && $object->element == 'facture') {
  7402. $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  7403. }
  7404. if (is_object($object) && $object->element == 'contrat') {
  7405. $substitutionarray['__URL_CONTRACT__'] = DOL_MAIN_URL_ROOT."/contrat/card.php?id=".$object->id;
  7406. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7407. $substitutionarray['__ONLINE_SIGN_URL__'] = getOnlineSignatureUrl(0, 'contract', $object->ref);
  7408. }
  7409. if (is_object($object) && $object->element == 'fichinter') {
  7410. $substitutionarray['__URL_FICHINTER__'] = DOL_MAIN_URL_ROOT."/fichinter/card.php?id=".$object->id;
  7411. require_once DOL_DOCUMENT_ROOT.'/core/lib/signature.lib.php';
  7412. $substitutionarray['__ONLINE_SIGN_FICHINTER_URL__'] = getOnlineSignatureUrl(0, 'fichinter', $object->ref);
  7413. }
  7414. if (is_object($object) && $object->element == 'supplier_proposal') {
  7415. $substitutionarray['__URL_SUPPLIER_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/supplier_proposal/card.php?id=".$object->id;
  7416. }
  7417. if (is_object($object) && $object->element == 'shipping') {
  7418. $substitutionarray['__URL_SHIPMENT__'] = DOL_MAIN_URL_ROOT."/expedition/card.php?id=".$object->id;
  7419. }
  7420. }
  7421. if (is_object($object) && $object->element == 'action') {
  7422. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  7423. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  7424. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  7425. }
  7426. }
  7427. }
  7428. if ((empty($exclude) || !in_array('objectamount', $exclude)) && (empty($include) || in_array('objectamount', $include))) {
  7429. include_once DOL_DOCUMENT_ROOT.'/core/lib/functionsnumtoword.lib.php';
  7430. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  7431. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  7432. $already_payed_all = 0;
  7433. if (is_object($object) && ($object instanceof Facture)) {
  7434. $already_payed_all = $object->sumpayed + $object->sumdeposit + $object->sumcreditnote;
  7435. }
  7436. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  7437. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  7438. $substitutionarray['__AMOUNT_TEXT__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, '', true) : '';
  7439. $substitutionarray['__AMOUNT_TEXTCURRENCY__'] = is_object($object) ? dol_convertToWord($object->total_ttc, $outputlangs, $conf->currency, true) : '';
  7440. $substitutionarray['__AMOUNT_REMAIN__'] = is_object($object) ? price2num($object->total_ttc - $already_payed_all, 'MT') : '';
  7441. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7442. $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)) : '';
  7443. $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)) : '';
  7444. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7445. $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  7446. }
  7447. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7448. $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  7449. }
  7450. // Amount keys formated in a currency
  7451. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7452. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7453. $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) : '';
  7454. $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)) : '';
  7455. if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
  7456. $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7457. }
  7458. if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
  7459. $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, -1, -1, $conf->currency) : null) : '';
  7460. }
  7461. $substitutionarray['__AMOUNT_MULTICURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? $object->multicurrency_total_ttc : '';
  7462. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXT__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, '', true) : '';
  7463. $substitutionarray['__AMOUNT_MULTICURRENCY_TEXTCURRENCY__'] = (is_object($object) && isset($object->multicurrency_total_ttc)) ? dol_convertToWord($object->multicurrency_total_ttc, $outputlangs, $object->multicurrency_code, true) : '';
  7464. // TODO Add other keys for foreign multicurrency
  7465. // For backward compatibility
  7466. if ($onlykey != 2) {
  7467. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  7468. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  7469. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  7470. }
  7471. }
  7472. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  7473. if ((empty($exclude) || !in_array('date', $exclude)) && (empty($include) || in_array('date', $include))) {
  7474. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  7475. $now = dol_now();
  7476. $tmp = dol_getdate($now, true);
  7477. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7478. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  7479. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  7480. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  7481. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  7482. $substitutionarray = array_merge($substitutionarray, array(
  7483. '__NOW_TMS__' => (int) $now,
  7484. '__NOW_TMS_YMD__' => dol_print_date($now, 'day', 0, $outputlangs),
  7485. '__DAY__' => (string) $tmp['mday'],
  7486. '__DAY_TEXT__' => $daytext, // Monday
  7487. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  7488. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  7489. '__MONTH__' => (string) $tmp['mon'],
  7490. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  7491. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  7492. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  7493. '__YEAR__' => (string) $tmp['year'],
  7494. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  7495. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  7496. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  7497. '__NEXT_DAY__' => (string) $tmp4['day'],
  7498. '__NEXT_MONTH__' => (string) $tmp5['month'],
  7499. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  7500. ));
  7501. }
  7502. if (isModEnabled('multicompany')) {
  7503. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  7504. }
  7505. if ((empty($exclude) || !in_array('system', $exclude)) && (empty($include) || in_array('user', $include))) {
  7506. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  7507. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  7508. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  7509. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  7510. }
  7511. return $substitutionarray;
  7512. }
  7513. /**
  7514. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  7515. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  7516. * Example of usage:
  7517. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  7518. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  7519. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  7520. *
  7521. * @param string $text Source string in which we must do substitution
  7522. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  7523. * @param Translate $outputlangs Output language
  7524. * @param int $converttextinhtmlifnecessary 0=Convert only value into HTML if text is already in HTML
  7525. * 1=Will also convert initial $text into HTML if we try to insert one value that is HTML
  7526. * @return string Output string after substitutions
  7527. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  7528. */
  7529. function make_substitutions($text, $substitutionarray, $outputlangs = null, $converttextinhtmlifnecessary = 0)
  7530. {
  7531. global $conf, $langs;
  7532. if (!is_array($substitutionarray)) {
  7533. return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  7534. }
  7535. if (empty($outputlangs)) {
  7536. $outputlangs = $langs;
  7537. }
  7538. // Is initial text HTML or simple text ?
  7539. $msgishtml = 0;
  7540. if (dol_textishtml($text, 1)) {
  7541. $msgishtml = 1;
  7542. }
  7543. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  7544. if (is_object($outputlangs)) {
  7545. $reg = array();
  7546. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
  7547. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  7548. $tmp = explode('|', $reg[1]);
  7549. if (!empty($tmp[1])) {
  7550. $outputlangs->load($tmp[1]);
  7551. }
  7552. $value = $outputlangs->transnoentitiesnoconv($reg[1]);
  7553. if (empty($converttextinhtmlifnecessary)) {
  7554. // convert $newval into HTML is necessary
  7555. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7556. } else {
  7557. if (! $msgishtml) {
  7558. $valueishtml = dol_textishtml($value, 1);
  7559. //var_dump("valueishtml=".$valueishtml);
  7560. if ($valueishtml) {
  7561. $text = dol_htmlentitiesbr($text);
  7562. $msgishtml = 1;
  7563. }
  7564. } else {
  7565. $value = dol_nl2br("$value");
  7566. }
  7567. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $value, $text);
  7568. }
  7569. }
  7570. }
  7571. // Make substitution for constant keys.
  7572. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  7573. $reg = array();
  7574. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
  7575. $keyfound = $reg[1];
  7576. if (isASecretKey($keyfound)) {
  7577. $value = '*****forbidden*****';
  7578. } else {
  7579. $value = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  7580. }
  7581. if (empty($converttextinhtmlifnecessary)) {
  7582. // convert $newval into HTML is necessary
  7583. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($value) : $value, $text);
  7584. } else {
  7585. if (! $msgishtml) {
  7586. $valueishtml = dol_textishtml($value, 1);
  7587. if ($valueishtml) {
  7588. $text = dol_htmlentitiesbr($text);
  7589. $msgishtml = 1;
  7590. }
  7591. } else {
  7592. $value = dol_nl2br("$value");
  7593. }
  7594. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $value, $text);
  7595. }
  7596. }
  7597. // Make substitution for array $substitutionarray
  7598. foreach ($substitutionarray as $key => $value) {
  7599. if (!isset($value)) {
  7600. continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  7601. }
  7602. if (($key == '__USER_SIGNATURE__' || $key == '__SENDEREMAIL_SIGNATURE__') && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
  7603. $value = ''; // Protection
  7604. }
  7605. if (empty($converttextinhtmlifnecessary)) {
  7606. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7607. } else {
  7608. if (! $msgishtml) {
  7609. $valueishtml = dol_textishtml($value, 1);
  7610. if ($valueishtml) {
  7611. $text = dol_htmlentitiesbr($text);
  7612. $msgishtml = 1;
  7613. }
  7614. } else {
  7615. $value = dol_nl2br("$value");
  7616. }
  7617. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  7618. }
  7619. }
  7620. return $text;
  7621. }
  7622. /**
  7623. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  7624. * In this case, method completesubstitutionarray provided by module is called.
  7625. *
  7626. * @param array $substitutionarray Array substitution old value => new value value
  7627. * @param Translate $outputlangs Output language
  7628. * @param Object $object Source object
  7629. * @param mixed $parameters Add more parameters (useful to pass product lines)
  7630. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  7631. * @return void
  7632. * @see make_substitutions()
  7633. */
  7634. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  7635. {
  7636. global $conf, $user;
  7637. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  7638. // Note: substitution key for each extrafields, using key __EXTRA_XXX__ is already available into the getCommonSubstitutionArray used to build the substitution array.
  7639. // Check if there is external substitution to do, requested by plugins
  7640. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  7641. foreach ($dirsubstitutions as $reldir) {
  7642. $dir = dol_buildpath($reldir, 0);
  7643. // Check if directory exists
  7644. if (!dol_is_dir($dir)) {
  7645. continue;
  7646. }
  7647. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  7648. foreach ($substitfiles as $substitfile) {
  7649. $reg = array();
  7650. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
  7651. $module = $reg[1];
  7652. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  7653. // Include the user's functions file
  7654. require_once $dir.$substitfile['name'];
  7655. // Call the user's function, and only if it is defined
  7656. $function_name = $module."_".$callfunc;
  7657. if (function_exists($function_name)) {
  7658. $function_name($substitutionarray, $outputlangs, $object, $parameters);
  7659. }
  7660. }
  7661. }
  7662. }
  7663. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  7664. // to list all tags in odt template
  7665. $tags = '';
  7666. foreach ($substitutionarray as $key => $value) {
  7667. $tags .= '{'.$key.'} => '.$value."\n";
  7668. }
  7669. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  7670. }
  7671. }
  7672. /**
  7673. * Format output for start and end date
  7674. *
  7675. * @param int $date_start Start date
  7676. * @param int $date_end End date
  7677. * @param string $format Output format
  7678. * @param Translate $outputlangs Output language
  7679. * @return void
  7680. */
  7681. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  7682. {
  7683. print get_date_range($date_start, $date_end, $format, $outputlangs);
  7684. }
  7685. /**
  7686. * Format output for start and end date
  7687. *
  7688. * @param int $date_start Start date
  7689. * @param int $date_end End date
  7690. * @param string $format Output date format ('day', 'dayhour', ...)
  7691. * @param Translate $outputlangs Output language
  7692. * @param integer $withparenthesis 1=Add parenthesis, 0=no parenthesis
  7693. * @return string String
  7694. */
  7695. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  7696. {
  7697. global $langs;
  7698. $out = '';
  7699. if (!is_object($outputlangs)) {
  7700. $outputlangs = $langs;
  7701. }
  7702. if ($date_start && $date_end) {
  7703. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7704. }
  7705. if ($date_start && !$date_end) {
  7706. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7707. }
  7708. if (!$date_start && $date_end) {
  7709. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  7710. }
  7711. return $out;
  7712. }
  7713. /**
  7714. * Return firstname and lastname in correct order
  7715. *
  7716. * @param string $firstname Firstname
  7717. * @param string $lastname Lastname
  7718. * @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
  7719. * @return string Firstname + lastname or Lastname + firstname
  7720. */
  7721. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  7722. {
  7723. global $conf;
  7724. $ret = '';
  7725. // If order not defined, we use the setup
  7726. if ($nameorder < 0) {
  7727. $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  7728. }
  7729. if ($nameorder == 1) {
  7730. $ret .= $firstname;
  7731. if ($firstname && $lastname) {
  7732. $ret .= ' ';
  7733. }
  7734. $ret .= $lastname;
  7735. } elseif ($nameorder == 2 || $nameorder == 3) {
  7736. $ret .= $firstname;
  7737. if (empty($ret) && $nameorder == 3) {
  7738. $ret .= $lastname;
  7739. }
  7740. } else { // 0, 4 or 5
  7741. $ret .= $lastname;
  7742. if (empty($ret) && $nameorder == 5) {
  7743. $ret .= $firstname;
  7744. }
  7745. if ($nameorder == 0) {
  7746. if ($firstname && $lastname) {
  7747. $ret .= ' ';
  7748. }
  7749. $ret .= $firstname;
  7750. }
  7751. }
  7752. return $ret;
  7753. }
  7754. /**
  7755. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  7756. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7757. * Note: Prefer to use setEventMessages instead.
  7758. *
  7759. * @param string|string[] $mesgs Message string or array
  7760. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7761. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  7762. * @return void
  7763. * @see dol_htmloutput_events()
  7764. */
  7765. function setEventMessage($mesgs, $style = 'mesgs', $noduplicate = 0)
  7766. {
  7767. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  7768. if (!is_array($mesgs)) {
  7769. // If mesgs is a string
  7770. if ($mesgs) {
  7771. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesgs, $_SESSION['dol_events'][$style])) {
  7772. return;
  7773. }
  7774. $_SESSION['dol_events'][$style][] = $mesgs;
  7775. }
  7776. } else {
  7777. // If mesgs is an array
  7778. foreach ($mesgs as $mesg) {
  7779. if ($mesg) {
  7780. if (!empty($noduplicate) && isset($_SESSION['dol_events'][$style]) && in_array($mesg, $_SESSION['dol_events'][$style])) {
  7781. return;
  7782. }
  7783. $_SESSION['dol_events'][$style][] = $mesg;
  7784. }
  7785. }
  7786. }
  7787. }
  7788. /**
  7789. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  7790. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  7791. *
  7792. * @param string $mesg Message string
  7793. * @param array|null $mesgs Message array
  7794. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  7795. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  7796. * @param int $noduplicate 1 means we do not add the message if already present in session stack
  7797. * @return void
  7798. * @see dol_htmloutput_events()
  7799. */
  7800. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '', $noduplicate = 0)
  7801. {
  7802. if (empty($mesg) && empty($mesgs)) {
  7803. dol_syslog("Try to add a message in stack, but value to add is empty message", LOG_WARNING);
  7804. } else {
  7805. if ($messagekey) {
  7806. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  7807. // TODO
  7808. $mesg .= '';
  7809. }
  7810. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey])) {
  7811. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
  7812. dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  7813. }
  7814. if (empty($mesgs)) {
  7815. setEventMessage($mesg, $style, $noduplicate);
  7816. } else {
  7817. if (!empty($mesg) && !in_array($mesg, $mesgs)) {
  7818. setEventMessage($mesg, $style, $noduplicate); // Add message string if not already into array
  7819. }
  7820. setEventMessage($mesgs, $style, $noduplicate);
  7821. }
  7822. }
  7823. }
  7824. }
  7825. /**
  7826. * Print formated messages to output (Used to show messages on html output).
  7827. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  7828. * no need to call it explicitely.
  7829. *
  7830. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  7831. * @return void
  7832. * @see dol_htmloutput_mesg()
  7833. */
  7834. function dol_htmloutput_events($disabledoutputofmessages = 0)
  7835. {
  7836. // Show mesgs
  7837. if (isset($_SESSION['dol_events']['mesgs'])) {
  7838. if (empty($disabledoutputofmessages)) {
  7839. dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  7840. }
  7841. unset($_SESSION['dol_events']['mesgs']);
  7842. }
  7843. // Show errors
  7844. if (isset($_SESSION['dol_events']['errors'])) {
  7845. if (empty($disabledoutputofmessages)) {
  7846. dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  7847. }
  7848. unset($_SESSION['dol_events']['errors']);
  7849. }
  7850. // Show warnings
  7851. if (isset($_SESSION['dol_events']['warnings'])) {
  7852. if (empty($disabledoutputofmessages)) {
  7853. dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  7854. }
  7855. unset($_SESSION['dol_events']['warnings']);
  7856. }
  7857. }
  7858. /**
  7859. * Get formated messages to output (Used to show messages on html output).
  7860. * This include also the translation of the message key.
  7861. *
  7862. * @param string $mesgstring Message string or message key
  7863. * @param string[] $mesgarray Array of message strings or message keys
  7864. * @param string $style Style of message output ('ok' or 'error')
  7865. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7866. * @return string Return html output
  7867. *
  7868. * @see dol_print_error()
  7869. * @see dol_htmloutput_errors()
  7870. * @see setEventMessages()
  7871. */
  7872. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  7873. {
  7874. global $conf, $langs;
  7875. $ret = 0;
  7876. $return = '';
  7877. $out = '';
  7878. $divstart = $divend = '';
  7879. // If inline message with no format, we add it.
  7880. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
  7881. $divstart = '<div class="'.$style.' clearboth">';
  7882. $divend = '</div>';
  7883. }
  7884. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring) {
  7885. $langs->load("errors");
  7886. $out .= $divstart;
  7887. if (is_array($mesgarray) && count($mesgarray)) {
  7888. foreach ($mesgarray as $message) {
  7889. $ret++;
  7890. $out .= $langs->trans($message);
  7891. if ($ret < count($mesgarray)) {
  7892. $out .= "<br>\n";
  7893. }
  7894. }
  7895. }
  7896. if ($mesgstring) {
  7897. $ret++;
  7898. $out .= $langs->trans($mesgstring);
  7899. }
  7900. $out .= $divend;
  7901. }
  7902. if ($out) {
  7903. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
  7904. $return = '<script nonce="'.getNonce().'">
  7905. $(document).ready(function() {
  7906. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  7907. if (block) {
  7908. $.dolEventValid("","'.dol_escape_js($out).'");
  7909. } else {
  7910. /* jnotify(message, preset of message type, keepmessage) */
  7911. $.jnotify("'.dol_escape_js($out).'",
  7912. "'.($style == "ok" ? 3000 : $style).'",
  7913. '.($style == "ok" ? "false" : "true").',
  7914. { remove: function (){} } );
  7915. }
  7916. });
  7917. </script>';
  7918. } else {
  7919. $return = $out;
  7920. }
  7921. }
  7922. return $return;
  7923. }
  7924. /**
  7925. * Get formated error messages to output (Used to show messages on html output).
  7926. *
  7927. * @param string $mesgstring Error message
  7928. * @param array $mesgarray Error messages array
  7929. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  7930. * @return string Return html output
  7931. *
  7932. * @see dol_print_error()
  7933. * @see dol_htmloutput_mesg()
  7934. */
  7935. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  7936. {
  7937. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  7938. }
  7939. /**
  7940. * Print formated messages to output (Used to show messages on html output).
  7941. *
  7942. * @param string $mesgstring Message string or message key
  7943. * @param string[] $mesgarray Array of message strings or message keys
  7944. * @param string $style Which style to use ('ok', 'warning', 'error')
  7945. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  7946. * @return void
  7947. *
  7948. * @see dol_print_error()
  7949. * @see dol_htmloutput_errors()
  7950. * @see setEventMessages()
  7951. */
  7952. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  7953. {
  7954. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
  7955. return;
  7956. }
  7957. $iserror = 0;
  7958. $iswarning = 0;
  7959. if (is_array($mesgarray)) {
  7960. foreach ($mesgarray as $val) {
  7961. if ($val && preg_match('/class="error"/i', $val)) {
  7962. $iserror++;
  7963. break;
  7964. }
  7965. if ($val && preg_match('/class="warning"/i', $val)) {
  7966. $iswarning++;
  7967. break;
  7968. }
  7969. }
  7970. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
  7971. $iserror++;
  7972. } elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
  7973. $iswarning++;
  7974. }
  7975. if ($style == 'error') {
  7976. $iserror++;
  7977. }
  7978. if ($style == 'warning') {
  7979. $iswarning++;
  7980. }
  7981. if ($iserror || $iswarning) {
  7982. // Remove div from texts
  7983. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  7984. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  7985. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  7986. // Remove div from texts array
  7987. if (is_array($mesgarray)) {
  7988. $newmesgarray = array();
  7989. foreach ($mesgarray as $val) {
  7990. if (is_string($val)) {
  7991. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  7992. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  7993. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  7994. $newmesgarray[] = $tmpmesgstring;
  7995. } else {
  7996. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  7997. }
  7998. }
  7999. $mesgarray = $newmesgarray;
  8000. }
  8001. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  8002. } else {
  8003. print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  8004. }
  8005. }
  8006. /**
  8007. * Print formated error messages to output (Used to show messages on html output).
  8008. *
  8009. * @param string $mesgstring Error message
  8010. * @param array $mesgarray Error messages array
  8011. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  8012. * @return void
  8013. *
  8014. * @see dol_print_error()
  8015. * @see dol_htmloutput_mesg()
  8016. */
  8017. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  8018. {
  8019. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  8020. }
  8021. /**
  8022. * Advanced sort array by second index function, which produces ascending (default)
  8023. * or descending output and uses optionally natural case insensitive sorting (which
  8024. * can be optionally case sensitive as well).
  8025. *
  8026. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  8027. * @param string $index Key in array to use for sorting criteria
  8028. * @param int $order Sort order ('asc' or 'desc')
  8029. * @param int $natsort If values are strings (I said value not type): 0=Use alphabetical order, 1=use "natural" sort (natsort)
  8030. * 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
  8031. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  8032. * @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.
  8033. * @return array Sorted array
  8034. */
  8035. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  8036. {
  8037. // Clean parameters
  8038. $order = strtolower($order);
  8039. if (is_array($array)) {
  8040. $sizearray = count($array);
  8041. if ($sizearray > 0) {
  8042. $temp = array();
  8043. foreach (array_keys($array) as $key) {
  8044. if (is_object($array[$key])) {
  8045. $temp[$key] = empty($array[$key]->$index) ? 0 : $array[$key]->$index;
  8046. } else {
  8047. $temp[$key] = empty($array[$key][$index]) ? 0 : $array[$key][$index];
  8048. }
  8049. if ($natsort == -1) {
  8050. $temp[$key] = '___'.$temp[$key]; // We add a string at begin of value to force an alpha order when using asort.
  8051. }
  8052. }
  8053. if (empty($natsort) || $natsort == -1) {
  8054. if ($order == 'asc') {
  8055. asort($temp);
  8056. } else {
  8057. arsort($temp);
  8058. }
  8059. } else {
  8060. if ($case_sensitive) {
  8061. natsort($temp);
  8062. } else {
  8063. natcasesort($temp); // natecasesort is not sensible to case
  8064. }
  8065. if ($order != 'asc') {
  8066. $temp = array_reverse($temp, true);
  8067. }
  8068. }
  8069. $sorted = array();
  8070. foreach (array_keys($temp) as $key) {
  8071. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  8072. }
  8073. return $sorted;
  8074. }
  8075. }
  8076. return $array;
  8077. }
  8078. /**
  8079. * Check if a string is in UTF8
  8080. *
  8081. * @param string $str String to check
  8082. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  8083. */
  8084. function utf8_check($str)
  8085. {
  8086. $str = (string) $str; // Sometimes string is an int.
  8087. // We must use here a binary strlen function (so not dol_strlen)
  8088. $strLength = dol_strlen($str);
  8089. for ($i = 0; $i < $strLength; $i++) {
  8090. if (ord($str[$i]) < 0x80) {
  8091. continue; // 0bbbbbbb
  8092. } elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
  8093. $n = 1; // 110bbbbb
  8094. } elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
  8095. $n = 2; // 1110bbbb
  8096. } elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
  8097. $n = 3; // 11110bbb
  8098. } elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
  8099. $n = 4; // 111110bb
  8100. } elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
  8101. $n = 5; // 1111110b
  8102. } else {
  8103. return false; // Does not match any model
  8104. }
  8105. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  8106. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
  8107. return false;
  8108. }
  8109. }
  8110. }
  8111. return true;
  8112. }
  8113. /**
  8114. * Check if a string is in UTF8
  8115. *
  8116. * @param string $str String to check
  8117. * @return boolean True if string is valid UTF8 string, false if corrupted
  8118. */
  8119. function utf8_valid($str)
  8120. {
  8121. /* 2 other methods to test if string is utf8
  8122. $validUTF8 = mb_check_encoding($messagetext, 'UTF-8');
  8123. $validUTF8b = ! (false === mb_detect_encoding($messagetext, 'UTF-8', true));
  8124. */
  8125. return preg_match('//u', $str) ? true : false;
  8126. }
  8127. /**
  8128. * Check if a string is in ASCII
  8129. *
  8130. * @param string $str String to check
  8131. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  8132. */
  8133. function ascii_check($str)
  8134. {
  8135. if (function_exists('mb_check_encoding')) {
  8136. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  8137. if (!mb_check_encoding($str, 'ASCII')) {
  8138. return false;
  8139. }
  8140. } else {
  8141. if (preg_match('/[^\x00-\x7f]/', $str)) {
  8142. return false; // Contains a byte > 7f
  8143. }
  8144. }
  8145. return true;
  8146. }
  8147. /**
  8148. * Return a string encoded into OS filesystem encoding. This function is used to define
  8149. * value to pass to filesystem PHP functions.
  8150. *
  8151. * @param string $str String to encode (UTF-8)
  8152. * @return string Encoded string (UTF-8, ISO-8859-1)
  8153. */
  8154. function dol_osencode($str)
  8155. {
  8156. global $conf;
  8157. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  8158. if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
  8159. $tmp = 'iso-8859-1'; // By default for windows
  8160. }
  8161. if (empty($tmp)) {
  8162. $tmp = 'utf-8'; // By default for other
  8163. }
  8164. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) {
  8165. $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  8166. }
  8167. if ($tmp == 'iso-8859-1') {
  8168. return mb_convert_encoding($str, 'ISO-8859-1', 'UTF-8');
  8169. }
  8170. return $str;
  8171. }
  8172. /**
  8173. * Return an id or code from a code or id.
  8174. * Store also Code-Id into a cache to speed up next request on same key.
  8175. *
  8176. * @param DoliDB $db Database handler
  8177. * @param string $key Code or Id to get Id or Code
  8178. * @param string $tablename Table name without prefix
  8179. * @param string $fieldkey Field to search the key into
  8180. * @param string $fieldid Field to get
  8181. * @param int $entityfilter Filter by entity
  8182. * @param string $filters Filters to add. WARNING: string must be escaped for SQL and not coming from user input.
  8183. * @return int <0 if KO, Id of code if OK
  8184. * @see $langs->getLabelFromKey
  8185. */
  8186. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0, $filters = '')
  8187. {
  8188. global $cache_codes;
  8189. // If key empty
  8190. if ($key == '') {
  8191. return '';
  8192. }
  8193. // Check in cache
  8194. if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
  8195. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  8196. }
  8197. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  8198. $sql = "SELECT ".$fieldid." as valuetoget";
  8199. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  8200. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  8201. if (!empty($entityfilter)) {
  8202. $sql .= " AND entity IN (".getEntity($tablename).")";
  8203. }
  8204. if ($filters) {
  8205. $sql .= $filters;
  8206. }
  8207. $resql = $db->query($sql);
  8208. if ($resql) {
  8209. $obj = $db->fetch_object($resql);
  8210. if ($obj) {
  8211. $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  8212. } else {
  8213. $cache_codes[$tablename][$key][$fieldid] = '';
  8214. }
  8215. $db->free($resql);
  8216. return $cache_codes[$tablename][$key][$fieldid];
  8217. } else {
  8218. return -1;
  8219. }
  8220. }
  8221. /**
  8222. * Verify if condition in string is ok or not
  8223. *
  8224. * @param string $strToEvaluate String with condition to check
  8225. * @return boolean True or False. Note: It returns also True if $strToEvaluate is ''. False if error
  8226. */
  8227. function verifCond($strToEvaluate)
  8228. {
  8229. global $user, $conf, $langs;
  8230. global $leftmenu;
  8231. global $rights; // To export to dol_eval function
  8232. //print $strToEvaluate."<br>\n";
  8233. $rights = true;
  8234. if (isset($strToEvaluate) && $strToEvaluate !== '') {
  8235. //var_dump($strToEvaluate);
  8236. $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
  8237. $rights = $rep && (!is_string($rep) || strpos($rep, 'Bad string syntax to evaluate') === false);
  8238. //var_dump($rights);
  8239. }
  8240. return $rights;
  8241. }
  8242. /**
  8243. * Replace eval function to add more security.
  8244. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  8245. *
  8246. * @param string $s String to evaluate
  8247. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  8248. * @param int $hideerrors 1=Hide errors
  8249. * @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' (rarely used)=Accept also '[]'
  8250. * @return mixed Nothing or return result of eval
  8251. */
  8252. function dol_eval($s, $returnvalue = 0, $hideerrors = 1, $onlysimplestring = '1')
  8253. {
  8254. // Only global variables can be changed by eval function and returned to caller
  8255. global $db, $langs, $user, $conf, $website, $websitepage;
  8256. global $action, $mainmenu, $leftmenu;
  8257. global $mysoc;
  8258. global $objectoffield;
  8259. // Old variables used
  8260. global $rights;
  8261. global $object;
  8262. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  8263. global $soc; // For backward compatibility
  8264. try {
  8265. // Test on dangerous char (used for RCE), we allow only characters to make PHP variable testing
  8266. if ($onlysimplestring == '1') {
  8267. // We must accept: '1 && getDolGlobalInt("doesnotexist1") && $conf->global->MAIN_FEATURES_LEVEL'
  8268. // We must accept: '$conf->barcode->enabled || preg_match(\'/^AAA/\',$leftmenu)'
  8269. // We must accept: '$user->rights->cabinetmed->read && !$object->canvas=="patient@cabinetmed"'
  8270. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@', '/').']/i', $s)) {
  8271. if ($returnvalue) {
  8272. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8273. } else {
  8274. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8275. return '';
  8276. }
  8277. // TODO
  8278. // We can exclude all parenthesis ( that are not '($db' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match(' and 'isModEnabled('
  8279. // ...
  8280. }
  8281. } elseif ($onlysimplestring == '2') {
  8282. // 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"
  8283. if (preg_match('/[^a-z0-9\s'.preg_quote('^$_+-.*>&|=!?():"\',/@[]', '/').']/i', $s)) {
  8284. if ($returnvalue) {
  8285. return 'Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s;
  8286. } else {
  8287. dol_syslog('Bad string syntax to evaluate (found chars that are not chars for simplestring): '.$s);
  8288. return '';
  8289. }
  8290. // TODO
  8291. // We can exclude all parenthesis ( that are not '($db' and 'getDolGlobalInt(' and 'getDolGlobalString(' and 'preg_match(' and 'isModEnabled('
  8292. // ...
  8293. }
  8294. }
  8295. if (is_array($s) || $s === 'Array') {
  8296. return 'Bad string syntax to evaluate (value is Array) '.var_export($s, true);
  8297. }
  8298. if (strpos($s, '::') !== false) {
  8299. if ($returnvalue) {
  8300. return 'Bad string syntax to evaluate (double : char is forbidden): '.$s;
  8301. } else {
  8302. dol_syslog('Bad string syntax to evaluate (double : char is forbidden): '.$s);
  8303. return '';
  8304. }
  8305. }
  8306. if (strpos($s, '`') !== false) {
  8307. if ($returnvalue) {
  8308. return 'Bad string syntax to evaluate (backtick char is forbidden): '.$s;
  8309. } else {
  8310. dol_syslog('Bad string syntax to evaluate (backtick char is forbidden): '.$s);
  8311. return '';
  8312. }
  8313. }
  8314. if (preg_match('/[^0-9]+\.[^0-9]+/', $s)) { // We refuse . if not between 2 numbers
  8315. if ($returnvalue) {
  8316. return 'Bad string syntax to evaluate (dot char is forbidden): '.$s;
  8317. } else {
  8318. dol_syslog('Bad string syntax to evaluate (dot char is forbidden): '.$s);
  8319. return '';
  8320. }
  8321. }
  8322. // We block use of php exec or php file functions
  8323. $forbiddenphpstrings = array('$$');
  8324. $forbiddenphpstrings = array_merge($forbiddenphpstrings, array('_ENV', '_SESSION', '_COOKIE', '_GET', '_POST', '_REQUEST'));
  8325. $forbiddenphpfunctions = array("exec", "passthru", "shell_exec", "system", "proc_open", "popen", "eval", "dol_eval", "executeCLI", "verifCond", "base64_decode");
  8326. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "require", "include", "mkdir", "rmdir", "symlink", "touch", "unlink", "umask"));
  8327. $forbiddenphpfunctions = array_merge($forbiddenphpfunctions, array("function", "call_user_func"));
  8328. $forbiddenphpregex = 'global\s+\$|\b('.implode('|', $forbiddenphpfunctions).')\b';
  8329. do {
  8330. $oldstringtoclean = $s;
  8331. $s = str_ireplace($forbiddenphpstrings, '__forbiddenstring__', $s);
  8332. $s = preg_replace('/'.$forbiddenphpregex.'/i', '__forbiddenstring__', $s);
  8333. //$s = preg_replace('/\$[a-zA-Z0-9_\->\$]+\(/i', '', $s); // Remove $function( call and $mycall->mymethod(
  8334. } while ($oldstringtoclean != $s);
  8335. if (strpos($s, '__forbiddenstring__') !== false) {
  8336. dol_syslog('Bad string syntax to evaluate: '.$s, LOG_WARNING);
  8337. if ($returnvalue) {
  8338. return 'Bad string syntax to evaluate: '.$s;
  8339. } else {
  8340. dol_syslog('Bad string syntax to evaluate: '.$s);
  8341. return '';
  8342. }
  8343. }
  8344. //print $s."<br>\n";
  8345. if ($returnvalue) {
  8346. if ($hideerrors) {
  8347. return @eval('return '.$s.';');
  8348. } else {
  8349. return eval('return '.$s.';');
  8350. }
  8351. } else {
  8352. if ($hideerrors) {
  8353. @eval($s);
  8354. } else {
  8355. eval($s);
  8356. }
  8357. }
  8358. } catch (Error $e) {
  8359. $error = 'dol_eval try/catch error : ';
  8360. $error .= $e->getMessage();
  8361. dol_syslog($error);
  8362. }
  8363. }
  8364. /**
  8365. * Return if var element is ok
  8366. *
  8367. * @param string $element Variable to check
  8368. * @return boolean Return true of variable is not empty
  8369. */
  8370. function dol_validElement($element)
  8371. {
  8372. return (trim($element) != '');
  8373. }
  8374. /**
  8375. * Return img flag of country for a language code or country code.
  8376. *
  8377. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  8378. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  8379. * @param int $notitlealt No title alt
  8380. * @return string HTML img string with flag.
  8381. */
  8382. function picto_from_langcode($codelang, $moreatt = '', $notitlealt = 0)
  8383. {
  8384. if (empty($codelang)) {
  8385. return '';
  8386. }
  8387. if ($codelang == 'auto') {
  8388. return '<span class="fa fa-language"></span>';
  8389. }
  8390. $langtocountryflag = array(
  8391. 'ar_AR' => '',
  8392. 'ca_ES' => 'catalonia',
  8393. 'da_DA' => 'dk',
  8394. 'fr_CA' => 'mq',
  8395. 'sv_SV' => 'se',
  8396. 'sw_SW' => 'unknown',
  8397. 'AQ' => 'unknown',
  8398. 'CW' => 'unknown',
  8399. 'IM' => 'unknown',
  8400. 'JE' => 'unknown',
  8401. 'MF' => 'unknown',
  8402. 'BL' => 'unknown',
  8403. 'SX' => 'unknown'
  8404. );
  8405. if (isset($langtocountryflag[$codelang])) {
  8406. $flagImage = $langtocountryflag[$codelang];
  8407. } else {
  8408. $tmparray = explode('_', $codelang);
  8409. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  8410. }
  8411. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt, 0, $notitlealt);
  8412. }
  8413. /**
  8414. * Return default language from country code.
  8415. * Return null if not found.
  8416. *
  8417. * @param string $countrycode Country code like 'US', 'FR', 'CA', 'ES', 'IN', 'MX', ...
  8418. * @return string Value of locale like 'en_US', 'fr_FR', ... or null if not found
  8419. */
  8420. function getLanguageCodeFromCountryCode($countrycode)
  8421. {
  8422. global $mysoc;
  8423. if (empty($countrycode)) {
  8424. return null;
  8425. }
  8426. if (strtoupper($countrycode) == 'MQ') {
  8427. return 'fr_CA';
  8428. }
  8429. if (strtoupper($countrycode) == 'SE') {
  8430. return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  8431. }
  8432. if (strtoupper($countrycode) == 'CH') {
  8433. if ($mysoc->country_code == 'FR') {
  8434. return 'fr_CH';
  8435. }
  8436. if ($mysoc->country_code == 'DE') {
  8437. return 'de_CH';
  8438. }
  8439. if ($mysoc->country_code == 'IT') {
  8440. return 'it_CH';
  8441. }
  8442. }
  8443. // Locale list taken from:
  8444. // http://stackoverflow.com/questions/3191664/
  8445. // list-of-all-locales-and-their-short-codes
  8446. $locales = array(
  8447. 'af-ZA',
  8448. 'am-ET',
  8449. 'ar-AE',
  8450. 'ar-BH',
  8451. 'ar-DZ',
  8452. 'ar-EG',
  8453. 'ar-IQ',
  8454. 'ar-JO',
  8455. 'ar-KW',
  8456. 'ar-LB',
  8457. 'ar-LY',
  8458. 'ar-MA',
  8459. 'ar-OM',
  8460. 'ar-QA',
  8461. 'ar-SA',
  8462. 'ar-SY',
  8463. 'ar-TN',
  8464. 'ar-YE',
  8465. //'as-IN', // Moved after en-IN
  8466. 'ba-RU',
  8467. 'be-BY',
  8468. 'bg-BG',
  8469. 'bn-BD',
  8470. //'bn-IN', // Moved after en-IN
  8471. 'bo-CN',
  8472. 'br-FR',
  8473. 'ca-ES',
  8474. 'co-FR',
  8475. 'cs-CZ',
  8476. 'cy-GB',
  8477. 'da-DK',
  8478. 'de-AT',
  8479. 'de-CH',
  8480. 'de-DE',
  8481. 'de-LI',
  8482. 'de-LU',
  8483. 'dv-MV',
  8484. 'el-GR',
  8485. 'en-AU',
  8486. 'en-BZ',
  8487. 'en-CA',
  8488. 'en-GB',
  8489. 'en-IE',
  8490. 'en-IN',
  8491. 'as-IN', // as-IN must be after en-IN (en in priority if country is IN)
  8492. 'bn-IN', // bn-IN must be after en-IN (en in priority if country is IN)
  8493. 'en-JM',
  8494. 'en-MY',
  8495. 'en-NZ',
  8496. 'en-PH',
  8497. 'en-SG',
  8498. 'en-TT',
  8499. 'en-US',
  8500. 'en-ZA',
  8501. 'en-ZW',
  8502. 'es-AR',
  8503. 'es-BO',
  8504. 'es-CL',
  8505. 'es-CO',
  8506. 'es-CR',
  8507. 'es-DO',
  8508. 'es-EC',
  8509. 'es-ES',
  8510. 'es-GT',
  8511. 'es-HN',
  8512. 'es-MX',
  8513. 'es-NI',
  8514. 'es-PA',
  8515. 'es-PE',
  8516. 'es-PR',
  8517. 'es-PY',
  8518. 'es-SV',
  8519. 'es-US',
  8520. 'es-UY',
  8521. 'es-VE',
  8522. 'et-EE',
  8523. 'eu-ES',
  8524. 'fa-IR',
  8525. 'fi-FI',
  8526. 'fo-FO',
  8527. 'fr-BE',
  8528. 'fr-CA',
  8529. 'fr-CH',
  8530. 'fr-FR',
  8531. 'fr-LU',
  8532. 'fr-MC',
  8533. 'fy-NL',
  8534. 'ga-IE',
  8535. 'gd-GB',
  8536. 'gl-ES',
  8537. 'gu-IN',
  8538. 'he-IL',
  8539. 'hi-IN',
  8540. 'hr-BA',
  8541. 'hr-HR',
  8542. 'hu-HU',
  8543. 'hy-AM',
  8544. 'id-ID',
  8545. 'ig-NG',
  8546. 'ii-CN',
  8547. 'is-IS',
  8548. 'it-CH',
  8549. 'it-IT',
  8550. 'ja-JP',
  8551. 'ka-GE',
  8552. 'kk-KZ',
  8553. 'kl-GL',
  8554. 'km-KH',
  8555. 'kn-IN',
  8556. 'ko-KR',
  8557. 'ky-KG',
  8558. 'lb-LU',
  8559. 'lo-LA',
  8560. 'lt-LT',
  8561. 'lv-LV',
  8562. 'mi-NZ',
  8563. 'mk-MK',
  8564. 'ml-IN',
  8565. 'mn-MN',
  8566. 'mr-IN',
  8567. 'ms-BN',
  8568. 'ms-MY',
  8569. 'mt-MT',
  8570. 'nb-NO',
  8571. 'ne-NP',
  8572. 'nl-BE',
  8573. 'nl-NL',
  8574. 'nn-NO',
  8575. 'oc-FR',
  8576. 'or-IN',
  8577. 'pa-IN',
  8578. 'pl-PL',
  8579. 'ps-AF',
  8580. 'pt-BR',
  8581. 'pt-PT',
  8582. 'rm-CH',
  8583. 'ro-MD',
  8584. 'ro-RO',
  8585. 'ru-RU',
  8586. 'rw-RW',
  8587. 'sa-IN',
  8588. 'se-FI',
  8589. 'se-NO',
  8590. 'se-SE',
  8591. 'si-LK',
  8592. 'sk-SK',
  8593. 'sl-SI',
  8594. 'sq-AL',
  8595. 'sv-FI',
  8596. 'sv-SE',
  8597. 'sw-KE',
  8598. 'ta-IN',
  8599. 'te-IN',
  8600. 'th-TH',
  8601. 'tk-TM',
  8602. 'tn-ZA',
  8603. 'tr-TR',
  8604. 'tt-RU',
  8605. 'ug-CN',
  8606. 'uk-UA',
  8607. 'ur-PK',
  8608. 'vi-VN',
  8609. 'wo-SN',
  8610. 'xh-ZA',
  8611. 'yo-NG',
  8612. 'zh-CN',
  8613. 'zh-HK',
  8614. 'zh-MO',
  8615. 'zh-SG',
  8616. 'zh-TW',
  8617. 'zu-ZA',
  8618. );
  8619. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  8620. if (in_array($buildprimarykeytotest, $locales)) {
  8621. return strtolower($countrycode).'_'.strtoupper($countrycode);
  8622. }
  8623. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) { // Need extension php-intl
  8624. foreach ($locales as $locale) {
  8625. $locale_language = locale_get_primary_language($locale);
  8626. $locale_region = locale_get_region($locale);
  8627. if (strtoupper($countrycode) == $locale_region) {
  8628. //var_dump($locale.' - '.$locale_language.' - '.$locale_region);
  8629. return strtolower($locale_language).'_'.strtoupper($locale_region);
  8630. }
  8631. }
  8632. } else {
  8633. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  8634. }
  8635. return null;
  8636. }
  8637. /**
  8638. * Complete or removed entries into a head array (used to build tabs).
  8639. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  8640. * Or by change using hook completeTabsHead
  8641. *
  8642. * @param Conf $conf Object conf
  8643. * @param Translate $langs Object langs
  8644. * @param object|null $object Object object
  8645. * @param array $head Object head
  8646. * @param int $h New position to fill
  8647. * @param string $type Value for object where objectvalue can be
  8648. * 'thirdparty' to add a tab in third party view
  8649. * 'intervention' to add a tab in intervention view
  8650. * 'supplier_order' to add a tab in purchase order view
  8651. * 'supplier_invoice' to add a tab in purchase invoice view
  8652. * 'invoice' to add a tab in sales invoice view
  8653. * 'order' to add a tab in sales order view
  8654. * 'contract' to add a tabl in contract view
  8655. * 'product' to add a tab in product view
  8656. * 'propal' to add a tab in propal view
  8657. * 'user' to add a tab in user view
  8658. * 'group' to add a tab in group view
  8659. * 'member' to add a tab in fundation member view
  8660. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  8661. * 'ecm' to add a tab for another ecm view
  8662. * 'stock' to add a tab for warehouse view
  8663. * @param string $mode 'add' to complete head, 'remove' to remove entries
  8664. * @param string $filterorigmodule Filter on module origin: 'external' will show only external modules. 'core' only core modules. No filter (default) will add both.
  8665. * @return void
  8666. */
  8667. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add', $filterorigmodule = '')
  8668. {
  8669. global $hookmanager, $db;
  8670. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type])) {
  8671. foreach ($conf->modules_parts['tabs'][$type] as $value) {
  8672. $values = explode(':', $value);
  8673. $reg = array();
  8674. if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
  8675. if (count($values) == 6) {
  8676. // new declaration with permissions:
  8677. // $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8678. // $value='objecttype:+tabname1:Title1,class,pathfile,method:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  8679. if ($values[0] != $type) {
  8680. continue;
  8681. }
  8682. if (verifCond($values[4])) {
  8683. if ($values[3]) {
  8684. if ($filterorigmodule) { // If a filter of module origin has been requested
  8685. if (strpos($values[3], '@')) { // This is an external module
  8686. if ($filterorigmodule != 'external') {
  8687. continue;
  8688. }
  8689. } else { // This looks a core module
  8690. if ($filterorigmodule != 'core') {
  8691. continue;
  8692. }
  8693. }
  8694. }
  8695. $langs->load($values[3]);
  8696. }
  8697. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8698. // If label is "SUBSTITUION_..."
  8699. $substitutionarray = array();
  8700. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8701. $label = make_substitutions($reg[1], $substitutionarray);
  8702. } else {
  8703. // If label is "Label,Class,File,Method", we call the method to show content inside the badge
  8704. $labeltemp = explode(',', $values[2]);
  8705. $label = $langs->trans($labeltemp[0]);
  8706. if (!empty($labeltemp[1]) && is_object($object) && !empty($object->id)) {
  8707. dol_include_once($labeltemp[2]);
  8708. $classtoload = $labeltemp[1];
  8709. if (class_exists($classtoload)) {
  8710. $obj = new $classtoload($db);
  8711. $function = $labeltemp[3];
  8712. if ($obj && $function && method_exists($obj, $function)) {
  8713. $nbrec = $obj->$function($object->id, $obj);
  8714. $label .= '<span class="badge marginleftonlyshort">'.$nbrec.'</span>';
  8715. }
  8716. }
  8717. }
  8718. }
  8719. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  8720. $head[$h][1] = $label;
  8721. $head[$h][2] = str_replace('+', '', $values[1]);
  8722. $h++;
  8723. }
  8724. } elseif (count($values) == 5) { // case deprecated
  8725. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  8726. if ($values[0] != $type) {
  8727. continue;
  8728. }
  8729. if ($values[3]) {
  8730. if ($filterorigmodule) { // If a filter of module origin has been requested
  8731. if (strpos($values[3], '@')) { // This is an external module
  8732. if ($filterorigmodule != 'external') {
  8733. continue;
  8734. }
  8735. } else { // This looks a core module
  8736. if ($filterorigmodule != 'core') {
  8737. continue;
  8738. }
  8739. }
  8740. }
  8741. $langs->load($values[3]);
  8742. }
  8743. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
  8744. $substitutionarray = array();
  8745. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  8746. $label = make_substitutions($reg[1], $substitutionarray);
  8747. } else {
  8748. $label = $langs->trans($values[2]);
  8749. }
  8750. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  8751. $head[$h][1] = $label;
  8752. $head[$h][2] = str_replace('+', '', $values[1]);
  8753. $h++;
  8754. }
  8755. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
  8756. if ($values[0] != $type) {
  8757. continue;
  8758. }
  8759. $tabname = str_replace('-', '', $values[1]);
  8760. foreach ($head as $key => $val) {
  8761. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  8762. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  8763. if ($head[$key][2] == $tabname && $condition) {
  8764. unset($head[$key]);
  8765. break;
  8766. }
  8767. }
  8768. }
  8769. }
  8770. }
  8771. // No need to make a return $head. Var is modified as a reference
  8772. if (!empty($hookmanager)) {
  8773. $parameters = array('object' => $object, 'mode' => $mode, 'head' => &$head, 'filterorigmodule' => $filterorigmodule);
  8774. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  8775. if ($reshook > 0) { // Hook ask to replace completely the array
  8776. $head = $hookmanager->resArray;
  8777. } else { // Hook
  8778. $head = array_merge($head, $hookmanager->resArray);
  8779. }
  8780. $h = count($head);
  8781. }
  8782. }
  8783. /**
  8784. * Print common footer :
  8785. * conf->global->MAIN_HTML_FOOTER
  8786. * js for switch of menu hider
  8787. * js for conf->global->MAIN_GOOGLE_AN_ID
  8788. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  8789. * js for conf->logbuffer
  8790. *
  8791. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  8792. * @return void
  8793. */
  8794. function printCommonFooter($zone = 'private')
  8795. {
  8796. global $conf, $hookmanager, $user, $debugbar;
  8797. global $action;
  8798. global $micro_start_time;
  8799. if ($zone == 'private') {
  8800. print "\n".'<!-- Common footer for private page -->'."\n";
  8801. } else {
  8802. print "\n".'<!-- Common footer for public page -->'."\n";
  8803. }
  8804. // A div to store page_y POST parameter so we can read it using javascript
  8805. print "\n<!-- A div to store page_y POST parameter -->\n";
  8806. print '<div id="page_y" style="display: none;">'.(GETPOST('page_y') ? GETPOST('page_y') : '').'</div>'."\n";
  8807. $parameters = array();
  8808. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  8809. if (empty($reshook)) {
  8810. if (!empty($conf->global->MAIN_HTML_FOOTER)) {
  8811. print $conf->global->MAIN_HTML_FOOTER."\n";
  8812. }
  8813. print "\n";
  8814. if (!empty($conf->use_javascript_ajax)) {
  8815. print "\n<!-- A script section to add menuhider handler on backoffice, manage focus and madatory fields, tuning info, ... -->\n";
  8816. print '<script>'."\n";
  8817. print 'jQuery(document).ready(function() {'."\n";
  8818. if ($zone == 'private' && empty($conf->dol_use_jmobile)) {
  8819. print "\n";
  8820. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  8821. print 'jQuery("li.menuhider").click(function(event) {';
  8822. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  8823. print ' console.log("We click on .menuhider");'."\n";
  8824. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  8825. print '});'."\n";
  8826. }
  8827. // Management of focus and mandatory for fields
  8828. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))) || ((empty($action) || $action == 'addline') && (preg_match('/card\.php/', $_SERVER["PHP_SELF"])))) {
  8829. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  8830. $relativepathstring = $_SERVER["PHP_SELF"];
  8831. // Clean $relativepathstring
  8832. if (constant('DOL_URL_ROOT')) {
  8833. $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  8834. }
  8835. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  8836. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  8837. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  8838. if (!empty($user->default_values[$relativepathstring]['focus'])) {
  8839. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval) {
  8840. $qualified = 0;
  8841. if ($defkey != '_noquery_') {
  8842. $tmpqueryarraytohave = explode('&', $defkey);
  8843. $foundintru = 0;
  8844. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8845. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8846. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8847. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8848. $foundintru = 1;
  8849. }
  8850. }
  8851. if (!$foundintru) {
  8852. $qualified = 1;
  8853. }
  8854. //var_dump($defkey.'-'.$qualified);
  8855. } else {
  8856. $qualified = 1;
  8857. }
  8858. if ($qualified) {
  8859. foreach ($defval as $paramkey => $paramval) {
  8860. // Set focus on field
  8861. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  8862. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  8863. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  8864. }
  8865. }
  8866. }
  8867. }
  8868. if (!empty($user->default_values[$relativepathstring]['mandatory'])) {
  8869. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval) {
  8870. $qualified = 0;
  8871. if ($defkey != '_noquery_') {
  8872. $tmpqueryarraytohave = explode('&', $defkey);
  8873. $foundintru = 0;
  8874. foreach ($tmpqueryarraytohave as $tmpquerytohave) {
  8875. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  8876. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  8877. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) {
  8878. $foundintru = 1;
  8879. }
  8880. }
  8881. if (!$foundintru) {
  8882. $qualified = 1;
  8883. }
  8884. //var_dump($defkey.'-'.$qualified);
  8885. } else {
  8886. $qualified = 1;
  8887. }
  8888. if ($qualified) {
  8889. foreach ($defval as $paramkey => $paramval) {
  8890. // Add property 'required' on input
  8891. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8892. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8893. 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";
  8894. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  8895. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'-1\']").prop(\'value\', \'\');'."\n";
  8896. print 'jQuery("select[name=\''.$paramkey.'\'] option[value=\'0\']").prop(\'value\', \'\');'."\n";
  8897. // Add 'field required' class on closest td for all input elements : input, textarea and select
  8898. print 'jQuery(":input[name=\'' . $paramkey . '\']").closest("tr").find("td:first").addClass("fieldrequired");' . "\n";
  8899. }
  8900. }
  8901. }
  8902. }
  8903. }
  8904. print '});'."\n";
  8905. // End of tuning
  8906. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO)) {
  8907. print "\n";
  8908. print "/* JS CODE TO ENABLE to add memory info */\n";
  8909. print 'window.console && console.log("';
  8910. if (!empty($conf->global->MEMCACHED_SERVER)) {
  8911. print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  8912. }
  8913. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  8914. if (!empty($micro_start_time)) { // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  8915. $micro_end_time = microtime(true);
  8916. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  8917. }
  8918. if (function_exists("memory_get_usage")) {
  8919. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  8920. }
  8921. if (function_exists("memory_get_peak_usage")) {
  8922. print ' - Real mem peak: '.memory_get_peak_usage(true);
  8923. }
  8924. if (function_exists("zend_loader_file_encoded")) {
  8925. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  8926. }
  8927. print '");'."\n";
  8928. }
  8929. print "\n".'</script>'."\n";
  8930. // Google Analytics
  8931. // TODO Add a hook here
  8932. if (isModEnabled('google') && !empty($conf->global->MAIN_GOOGLE_AN_ID)) {
  8933. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  8934. foreach ($tmptagarray as $tmptag) {
  8935. print "\n";
  8936. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  8937. print '
  8938. <!-- Global site tag (gtag.js) - Google Analytics -->
  8939. <script nonce="'.getNonce().'" async src="https://www.googletagmanager.com/gtag/js?id='.trim($tmptag).'"></script>
  8940. <script>
  8941. window.dataLayer = window.dataLayer || [];
  8942. function gtag(){dataLayer.push(arguments);}
  8943. gtag(\'js\', new Date());
  8944. gtag(\'config\', \''.trim($tmptag).'\');
  8945. </script>';
  8946. print "\n";
  8947. }
  8948. }
  8949. }
  8950. // Add Xdebug coverage of code
  8951. if (defined('XDEBUGCOVERAGE')) {
  8952. print_r(xdebug_get_code_coverage());
  8953. }
  8954. // Add DebugBar data
  8955. if (!empty($user->rights->debugbar->read) && is_object($debugbar)) {
  8956. $debugbar['time']->stopMeasure('pageaftermaster');
  8957. print '<!-- Output debugbar data -->'."\n";
  8958. $renderer = $debugbar->getRenderer();
  8959. print $debugbar->getRenderer()->render();
  8960. } elseif (count($conf->logbuffer)) { // If there is some logs in buffer to show
  8961. print "\n";
  8962. print "<!-- Start of log output\n";
  8963. //print '<div class="hidden">'."\n";
  8964. foreach ($conf->logbuffer as $logline) {
  8965. print $logline."<br>\n";
  8966. }
  8967. //print '</div>'."\n";
  8968. print "End of log output -->\n";
  8969. }
  8970. }
  8971. }
  8972. /**
  8973. * Split a string with 2 keys into key array.
  8974. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  8975. *
  8976. * @param string $string String to explode
  8977. * @param string $delimiter Delimiter between each couple of data. Example: ';' or '[\n;]+' or '(\n\r|\r|\n|;)'
  8978. * @param string $kv Delimiter between key and value
  8979. * @return array Array of data exploded
  8980. */
  8981. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  8982. {
  8983. if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\(.*\)$/sm', $delimiter)) {
  8984. // This is a regex string
  8985. $newdelimiter = $delimiter;
  8986. } else {
  8987. // This is a simple string
  8988. $newdelimiter = preg_quote($delimiter, '/');
  8989. }
  8990. if ($a = preg_split('/'.$newdelimiter.'/', $string)) {
  8991. $ka = array();
  8992. foreach ($a as $s) { // each part
  8993. if ($s) {
  8994. if ($pos = strpos($s, $kv)) { // key/value delimiter
  8995. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  8996. } else { // key delimiter not found
  8997. $ka[] = trim($s);
  8998. }
  8999. }
  9000. }
  9001. return $ka;
  9002. }
  9003. return array();
  9004. }
  9005. /**
  9006. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  9007. *
  9008. * @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.
  9009. * @return void
  9010. */
  9011. function dol_set_focus($selector)
  9012. {
  9013. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  9014. print '<script nonce="'.getNonce().'">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  9015. }
  9016. /**
  9017. * Return getmypid() or random PID when function is disabled
  9018. * Some web hosts disable this php function for security reasons
  9019. * and sometimes we can't redeclare function.
  9020. *
  9021. * @return int
  9022. */
  9023. function dol_getmypid()
  9024. {
  9025. if (!function_exists('getmypid')) {
  9026. return mt_rand(99900000, 99965535);
  9027. } else {
  9028. return getmypid(); // May be a number on 64 bits (depending on OS)
  9029. }
  9030. }
  9031. /**
  9032. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  9033. *
  9034. * @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")
  9035. * @param string $value The value to look for.
  9036. * If param $mode is 0, can contains several keywords separated with a space or |
  9037. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  9038. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  9039. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < -1000"
  9040. * If param $mode is 2 or -2, can contains a list of int id separated by comma like "1,3,4"
  9041. * If param $mode is 3 or -3, can contains a list of string separated by comma like "a,b,c".
  9042. * @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'), -2 is for exclude list,
  9043. * 3=value is list of string separated with comma (Example 'text 1,text 2'), -3 if for exclude list, 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'
  9044. * @param integer $nofirstand 1=Do not output the first 'AND'
  9045. * @return string $res The statement to append to the SQL query
  9046. * @see dolSqlDateFilter()
  9047. */
  9048. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  9049. {
  9050. global $db, $langs;
  9051. $value = trim($value);
  9052. if ($mode == 0) {
  9053. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  9054. }
  9055. if ($mode == 1) {
  9056. $value = preg_replace('/([!<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can then explode on space to get all tests to do
  9057. }
  9058. $value = preg_replace('/\s*\|\s*/', '|', $value);
  9059. $crits = explode(' ', $value);
  9060. $res = '';
  9061. if (!is_array($fields)) {
  9062. $fields = array($fields);
  9063. }
  9064. $i1 = 0; // count the nb of and criteria added (all fields / criterias)
  9065. foreach ($crits as $crit) { // Loop on each AND criteria
  9066. $crit = trim($crit);
  9067. $i2 = 0; // count the nb of valid criteria added for this this first criteria
  9068. $newres = '';
  9069. foreach ($fields as $field) {
  9070. if ($mode == 1) {
  9071. $tmpcrits = explode('|', $crit);
  9072. $i3 = 0; // count the nb of valid criteria added for this current field
  9073. foreach ($tmpcrits as $tmpcrit) {
  9074. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9075. continue;
  9076. }
  9077. $tmpcrit = trim($tmpcrit);
  9078. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9079. $operator = '=';
  9080. $newcrit = preg_replace('/([!<>=]+)/', '', $tmpcrit);
  9081. $reg = array();
  9082. preg_match('/([!<>=]+)/', $tmpcrit, $reg);
  9083. if (!empty($reg[1])) {
  9084. $operator = $reg[1];
  9085. }
  9086. if ($newcrit != '') {
  9087. $numnewcrit = price2num($newcrit);
  9088. if (is_numeric($numnewcrit)) {
  9089. $newres .= $field.' '.$operator.' '.((float) $numnewcrit); // should be a numeric
  9090. } else {
  9091. $newres .= '1 = 2'; // force false, we received a corrupted data
  9092. }
  9093. $i3++; // a criteria was added to string
  9094. }
  9095. }
  9096. $i2++; // a criteria for 1 more field was added to string
  9097. } elseif ($mode == 2 || $mode == -2) {
  9098. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  9099. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  9100. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  9101. if ($mode == -2) {
  9102. $newres .= ' OR '.$field.' IS NULL';
  9103. }
  9104. $i2++; // a criteria for 1 more field was added to string
  9105. } elseif ($mode == 3 || $mode == -3) {
  9106. $tmparray = explode(',', $crit);
  9107. if (count($tmparray)) {
  9108. $listofcodes = '';
  9109. foreach ($tmparray as $val) {
  9110. $val = trim($val);
  9111. if ($val) {
  9112. $listofcodes .= ($listofcodes ? ',' : '');
  9113. $listofcodes .= "'".$db->escape($val)."'";
  9114. }
  9115. }
  9116. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  9117. $i2++; // a criteria for 1 more field was added to string
  9118. }
  9119. if ($mode == -3) {
  9120. $newres .= ' OR '.$field.' IS NULL';
  9121. }
  9122. } elseif ($mode == 4) {
  9123. $tmparray = explode(',', $crit);
  9124. if (count($tmparray)) {
  9125. $listofcodes = '';
  9126. foreach ($tmparray as $val) {
  9127. $val = trim($val);
  9128. if ($val) {
  9129. $newres .= ($i2 > 0 ? " OR (" : "(").$field." LIKE '".$db->escape($val).",%'";
  9130. $newres .= ' OR '.$field." = '".$db->escape($val)."'";
  9131. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val)."'";
  9132. $newres .= ' OR '.$field." LIKE '%,".$db->escape($val).",%'";
  9133. $newres .= ')';
  9134. $i2++; // a criteria for 1 more field was added to string (we can add several citeria for the same field as it is a multiselect search criteria)
  9135. }
  9136. }
  9137. }
  9138. } else { // $mode=0
  9139. $tmpcrits = explode('|', $crit);
  9140. $i3 = 0; // count the nb of valid criteria added for the current couple criteria/field
  9141. foreach ($tmpcrits as $tmpcrit) { // loop on each OR criteria
  9142. if ($tmpcrit !== '0' && empty($tmpcrit)) {
  9143. continue;
  9144. }
  9145. $tmpcrit = trim($tmpcrit);
  9146. if ($tmpcrit == '^$' || strpos($crit, '!') === 0) { // If we search empty, we must combined different OR fields with AND
  9147. $newres .= (($i2 > 0 || $i3 > 0) ? ' AND ' : '');
  9148. } else {
  9149. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  9150. }
  9151. if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
  9152. $newres .= $field." = ".(is_numeric($tmpcrit) ? ((float) $tmpcrit) : '0');
  9153. } else {
  9154. $tmpcrit2 = $tmpcrit;
  9155. $tmpbefore = '%';
  9156. $tmpafter = '%';
  9157. $tmps = '';
  9158. if (preg_match('/^!/', $tmpcrit)) {
  9159. $tmps .= $field." NOT LIKE "; // ! as exclude character
  9160. $tmpcrit2 = preg_replace('/^!/', '', $tmpcrit2);
  9161. } else {
  9162. $tmps .= $field." LIKE ";
  9163. }
  9164. $tmps .= "'";
  9165. if (preg_match('/^[\^\$]/', $tmpcrit)) {
  9166. $tmpbefore = '';
  9167. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  9168. }
  9169. if (preg_match('/[\^\$]$/', $tmpcrit)) {
  9170. $tmpafter = '';
  9171. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  9172. }
  9173. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9174. $tmps = "(".$tmps;
  9175. }
  9176. $newres .= $tmps;
  9177. $newres .= $tmpbefore;
  9178. $newres .= $db->escape($tmpcrit2);
  9179. $newres .= $tmpafter;
  9180. $newres .= "'";
  9181. if ($tmpcrit2 == '' || preg_match('/^!/', $tmpcrit)) {
  9182. $newres .= " OR ".$field." IS NULL)";
  9183. }
  9184. }
  9185. $i3++;
  9186. }
  9187. $i2++; // a criteria for 1 more field was added to string
  9188. }
  9189. }
  9190. if ($newres) {
  9191. $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  9192. }
  9193. $i1++;
  9194. }
  9195. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  9196. return $res;
  9197. }
  9198. /**
  9199. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  9200. *
  9201. * @param Object $object Object
  9202. * @return string Url string
  9203. */
  9204. function showDirectDownloadLink($object)
  9205. {
  9206. global $conf, $langs;
  9207. $out = '';
  9208. $url = $object->getLastMainDocLink($object->element);
  9209. $out .= img_picto($langs->trans("PublicDownloadLinkDesc"), 'globe').' <span class="opacitymedium">'.$langs->trans("DirectDownloadLink").'</span><br>';
  9210. if ($url) {
  9211. $out .= '<div class="urllink"><input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'"></div>';
  9212. $out .= ajax_autoselect("directdownloadlink", 0);
  9213. } else {
  9214. $out .= '<div class="urllink">'.$langs->trans("FileNotShared").'</div>';
  9215. }
  9216. return $out;
  9217. }
  9218. /**
  9219. * Return the filename of file to get the thumbs
  9220. *
  9221. * @param string $file Original filename (full or relative path)
  9222. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  9223. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  9224. * @return string New file name (full or relative path, including the thumbs/). May be the original path if no thumb can exists.
  9225. */
  9226. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  9227. {
  9228. $dirName = dirname($file);
  9229. if ($dirName == '.') {
  9230. $dirName = '';
  9231. }
  9232. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  9233. $fileName = basename($fileName);
  9234. if (empty($extImgTarget)) {
  9235. $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  9236. }
  9237. if (empty($extImgTarget)) {
  9238. $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  9239. }
  9240. if (empty($extImgTarget)) {
  9241. $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  9242. }
  9243. if (empty($extImgTarget)) {
  9244. $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  9245. }
  9246. if (empty($extImgTarget)) {
  9247. $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  9248. }
  9249. if (empty($extImgTarget)) {
  9250. $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  9251. }
  9252. if (!$extImgTarget) {
  9253. return $file;
  9254. }
  9255. $subdir = '';
  9256. if ($extName) {
  9257. $subdir = 'thumbs/';
  9258. }
  9259. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  9260. }
  9261. /**
  9262. * Return URL we can use for advanced preview links
  9263. *
  9264. * @param string $modulepart propal, facture, facture_fourn, ...
  9265. * @param string $relativepath Relative path of docs.
  9266. * @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)
  9267. * @param string $param More param on http links
  9268. * @return string|array Output string with href link or array with all components of link
  9269. */
  9270. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  9271. {
  9272. global $conf, $langs;
  9273. if (empty($conf->use_javascript_ajax)) {
  9274. return '';
  9275. }
  9276. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  9277. if ($alldata == 1) {
  9278. if ($isAllowedForPreview) {
  9279. 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));
  9280. } else {
  9281. return array();
  9282. }
  9283. }
  9284. // old behavior, return a string
  9285. if ($isAllowedForPreview) {
  9286. 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')).'\')';
  9287. } else {
  9288. return '';
  9289. }
  9290. }
  9291. /**
  9292. * Make content of an input box selected when we click into input field.
  9293. *
  9294. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  9295. * @param string $addlink Add a 'link to' after
  9296. * @param string $textonlink Text to show on link or 'image'
  9297. * @return string
  9298. */
  9299. function ajax_autoselect($htmlname, $addlink = '', $textonlink = 'Link')
  9300. {
  9301. global $langs;
  9302. $out = '<script nonce="'.getNonce().'">
  9303. jQuery(document).ready(function () {
  9304. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  9305. });
  9306. </script>';
  9307. if ($addlink) {
  9308. if ($textonlink === 'image') {
  9309. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.img_picto('', 'globe').'</a>';
  9310. } else {
  9311. $out .= ' <a href="'.$addlink.'" target="_blank" rel="noopener noreferrer">'.$langs->trans("Link").'</a>';
  9312. }
  9313. }
  9314. return $out;
  9315. }
  9316. /**
  9317. * Return if a file is qualified for preview
  9318. *
  9319. * @param string $file Filename we looking for information
  9320. * @return int 1 If allowed, 0 otherwise
  9321. * @see dol_mimetype(), image_format_supported() from images.lib.php
  9322. */
  9323. function dolIsAllowedForPreview($file)
  9324. {
  9325. global $conf;
  9326. // Check .noexe extension in filename
  9327. if (preg_match('/\.noexe$/i', $file)) {
  9328. return 0;
  9329. }
  9330. // Check mime types
  9331. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  9332. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) {
  9333. $mime_preview[] = 'svg+xml';
  9334. }
  9335. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  9336. //$mime_preview[]='archive';
  9337. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  9338. if ($num_mime !== false) {
  9339. return 1;
  9340. }
  9341. // By default, not allowed for preview
  9342. return 0;
  9343. }
  9344. /**
  9345. * Return MIME type of a file from its name with extension.
  9346. *
  9347. * @param string $file Filename we looking for MIME type
  9348. * @param string $default Default mime type if extension not found in known list
  9349. * @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
  9350. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  9351. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  9352. */
  9353. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  9354. {
  9355. $mime = $default;
  9356. $imgmime = 'other.png';
  9357. $famime = 'file-o';
  9358. $srclang = '';
  9359. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  9360. // Plain text files
  9361. if (preg_match('/\.txt$/i', $tmpfile)) {
  9362. $mime = 'text/plain';
  9363. $imgmime = 'text.png';
  9364. $famime = 'file-text-o';
  9365. }
  9366. if (preg_match('/\.rtx$/i', $tmpfile)) {
  9367. $mime = 'text/richtext';
  9368. $imgmime = 'text.png';
  9369. $famime = 'file-text-o';
  9370. }
  9371. if (preg_match('/\.csv$/i', $tmpfile)) {
  9372. $mime = 'text/csv';
  9373. $imgmime = 'text.png';
  9374. $famime = 'file-text-o';
  9375. }
  9376. if (preg_match('/\.tsv$/i', $tmpfile)) {
  9377. $mime = 'text/tab-separated-values';
  9378. $imgmime = 'text.png';
  9379. $famime = 'file-text-o';
  9380. }
  9381. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) {
  9382. $mime = 'text/plain';
  9383. $imgmime = 'text.png';
  9384. $famime = 'file-text-o';
  9385. }
  9386. if (preg_match('/\.ini$/i', $tmpfile)) {
  9387. $mime = 'text/plain';
  9388. $imgmime = 'text.png';
  9389. $srclang = 'ini';
  9390. $famime = 'file-text-o';
  9391. }
  9392. if (preg_match('/\.md$/i', $tmpfile)) {
  9393. $mime = 'text/plain';
  9394. $imgmime = 'text.png';
  9395. $srclang = 'md';
  9396. $famime = 'file-text-o';
  9397. }
  9398. if (preg_match('/\.css$/i', $tmpfile)) {
  9399. $mime = 'text/css';
  9400. $imgmime = 'css.png';
  9401. $srclang = 'css';
  9402. $famime = 'file-text-o';
  9403. }
  9404. if (preg_match('/\.lang$/i', $tmpfile)) {
  9405. $mime = 'text/plain';
  9406. $imgmime = 'text.png';
  9407. $srclang = 'lang';
  9408. $famime = 'file-text-o';
  9409. }
  9410. // Certificate files
  9411. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) {
  9412. $mime = 'text/plain';
  9413. $imgmime = 'text.png';
  9414. $famime = 'file-text-o';
  9415. }
  9416. // XML based (HTML/XML/XAML)
  9417. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) {
  9418. $mime = 'text/html';
  9419. $imgmime = 'html.png';
  9420. $srclang = 'html';
  9421. $famime = 'file-text-o';
  9422. }
  9423. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) {
  9424. $mime = 'text/xml';
  9425. $imgmime = 'other.png';
  9426. $srclang = 'xml';
  9427. $famime = 'file-text-o';
  9428. }
  9429. if (preg_match('/\.xaml$/i', $tmpfile)) {
  9430. $mime = 'text/xml';
  9431. $imgmime = 'other.png';
  9432. $srclang = 'xaml';
  9433. $famime = 'file-text-o';
  9434. }
  9435. // Languages
  9436. if (preg_match('/\.bas$/i', $tmpfile)) {
  9437. $mime = 'text/plain';
  9438. $imgmime = 'text.png';
  9439. $srclang = 'bas';
  9440. $famime = 'file-code-o';
  9441. }
  9442. if (preg_match('/\.(c)$/i', $tmpfile)) {
  9443. $mime = 'text/plain';
  9444. $imgmime = 'text.png';
  9445. $srclang = 'c';
  9446. $famime = 'file-code-o';
  9447. }
  9448. if (preg_match('/\.(cpp)$/i', $tmpfile)) {
  9449. $mime = 'text/plain';
  9450. $imgmime = 'text.png';
  9451. $srclang = 'cpp';
  9452. $famime = 'file-code-o';
  9453. }
  9454. if (preg_match('/\.cs$/i', $tmpfile)) {
  9455. $mime = 'text/plain';
  9456. $imgmime = 'text.png';
  9457. $srclang = 'cs';
  9458. $famime = 'file-code-o';
  9459. }
  9460. if (preg_match('/\.(h)$/i', $tmpfile)) {
  9461. $mime = 'text/plain';
  9462. $imgmime = 'text.png';
  9463. $srclang = 'h';
  9464. $famime = 'file-code-o';
  9465. }
  9466. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) {
  9467. $mime = 'text/plain';
  9468. $imgmime = 'text.png';
  9469. $srclang = 'java';
  9470. $famime = 'file-code-o';
  9471. }
  9472. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) {
  9473. $mime = 'text/plain';
  9474. $imgmime = 'php.png';
  9475. $srclang = 'php';
  9476. $famime = 'file-code-o';
  9477. }
  9478. if (preg_match('/\.phtml$/i', $tmpfile)) {
  9479. $mime = 'text/plain';
  9480. $imgmime = 'php.png';
  9481. $srclang = 'php';
  9482. $famime = 'file-code-o';
  9483. }
  9484. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) {
  9485. $mime = 'text/plain';
  9486. $imgmime = 'pl.png';
  9487. $srclang = 'perl';
  9488. $famime = 'file-code-o';
  9489. }
  9490. if (preg_match('/\.sql$/i', $tmpfile)) {
  9491. $mime = 'text/plain';
  9492. $imgmime = 'text.png';
  9493. $srclang = 'sql';
  9494. $famime = 'file-code-o';
  9495. }
  9496. if (preg_match('/\.js$/i', $tmpfile)) {
  9497. $mime = 'text/x-javascript';
  9498. $imgmime = 'jscript.png';
  9499. $srclang = 'js';
  9500. $famime = 'file-code-o';
  9501. }
  9502. // Open office
  9503. if (preg_match('/\.odp$/i', $tmpfile)) {
  9504. $mime = 'application/vnd.oasis.opendocument.presentation';
  9505. $imgmime = 'ooffice.png';
  9506. $famime = 'file-powerpoint-o';
  9507. }
  9508. if (preg_match('/\.ods$/i', $tmpfile)) {
  9509. $mime = 'application/vnd.oasis.opendocument.spreadsheet';
  9510. $imgmime = 'ooffice.png';
  9511. $famime = 'file-excel-o';
  9512. }
  9513. if (preg_match('/\.odt$/i', $tmpfile)) {
  9514. $mime = 'application/vnd.oasis.opendocument.text';
  9515. $imgmime = 'ooffice.png';
  9516. $famime = 'file-word-o';
  9517. }
  9518. // MS Office
  9519. if (preg_match('/\.mdb$/i', $tmpfile)) {
  9520. $mime = 'application/msaccess';
  9521. $imgmime = 'mdb.png';
  9522. $famime = 'file-o';
  9523. }
  9524. if (preg_match('/\.doc[xm]?$/i', $tmpfile)) {
  9525. $mime = 'application/msword';
  9526. $imgmime = 'doc.png';
  9527. $famime = 'file-word-o';
  9528. }
  9529. if (preg_match('/\.dot[xm]?$/i', $tmpfile)) {
  9530. $mime = 'application/msword';
  9531. $imgmime = 'doc.png';
  9532. $famime = 'file-word-o';
  9533. }
  9534. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) {
  9535. $mime = 'application/vnd.ms-excel';
  9536. $imgmime = 'xls.png';
  9537. $famime = 'file-excel-o';
  9538. }
  9539. if (preg_match('/\.xla(m)?$/i', $tmpfile)) {
  9540. $mime = 'application/vnd.ms-excel';
  9541. $imgmime = 'xls.png';
  9542. $famime = 'file-excel-o';
  9543. }
  9544. if (preg_match('/\.xls$/i', $tmpfile)) {
  9545. $mime = 'application/vnd.ms-excel';
  9546. $imgmime = 'xls.png';
  9547. $famime = 'file-excel-o';
  9548. }
  9549. if (preg_match('/\.xls[bmx]$/i', $tmpfile)) {
  9550. $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  9551. $imgmime = 'xls.png';
  9552. $famime = 'file-excel-o';
  9553. }
  9554. if (preg_match('/\.pps[mx]?$/i', $tmpfile)) {
  9555. $mime = 'application/vnd.ms-powerpoint';
  9556. $imgmime = 'ppt.png';
  9557. $famime = 'file-powerpoint-o';
  9558. }
  9559. if (preg_match('/\.ppt[mx]?$/i', $tmpfile)) {
  9560. $mime = 'application/x-mspowerpoint';
  9561. $imgmime = 'ppt.png';
  9562. $famime = 'file-powerpoint-o';
  9563. }
  9564. // Other
  9565. if (preg_match('/\.pdf$/i', $tmpfile)) {
  9566. $mime = 'application/pdf';
  9567. $imgmime = 'pdf.png';
  9568. $famime = 'file-pdf-o';
  9569. }
  9570. // Scripts
  9571. if (preg_match('/\.bat$/i', $tmpfile)) {
  9572. $mime = 'text/x-bat';
  9573. $imgmime = 'script.png';
  9574. $srclang = 'dos';
  9575. $famime = 'file-code-o';
  9576. }
  9577. if (preg_match('/\.sh$/i', $tmpfile)) {
  9578. $mime = 'text/x-sh';
  9579. $imgmime = 'script.png';
  9580. $srclang = 'bash';
  9581. $famime = 'file-code-o';
  9582. }
  9583. if (preg_match('/\.ksh$/i', $tmpfile)) {
  9584. $mime = 'text/x-ksh';
  9585. $imgmime = 'script.png';
  9586. $srclang = 'bash';
  9587. $famime = 'file-code-o';
  9588. }
  9589. if (preg_match('/\.bash$/i', $tmpfile)) {
  9590. $mime = 'text/x-bash';
  9591. $imgmime = 'script.png';
  9592. $srclang = 'bash';
  9593. $famime = 'file-code-o';
  9594. }
  9595. // Images
  9596. if (preg_match('/\.ico$/i', $tmpfile)) {
  9597. $mime = 'image/x-icon';
  9598. $imgmime = 'image.png';
  9599. $famime = 'file-image-o';
  9600. }
  9601. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) {
  9602. $mime = 'image/jpeg';
  9603. $imgmime = 'image.png';
  9604. $famime = 'file-image-o';
  9605. }
  9606. if (preg_match('/\.png$/i', $tmpfile)) {
  9607. $mime = 'image/png';
  9608. $imgmime = 'image.png';
  9609. $famime = 'file-image-o';
  9610. }
  9611. if (preg_match('/\.gif$/i', $tmpfile)) {
  9612. $mime = 'image/gif';
  9613. $imgmime = 'image.png';
  9614. $famime = 'file-image-o';
  9615. }
  9616. if (preg_match('/\.bmp$/i', $tmpfile)) {
  9617. $mime = 'image/bmp';
  9618. $imgmime = 'image.png';
  9619. $famime = 'file-image-o';
  9620. }
  9621. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) {
  9622. $mime = 'image/tiff';
  9623. $imgmime = 'image.png';
  9624. $famime = 'file-image-o';
  9625. }
  9626. if (preg_match('/\.svg$/i', $tmpfile)) {
  9627. $mime = 'image/svg+xml';
  9628. $imgmime = 'image.png';
  9629. $famime = 'file-image-o';
  9630. }
  9631. if (preg_match('/\.webp$/i', $tmpfile)) {
  9632. $mime = 'image/webp';
  9633. $imgmime = 'image.png';
  9634. $famime = 'file-image-o';
  9635. }
  9636. // Calendar
  9637. if (preg_match('/\.vcs$/i', $tmpfile)) {
  9638. $mime = 'text/calendar';
  9639. $imgmime = 'other.png';
  9640. $famime = 'file-text-o';
  9641. }
  9642. if (preg_match('/\.ics$/i', $tmpfile)) {
  9643. $mime = 'text/calendar';
  9644. $imgmime = 'other.png';
  9645. $famime = 'file-text-o';
  9646. }
  9647. // Other
  9648. if (preg_match('/\.torrent$/i', $tmpfile)) {
  9649. $mime = 'application/x-bittorrent';
  9650. $imgmime = 'other.png';
  9651. $famime = 'file-o';
  9652. }
  9653. // Audio
  9654. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) {
  9655. $mime = 'audio';
  9656. $imgmime = 'audio.png';
  9657. $famime = 'file-audio-o';
  9658. }
  9659. // Video
  9660. if (preg_match('/\.mp4$/i', $tmpfile)) {
  9661. $mime = 'video/mp4';
  9662. $imgmime = 'video.png';
  9663. $famime = 'file-video-o';
  9664. }
  9665. if (preg_match('/\.ogv$/i', $tmpfile)) {
  9666. $mime = 'video/ogg';
  9667. $imgmime = 'video.png';
  9668. $famime = 'file-video-o';
  9669. }
  9670. if (preg_match('/\.webm$/i', $tmpfile)) {
  9671. $mime = 'video/webm';
  9672. $imgmime = 'video.png';
  9673. $famime = 'file-video-o';
  9674. }
  9675. if (preg_match('/\.avi$/i', $tmpfile)) {
  9676. $mime = 'video/x-msvideo';
  9677. $imgmime = 'video.png';
  9678. $famime = 'file-video-o';
  9679. }
  9680. if (preg_match('/\.divx$/i', $tmpfile)) {
  9681. $mime = 'video/divx';
  9682. $imgmime = 'video.png';
  9683. $famime = 'file-video-o';
  9684. }
  9685. if (preg_match('/\.xvid$/i', $tmpfile)) {
  9686. $mime = 'video/xvid';
  9687. $imgmime = 'video.png';
  9688. $famime = 'file-video-o';
  9689. }
  9690. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) {
  9691. $mime = 'video';
  9692. $imgmime = 'video.png';
  9693. $famime = 'file-video-o';
  9694. }
  9695. // Archive
  9696. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh|zst)$/i', $tmpfile)) {
  9697. $mime = 'archive';
  9698. $imgmime = 'archive.png';
  9699. $famime = 'file-archive-o';
  9700. } // application/xxx where zzz is zip, ...
  9701. // Exe
  9702. if (preg_match('/\.(exe|com)$/i', $tmpfile)) {
  9703. $mime = 'application/octet-stream';
  9704. $imgmime = 'other.png';
  9705. $famime = 'file-o';
  9706. }
  9707. // Lib
  9708. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) {
  9709. $mime = 'library';
  9710. $imgmime = 'library.png';
  9711. $famime = 'file-o';
  9712. }
  9713. // Err
  9714. if (preg_match('/\.err$/i', $tmpfile)) {
  9715. $mime = 'error';
  9716. $imgmime = 'error.png';
  9717. $famime = 'file-text-o';
  9718. }
  9719. // Return string
  9720. if ($mode == 1) {
  9721. $tmp = explode('/', $mime);
  9722. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  9723. }
  9724. if ($mode == 2) {
  9725. return $imgmime;
  9726. }
  9727. if ($mode == 3) {
  9728. return $srclang;
  9729. }
  9730. if ($mode == 4) {
  9731. return $famime;
  9732. }
  9733. return $mime;
  9734. }
  9735. /**
  9736. * Return the value of a filed into a dictionary for the record $id.
  9737. * This also set all the values into a cache for a next search.
  9738. *
  9739. * @param string $tablename Name of table dictionary (without the MAIN_DB_PREFIX, example: 'c_holiday_types')
  9740. * @param string $field The name of field where to find the value to return
  9741. * @param int $id Id of line record
  9742. * @param bool $checkentity Add filter on entity
  9743. * @param string $rowidfield Name of the column rowid (to use for the filter on $id)
  9744. * @return string The value of field $field. This also set $dictvalues cache.
  9745. */
  9746. function getDictionaryValue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  9747. {
  9748. global $conf, $db;
  9749. $tablename = preg_replace('/^'.preg_quote(MAIN_DB_PREFIX, '/').'/', '', $tablename); // Clean name of table for backward compatibility.
  9750. $dictvalues = (isset($conf->cache['dictvalues_'.$tablename]) ? $conf->cache['dictvalues_'.$tablename] : null);
  9751. if (is_null($dictvalues)) {
  9752. $dictvalues = array();
  9753. $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
  9754. if ($checkentity) {
  9755. $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  9756. }
  9757. $resql = $db->query($sql);
  9758. if ($resql) {
  9759. while ($obj = $db->fetch_object($resql)) {
  9760. $dictvalues[$obj->{$rowidfield}] = $obj; // $obj is stdClass
  9761. }
  9762. } else {
  9763. dol_print_error($db);
  9764. }
  9765. $conf->cache['dictvalues_'.$tablename] = $dictvalues;
  9766. }
  9767. if (!empty($dictvalues[$id])) {
  9768. // Found
  9769. $tmp = $dictvalues[$id];
  9770. return (property_exists($tmp, $field) ? $tmp->$field : '');
  9771. } else {
  9772. // Not found
  9773. return '';
  9774. }
  9775. }
  9776. /**
  9777. * Return true if the color is light
  9778. *
  9779. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  9780. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  9781. */
  9782. function colorIsLight($stringcolor)
  9783. {
  9784. $stringcolor = str_replace('#', '', $stringcolor);
  9785. $res = -1;
  9786. if (!empty($stringcolor)) {
  9787. $res = 0;
  9788. $tmp = explode(',', $stringcolor);
  9789. if (count($tmp) > 1) { // This is a comma RGB ('255','255','255')
  9790. $r = $tmp[0];
  9791. $g = $tmp[1];
  9792. $b = $tmp[2];
  9793. } else {
  9794. $hexr = $stringcolor[0].$stringcolor[1];
  9795. $hexg = $stringcolor[2].$stringcolor[3];
  9796. $hexb = $stringcolor[4].$stringcolor[5];
  9797. $r = hexdec($hexr);
  9798. $g = hexdec($hexg);
  9799. $b = hexdec($hexb);
  9800. }
  9801. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  9802. if ($bright > 0.6) {
  9803. $res = 1;
  9804. }
  9805. }
  9806. return $res;
  9807. }
  9808. /**
  9809. * Function to test if an entry is enabled or not
  9810. *
  9811. * @param string $type_user 0=We test for internal user, 1=We test for external user
  9812. * @param array $menuentry Array for feature entry to test
  9813. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  9814. * @return int 0=Hide, 1=Show, 2=Show gray
  9815. */
  9816. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  9817. {
  9818. global $conf;
  9819. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  9820. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  9821. if (empty($menuentry['enabled'])) {
  9822. return 0; // Entry disabled by condition
  9823. }
  9824. if ($type_user && $menuentry['module']) {
  9825. $tmploops = explode('|', $menuentry['module']);
  9826. $found = 0;
  9827. foreach ($tmploops as $tmploop) {
  9828. if (in_array($tmploop, $listofmodulesforexternal)) {
  9829. $found++;
  9830. break;
  9831. }
  9832. }
  9833. if (!$found) {
  9834. return 0; // Entry is for menus all excluded to external users
  9835. }
  9836. }
  9837. if (!$menuentry['perms'] && $type_user) {
  9838. return 0; // No permissions and user is external
  9839. }
  9840. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
  9841. return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  9842. }
  9843. if (!$menuentry['perms']) {
  9844. return 2; // No permissions and user is external
  9845. }
  9846. return 1;
  9847. }
  9848. /**
  9849. * Round to next multiple.
  9850. *
  9851. * @param double $n Number to round up
  9852. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  9853. * @return integer Value rounded.
  9854. */
  9855. function roundUpToNextMultiple($n, $x = 5)
  9856. {
  9857. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  9858. }
  9859. /**
  9860. * Function dolGetBadge
  9861. *
  9862. * @param string $label label of badge no html : use in alt attribute for accessibility
  9863. * @param string $html optional : label of badge with html
  9864. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  9865. * @param string $mode default '' , 'pill', 'dot'
  9866. * @param string $url the url for link
  9867. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  9868. * @return string Html badge
  9869. */
  9870. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  9871. {
  9872. $attr = array(
  9873. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  9874. );
  9875. if (empty($html)) {
  9876. $html = $label;
  9877. }
  9878. if (!empty($url)) {
  9879. $attr['href'] = $url;
  9880. }
  9881. if ($mode === 'dot') {
  9882. $attr['class'] .= ' classfortooltip';
  9883. $attr['title'] = $html;
  9884. $attr['aria-label'] = $label;
  9885. $html = '';
  9886. }
  9887. // Override attr
  9888. if (!empty($params['attr']) && is_array($params['attr'])) {
  9889. foreach ($params['attr'] as $key => $value) {
  9890. if ($key == 'class') {
  9891. $attr['class'] .= ' '.$value;
  9892. } elseif ($key == 'classOverride') {
  9893. $attr['class'] = $value;
  9894. } else {
  9895. $attr[$key] = $value;
  9896. }
  9897. }
  9898. }
  9899. // TODO: add hook
  9900. // escape all attribute
  9901. $attr = array_map('dol_escape_htmltag', $attr);
  9902. $TCompiledAttr = array();
  9903. foreach ($attr as $key => $value) {
  9904. $TCompiledAttr[] = $key.'="'.$value.'"';
  9905. }
  9906. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  9907. $tag = !empty($url) ? 'a' : 'span';
  9908. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  9909. }
  9910. /**
  9911. * Output the badge of a status.
  9912. *
  9913. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  9914. * @param string $statusLabelShort Short label of badge no html
  9915. * @param string $html Optional : label of badge with html
  9916. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  9917. * @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
  9918. * @param string $url The url for link
  9919. * @param array $params Various params. Example: array('tooltip'=>'no|...', 'badgeParams'=>...)
  9920. * @return string Html status string
  9921. */
  9922. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  9923. {
  9924. global $conf;
  9925. $return = '';
  9926. $dolGetBadgeParams = array();
  9927. if (!empty($params['badgeParams'])) {
  9928. $dolGetBadgeParams = $params['badgeParams'];
  9929. }
  9930. // TODO : add a hook
  9931. if ($displayMode == 0) {
  9932. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  9933. } elseif ($displayMode == 1) {
  9934. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9935. } elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  9936. // Use status with images (for backward compatibility)
  9937. $return = '';
  9938. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  9939. $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>' : '');
  9940. // For small screen, we always use the short label instead of long label.
  9941. if (!empty($conf->dol_optimize_smallscreen)) {
  9942. if ($displayMode == 0) {
  9943. $displayMode = 1;
  9944. } elseif ($displayMode == 4) {
  9945. $displayMode = 2;
  9946. } elseif ($displayMode == 6) {
  9947. $displayMode = 5;
  9948. }
  9949. }
  9950. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  9951. $statusImg = array(
  9952. 'status0' => 'statut0',
  9953. 'status1' => 'statut1',
  9954. 'status2' => 'statut2',
  9955. 'status3' => 'statut3',
  9956. 'status4' => 'statut4',
  9957. 'status5' => 'statut5',
  9958. 'status6' => 'statut6',
  9959. 'status7' => 'statut7',
  9960. 'status8' => 'statut8',
  9961. 'status9' => 'statut9'
  9962. );
  9963. if (!empty($statusImg[$statusType])) {
  9964. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  9965. } else {
  9966. $htmlImg = img_picto($statusLabel, $statusType);
  9967. }
  9968. if ($displayMode === 2) {
  9969. $return = $htmlImg.' '.$htmlLabelShort;
  9970. } elseif ($displayMode === 3) {
  9971. $return = $htmlImg;
  9972. } elseif ($displayMode === 4) {
  9973. $return = $htmlImg.' '.$htmlLabel;
  9974. } elseif ($displayMode === 5) {
  9975. $return = $htmlLabelShort.' '.$htmlImg;
  9976. } else { // $displayMode >= 6
  9977. $return = $htmlLabel.' '.$htmlImg;
  9978. }
  9979. } elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  9980. // Use new badge
  9981. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  9982. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  9983. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : ($params['tooltip'] != 'no' ? $params['tooltip'] : '');
  9984. if ($displayMode == 3) {
  9985. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  9986. } elseif ($displayMode === 5) {
  9987. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  9988. } else {
  9989. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  9990. }
  9991. }
  9992. return $return;
  9993. }
  9994. /**
  9995. * Function dolGetButtonAction
  9996. *
  9997. * @param string $label Label or tooltip of button. Also used as tooltip in title attribute. Can be escaped HTML content or full simple text.
  9998. * @param string $text Optional : short label on button. Can be escaped HTML content or full simple text.
  9999. * @param string $actionType 'default', 'delete', 'danger', 'email', ...
  10000. * @param string|array $url Url for link or array of subbutton description
  10001. * @param string $id Attribute id of button
  10002. * @param int|boolean $userRight User action right
  10003. * // phpcs:disable
  10004. * @param array $params = [ // Various params for future : recommended rather than adding more function arguments
  10005. * 'attr' => [ // to add or override button attributes
  10006. * 'xxxxx' => '', // your xxxxx attribute you want
  10007. * 'class' => 'reposition', // to add more css class to the button class attribute
  10008. * 'classOverride' => '' // to replace class attribute of the button
  10009. * ],
  10010. * 'confirm' => [
  10011. * '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.
  10012. * 'title' => '', // Overide title of modal, if empty default title use "ConfirmBtnCommonTitle" lang key
  10013. * 'action-btn-label' => '', // Overide label of action button, if empty default label use "Confirm" lang key
  10014. * 'cancel-btn-label' => '', // Overide label of cancel button, if empty default label use "CloseDialog" lang key
  10015. * 'content' => '', // Overide text of content, if empty default content use "ConfirmBtnCommonContent" lang key
  10016. * 'modal' => true, // true|false to display dialog as a modal (with dark background)
  10017. * 'isDropDrown' => false, // true|false to display dialog as a dropdown (with dark background)
  10018. * ],
  10019. * ]
  10020. * // phpcs:enable
  10021. * @return string html button
  10022. */
  10023. function dolGetButtonAction($label, $text = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  10024. {
  10025. global $hookmanager, $action, $object, $langs;
  10026. // If $url is an array, we must build a dropdown button
  10027. if (is_array($url)) {
  10028. $out = '<div class="dropdown inline-block dropdown-holder">';
  10029. $out .= '<a style="margin-right: auto;" class="dropdown-toggle butAction" data-toggle="dropdown">'.$label.'</a>';
  10030. $out .= '<div class="dropdown-content">';
  10031. foreach ($url as $subbutton) {
  10032. if ($subbutton['enabled'] && $subbutton['perm']) {
  10033. if (!empty($subbutton['lang'])) {
  10034. $langs->load($subbutton['lang']);
  10035. }
  10036. $out .= dolGetButtonAction('', $langs->trans($subbutton['label']), 'default', DOL_URL_ROOT.$subbutton['url'].(empty($params['backtopage']) ? '' : '&amp;backtopage='.urlencode($params['backtopage'])), '', 1, array('isDropDown' => true));
  10037. }
  10038. }
  10039. $out .= "</div>";
  10040. $out .= "</div>";
  10041. return $out;
  10042. }
  10043. // If $url is a simple link
  10044. if (!empty($params['isDropdown']))
  10045. $class = "dropdown-item";
  10046. else {
  10047. $class = 'butAction';
  10048. if ($actionType == 'danger' || $actionType == 'delete') {
  10049. $class = 'butActionDelete';
  10050. if (!empty($url) && strpos($url, 'token=') === false) $url .= '&token='.newToken();
  10051. }
  10052. }
  10053. $attr = array(
  10054. 'class' => $class,
  10055. 'href' => empty($url) ? '' : $url,
  10056. 'title' => $label
  10057. );
  10058. if (empty($text)) {
  10059. $text = $label;
  10060. $attr['title'] = ''; // if html not set, leave label on title is redundant
  10061. } else {
  10062. $attr['title'] = $label;
  10063. $attr['aria-label'] = $label;
  10064. }
  10065. if (empty($userRight)) {
  10066. $attr['class'] = 'butActionRefused';
  10067. $attr['href'] = '';
  10068. $attr['title'] = (($label && $text && $label != $text) ? $label : $langs->trans('NotEnoughPermissions'));
  10069. }
  10070. if (!empty($id)) {
  10071. $attr['id'] = $id;
  10072. }
  10073. // Override attr
  10074. if (!empty($params['attr']) && is_array($params['attr'])) {
  10075. foreach ($params['attr'] as $key => $value) {
  10076. if ($key == 'class') {
  10077. $attr['class'] .= ' '.$value;
  10078. } elseif ($key == 'classOverride') {
  10079. $attr['class'] = $value;
  10080. } else {
  10081. $attr[$key] = $value;
  10082. }
  10083. }
  10084. }
  10085. // automatic add tooltip when title is detected
  10086. if (!empty($attr['title']) && !empty($attr['class']) && strpos($attr['class'], 'classfortooltip') === false) {
  10087. $attr['class'].= ' classfortooltip';
  10088. }
  10089. // Js Confirm button
  10090. if ($userRight && !empty($params['confirm'])) {
  10091. if (!is_array($params['confirm'])) {
  10092. $params['confirm'] = array();
  10093. }
  10094. if (empty($params['confirm']['url'])) {
  10095. $params['confirm']['url'] = $url . (strpos($url, '?') > 0 ? '&' : '?') . 'confirm=yes';
  10096. }
  10097. // for js desabled compatibility set $url as call to confirm action and $params['confirm']['url'] to confirmed action
  10098. $attr['data-confirm-url'] = $params['confirm']['url'];
  10099. $attr['data-confirm-title'] = !empty($params['confirm']['title']) ? $params['confirm']['title'] : $langs->trans('ConfirmBtnCommonTitle', $label);
  10100. $attr['data-confirm-content'] = !empty($params['confirm']['content']) ? $params['confirm']['content'] : $langs->trans('ConfirmBtnCommonContent', $label);
  10101. $attr['data-confirm-content'] = preg_replace("/\r|\n/", "", $attr['data-confirm-content']);
  10102. $attr['data-confirm-action-btn-label'] = !empty($params['confirm']['action-btn-label']) ? $params['confirm']['action-btn-label'] : $langs->trans('Confirm');
  10103. $attr['data-confirm-cancel-btn-label'] = !empty($params['confirm']['cancel-btn-label']) ? $params['confirm']['cancel-btn-label'] : $langs->trans('CloseDialog');
  10104. $attr['data-confirm-modal'] = !empty($params['confirm']['modal']) ? $params['confirm']['modal'] : true;
  10105. $attr['class'].= ' butActionConfirm';
  10106. }
  10107. if (isset($attr['href']) && empty($attr['href'])) {
  10108. unset($attr['href']);
  10109. }
  10110. // escape all attribute
  10111. $attr = array_map('dol_escape_htmltag', $attr);
  10112. $TCompiledAttr = array();
  10113. foreach ($attr as $key => $value) {
  10114. $TCompiledAttr[] = $key.'= "'.$value.'"';
  10115. }
  10116. $compiledAttributes = empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr);
  10117. $tag = !empty($attr['href']) ? 'a' : 'span';
  10118. $parameters = array(
  10119. 'TCompiledAttr' => $TCompiledAttr, // array
  10120. 'compiledAttributes' => $compiledAttributes, // string
  10121. 'attr' => $attr,
  10122. 'tag' => $tag,
  10123. 'label' => $label,
  10124. 'html' => $text,
  10125. 'actionType' => $actionType,
  10126. 'url' => $url,
  10127. 'id' => $id,
  10128. 'userRight' => $userRight,
  10129. 'params' => $params
  10130. );
  10131. $reshook = $hookmanager->executeHooks('dolGetButtonAction', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  10132. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  10133. if (empty($reshook)) {
  10134. if (dol_textishtml($text)) { // If content already HTML encoded
  10135. return '<' . $tag . ' ' . $compiledAttributes . '>' . $text . '</' . $tag . '>';
  10136. } else {
  10137. return '<' . $tag . ' ' . $compiledAttributes . '>' . dol_escape_htmltag($text) . '</' . $tag . '>';
  10138. }
  10139. } else {
  10140. return $hookmanager->resPrint;
  10141. }
  10142. }
  10143. /**
  10144. * Add space between dolGetButtonTitle
  10145. *
  10146. * @param string $moreClass more css class label
  10147. * @return string html of title separator
  10148. */
  10149. function dolGetButtonTitleSeparator($moreClass = "")
  10150. {
  10151. return '<span class="button-title-separator '.$moreClass.'" ></span>';
  10152. }
  10153. /**
  10154. * get field error icon
  10155. *
  10156. * @param string $fieldValidationErrorMsg message to add in tooltip
  10157. * @return string html output
  10158. */
  10159. function getFieldErrorIcon($fieldValidationErrorMsg)
  10160. {
  10161. $out = '';
  10162. if (!empty($fieldValidationErrorMsg)) {
  10163. $out.= '<span class="field-error-icon classfortooltip" title="'.dol_escape_htmltag($fieldValidationErrorMsg, 1).'" role="alert" >'; // role alert is used for accessibility
  10164. $out.= '<span class="fa fa-exclamation-circle" aria-hidden="true" ></span>'; // For accessibility icon is separated and aria-hidden
  10165. $out.= '</span>';
  10166. }
  10167. return $out;
  10168. }
  10169. /**
  10170. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  10171. *
  10172. * @param string $label label of button
  10173. * @param string $helpText optional : content for help tooltip
  10174. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  10175. * @param string $url the url for link
  10176. * @param string $id attribute id of button
  10177. * @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
  10178. * @param array $params various params for future : recommended rather than adding more function arguments
  10179. * @return string html button
  10180. */
  10181. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  10182. {
  10183. global $langs, $conf, $user;
  10184. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  10185. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  10186. return '';
  10187. }
  10188. $class = 'btnTitle';
  10189. if (in_array($iconClass, array('fa fa-plus-circle', 'fa fa-plus-circle size15x', 'fa fa-comment-dots', 'fa fa-paper-plane'))) {
  10190. $class .= ' btnTitlePlus';
  10191. }
  10192. $useclassfortooltip = 1;
  10193. if (!empty($params['morecss'])) {
  10194. $class .= ' '.$params['morecss'];
  10195. }
  10196. $attr = array(
  10197. 'class' => $class,
  10198. 'href' => empty($url) ? '' : $url
  10199. );
  10200. if (!empty($helpText)) {
  10201. $attr['title'] = dol_escape_htmltag($helpText);
  10202. } elseif (empty($attr['title']) && $label) {
  10203. $attr['title'] = $label;
  10204. $useclassfortooltip = 0;
  10205. }
  10206. if ($status == 2) {
  10207. $attr['class'] .= ' btnTitleSelected';
  10208. } elseif ($status <= 0) {
  10209. $attr['class'] .= ' refused';
  10210. $attr['href'] = '';
  10211. if ($status == -1) { // disable
  10212. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  10213. } elseif ($status == 0) { // Not enough permissions
  10214. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  10215. }
  10216. }
  10217. if (!empty($attr['title']) && $useclassfortooltip) {
  10218. $attr['class'] .= ' classfortooltip';
  10219. }
  10220. if (!empty($id)) {
  10221. $attr['id'] = $id;
  10222. }
  10223. // Override attr
  10224. if (!empty($params['attr']) && is_array($params['attr'])) {
  10225. foreach ($params['attr'] as $key => $value) {
  10226. if ($key == 'class') {
  10227. $attr['class'] .= ' '.$value;
  10228. } elseif ($key == 'classOverride') {
  10229. $attr['class'] = $value;
  10230. } else {
  10231. $attr[$key] = $value;
  10232. }
  10233. }
  10234. }
  10235. if (isset($attr['href']) && empty($attr['href'])) {
  10236. unset($attr['href']);
  10237. }
  10238. // TODO : add a hook
  10239. // escape all attribute
  10240. $attr = array_map('dol_escape_htmltag', $attr);
  10241. $TCompiledAttr = array();
  10242. foreach ($attr as $key => $value) {
  10243. $TCompiledAttr[] = $key.'="'.$value.'"';
  10244. }
  10245. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  10246. $tag = (empty($attr['href']) ? 'span' : 'a');
  10247. $button = '<'.$tag.' '.$compiledAttributes.'>';
  10248. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  10249. if (!empty($params['forcenohideoftext'])) {
  10250. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  10251. }
  10252. $button .= '</'.$tag.'>';
  10253. return $button;
  10254. }
  10255. /**
  10256. * Get an array with properties of an element.
  10257. *
  10258. * @param string $element_type Element type (Value of $object->element). Example:
  10259. * 'action', 'facture', 'project', 'project_task' or
  10260. * 'myobject@mymodule' or
  10261. * 'myobject_mysubobject' (where mymodule = myobject, like 'project_task')
  10262. * @return array array('module'=>, 'classpath'=>, 'element'=>, 'subelement'=>, 'classfile'=>, 'classname'=>, 'dir_output'=>)
  10263. * @see fetchObjectByElement()
  10264. */
  10265. function getElementProperties($element_type)
  10266. {
  10267. global $conf;
  10268. $regs = array();
  10269. $classfile = $classname = $classpath = $subdir = $dir_output = '';
  10270. // Parse element/subelement
  10271. $module = $element_type;
  10272. $element = $element_type;
  10273. $subelement = $element_type;
  10274. // If we ask a resource form external module (instead of default path)
  10275. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) { // 'myobject@mymodule'
  10276. $element = $subelement = $regs[1];
  10277. $module = $regs[2];
  10278. }
  10279. // If we ask a resource for a string with an element and a subelement
  10280. // Example 'project_task'
  10281. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) { // 'myobject_mysubobject' with myobject=mymodule
  10282. $module = $element = $regs[1];
  10283. $subelement = $regs[2];
  10284. }
  10285. // For compat and To work with non standard path
  10286. if ($element_type == "action") {
  10287. $classpath = 'comm/action/class';
  10288. $subelement = 'Actioncomm';
  10289. $module = 'agenda';
  10290. } elseif ($element_type == 'cronjob') {
  10291. $classpath = 'cron/class';
  10292. $module = 'cron';
  10293. } elseif ($element_type == 'adherent_type') {
  10294. $classpath = 'adherents/class';
  10295. $classfile = 'adherent_type';
  10296. $module = 'adherent';
  10297. $subelement = 'adherent_type';
  10298. $classname = 'AdherentType';
  10299. } elseif ($element_type == 'bank_account') {
  10300. $classpath = 'compta/bank/class';
  10301. $module = 'banque';
  10302. $classfile = 'account';
  10303. $classname = 'Account';
  10304. } elseif ($element_type == 'category') {
  10305. $classpath = 'categories/class';
  10306. $module = 'categorie';
  10307. $subelement = 'categorie';
  10308. } elseif ($element_type == 'contact') {
  10309. $classpath = 'contact/class';
  10310. $classfile = 'contact';
  10311. $module = 'societe';
  10312. $subelement = 'contact';
  10313. } elseif ($element_type == 'stock') {
  10314. $classpath = 'product/stock/class';
  10315. $classfile = 'entrepot';
  10316. $classname = 'Entrepot';
  10317. } elseif ($element_type == 'project') {
  10318. $classpath = 'projet/class';
  10319. $module = 'projet';
  10320. } elseif ($element_type == 'project_task') {
  10321. $classpath = 'projet/class';
  10322. $module = 'projet';
  10323. $subelement = 'task';
  10324. } elseif ($element_type == 'facture' || $element_type == 'invoice') {
  10325. $classpath = 'compta/facture/class';
  10326. $module = 'facture';
  10327. $subelement = 'facture';
  10328. } elseif ($element_type == 'commande' || $element_type == 'order') {
  10329. $classpath = 'commande/class';
  10330. $module = 'commande';
  10331. $subelement = 'commande';
  10332. } elseif ($element_type == 'propal') {
  10333. $classpath = 'comm/propal/class';
  10334. } elseif ($element_type == 'shipping') {
  10335. $classpath = 'expedition/class';
  10336. $classfile = 'expedition';
  10337. $classname = 'Expedition';
  10338. $module = 'expedition';
  10339. } elseif ($element_type == 'supplier_proposal') {
  10340. $classpath = 'supplier_proposal/class';
  10341. $module = 'supplier_proposal';
  10342. $element = 'supplierproposal';
  10343. $classfile = 'supplier_proposal';
  10344. $subelement = 'supplierproposal';
  10345. } elseif ($element_type == 'shipping') {
  10346. $classpath = 'expedition/class';
  10347. $subelement = 'expedition';
  10348. $module = 'expedition_bon';
  10349. } elseif ($element_type == 'delivery') {
  10350. $classpath = 'delivery/class';
  10351. $subelement = 'delivery';
  10352. $module = 'delivery_note';
  10353. } elseif ($element_type == 'contract') {
  10354. $classpath = 'contrat/class';
  10355. $module = 'contrat';
  10356. $subelement = 'contrat';
  10357. } elseif ($element_type == 'mailing') {
  10358. $classpath = 'comm/mailing/class';
  10359. $module = 'mailing';
  10360. $classfile = 'mailing';
  10361. $classname = 'Mailing';
  10362. $subelement = '';
  10363. } elseif ($element_type == 'member') {
  10364. $classpath = 'adherents/class';
  10365. $module = 'adherent';
  10366. $subelement = 'adherent';
  10367. } elseif ($element_type == 'usergroup') {
  10368. $classpath = 'user/class';
  10369. $module = 'user';
  10370. } elseif ($element_type == 'mo') {
  10371. $classpath = 'mrp/class';
  10372. $classfile = 'mo';
  10373. $classname = 'Mo';
  10374. $module = 'mrp';
  10375. $subelement = '';
  10376. } elseif ($element_type == 'cabinetmed_cons') {
  10377. $classpath = 'cabinetmed/class';
  10378. $module = 'cabinetmed';
  10379. $subelement = 'cabinetmedcons';
  10380. } elseif ($element_type == 'fichinter') {
  10381. $classpath = 'fichinter/class';
  10382. $module = 'ficheinter';
  10383. $subelement = 'fichinter';
  10384. } elseif ($element_type == 'dolresource' || $element_type == 'resource') {
  10385. $classpath = 'resource/class';
  10386. $module = 'resource';
  10387. $subelement = 'dolresource';
  10388. } elseif ($element_type == 'propaldet') {
  10389. $classpath = 'comm/propal/class';
  10390. $module = 'propal';
  10391. $subelement = 'propaleligne';
  10392. } elseif ($element_type == 'opensurvey_sondage') {
  10393. $classpath = 'opensurvey/class';
  10394. $module = 'opensurvey';
  10395. $subelement = 'opensurveysondage';
  10396. } elseif ($element_type == 'order_supplier') {
  10397. $classpath = 'fourn/class';
  10398. $module = 'fournisseur';
  10399. $classfile = 'fournisseur.commande';
  10400. $element = 'order_supplier';
  10401. $subelement = '';
  10402. $classname = 'CommandeFournisseur';
  10403. } elseif ($element_type == 'invoice_supplier') {
  10404. $classpath = 'fourn/class';
  10405. $module = 'fournisseur';
  10406. $classfile = 'fournisseur.facture';
  10407. $element = 'invoice_supplier';
  10408. $subelement = '';
  10409. $classname = 'FactureFournisseur';
  10410. } elseif ($element_type == "service") {
  10411. $classpath = 'product/class';
  10412. $subelement = 'product';
  10413. } elseif ($element_type == 'salary') {
  10414. $classpath = 'salaries/class';
  10415. $module = 'salaries';
  10416. } elseif ($element_type == 'productlot') {
  10417. $module = 'productbatch';
  10418. $classpath = 'product/stock/class';
  10419. $classfile = 'productlot';
  10420. $classname = 'Productlot';
  10421. $element = 'productlot';
  10422. $subelement = '';
  10423. } elseif ($element_type == 'websitepage') {
  10424. $classpath = 'website/class';
  10425. $classfile = 'websitepage';
  10426. $classname = 'Websitepage';
  10427. $module = 'website';
  10428. $subelement = 'websitepage';
  10429. } elseif ($element_type == 'fiscalyear') {
  10430. $classpath = 'core/class';
  10431. $module = 'accounting';
  10432. $subelement = 'fiscalyear';
  10433. } elseif ($element_type == 'chargesociales') {
  10434. $classpath = 'compta/sociales/class';
  10435. $module = 'tax';
  10436. } elseif ($element_type == 'tva') {
  10437. $classpath = 'compta/tva/class';
  10438. $module = 'tax';
  10439. $subdir = '/vat';
  10440. }
  10441. if (empty($classfile)) {
  10442. $classfile = strtolower($subelement);
  10443. }
  10444. if (empty($classname)) {
  10445. $classname = ucfirst($subelement);
  10446. }
  10447. if (empty($classpath)) {
  10448. $classpath = $module.'/class';
  10449. }
  10450. //print 'getElementProperties subdir='.$subdir;
  10451. // Set dir_output
  10452. if ($module && isset($conf->$module)) { // The generic case
  10453. if (!empty($conf->$module->multidir_output[$conf->entity])) {
  10454. $dir_output = $conf->$module->multidir_output[$conf->entity];
  10455. } elseif (!empty($conf->$module->output[$conf->entity])) {
  10456. $dir_output = $conf->$module->output[$conf->entity];
  10457. } elseif (!empty($conf->$module->dir_output)) {
  10458. $dir_output = $conf->$module->dir_output;
  10459. }
  10460. }
  10461. // Overwrite value for special cases
  10462. if ($element == 'order_supplier') {
  10463. $dir_output = $conf->fournisseur->commande->dir_output;
  10464. } elseif ($element == 'invoice_supplier') {
  10465. $dir_output = $conf->fournisseur->facture->dir_output;
  10466. }
  10467. $dir_output .= $subdir;
  10468. $element_properties = array(
  10469. 'module' => $module,
  10470. 'element' => $element,
  10471. 'subelement' => $subelement,
  10472. 'classpath' => $classpath,
  10473. 'classfile' => $classfile,
  10474. 'classname' => $classname,
  10475. 'dir_output' => $dir_output
  10476. );
  10477. return $element_properties;
  10478. }
  10479. /**
  10480. * Fetch an object from its id and element_type
  10481. * Inclusion of classes is automatic
  10482. *
  10483. * @param int $element_id Element id
  10484. * @param string $element_type Element type ('module' or 'myobject@mymodule' or 'mymodule_myobject')
  10485. * @param string $element_ref Element ref (Use this or element_id but not both)
  10486. * @return int|object object || 0 || <0 if error
  10487. */
  10488. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  10489. {
  10490. global $db;
  10491. $ret = 0;
  10492. $element_prop = getElementProperties($element_type);
  10493. //var_dump($element_prop);
  10494. if (is_array($element_prop) && isModEnabled($element_prop['module'])) {
  10495. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  10496. if (class_exists($element_prop['classname'])) {
  10497. $classname = $element_prop['classname'];
  10498. $objecttmp = new $classname($db);
  10499. $ret = $objecttmp->fetch($element_id, $element_ref);
  10500. if ($ret >= 0) {
  10501. if (empty($objecttmp->module)) {
  10502. $objecttmp->module = $element_prop['module'];
  10503. }
  10504. return $objecttmp;
  10505. }
  10506. } else {
  10507. return -1;
  10508. }
  10509. }
  10510. return $ret;
  10511. }
  10512. /**
  10513. * Return if a file can contains executable content
  10514. *
  10515. * @param string $filename File name to test
  10516. * @return boolean True if yes, False if no
  10517. */
  10518. function isAFileWithExecutableContent($filename)
  10519. {
  10520. 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)) {
  10521. return true;
  10522. }
  10523. return false;
  10524. }
  10525. /**
  10526. * Return the value of token currently saved into session with name 'newtoken'.
  10527. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  10528. *
  10529. * @since Dolibarr v10.0.7
  10530. * @return string
  10531. */
  10532. function newToken()
  10533. {
  10534. return empty($_SESSION['newtoken']) ? '' : $_SESSION['newtoken'];
  10535. }
  10536. /**
  10537. * Return the value of token currently saved into session with name 'token'.
  10538. * 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).
  10539. *
  10540. * @since Dolibarr v10.0.7
  10541. * @return string
  10542. */
  10543. function currentToken()
  10544. {
  10545. return isset($_SESSION['token']) ? $_SESSION['token'] : '';
  10546. }
  10547. /**
  10548. * Return a random string to be used as a nonce value for js
  10549. *
  10550. * @return string
  10551. */
  10552. function getNonce()
  10553. {
  10554. global $conf;
  10555. if (empty($conf->cache['nonce'])) {
  10556. $conf->cache['nonce'] = dolGetRandomBytes(8);
  10557. }
  10558. return $conf->cache['nonce'];
  10559. }
  10560. /**
  10561. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  10562. *
  10563. * @param string $header The first left header of the table (automatic translated)
  10564. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  10565. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  10566. * @param integer $emptyRows (optional) The count of empty rows after the first header
  10567. * @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"
  10568. * @return void
  10569. *
  10570. * @see finishSimpleTable()
  10571. */
  10572. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  10573. {
  10574. global $langs;
  10575. print '<div class="div-table-responsive-no-min">';
  10576. print '<table class="noborder centpercent">';
  10577. print '<tr class="liste_titre">';
  10578. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  10579. print $langs->trans($header);
  10580. // extra space between the first header and the number
  10581. if ($number > -1) {
  10582. print ' ';
  10583. }
  10584. if (!empty($link)) {
  10585. if (!empty($arguments)) {
  10586. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10587. } else {
  10588. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  10589. }
  10590. }
  10591. if ($number > -1) {
  10592. print '<span class="badge">'.$number.'</span>';
  10593. }
  10594. if (!empty($link)) {
  10595. print '</a>';
  10596. }
  10597. print '</th>';
  10598. if ($number < 0 && !empty($link)) {
  10599. print '<th class="right">';
  10600. if (!empty($arguments)) {
  10601. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  10602. } else {
  10603. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  10604. }
  10605. print $langs->trans("FullList");
  10606. print '</a>';
  10607. print '</th>';
  10608. }
  10609. print '</tr>';
  10610. }
  10611. /**
  10612. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  10613. *
  10614. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  10615. * @return void
  10616. *
  10617. * @see startSimpleTable()
  10618. */
  10619. function finishSimpleTable($addLineBreak = false)
  10620. {
  10621. print '</table>';
  10622. print '</div>';
  10623. if ($addLineBreak) {
  10624. print '<br>';
  10625. }
  10626. }
  10627. /**
  10628. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  10629. *
  10630. * @param integer $tableColumnCount The complete count columns of the table
  10631. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  10632. * @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)
  10633. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  10634. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  10635. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  10636. * @return void
  10637. */
  10638. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  10639. {
  10640. global $langs;
  10641. if ($num === 0) {
  10642. print '<tr class="oddeven">';
  10643. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  10644. print '</tr>';
  10645. return;
  10646. }
  10647. if ($nbofloop === 0) {
  10648. // don't show a summary line
  10649. return;
  10650. }
  10651. if ($num === 0) {
  10652. $colspan = $tableColumnCount;
  10653. } elseif ($num > $nbofloop) {
  10654. $colspan = $tableColumnCount;
  10655. } else {
  10656. $colspan = $tableColumnCount - 1;
  10657. }
  10658. if ($extraRightColumn) {
  10659. $colspan--;
  10660. }
  10661. print '<tr class="liste_total">';
  10662. if ($nbofloop > 0 && $num > $nbofloop) {
  10663. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  10664. } else {
  10665. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  10666. print '<td class="right" width="100">'.price($total).'</td>';
  10667. }
  10668. if ($extraRightColumn) {
  10669. print '<td></td>';
  10670. }
  10671. print '</tr>';
  10672. }
  10673. /**
  10674. * Return a file on output using a low memory. It can return very large files with no need of memory.
  10675. * WARNING: This close output buffers.
  10676. *
  10677. * @param string $fullpath_original_file_osencoded Full path of file to return.
  10678. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  10679. * @return void
  10680. */
  10681. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  10682. {
  10683. global $conf;
  10684. if ($method == -1) {
  10685. $method = 0;
  10686. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) {
  10687. $method = 1;
  10688. }
  10689. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) {
  10690. $method = 2;
  10691. }
  10692. }
  10693. // Be sure we don't have output buffering enabled to have readfile working correctly
  10694. while (ob_get_level()) {
  10695. ob_end_flush();
  10696. }
  10697. // Solution 0
  10698. if ($method == 0) {
  10699. readfile($fullpath_original_file_osencoded);
  10700. } elseif ($method == 1) {
  10701. // Solution 1
  10702. $handle = fopen($fullpath_original_file_osencoded, "rb");
  10703. while (!feof($handle)) {
  10704. print fread($handle, 8192);
  10705. }
  10706. fclose($handle);
  10707. } elseif ($method == 2) {
  10708. // Solution 2
  10709. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  10710. $handle2 = fopen("php://output", "wb");
  10711. stream_copy_to_stream($handle1, $handle2);
  10712. fclose($handle1);
  10713. fclose($handle2);
  10714. }
  10715. }
  10716. /**
  10717. * Create a button to copy $valuetocopy in the clipboard (for copy and paste feature).
  10718. * Code that handle the click is inside core/js/lib_foot.js.php.
  10719. *
  10720. * @param string $valuetocopy The value to print
  10721. * @param int $showonlyonhover Show the copy-paste button only on hover
  10722. * @param string $texttoshow Replace the value to show with this text. Use 'none' to show no text (only the copy-paste picto)
  10723. * @return string The string to print for the button
  10724. */
  10725. function showValueWithClipboardCPButton($valuetocopy, $showonlyonhover = 1, $texttoshow = '')
  10726. {
  10727. /*
  10728. global $conf;
  10729. if (!empty($conf->dol_no_mouse_hover)) {
  10730. $showonlyonhover = 0;
  10731. }*/
  10732. $tag = 'span'; // Using div (like any style of type 'block') does not work when using the js copy code.
  10733. if ($texttoshow === 'none') {
  10734. $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>';
  10735. } elseif ($texttoshow) {
  10736. $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>';
  10737. } else {
  10738. $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>';
  10739. }
  10740. return $result;
  10741. }
  10742. /**
  10743. * Decode an encode string. The string can be encoded in json format (recommended) or with serialize (avoid this)
  10744. *
  10745. * @param string $stringtodecode String to decode (json or serialize coded)
  10746. * @return mixed The decoded object.
  10747. */
  10748. function jsonOrUnserialize($stringtodecode)
  10749. {
  10750. $result = json_decode($stringtodecode);
  10751. if ($result === null) {
  10752. $result = unserialize($stringtodecode);
  10753. }
  10754. return $result;
  10755. }
  10756. /**
  10757. * forgeSQLFromUniversalSearchCriteria
  10758. *
  10759. * @param string $filter String with universal search string. Must be '(aaa:bbb:...) OR (ccc:ddd:...) ...' with
  10760. * aaa is a field name (with alias or not) and
  10761. * bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'.
  10762. * @param string $errorstr Error message string
  10763. * @param int $noand 1=Do not add the AND before the condition string.
  10764. * @param int $nopar 1=Do not add the perenthesis around the condition string.
  10765. * @param int $noerror 1=If search criteria is not valid, does not return an error string but invalidate the SQL
  10766. * @return string Return forged SQL string
  10767. */
  10768. function forgeSQLFromUniversalSearchCriteria($filter, &$errorstr = '', $noand = 0, $nopar = 0, $noerror = 0)
  10769. {
  10770. if (!preg_match('/^\(.*\)$/', $filter)) { // If $filter does not start and end with ()
  10771. $filter = '(' . $filter . ')';
  10772. }
  10773. $regexstring = '\(([a-zA-Z0-9_\.]+:[<>!=insotlke]+:[^\(\)]+)\)'; // Must be (aaa:bbb:...) with aaa is a field name (with alias or not) and bbb is one of this operator '=', '<', '>', '<=', '>=', '!=', 'in', 'notin', 'like', 'notlike', 'is', 'isnot'
  10774. if (!dolCheckFilters($filter, $errorstr)) {
  10775. if ($noerror) {
  10776. return '1 = 2';
  10777. } else {
  10778. return 'Filter syntax error - '.$errorstr; // Bad balance of parenthesis, we return an error message or force a SQL not found
  10779. }
  10780. }
  10781. // Test the filter syntax
  10782. $t = preg_replace_callback('/'.$regexstring.'/i', 'dolForgeDummyCriteriaCallback', $filter);
  10783. $t = str_replace(array('and','or','AND','OR',' '), '', $t); // Remove the only strings allowed between each () criteria
  10784. // If the string result contains something else than '()', the syntax was wrong
  10785. if (preg_match('/[^\(\)]/', $t)) {
  10786. $errorstr = 'Bad syntax of the search string';
  10787. if ($noerror) {
  10788. return '1 = 2';
  10789. } else {
  10790. return 'Filter syntax error - '.$errorstr; // Bad syntax of the search string, we return an error message or force a SQL not found
  10791. }
  10792. }
  10793. return ($noand ? "" : " AND ").($nopar ? "" : '(').preg_replace_callback('/'.$regexstring.'/i', 'dolForgeCriteriaCallback', $filter).($nopar ? "" : ')');
  10794. }
  10795. /**
  10796. * Return if a $sqlfilters parameter has a valid balance of parenthesis
  10797. *
  10798. * @param string $sqlfilters sqlfilter string
  10799. * @param string $error Error message
  10800. * @return boolean True if valid, False if not valid ($error is filled with the reason in such a case)
  10801. */
  10802. function dolCheckFilters($sqlfilters, &$error = '')
  10803. {
  10804. //$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
  10805. //$tmp=preg_replace_all('/'.$regexstring.'/', '', $sqlfilters);
  10806. $tmp = $sqlfilters;
  10807. $i = 0; $nb = strlen($tmp);
  10808. $counter = 0;
  10809. while ($i < $nb) {
  10810. if ($tmp[$i] == '(') {
  10811. $counter++;
  10812. }
  10813. if ($tmp[$i] == ')') {
  10814. $counter--;
  10815. }
  10816. if ($counter < 0) {
  10817. $error = "Wrond balance of parenthesis in sqlfilters=".$sqlfilters;
  10818. dol_syslog($error, LOG_WARNING);
  10819. return false;
  10820. }
  10821. $i++;
  10822. }
  10823. return true;
  10824. }
  10825. /**
  10826. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  10827. * This method is called by forgeSQLFromUniversalSearchCriteria()
  10828. *
  10829. * @param array $matches Array of found string by regex search. Example: "t.ref:like:'SO-%'" or "t.date_creation:<:'20160101'" or "t.nature:is:NULL"
  10830. * @return string Forged criteria. Example: "" or "()"
  10831. */
  10832. function dolForgeDummyCriteriaCallback($matches)
  10833. {
  10834. //dol_syslog("Convert matches ".$matches[1]);
  10835. if (empty($matches[1])) {
  10836. return '';
  10837. }
  10838. $tmp = explode(':', $matches[1]);
  10839. if (count($tmp) < 3) {
  10840. return '';
  10841. }
  10842. return '()'; // An empty criteria
  10843. }
  10844. /**
  10845. * Function to forge a SQL criteria from a Dolibarr filter syntax string.
  10846. * This method is called by forgeSQLFromUniversalSearchCriteria()
  10847. *
  10848. * @param array $matches Array of found string by regex search.
  10849. * 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"
  10850. * @return string Forged criteria. Example: "t.field LIKE 'abc%'"
  10851. */
  10852. function dolForgeCriteriaCallback($matches)
  10853. {
  10854. global $db;
  10855. //dol_syslog("Convert matches ".$matches[1]);
  10856. if (empty($matches[1])) {
  10857. return '';
  10858. }
  10859. $tmp = explode(':', $matches[1]);
  10860. if (count($tmp) < 3) {
  10861. return '';
  10862. }
  10863. $operand = preg_replace('/[^a-z0-9\._]/i', '', trim($tmp[0]));
  10864. $operator = strtoupper(preg_replace('/[^a-z<>!=]/i', '', trim($tmp[1])));
  10865. if ($operator == 'NOTLIKE') {
  10866. $operator = 'NOT LIKE';
  10867. }
  10868. if ($operator == 'ISNOT') {
  10869. $operator = 'IS NOT';
  10870. }
  10871. if ($operator == '!=') {
  10872. $operator = '<>';
  10873. }
  10874. $tmpescaped = $tmp[2];
  10875. $regbis = array();
  10876. if ($operator == 'IN') { // IN is allowed for list of ID or code only
  10877. //if (!preg_match('/^\(.*\)$/', $tmpescaped)) {
  10878. $tmpescaped = '('.$db->escape($db->sanitize($tmpescaped, 1, 0)).')';
  10879. //} else {
  10880. // $tmpescaped = $db->escape($db->sanitize($tmpescaped, 1));
  10881. //}
  10882. } elseif ($operator == 'LIKE' || $operator == 'NOT LIKE') {
  10883. if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  10884. $tmpescaped = $regbis[1];
  10885. }
  10886. //$tmpescaped = "'".$db->escapeforlike($db->escape($regbis[1]))."'";
  10887. $tmpescaped = "'".$db->escape($tmpescaped)."'"; // We do not escape the _ and % so the like will works
  10888. } elseif (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) {
  10889. $tmpescaped = "'".$db->escape($regbis[1])."'";
  10890. } else {
  10891. if (strtoupper($tmpescaped) == 'NULL') {
  10892. $tmpescaped = 'NULL';
  10893. } elseif (is_int($tmpescaped)) {
  10894. $tmpescaped = (int) $tmpescaped;
  10895. } else {
  10896. $tmpescaped = (float) $tmpescaped;
  10897. }
  10898. }
  10899. return '('.$db->escape($operand).' '.strtoupper($operator).' '.$tmpescaped.')';
  10900. }
  10901. /**
  10902. * Get timeline icon
  10903. *
  10904. * @param ActionComm $actionstatic actioncomm
  10905. * @param array $histo histo
  10906. * @param int $key key
  10907. * @return string
  10908. */
  10909. function getTimelineIcon($actionstatic, &$histo, $key)
  10910. {
  10911. global $conf, $langs;
  10912. $out = '<!-- timeline icon -->'."\n";
  10913. $iconClass = 'fa fa-comments';
  10914. $img_picto = '';
  10915. $colorClass = '';
  10916. $pictoTitle = '';
  10917. if ($histo[$key]['percent'] == -1) {
  10918. $colorClass = 'timeline-icon-not-applicble';
  10919. $pictoTitle = $langs->trans('StatusNotApplicable');
  10920. } elseif ($histo[$key]['percent'] == 0) {
  10921. $colorClass = 'timeline-icon-todo';
  10922. $pictoTitle = $langs->trans('StatusActionToDo').' (0%)';
  10923. } elseif ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100) {
  10924. $colorClass = 'timeline-icon-in-progress';
  10925. $pictoTitle = $langs->trans('StatusActionInProcess').' ('.$histo[$key]['percent'].'%)';
  10926. } elseif ($histo[$key]['percent'] >= 100) {
  10927. $colorClass = 'timeline-icon-done';
  10928. $pictoTitle = $langs->trans('StatusActionDone').' (100%)';
  10929. }
  10930. if ($actionstatic->code == 'AC_TICKET_CREATE') {
  10931. $iconClass = 'fa fa-ticket';
  10932. } elseif ($actionstatic->code == 'AC_TICKET_MODIFY') {
  10933. $iconClass = 'fa fa-pencilxxx';
  10934. } elseif (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  10935. $iconClass = 'fa fa-comments';
  10936. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  10937. $iconClass = 'fa fa-mask';
  10938. } elseif (!empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  10939. if ($actionstatic->type_picto) {
  10940. $img_picto = img_picto('', $actionstatic->type_picto);
  10941. } else {
  10942. if ($actionstatic->type_code == 'AC_RDV') {
  10943. $iconClass = 'fa fa-handshake';
  10944. } elseif ($actionstatic->type_code == 'AC_TEL') {
  10945. $iconClass = 'fa fa-phone';
  10946. } elseif ($actionstatic->type_code == 'AC_FAX') {
  10947. $iconClass = 'fa fa-fax';
  10948. } elseif ($actionstatic->type_code == 'AC_EMAIL') {
  10949. $iconClass = 'fa fa-envelope';
  10950. } elseif ($actionstatic->type_code == 'AC_INT') {
  10951. $iconClass = 'fa fa-shipping-fast';
  10952. } elseif ($actionstatic->type_code == 'AC_OTH_AUTO') {
  10953. $iconClass = 'fa fa-robot';
  10954. } elseif (!preg_match('/_AUTO/', $actionstatic->type_code)) {
  10955. $iconClass = 'fa fa-robot';
  10956. }
  10957. }
  10958. }
  10959. $out .= '<i class="'.$iconClass.' '.$colorClass.'" title="'.$pictoTitle.'">'.$img_picto.'</i>'."\n";
  10960. return $out;
  10961. }
  10962. /**
  10963. * getActionCommEcmList
  10964. *
  10965. * @param ActionComm $object Object ActionComm
  10966. * @return array Array of documents in index table
  10967. */
  10968. function getActionCommEcmList($object)
  10969. {
  10970. global $conf, $db;
  10971. $documents = array();
  10972. $sql = 'SELECT ecm.rowid as id, ecm.src_object_type, ecm.src_object_id, ecm.filepath, ecm.filename';
  10973. $sql .= ' FROM '.MAIN_DB_PREFIX.'ecm_files ecm';
  10974. $sql .= " WHERE ecm.filepath = 'agenda/".((int) $object->id)."'";
  10975. //$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
  10976. $sql .= ' ORDER BY ecm.position ASC';
  10977. $resql = $db->query($sql);
  10978. if ($resql) {
  10979. if ($db->num_rows($resql)) {
  10980. while ($obj = $db->fetch_object($resql)) {
  10981. $documents[$obj->id] = $obj;
  10982. }
  10983. }
  10984. }
  10985. return $documents;
  10986. }
  10987. /**
  10988. * Show html area with actions in messaging format.
  10989. * Note: Global parameter $param must be defined.
  10990. *
  10991. * @param Conf $conf Object conf
  10992. * @param Translate $langs Object langs
  10993. * @param DoliDB $db Object db
  10994. * @param mixed $filterobj Filter on object Adherent|Societe|Project|Product|CommandeFournisseur|Dolresource|Ticket|... to list events linked to an object
  10995. * @param Contact $objcon Filter on object contact to filter events on a contact
  10996. * @param int $noprint Return string but does not output it
  10997. * @param string $actioncode Filter on actioncode
  10998. * @param string $donetodo Filter on event 'done' or 'todo' or ''=nofilter (all).
  10999. * @param array $filters Filter on other fields
  11000. * @param string $sortfield Sort field
  11001. * @param string $sortorder Sort order
  11002. * @return string|void Return html part or void if noprint is 1
  11003. */
  11004. function show_actions_messaging($conf, $langs, $db, $filterobj, $objcon = '', $noprint = 0, $actioncode = '', $donetodo = 'done', $filters = array(), $sortfield = 'a.datep,a.id', $sortorder = 'DESC')
  11005. {
  11006. global $user, $conf;
  11007. global $form;
  11008. global $param, $massactionbutton;
  11009. dol_include_once('/comm/action/class/actioncomm.class.php');
  11010. // Check parameters
  11011. if (!is_object($filterobj) && !is_object($objcon)) {
  11012. dol_print_error('', 'BadParameter');
  11013. }
  11014. $histo = array();
  11015. $numaction = 0;
  11016. $now = dol_now();
  11017. $sortfield_list = explode(',', $sortfield);
  11018. $sortfield_label_list = array('a.id' => 'id', 'a.datep' => 'dp', 'a.percent' => 'percent');
  11019. $sortfield_new_list = array();
  11020. foreach ($sortfield_list as $sortfield_value) {
  11021. $sortfield_new_list[] = $sortfield_label_list[trim($sortfield_value)];
  11022. }
  11023. $sortfield_new = implode(',', $sortfield_new_list);
  11024. if (isModEnabled('agenda')) {
  11025. // Search histo on actioncomm
  11026. if (is_object($objcon) && $objcon->id > 0) {
  11027. $sql = "SELECT DISTINCT a.id, a.label as label,";
  11028. } else {
  11029. $sql = "SELECT a.id, a.label as label,";
  11030. }
  11031. $sql .= " a.datep as dp,";
  11032. $sql .= " a.note as message,";
  11033. $sql .= " a.datep2 as dp2,";
  11034. $sql .= " a.percent as percent, 'action' as type,";
  11035. $sql .= " a.fk_element, a.elementtype,";
  11036. $sql .= " a.fk_contact,";
  11037. $sql .= " a.email_from as msg_from,";
  11038. $sql .= " c.code as acode, c.libelle as alabel, c.picto as apicto,";
  11039. $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";
  11040. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11041. $sql .= ", sp.lastname, sp.firstname";
  11042. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11043. $sql .= ", m.lastname, m.firstname";
  11044. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11045. $sql .= ", o.ref";
  11046. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11047. $sql .= ", o.ref";
  11048. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11049. $sql .= ", o.ref";
  11050. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11051. $sql .= ", o.ref";
  11052. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11053. $sql .= ", o.ref";
  11054. }
  11055. $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a";
  11056. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on u.rowid = a.fk_user_action";
  11057. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_actioncomm as c ON a.fk_action = c.id";
  11058. $force_filter_contact = false;
  11059. if (is_object($objcon) && $objcon->id > 0) {
  11060. $force_filter_contact = true;
  11061. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."actioncomm_resources as r ON a.id = r.fk_actioncomm";
  11062. $sql .= " AND r.element_type = '".$db->escape($objcon->table_element)."' AND r.fk_element = ".((int) $objcon->id);
  11063. }
  11064. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11065. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid";
  11066. } elseif (is_object($filterobj) && get_class($filterobj) == 'Dolresource') {
  11067. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_resources as er";
  11068. $sql .= " ON er.resource_type = 'dolresource'";
  11069. $sql .= " AND er.element_id = a.id";
  11070. $sql .= " AND er.resource_id = ".((int) $filterobj->id);
  11071. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11072. $sql .= ", ".MAIN_DB_PREFIX."adherent as m";
  11073. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11074. $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as o";
  11075. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11076. $sql .= ", ".MAIN_DB_PREFIX."product as o";
  11077. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11078. $sql .= ", ".MAIN_DB_PREFIX."ticket as o";
  11079. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11080. $sql .= ", ".MAIN_DB_PREFIX."bom_bom as o";
  11081. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11082. $sql .= ", ".MAIN_DB_PREFIX."contrat as o";
  11083. }
  11084. $sql .= " WHERE a.entity IN (".getEntity('agenda').")";
  11085. if ($force_filter_contact === false) {
  11086. if (is_object($filterobj) && in_array(get_class($filterobj), array('Societe', 'Client', 'Fournisseur')) && $filterobj->id) {
  11087. $sql .= " AND a.fk_soc = ".((int) $filterobj->id);
  11088. } elseif (is_object($filterobj) && get_class($filterobj) == 'Project' && $filterobj->id) {
  11089. $sql .= " AND a.fk_project = ".((int) $filterobj->id);
  11090. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11091. $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'";
  11092. if ($filterobj->id) {
  11093. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11094. }
  11095. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11096. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'";
  11097. if ($filterobj->id) {
  11098. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11099. }
  11100. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11101. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'";
  11102. if ($filterobj->id) {
  11103. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11104. }
  11105. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11106. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'";
  11107. if ($filterobj->id) {
  11108. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11109. }
  11110. } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') {
  11111. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'";
  11112. if ($filterobj->id) {
  11113. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11114. }
  11115. } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') {
  11116. $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'";
  11117. if ($filterobj->id) {
  11118. $sql .= " AND a.fk_element = ".((int) $filterobj->id);
  11119. }
  11120. }
  11121. }
  11122. // Condition on actioncode
  11123. if (!empty($actioncode)) {
  11124. if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) {
  11125. if ($actioncode == 'AC_NON_AUTO') {
  11126. $sql .= " AND c.type != 'systemauto'";
  11127. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11128. $sql .= " AND c.type = 'systemauto'";
  11129. } else {
  11130. if ($actioncode == 'AC_OTH') {
  11131. $sql .= " AND c.type != 'systemauto'";
  11132. } elseif ($actioncode == 'AC_OTH_AUTO') {
  11133. $sql .= " AND c.type = 'systemauto'";
  11134. }
  11135. }
  11136. } else {
  11137. if ($actioncode == 'AC_NON_AUTO') {
  11138. $sql .= " AND c.type != 'systemauto'";
  11139. } elseif ($actioncode == 'AC_ALL_AUTO') {
  11140. $sql .= " AND c.type = 'systemauto'";
  11141. } else {
  11142. $sql .= " AND c.code = '".$db->escape($actioncode)."'";
  11143. }
  11144. }
  11145. }
  11146. if ($donetodo == 'todo') {
  11147. $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11148. } elseif ($donetodo == 'done') {
  11149. $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11150. }
  11151. if (is_array($filters) && $filters['search_agenda_label']) {
  11152. $sql .= natural_search('a.label', $filters['search_agenda_label']);
  11153. }
  11154. }
  11155. // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing.
  11156. if (isModEnabled('mailing') && !empty($objcon->email)
  11157. && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) {
  11158. $langs->load("mails");
  11159. $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";
  11160. $sql2 .= ", null as fk_element, '' as elementtype, null as contact_id";
  11161. $sql2 .= ", 'AC_EMAILING' as acode, '' as alabel, '' as apicto";
  11162. $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
  11163. if (is_object($filterobj) && get_class($filterobj) == 'Societe') {
  11164. $sql2 .= ", '' as lastname, '' as firstname";
  11165. } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') {
  11166. $sql2 .= ", '' as lastname, '' as firstname";
  11167. } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') {
  11168. $sql2 .= ", '' as ref";
  11169. } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') {
  11170. $sql2 .= ", '' as ref";
  11171. } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') {
  11172. $sql2 .= ", '' as ref";
  11173. }
  11174. $sql2 .= " FROM ".MAIN_DB_PREFIX."mailing as m, ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."user as u";
  11175. $sql2 .= " WHERE mc.email = '".$db->escape($objcon->email)."'"; // Search is done on email.
  11176. $sql2 .= " AND mc.statut = 1";
  11177. $sql2 .= " AND u.rowid = m.fk_user_valid";
  11178. $sql2 .= " AND mc.fk_mailing=m.rowid";
  11179. }
  11180. if (!empty($sql) && !empty($sql2)) {
  11181. $sql = $sql." UNION ".$sql2;
  11182. } elseif (empty($sql) && !empty($sql2)) {
  11183. $sql = $sql2;
  11184. }
  11185. // TODO Add limit in nb of results
  11186. if ($sql) { // May not be defined if module Agenda is not enabled and mailing module disabled too
  11187. $sql .= $db->order($sortfield_new, $sortorder);
  11188. dol_syslog("function.lib::show_actions_messaging", LOG_DEBUG);
  11189. $resql = $db->query($sql);
  11190. if ($resql) {
  11191. $i = 0;
  11192. $num = $db->num_rows($resql);
  11193. while ($i < $num) {
  11194. $obj = $db->fetch_object($resql);
  11195. if ($obj->type == 'action') {
  11196. $contactaction = new ActionComm($db);
  11197. $contactaction->id = $obj->id;
  11198. $result = $contactaction->fetchResources();
  11199. if ($result < 0) {
  11200. dol_print_error($db);
  11201. setEventMessage("actions.lib::show_actions_messaging Error fetch ressource", 'errors');
  11202. }
  11203. //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))";
  11204. //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))";
  11205. $tododone = '';
  11206. if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->dp > $now)) {
  11207. $tododone = 'todo';
  11208. }
  11209. $histo[$numaction] = array(
  11210. 'type'=>$obj->type,
  11211. 'tododone'=>$tododone,
  11212. 'id'=>$obj->id,
  11213. 'datestart'=>$db->jdate($obj->dp),
  11214. 'dateend'=>$db->jdate($obj->dp2),
  11215. 'note'=>$obj->label,
  11216. 'message'=>$obj->message,
  11217. 'percent'=>$obj->percent,
  11218. 'userid'=>$obj->user_id,
  11219. 'login'=>$obj->user_login,
  11220. 'userfirstname'=>$obj->user_firstname,
  11221. 'userlastname'=>$obj->user_lastname,
  11222. 'userphoto'=>$obj->user_photo,
  11223. 'msg_from'=>$obj->msg_from,
  11224. 'contact_id'=>$obj->fk_contact,
  11225. 'socpeopleassigned' => $contactaction->socpeopleassigned,
  11226. 'lastname' => (empty($obj->lastname) ? '' : $obj->lastname),
  11227. 'firstname' => (empty($obj->firstname) ? '' : $obj->firstname),
  11228. 'fk_element'=>$obj->fk_element,
  11229. 'elementtype'=>$obj->elementtype,
  11230. // Type of event
  11231. 'acode'=>$obj->acode,
  11232. 'alabel'=>$obj->alabel,
  11233. 'libelle'=>$obj->alabel, // deprecated
  11234. 'apicto'=>$obj->apicto
  11235. );
  11236. } else {
  11237. $histo[$numaction] = array(
  11238. 'type'=>$obj->type,
  11239. 'tododone'=>'done',
  11240. 'id'=>$obj->id,
  11241. 'datestart'=>$db->jdate($obj->dp),
  11242. 'dateend'=>$db->jdate($obj->dp2),
  11243. 'note'=>$obj->label,
  11244. 'message'=>$obj->message,
  11245. 'percent'=>$obj->percent,
  11246. 'acode'=>$obj->acode,
  11247. 'userid'=>$obj->user_id,
  11248. 'login'=>$obj->user_login,
  11249. 'userfirstname'=>$obj->user_firstname,
  11250. 'userlastname'=>$obj->user_lastname,
  11251. 'userphoto'=>$obj->user_photo
  11252. );
  11253. }
  11254. $numaction++;
  11255. $i++;
  11256. }
  11257. } else {
  11258. dol_print_error($db);
  11259. }
  11260. }
  11261. // Set $out to show events
  11262. $out = '';
  11263. if (!isModEnabled('agenda')) {
  11264. $langs->loadLangs(array("admin", "errors"));
  11265. $out = info_admin($langs->trans("WarningModuleXDisabledSoYouMayMissEventHere", $langs->transnoentitiesnoconv("Module2400Name")), 0, 0, 'warning');
  11266. }
  11267. if (isModEnabled('agenda') || (isModEnabled('mailing') && !empty($objcon->email))) {
  11268. $delay_warning = $conf->global->MAIN_DELAY_ACTIONS_TODO * 24 * 60 * 60;
  11269. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  11270. include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  11271. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  11272. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  11273. $formactions = new FormActions($db);
  11274. $actionstatic = new ActionComm($db);
  11275. $userstatic = new User($db);
  11276. $contactstatic = new Contact($db);
  11277. $userGetNomUrlCache = array();
  11278. $contactGetNomUrlCache = array();
  11279. $out .= '<div class="filters-container" >';
  11280. $out .= '<form name="listactionsfilter" class="listactionsfilter" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
  11281. $out .= '<input type="hidden" name="token" value="'.newToken().'">';
  11282. if ($objcon && get_class($objcon) == 'Contact' &&
  11283. (is_null($filterobj) || get_class($filterobj) == 'Societe')) {
  11284. $out .= '<input type="hidden" name="id" value="'.$objcon->id.'" />';
  11285. } else {
  11286. $out .= '<input type="hidden" name="id" value="'.$filterobj->id.'" />';
  11287. }
  11288. if ($filterobj && get_class($filterobj) == 'Societe') {
  11289. $out .= '<input type="hidden" name="socid" value="'.$filterobj->id.'" />';
  11290. }
  11291. $out .= "\n";
  11292. $out .= '<div class="div-table-responsive-no-min">';
  11293. $out .= '<table class="noborder borderbottom centpercent">';
  11294. $out .= '<tr class="liste_titre">';
  11295. $out .= getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', '', $param, '', $sortfield, $sortorder, '')."\n";
  11296. $out .= '<th class="liste_titre"><strong class="hideonsmartphone">'.$langs->trans("Search").' : </strong></th>';
  11297. if ($donetodo) {
  11298. $out .= '<th class="liste_titre"></th>';
  11299. }
  11300. $out .= '<th class="liste_titre">';
  11301. $out .= '<span class="fas fa-square inline-block fawidth30" style=" color: #ddd;" title="'.$langs->trans("ActionType").'"></span>';
  11302. //$out .= img_picto($langs->trans("Type"), 'type');
  11303. $out .= $formactions->select_type_actions($actioncode, "actioncode", '', empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : -1, 0, 0, 1, 'minwidth200imp');
  11304. $out .= '</th>';
  11305. $out .= '<th class="liste_titre maxwidth100onsmartphone">';
  11306. $out .= '<input type="text" class="maxwidth100onsmartphone" name="search_agenda_label" value="'.$filters['search_agenda_label'].'" placeholder="'.$langs->trans("Label").'">';
  11307. $out .= '</th>';
  11308. $out .= '<th class="liste_titre width50 middle">';
  11309. $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1);
  11310. $out .= $searchpicto;
  11311. $out .= '</th>';
  11312. $out .= '</tr>';
  11313. $out .= '</table>';
  11314. $out .= '</form>';
  11315. $out .= '</div>';
  11316. $out .= "\n";
  11317. $out .= '<ul class="timeline">';
  11318. if ($donetodo) {
  11319. $tmp = '';
  11320. if (get_class($filterobj) == 'Societe') {
  11321. $tmp .= '<a href="'.DOL_URL_ROOT.'/comm/action/list.php?mode=show_list&socid='.$filterobj->id.'&status=done">';
  11322. }
  11323. $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : '');
  11324. $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : '');
  11325. $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : '');
  11326. //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort");
  11327. if (get_class($filterobj) == 'Societe') {
  11328. $tmp .= '</a>';
  11329. }
  11330. $out .= getTitleFieldOfList($tmp);
  11331. }
  11332. //require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
  11333. //$caction=new CActionComm($db);
  11334. //$arraylist=$caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE)?1:0), '', 1);
  11335. $actualCycleDate = false;
  11336. // Loop on each event to show it
  11337. foreach ($histo as $key => $value) {
  11338. $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo
  11339. $actionstatic->type_picto = $histo[$key]['apicto'];
  11340. $actionstatic->type_code = $histo[$key]['acode'];
  11341. $url = DOL_URL_ROOT.'/comm/action/card.php?id='.$histo[$key]['id'];
  11342. $tmpa = dol_getdate($histo[$key]['datestart'], false);
  11343. if ($actualCycleDate !== $tmpa['year'].'-'.$tmpa['yday']) {
  11344. $actualCycleDate = $tmpa['year'].'-'.$tmpa['yday'];
  11345. $out .= '<!-- timeline time label -->';
  11346. $out .= '<li class="time-label">';
  11347. $out .= '<span class="timeline-badge-date">';
  11348. $out .= dol_print_date($histo[$key]['datestart'], 'daytext', 'tzuserrel', $langs);
  11349. $out .= '</span>';
  11350. $out .= '</li>';
  11351. $out .= '<!-- /.timeline-label -->';
  11352. }
  11353. $out .= '<!-- timeline item -->'."\n";
  11354. $out .= '<li class="timeline-code-'.strtolower($actionstatic->code).'">';
  11355. $out .= getTimelineIcon($actionstatic, $histo, $key);
  11356. $out .= '<div class="timeline-item">'."\n";
  11357. $out .= '<span class="timeline-header-action">';
  11358. if (isset($histo[$key]['type']) && $histo[$key]['type'] == 'mailing') {
  11359. $out .= '<a class="timeline-btn" href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11360. $out .= $histo[$key]['id'];
  11361. $out .= '</a> ';
  11362. } else {
  11363. $out .= $actionstatic->getNomUrl(1, -1, 'valignmiddle').' ';
  11364. }
  11365. if ($user->hasRight('agenda', 'allactions', 'create') ||
  11366. (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && !empty($user->rights->agenda->myactions->create))) {
  11367. $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>';
  11368. }
  11369. $out .= '</span>';
  11370. // Date
  11371. $out .= '<span class="time"><i class="fa fa-clock-o"></i> ';
  11372. $out .= dol_print_date($histo[$key]['datestart'], 'dayhour', 'tzuserrel');
  11373. if ($histo[$key]['dateend'] && $histo[$key]['dateend'] != $histo[$key]['datestart']) {
  11374. $tmpa = dol_getdate($histo[$key]['datestart'], true);
  11375. $tmpb = dol_getdate($histo[$key]['dateend'], true);
  11376. if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) {
  11377. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'hour', 'tzuserrel');
  11378. } else {
  11379. $out .= '-'.dol_print_date($histo[$key]['dateend'], 'dayhour', 'tzuserrel');
  11380. }
  11381. }
  11382. $late = 0;
  11383. if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11384. $late = 1;
  11385. }
  11386. if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11387. $late = 1;
  11388. }
  11389. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) {
  11390. $late = 1;
  11391. }
  11392. if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) {
  11393. $late = 1;
  11394. }
  11395. if ($late) {
  11396. $out .= img_warning($langs->trans("Late")).' ';
  11397. }
  11398. $out .= "</span>\n";
  11399. // Ref
  11400. $out .= '<h3 class="timeline-header">';
  11401. // Author of event
  11402. $out .= '<div class="messaging-author inline-block">';
  11403. if ($histo[$key]['userid'] > 0) {
  11404. if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ?
  11405. $userstatic->fetch($histo[$key]['userid']);
  11406. $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', '');
  11407. }
  11408. $out .= $userGetNomUrlCache[$histo[$key]['userid']];
  11409. } elseif (!empty($histo[$key]['msg_from']) && $actionstatic->code == 'TICKET_MSG') {
  11410. if (!isset($contactGetNomUrlCache[$histo[$key]['msg_from']])) {
  11411. if ($contactstatic->fetch(0, null, '', $histo[$key]['msg_from']) > 0) {
  11412. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $contactstatic->getNomUrl(-1, '', 16);
  11413. } else {
  11414. $contactGetNomUrlCache[$histo[$key]['msg_from']] = $histo[$key]['msg_from'];
  11415. }
  11416. }
  11417. $out .= $contactGetNomUrlCache[$histo[$key]['msg_from']];
  11418. }
  11419. $out .= '</div>';
  11420. // Title
  11421. $libelle = '';
  11422. $out .= ' <div class="messaging-title inline-block">';
  11423. if (preg_match('/^TICKET_MSG/', $actionstatic->code)) {
  11424. $out .= $langs->trans('TicketNewMessage');
  11425. } elseif (preg_match('/^TICKET_MSG_PRIVATE/', $actionstatic->code)) {
  11426. $out .= $langs->trans('TicketNewMessage').' <em>('.$langs->trans('Private').')</em>';
  11427. } elseif (isset($histo[$key]['type'])) {
  11428. if ($histo[$key]['type'] == 'action') {
  11429. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11430. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : $histo[$key]['alabel']);
  11431. $libelle = $histo[$key]['note'];
  11432. $actionstatic->id = $histo[$key]['id'];
  11433. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11434. } elseif ($histo[$key]['type'] == 'mailing') {
  11435. $out .= '<a href="'.DOL_URL_ROOT.'/comm/mailing/card.php?id='.$histo[$key]['id'].'">'.img_object($langs->trans("ShowEMailing"), "email").' ';
  11436. $transcode = $langs->transnoentitiesnoconv("Action".$histo[$key]['acode']);
  11437. $libelle = ($transcode != "Action".$histo[$key]['acode'] ? $transcode : 'Send mass mailing');
  11438. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11439. } else {
  11440. $libelle .= $histo[$key]['note'];
  11441. $out .= dol_escape_htmltag(dol_trunc($libelle, 120));
  11442. }
  11443. }
  11444. $out .= '</div>';
  11445. $out .= '</h3>';
  11446. if (!empty($histo[$key]['message'] && $histo[$key]['message'] != $libelle)
  11447. && $actionstatic->code != 'AC_TICKET_CREATE'
  11448. && $actionstatic->code != 'AC_TICKET_MODIFY'
  11449. ) {
  11450. $out .= '<div class="timeline-body">';
  11451. $out .= $histo[$key]['message'];
  11452. $out .= '</div>';
  11453. }
  11454. // Timeline footer
  11455. $footer = '';
  11456. // Contact for this action
  11457. if (isset($histo[$key]['socpeopleassigned']) && is_array($histo[$key]['socpeopleassigned']) && count($histo[$key]['socpeopleassigned']) > 0) {
  11458. $contactList = '';
  11459. foreach ($histo[$key]['socpeopleassigned'] as $cid => $Tab) {
  11460. $contact = new Contact($db);
  11461. $result = $contact->fetch($cid);
  11462. if ($result < 0) {
  11463. dol_print_error($db, $contact->error);
  11464. }
  11465. if ($result > 0) {
  11466. $contactList .= !empty($contactList) ? ', ' : '';
  11467. $contactList .= $contact->getNomUrl(1);
  11468. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11469. if (!empty($contact->phone_pro)) {
  11470. $contactList .= '('.dol_print_phone($contact->phone_pro).')';
  11471. }
  11472. }
  11473. }
  11474. }
  11475. $footer .= $langs->trans('ActionOnContact').' : '.$contactList;
  11476. } elseif (empty($objcon->id) && isset($histo[$key]['contact_id']) && $histo[$key]['contact_id'] > 0) {
  11477. $contact = new Contact($db);
  11478. $result = $contact->fetch($histo[$key]['contact_id']);
  11479. if ($result < 0) {
  11480. dol_print_error($db, $contact->error);
  11481. }
  11482. if ($result > 0) {
  11483. $footer .= $contact->getNomUrl(1);
  11484. if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') {
  11485. if (!empty($contact->phone_pro)) {
  11486. $footer .= '('.dol_print_phone($contact->phone_pro).')';
  11487. }
  11488. }
  11489. }
  11490. }
  11491. $documents = getActionCommEcmList($actionstatic);
  11492. if (!empty($documents)) {
  11493. $footer .= '<div class="timeline-documents-container">';
  11494. foreach ($documents as $doc) {
  11495. $footer .= '<span id="document_'.$doc->id.'" class="timeline-documents" ';
  11496. $footer .= ' data-id="'.$doc->id.'" ';
  11497. $footer .= ' data-path="'.$doc->filepath.'"';
  11498. $footer .= ' data-filename="'.dol_escape_htmltag($doc->filename).'" ';
  11499. $footer .= '>';
  11500. $filePath = DOL_DATA_ROOT.'/'.$doc->filepath.'/'.$doc->filename;
  11501. $mime = dol_mimetype($filePath);
  11502. $file = $actionstatic->id.'/'.$doc->filename;
  11503. $thumb = $actionstatic->id.'/thumbs/'.substr($doc->filename, 0, strrpos($doc->filename, '.')).'_mini'.substr($doc->filename, strrpos($doc->filename, '.'));
  11504. $doclink = dol_buildpath('document.php', 1).'?modulepart=actions&attachment=0&file='.urlencode($file).'&entity='.$conf->entity;
  11505. $viewlink = dol_buildpath('viewimage.php', 1).'?modulepart=actions&file='.urlencode($thumb).'&entity='.$conf->entity;
  11506. $mimeAttr = ' mime="'.$mime.'" ';
  11507. $class = '';
  11508. if (in_array($mime, array('image/png', 'image/jpeg', 'application/pdf'))) {
  11509. $class .= ' documentpreview';
  11510. }
  11511. $footer .= '<a href="'.$doclink.'" class="btn-link '.$class.'" target="_blank" rel="noopener noreferrer" '.$mimeAttr.' >';
  11512. $footer .= img_mime($filePath).' '.$doc->filename;
  11513. $footer .= '</a>';
  11514. $footer .= '</span>';
  11515. }
  11516. $footer .= '</div>';
  11517. }
  11518. if (!empty($footer)) {
  11519. $out .= '<div class="timeline-footer">'.$footer.'</div>';
  11520. }
  11521. $out .= '</div>'."\n"; // end timeline-item
  11522. $out .= '</li>';
  11523. $out .= '<!-- END timeline item -->';
  11524. $i++;
  11525. }
  11526. $out .= "</ul>\n";
  11527. if (empty($histo)) {
  11528. $out .= '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
  11529. }
  11530. }
  11531. if ($noprint) {
  11532. return $out;
  11533. } else {
  11534. print $out;
  11535. }
  11536. }
  11537. /**
  11538. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  11539. * optionally hour, minute, second) fields to return a timestamp.
  11540. *
  11541. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  11542. * @param string $hourTime 'getpost' to include hour, minute, second values from the HTTP request, 'XX:YY:ZZ' to set
  11543. * hour, minute, second respectively (for instance '23:59:59')
  11544. * @param string $gm Passed to dol_mktime
  11545. * @return int|string Date as a timestamp, '' or false if error
  11546. */
  11547. function GETPOSTDATE($prefix, $hourTime = '', $gm = 'auto')
  11548. {
  11549. if ($hourTime === 'getpost') {
  11550. $hour = GETPOSTINT($prefix . 'hour');
  11551. $minute = GETPOSTINT($prefix . 'minute');
  11552. $second = GETPOSTINT($prefix . 'second');
  11553. } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $hourTime, $m)) {
  11554. $hour = intval($m[1]);
  11555. $minute = intval($m[2]);
  11556. $second = intval($m[3]);
  11557. } else {
  11558. $hour = $minute = $second = 0;
  11559. }
  11560. // normalize out of range values
  11561. $hour = min($hour, 23);
  11562. $minute = min($minute, 59);
  11563. $second = min($second, 59);
  11564. return dol_mktime($hour, $minute, $second, GETPOSTINT($prefix . 'month'), GETPOSTINT($prefix . 'day'), GETPOSTINT($prefix . 'year'), $gm);
  11565. }
  11566. /**
  11567. * Helper function that combines values of a dolibarr DatePicker (such as Form::selectDate) for year, month, day (and
  11568. * optionally hour, minute, second) fields to return a a portion of URL reproducing the values from the current HTTP
  11569. * request.
  11570. *
  11571. * @param string $prefix Prefix used to build the date selector (for instance using Form::selectDate)
  11572. * @param int $timestamp If null, the timestamp will be created from request data
  11573. * @param bool $hourTime If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  11574. * @param bool $gm If timestamp is null, will be passed to GETPOSTDATE to construct the timestamp
  11575. * @return string Portion of URL with query parameters for the specified date
  11576. */
  11577. function buildParamDate($prefix, $timestamp = null, $hourTime = '', $gm = 'auto')
  11578. {
  11579. if ($timestamp === null) $timestamp = GETPOSTDATE($prefix, $hourTime, $gm);
  11580. $TParam = array(
  11581. $prefix . 'day' => intval(dol_print_date($timestamp, '%d')),
  11582. $prefix . 'month' => intval(dol_print_date($timestamp, '%m')),
  11583. $prefix . 'year' => intval(dol_print_date($timestamp, '%Y')),
  11584. );
  11585. if ($hourTime === 'getpost' || ($timestamp !== null && dol_print_date($timestamp, '%H:%M:%S') !== '00:00:00')) {
  11586. $TParam = array_merge($TParam, array(
  11587. $prefix . 'hour' => intval(dol_print_date($timestamp, '%H')),
  11588. $prefix . 'minute' => intval(dol_print_date($timestamp, '%M')),
  11589. $prefix . 'second' => intval(dol_print_date($timestamp, '%S'))
  11590. ));
  11591. }
  11592. return '&' . http_build_query($TParam);
  11593. }