functions.lib.php 379 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141
  1. <?php
  2. /* Copyright (C) 2000-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2018 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  6. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  7. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  8. * Copyright (C) 2005-2019 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2008 Raphael Bertrand (Resultic) <raphael.bertrand@resultic.fr>
  10. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  12. * Copyright (C) 2013-2017 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-2020 Frédéric France <frederic.france@netlogic.fr>
  17. * Copyright (C) 2019 Thibault Foucart <support@ptibogxiv.net>
  18. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  19. *
  20. * This program is free software; you can redistribute it and/or modify
  21. * it under the terms of the GNU General Public License as published by
  22. * the Free Software Foundation; either version 3 of the License, or
  23. * (at your option) any later version.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU General Public License
  31. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  32. * or see https://www.gnu.org/
  33. */
  34. /**
  35. * \file htdocs/core/lib/functions.lib.php
  36. * \brief A set of functions for Dolibarr
  37. * This file contains all frequently used functions.
  38. */
  39. include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
  40. /**
  41. * Return a DoliDB instance (database handler).
  42. *
  43. * @param string $type Type of database (mysql, pgsql...)
  44. * @param string $host Address of database server
  45. * @param string $user Authorized username
  46. * @param string $pass Password
  47. * @param string $name Name of database
  48. * @param int $port Port of database server
  49. * @return DoliDB A DoliDB instance
  50. */
  51. function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
  52. {
  53. require_once DOL_DOCUMENT_ROOT."/core/db/".$type.'.class.php';
  54. $class = 'DoliDB'.ucfirst($type);
  55. $dolidb = new $class($type, $host, $user, $pass, $name, $port);
  56. return $dolidb;
  57. }
  58. /**
  59. * Get list of entity id to use.
  60. *
  61. * @param string $element Current element
  62. * 'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
  63. * 'product', 'productprice', 'stock', 'bom', 'mo',
  64. * 'propal', 'supplier_proposal', 'invoice', 'supplier_invoice', 'payment_various',
  65. * 'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
  66. * 'commande', 'supplier_order', 'expedition', 'intervention', 'survey',
  67. * 'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
  68. * 'email_template', 'event', 'donation'
  69. * 'c_paiement', 'c_payment_term', ...
  70. * @param int $shared 0=Return id of current entity only,
  71. * 1=Return id of current entity + shared entities (default)
  72. * @param object $currentobject Current object if needed
  73. * @return mixed Entity id(s) to use ( eg. entity IN ('.getEntity(elementname).')' )
  74. */
  75. function getEntity($element, $shared = 1, $currentobject = null)
  76. {
  77. global $conf, $mc;
  78. // fix different element names (France to English)
  79. switch ($element) {
  80. case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php"
  81. case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php"
  82. }
  83. if (is_object($mc))
  84. {
  85. return $mc->getEntity($element, $shared, $currentobject);
  86. } else {
  87. $out = '';
  88. $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
  89. if (in_array($element, $addzero)) $out .= '0,';
  90. $out .= ((int) $conf->entity);
  91. return $out;
  92. }
  93. }
  94. /**
  95. * Set entity id to use when to create an object
  96. *
  97. * @param object $currentobject Current object
  98. * @return mixed Entity id to use ( eg. entity = '.setEntity($object) )
  99. */
  100. function setEntity($currentobject)
  101. {
  102. global $conf, $mc;
  103. if (is_object($mc) && method_exists($mc, 'setEntity'))
  104. {
  105. return $mc->setEntity($currentobject);
  106. } else {
  107. return ((is_object($currentobject) && $currentobject->id > 0 && $currentobject->entity > 0) ? $currentobject->entity : $conf->entity);
  108. }
  109. }
  110. /**
  111. * Return if string has a name dedicated to store a secret
  112. *
  113. * @param string $keyname Name of key to test
  114. * @return boolean True if key is used to store a secret
  115. */
  116. function isASecretKey($keyname)
  117. {
  118. return preg_match('/(_pass|password|_pw|_key|securekey|serverkey|secret\d?|p12key|exportkey|_PW_[a-z]+|token)$/i', $keyname);
  119. }
  120. /**
  121. * Return information about user browser
  122. *
  123. * Returns array with the following format:
  124. * array(
  125. * 'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
  126. * 'browserversion' => Browser version. Empty if unknown
  127. * 'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
  128. * 'layout' => (tablet|phone|classic)
  129. * 'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
  130. * 'tablet' => true/false
  131. * )
  132. *
  133. * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
  134. * @return array Check function documentation
  135. */
  136. function getBrowserInfo($user_agent)
  137. {
  138. include_once DOL_DOCUMENT_ROOT.'/includes/mobiledetect/mobiledetectlib/Mobile_Detect.php';
  139. $name = 'unknown';
  140. $version = '';
  141. $os = 'unknown';
  142. $phone = '';
  143. $detectmobile = new Mobile_Detect(null, $user_agent);
  144. $tablet = $detectmobile->isTablet();
  145. if ($detectmobile->isMobile()) {
  146. $phone = 'unknown';
  147. // If phone/smartphone, we set phone os name.
  148. if ($detectmobile->is('AndroidOS')) {
  149. $os = $phone = 'android';
  150. } elseif ($detectmobile->is('BlackBerryOS')) {
  151. $os = $phone = 'blackberry';
  152. } elseif ($detectmobile->is('iOS')) {
  153. $os = 'ios';
  154. $phone = 'iphone';
  155. } elseif ($detectmobile->is('PalmOS')) {
  156. $os = $phone = 'palm';
  157. } elseif ($detectmobile->is('SymbianOS')) {
  158. $os = 'symbian';
  159. } elseif ($detectmobile->is('webOS')) {
  160. $os = 'webos';
  161. } elseif ($detectmobile->is('MaemoOS')) {
  162. $os = 'maemo';
  163. } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
  164. $os = 'windows';
  165. }
  166. }
  167. // OS
  168. if (preg_match('/linux/i', $user_agent)) { $os = 'linux'; } elseif (preg_match('/macintosh/i', $user_agent)) { $os = 'macintosh'; } elseif (preg_match('/windows/i', $user_agent)) { $os = 'windows'; }
  169. // Name
  170. $reg = array();
  171. if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'firefox'; $version = $reg[2]; } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'edge'; $version = $reg[2]; } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) { $name = 'chrome'; $version = $reg[2]; } // we can have 'chrome (Mozilla...) chrome x.y' in one string
  172. elseif (preg_match('/chrome/i', $user_agent, $reg)) { $name = 'chrome'; } elseif (preg_match('/iceweasel/i', $user_agent)) { $name = 'iceweasel'; } elseif (preg_match('/epiphany/i', $user_agent)) { $name = 'epiphany'; } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'safari'; $version = $reg[2]; } // Safari is often present in string for mobile but its not.
  173. elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) { $name = 'opera'; $version = $reg[2]; } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end
  174. elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) { $name = 'ie'; $version = end($reg); } // MS products at end
  175. elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) { $name = 'lynxlinks'; $version = $reg[4]; }
  176. if ($tablet) {
  177. $layout = 'tablet';
  178. } elseif ($phone) {
  179. $layout = 'phone';
  180. } else {
  181. $layout = 'classic';
  182. }
  183. return array(
  184. 'browsername' => $name,
  185. 'browserversion' => $version,
  186. 'browseros' => $os,
  187. 'layout' => $layout,
  188. 'phone' => $phone,
  189. 'tablet' => $tablet
  190. );
  191. }
  192. /**
  193. * Function called at end of web php process
  194. *
  195. * @return void
  196. */
  197. function dol_shutdown()
  198. {
  199. global $conf, $user, $langs, $db;
  200. $disconnectdone = false; $depth = 0;
  201. if (is_object($db) && !empty($db->connected)) { $depth = $db->transaction_opened; $disconnectdone = $db->close(); }
  202. dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ?LOG_WARNING:LOG_INFO));
  203. }
  204. /**
  205. * Return true if we are in a context of submitting the parameter $paramname
  206. *
  207. * @param string $paramname Name or parameter to test
  208. * @return boolean True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
  209. */
  210. function GETPOSTISSET($paramname)
  211. {
  212. $isset = false;
  213. $relativepathstring = $_SERVER["PHP_SELF"];
  214. // Clean $relativepathstring
  215. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  216. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  217. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  218. //var_dump($relativepathstring);
  219. //var_dump($user->default_values);
  220. // Code for search criteria persistence.
  221. // Retrieve values if restore_lastsearch_values
  222. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  223. {
  224. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  225. {
  226. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  227. if (is_array($tmp))
  228. {
  229. foreach ($tmp as $key => $val)
  230. {
  231. if ($key == $paramname) // We are on the requested parameter
  232. {
  233. $isset = true;
  234. break;
  235. }
  236. }
  237. }
  238. }
  239. // If there is saved contextpage, page or limit
  240. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  241. {
  242. $isset = true;
  243. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  244. {
  245. $isset = true;
  246. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  247. {
  248. $isset = true;
  249. }
  250. } else {
  251. $isset = (isset($_POST[$paramname]) || isset($_GET[$paramname])); // We must keep $_POST and $_GET here
  252. }
  253. return $isset;
  254. }
  255. /**
  256. * Return value of a param into GET or POST supervariable.
  257. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  258. * Note: The property $user->default_values is loaded by main.php when loading the user.
  259. *
  260. * @param string $paramname Name of parameter to found
  261. * @param string $check Type of check
  262. * ''=no check (deprecated)
  263. * 'none'=no check (only for param that should have very rich content)
  264. * 'array', 'array:restricthtml' or 'array:aZ09' to check it's an array
  265. * 'int'=check it's numeric (integer or float)
  266. * 'intcomma'=check it's integer+comma ('1,2,3,4...')
  267. * 'alpha'=Same than alphanohtml since v13
  268. * 'alphanohtml'=check there is no html content and no " and no ../
  269. * 'aZ'=check it's a-z only
  270. * 'aZ09'=check it's simple alpha string (recommended for keys)
  271. * 'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
  272. * 'nohtml'=check there is no html content and no " and no ../
  273. * 'restricthtml'=check html content is restricted to some tags only
  274. * 'custom'= custom filter specify $filter and $options)
  275. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  276. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  277. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  278. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  279. * @return string|array Value found (string or array), or '' if check fails
  280. */
  281. function GETPOST($paramname, $check = 'alphanohtml', $method = 0, $filter = null, $options = null, $noreplace = 0)
  282. {
  283. global $mysoc, $user, $conf;
  284. if (empty($paramname)) return 'BadFirstParameterForGETPOST';
  285. if (empty($check))
  286. {
  287. dol_syslog("Deprecated use of GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  288. // Enable this line to know who call the GETPOST with '' $check parameter.
  289. //var_dump(debug_backtrace()[0]);
  290. }
  291. if (empty($method)) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
  292. elseif ($method == 1) $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
  293. elseif ($method == 2) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
  294. elseif ($method == 3) $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
  295. else return 'BadThirdParameterForGETPOST';
  296. if (empty($method) || $method == 3 || $method == 4)
  297. {
  298. $relativepathstring = $_SERVER["PHP_SELF"];
  299. // Clean $relativepathstring
  300. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  301. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  302. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  303. //var_dump($relativepathstring);
  304. //var_dump($user->default_values);
  305. // Code for search criteria persistence.
  306. // Retrieve values if restore_lastsearch_values
  307. if (!empty($_GET['restore_lastsearch_values'])) // Use $_GET here and not GETPOST
  308. {
  309. if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) // If there is saved values
  310. {
  311. $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
  312. if (is_array($tmp))
  313. {
  314. foreach ($tmp as $key => $val)
  315. {
  316. if ($key == $paramname) // We are on the requested parameter
  317. {
  318. $out = $val;
  319. break;
  320. }
  321. }
  322. }
  323. }
  324. // If there is saved contextpage, page or limit
  325. if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring]))
  326. {
  327. $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
  328. } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring]))
  329. {
  330. $out = $_SESSION['lastsearch_page_'.$relativepathstring];
  331. } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring]))
  332. {
  333. $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
  334. }
  335. } // Else, retrieve default values if we are not doing a sort
  336. elseif (!isset($_GET['sortfield'])) // 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
  337. {
  338. if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  339. {
  340. // Search default value from $object->field
  341. global $object;
  342. if (is_object($object) && isset($object->fields[$paramname]['default']))
  343. {
  344. $out = $object->fields[$paramname]['default'];
  345. }
  346. }
  347. if (!empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES))
  348. {
  349. if (!empty($_GET['action']) && (preg_match('/^create/', $_GET['action']) || preg_match('/^presend/', $_GET['action'])) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  350. {
  351. // Now search in setup to overwrite default values
  352. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  353. {
  354. if (isset($user->default_values[$relativepathstring]['createform']))
  355. {
  356. foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval)
  357. {
  358. $qualified = 0;
  359. if ($defkey != '_noquery_')
  360. {
  361. $tmpqueryarraytohave = explode('&', $defkey);
  362. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  363. $foundintru = 0;
  364. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  365. {
  366. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  367. }
  368. if (!$foundintru) $qualified = 1;
  369. //var_dump($defkey.'-'.$qualified);
  370. } else $qualified = 1;
  371. if ($qualified)
  372. {
  373. if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname]))
  374. {
  375. $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
  376. break;
  377. }
  378. }
  379. }
  380. }
  381. }
  382. } // Management of default search_filters and sort order
  383. elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname]))
  384. {
  385. if (!empty($user->default_values)) // $user->default_values defined from menu 'Setup - Default values'
  386. {
  387. //var_dump($user->default_values[$relativepathstring]);
  388. if ($paramname == 'sortfield' || $paramname == 'sortorder') // Sorted on which fields ? ASC or DESC ?
  389. {
  390. if (isset($user->default_values[$relativepathstring]['sortorder'])) // Even if paramname is sortfield, data are stored into ['sortorder...']
  391. {
  392. foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval)
  393. {
  394. $qualified = 0;
  395. if ($defkey != '_noquery_')
  396. {
  397. $tmpqueryarraytohave = explode('&', $defkey);
  398. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  399. $foundintru = 0;
  400. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  401. {
  402. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  403. }
  404. if (!$foundintru) $qualified = 1;
  405. //var_dump($defkey.'-'.$qualified);
  406. } else $qualified = 1;
  407. if ($qualified)
  408. {
  409. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  410. foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val)
  411. {
  412. if ($out) $out .= ', ';
  413. if ($paramname == 'sortfield')
  414. {
  415. $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
  416. }
  417. if ($paramname == 'sortorder')
  418. {
  419. $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
  420. }
  421. }
  422. //break; // No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
  423. }
  424. }
  425. }
  426. } elseif (isset($user->default_values[$relativepathstring]['filters']))
  427. {
  428. foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) // $defkey is a querystring like 'a=b&c=d', $defval is key of user
  429. {
  430. $qualified = 0;
  431. if ($defkey != '_noquery_')
  432. {
  433. $tmpqueryarraytohave = explode('&', $defkey);
  434. $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  435. $foundintru = 0;
  436. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  437. {
  438. if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) $foundintru = 1;
  439. }
  440. if (!$foundintru) $qualified = 1;
  441. //var_dump($defkey.'-'.$qualified);
  442. } else $qualified = 1;
  443. if ($qualified)
  444. {
  445. // We must keep $_POST and $_GET here
  446. if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all']))
  447. {
  448. // We made a search from quick search menu, do we still use default filter ?
  449. if (empty($conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH))
  450. {
  451. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  452. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  453. }
  454. } else {
  455. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
  456. $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
  457. }
  458. break;
  459. }
  460. }
  461. }
  462. }
  463. }
  464. }
  465. }
  466. }
  467. // Substitution variables for GETPOST (used to get final url with variable parameters or final default value with variable parameters)
  468. // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
  469. // 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.
  470. if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace))
  471. {
  472. $reg = array();
  473. $maxloop = 20; $loopnb = 0; // Protection against infinite loop
  474. 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.
  475. {
  476. $loopnb++; $newout = '';
  477. if ($reg[1] == 'DAY') {
  478. $tmp = dol_getdate(dol_now(), true);
  479. $newout = $tmp['mday'];
  480. } elseif ($reg[1] == 'MONTH') {
  481. $tmp = dol_getdate(dol_now(), true);
  482. $newout = $tmp['mon'];
  483. } elseif ($reg[1] == 'YEAR') {
  484. $tmp = dol_getdate(dol_now(), true);
  485. $newout = $tmp['year'];
  486. } elseif ($reg[1] == 'PREVIOUS_DAY') {
  487. $tmp = dol_getdate(dol_now(), true);
  488. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  489. $newout = $tmp2['day'];
  490. } elseif ($reg[1] == 'PREVIOUS_MONTH') {
  491. $tmp = dol_getdate(dol_now(), true);
  492. $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  493. $newout = $tmp2['month'];
  494. } elseif ($reg[1] == 'PREVIOUS_YEAR') {
  495. $tmp = dol_getdate(dol_now(), true);
  496. $newout = ($tmp['year'] - 1);
  497. } elseif ($reg[1] == 'NEXT_DAY') {
  498. $tmp = dol_getdate(dol_now(), true);
  499. $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  500. $newout = $tmp2['day'];
  501. } elseif ($reg[1] == 'NEXT_MONTH') {
  502. $tmp = dol_getdate(dol_now(), true);
  503. $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
  504. $newout = $tmp2['month'];
  505. } elseif ($reg[1] == 'NEXT_YEAR') {
  506. $tmp = dol_getdate(dol_now(), true);
  507. $newout = ($tmp['year'] + 1);
  508. } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
  509. $newout = $mysoc->country_id;
  510. } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
  511. $newout = $user->id;
  512. } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
  513. $newout = $user->fk_user;
  514. } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
  515. $newout = $conf->entity;
  516. } else {
  517. $newout = ''; // Key not found, we replace with empty string
  518. }
  519. //var_dump('__'.$reg[1].'__ -> '.$newout);
  520. $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
  521. }
  522. }
  523. // Check rule
  524. if (preg_match('/^array/', $check)) { // If 'array' or 'array:restricthtml' or 'array:aZ09'
  525. if (!is_array($out) || empty($out)) {
  526. $out = array();
  527. } else {
  528. $tmparray = explode(':', $check);
  529. if (!empty($tmparray[1])) {
  530. $tmpcheck = $tmparray[1];
  531. } else {
  532. $tmpcheck = 'alphanohtml';
  533. }
  534. foreach ($out as $outkey => $outval) {
  535. $out[$outkey] = checkVal($outval, $tmpcheck, $filter, $options);
  536. }
  537. }
  538. }
  539. else {
  540. $out = checkVal($out, $check, $filter, $options);
  541. }
  542. // Sanitizing for special parameters. There is no reason to allow the backtopage parameter to contains an external URL.
  543. if ($paramname == 'backtopage') {
  544. $out = str_replace('\\', '/', $out);
  545. $out = preg_replace(array('/^\/\/+/', '/^[a-z]*:/i'), '', $out);
  546. }
  547. // Code for search criteria persistence.
  548. // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
  549. if (empty($method) || $method == 3 || $method == 4)
  550. {
  551. if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield')))
  552. {
  553. //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
  554. // We save search key only if $out not empty that means:
  555. // - posted value not empty, or
  556. // - 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).
  557. if ($out != '') // $out = '0' or 'abc', it is a search criteria to keep
  558. {
  559. $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
  560. }
  561. }
  562. }
  563. return $out;
  564. }
  565. /**
  566. * Return value of a param into GET or POST supervariable.
  567. * Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
  568. * Note: The property $user->default_values is loaded by main.php when loading the user.
  569. *
  570. * @param string $paramname Name of parameter to found
  571. * @param int $method Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get)
  572. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  573. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  574. * @param string $noreplace Force disable of replacement of __xxx__ strings.
  575. * @return int Value found (int)
  576. */
  577. function GETPOSTINT($paramname, $method = 0, $filter = null, $options = null, $noreplace = 0)
  578. {
  579. return (int) GETPOST($paramname, 'int', $method, $filter, $options, $noreplace);
  580. }
  581. /**
  582. * Return a value after checking on a rule.
  583. *
  584. * @param string $out Value to get/check
  585. * @param string $check Type of check
  586. * @param int $filter Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
  587. * @param mixed $options Options to pass to filter_var when $check is set to 'custom'
  588. * @return string|array Value found (string or array), or '' if check fails
  589. */
  590. function checkVal($out = '', $check = 'alphanohtml', $filter = null, $options = null)
  591. {
  592. // Check is done after replacement
  593. switch ($check)
  594. {
  595. case 'none':
  596. break;
  597. case 'int': // Check param is a numeric value (integer but also float or hexadecimal)
  598. if (!is_numeric($out)) { $out = ''; }
  599. break;
  600. case 'intcomma':
  601. if (preg_match('/[^0-9,-]+/i', $out)) $out = '';
  602. break;
  603. case 'san_alpha':
  604. $out = filter_var($out, FILTER_SANITIZE_STRING);
  605. break;
  606. case 'email':
  607. $out = filter_var($out, FILTER_SANITIZE_EMAIL);
  608. break;
  609. case 'aZ':
  610. if (!is_array($out))
  611. {
  612. $out = trim($out);
  613. if (preg_match('/[^a-z]+/i', $out)) $out = '';
  614. }
  615. break;
  616. case 'aZ09':
  617. if (!is_array($out))
  618. {
  619. $out = trim($out);
  620. if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) $out = '';
  621. }
  622. break;
  623. case 'aZ09comma': // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
  624. if (!is_array($out))
  625. {
  626. $out = trim($out);
  627. if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) $out = '';
  628. }
  629. break;
  630. case 'nohtml':
  631. $out = dol_string_nohtmltag($out, 0);
  632. break;
  633. case 'alpha': // No html and no " and no ../
  634. case 'alphanohtml': // Recommended for most scalar parameters and search parameters
  635. if (!is_array($out)) {
  636. // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
  637. // '../' is dangerous because it allows dir transversals
  638. $out = str_replace(array('&quot;', '"', '../'), '', trim($out));
  639. // keep lines feed
  640. $out = dol_string_nohtmltag($out, 0);
  641. }
  642. break;
  643. case 'restricthtml': // Recommended for most html textarea
  644. $out = dol_string_onlythesehtmltags($out, 0, 1, 1);
  645. break;
  646. case 'custom':
  647. if (empty($filter)) return 'BadFourthParameterForGETPOST';
  648. $out = filter_var($out, $filter, $options);
  649. break;
  650. }
  651. return $out;
  652. }
  653. if (!function_exists('dol_getprefix'))
  654. {
  655. /**
  656. * Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
  657. * The prefix is unique for instance and avoid conflict between multi-instances, even when having two instances with same root dir
  658. * or two instances in same virtual servers.
  659. *
  660. * @param string $mode '' (prefix for session name) or 'email' (prefix for email id)
  661. * @return string A calculated prefix
  662. */
  663. function dol_getprefix($mode = '')
  664. {
  665. global $conf;
  666. // If prefix is for email
  667. if ($mode == 'email')
  668. {
  669. if (!empty($conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
  670. {
  671. if ($conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') return $conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
  672. elseif (isset($_SERVER["SERVER_NAME"])) return $_SERVER["SERVER_NAME"];
  673. }
  674. // The recommended value (may be not defined for old versions)
  675. if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id;
  676. // For backward compatibility
  677. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  678. }
  679. // The recommended value (may be not defined for old versions)
  680. if (!empty($conf->file->instance_unique_id)) return $conf->file->instance_unique_id;
  681. // For backward compatibility
  682. if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"]))
  683. {
  684. return dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  685. }
  686. return dol_hash(DOL_DOCUMENT_ROOT.DOL_URL_ROOT, '3');
  687. }
  688. }
  689. /**
  690. * Make an include_once using default root and alternate root if it fails.
  691. * To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
  692. * To link to a module file from a module file, use include './mymodulefile';
  693. * To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
  694. *
  695. * @param string $relpath Relative path to file (Ie: mydir/myfile, ../myfile, ...)
  696. * @param string $classname Class name (deprecated)
  697. * @return bool True if load is a success, False if it fails
  698. */
  699. function dol_include_once($relpath, $classname = '')
  700. {
  701. 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']
  702. $fullpath = dol_buildpath($relpath);
  703. if (!file_exists($fullpath)) {
  704. dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_WARNING);
  705. return false;
  706. }
  707. if (!empty($classname) && !class_exists($classname)) {
  708. return include $fullpath;
  709. } else {
  710. return include_once $fullpath;
  711. }
  712. }
  713. /**
  714. * Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
  715. *
  716. * @param string $path Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
  717. * @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)
  718. * @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)
  719. * 1:If $type==0 and if file was not found into alternate dir, return empty string
  720. * 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
  721. * @return string Full filesystem path (if path=0) or '' if file not found, Full url path (if mode=1)
  722. */
  723. function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
  724. {
  725. global $conf;
  726. $path = preg_replace('/^\//', '', $path);
  727. if (empty($type)) // For a filesystem path
  728. {
  729. $res = DOL_DOCUMENT_ROOT.'/'.$path; // Standard default path
  730. if (is_array($conf->file->dol_document_root))
  731. {
  732. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array("main"=>"/home/main/htdocs", "alt0"=>"/home/dirmod/htdocs", ...)
  733. {
  734. if ($key == 'main')
  735. {
  736. continue;
  737. }
  738. if (file_exists($dirroot.'/'.$path))
  739. {
  740. $res = $dirroot.'/'.$path;
  741. return $res;
  742. }
  743. }
  744. }
  745. if ($returnemptyifnotfound) // Not found into alternate dir
  746. {
  747. if ($returnemptyifnotfound == 1 || !file_exists($res)) return '';
  748. }
  749. } else // For an url path
  750. {
  751. // We try to get local path of file on filesystem from url
  752. // Note that trying to know if a file on disk exist by forging path on disk from url
  753. // works only for some web server and some setup. This is bugged when
  754. // using proxy, rewriting, virtual path, etc...
  755. $res = '';
  756. if ($type == 1) $res = DOL_URL_ROOT.'/'.$path; // Standard value
  757. if ($type == 2) $res = DOL_MAIN_URL_ROOT.'/'.$path; // Standard value
  758. if ($type == 3) $res = DOL_URL_ROOT.'/'.$path;
  759. foreach ($conf->file->dol_document_root as $key => $dirroot) // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
  760. {
  761. if ($key == 'main')
  762. {
  763. if ($type == 3)
  764. {
  765. global $dolibarr_main_url_root;
  766. // Define $urlwithroot
  767. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  768. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  769. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  770. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
  771. }
  772. continue;
  773. }
  774. preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
  775. if (!empty($regs[1]))
  776. {
  777. //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
  778. if (file_exists($dirroot.'/'.$regs[1]))
  779. {
  780. if ($type == 1)
  781. {
  782. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  783. }
  784. if ($type == 2)
  785. {
  786. $res = (preg_match('/^http/i', $conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).$conf->file->dol_url_root[$key].'/'.$path;
  787. }
  788. if ($type == 3)
  789. {
  790. global $dolibarr_main_url_root;
  791. // Define $urlwithroot
  792. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  793. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  794. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  795. $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
  796. }
  797. break;
  798. }
  799. }
  800. }
  801. }
  802. return $res;
  803. }
  804. /**
  805. * Create a clone of instance of object (new instance with same value for properties)
  806. * With native = 0: Property that are reference are also new object (full isolation clone). This means $this->db of new object is not valid.
  807. * 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.
  808. *
  809. * @param object $object Object to clone
  810. * @param int $native 0=Full isolation method, 1=Native PHP method
  811. * @return object Clone object
  812. * @see https://php.net/manual/language.oop5.cloning.php
  813. */
  814. function dol_clone($object, $native = 0)
  815. {
  816. if (empty($native))
  817. {
  818. $myclone = unserialize(serialize($object));
  819. } else {
  820. $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)
  821. }
  822. return $myclone;
  823. }
  824. /**
  825. * Optimize a size for some browsers (phone, smarphone, ...)
  826. *
  827. * @param int $size Size we want
  828. * @param string $type Type of optimizing:
  829. * '' = function used to define a size for truncation
  830. * 'width' = function is used to define a width
  831. * @return int New size after optimizing
  832. */
  833. function dol_size($size, $type = '')
  834. {
  835. global $conf;
  836. if (empty($conf->dol_optimize_smallscreen)) return $size;
  837. if ($type == 'width' && $size > 250) return 250;
  838. else return 10;
  839. }
  840. /**
  841. * Clean a string to use it as a file name
  842. *
  843. * @param string $str String to clean
  844. * @param string $newstr String to replace bad chars with
  845. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  846. * @return string String cleaned (a-zA-Z_)
  847. *
  848. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizePathName()
  849. */
  850. function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
  851. {
  852. // List of special chars for filenames in windows are defined on page https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file
  853. // Char '>' '<' '|' '$' and ';' are special chars for shells.
  854. // Char '/' and '\' are file delimiters.
  855. $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', ':', '°', '$', ';');
  856. return dol_string_nospecial($unaccent ?dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  857. }
  858. /**
  859. * Clean a string to use it as a path name
  860. *
  861. * @param string $str String to clean
  862. * @param string $newstr String to replace bad chars with
  863. * @param int $unaccent 1=Remove also accent (default), 0 do not remove them
  864. * @return string String cleaned (a-zA-Z_)
  865. *
  866. * @see dol_string_nospecial(), dol_string_unaccent(), dol_sanitizeFileName()
  867. */
  868. function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
  869. {
  870. $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°');
  871. return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
  872. }
  873. /**
  874. * Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
  875. *
  876. * @param string $str String to clean
  877. * @return string Cleaned string
  878. *
  879. * @see dol_sanitizeFilename(), dol_string_nospecial()
  880. */
  881. function dol_string_unaccent($str)
  882. {
  883. if (utf8_check($str))
  884. {
  885. // See http://www.utf8-chartable.de/
  886. $string = rawurlencode($str);
  887. $replacements = array(
  888. '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
  889. '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
  890. '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
  891. '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
  892. '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
  893. '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
  894. '%C3%A7' => 'c',
  895. '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
  896. '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
  897. '%C3%B1' => 'n',
  898. '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
  899. '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
  900. '%C3%BF' => 'y'
  901. );
  902. $string = strtr($string, $replacements);
  903. return rawurldecode($string);
  904. } else {
  905. // See http://www.ascii-code.com/
  906. $string = strtr(
  907. $str,
  908. "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
  909. \xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
  910. \xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
  911. \xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
  912. \xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
  913. \xF9\xFA\xFB\xFC\xFD\xFF",
  914. "AAAAAAC
  915. EEEEIIIIDN
  916. OOOOOUUUY
  917. aaaaaaceeee
  918. iiiidnooooo
  919. uuuuyy"
  920. );
  921. $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"));
  922. return $string;
  923. }
  924. }
  925. /**
  926. * Clean a string from all punctuation characters to use it as a ref or login.
  927. * This is a more complete function than dol_sanitizeFileName.
  928. *
  929. * @param string $str String to clean
  930. * @param string $newstr String to replace forbidden chars with
  931. * @param array $badcharstoreplace List of forbidden characters
  932. * @return string Cleaned string
  933. *
  934. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nounprintableascii()
  935. */
  936. function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
  937. {
  938. $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
  939. $forbidden_chars_to_remove = array();
  940. if (is_array($badcharstoreplace)) $forbidden_chars_to_replace = $badcharstoreplace;
  941. //$forbidden_chars_to_remove=array("(",")");
  942. return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
  943. }
  944. /**
  945. * Clean a string from all non printable ASCII chars (0x00-0x1F and 0x7F). It can also removes also Tab-CR-LF. UTF8 chars remains.
  946. * This can be used to sanitize a string and view its real content. Some hacks try to obfuscate attacks by inserting non printable chars.
  947. * Note, for information: UTF8 on 1 byte are: \x00-\7F
  948. * 2 bytes are: byte 1 \xc0-\xdf, byte 2 = \x80-\xbf
  949. * 3 bytes are: byte 1 \xe0-\xef, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf
  950. * 4 bytes are: byte 1 \xf0-\xf7, byte 2 = \x80-\xbf, byte 3 = \x80-\xbf, byte 4 = \x80-\xbf
  951. * @param string $str String to clean
  952. * @param int $removetabcrlf Remove also CR-LF
  953. * @return string Cleaned string
  954. *
  955. * @see dol_sanitizeFilename(), dol_string_unaccent(), dol_string_nospecial()
  956. */
  957. function dol_string_nounprintableascii($str, $removetabcrlf = 1)
  958. {
  959. if ($removetabcrlf) {
  960. return preg_replace('/[\x00-\x1F\x7F]/u', '', $str); // /u operator makes UTF8 valid characters being ignored so are not included into the replace
  961. } else {
  962. 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
  963. }
  964. }
  965. /**
  966. * Returns text escaped for inclusion into javascript code
  967. *
  968. * @param string $stringtoescape String to escape
  969. * @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 \
  970. * @param int $noescapebackslashn 0=Escape also \n. 1=Do not escape \n.
  971. * @return string Escaped string. Both ' and " are escaped into ' if they are escaped.
  972. */
  973. function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
  974. {
  975. // escape quotes and backslashes, newlines, etc.
  976. $substitjs = array("&#039;"=>"\\'", "\r"=>'\\r');
  977. //$substitjs['</']='<\/'; // We removed this. Should be useless.
  978. if (empty($noescapebackslashn)) { $substitjs["\n"] = '\\n'; $substitjs['\\'] = '\\\\'; }
  979. if (empty($mode)) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\'"; } elseif ($mode == 1) $substitjs["'"] = "\\'";
  980. elseif ($mode == 2) { $substitjs['"'] = '\\"'; } elseif ($mode == 3) { $substitjs["'"] = "\\'"; $substitjs['"'] = "\\\""; }
  981. return strtr($stringtoescape, $substitjs);
  982. }
  983. /**
  984. * Returns text escaped for inclusion into javascript code
  985. *
  986. * @param string $stringtoescape String to escape
  987. * @return string Escaped string for json content.
  988. */
  989. function dol_escape_json($stringtoescape)
  990. {
  991. return str_replace('"', '\"', $stringtoescape);
  992. }
  993. /**
  994. * Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
  995. *
  996. * @param string $stringtoescape String to escape
  997. * @param int $keepb 1=Keep b tags and escape them, 0=remove them
  998. * @param int $keepn 1=Preserve \r\n strings (otherwise, replace them with escaped value). Set to 1 when escaping for a <textarea>.
  999. * @param string $keepmoretags '' or 'common' or list of tags
  1000. * @param int $escapeonlyhtmltags 1=Escape only html tags, not the special chars like accents.
  1001. * @return string Escaped string
  1002. * @see dol_string_nohtmltag(), dol_string_nospecial(), dol_string_unaccent()
  1003. */
  1004. function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0, $keepmoretags = '', $escapeonlyhtmltags = 0)
  1005. {
  1006. if ($keepmoretags == 'common') $keepmoretags = 'html,body,a,b,em,i,u,ul,li,br,div,img,font,p,span,strong,table,tr,td,th,tbody';
  1007. // TODO Implement $keepmoretags
  1008. // escape quotes and backslashes, newlines, etc.
  1009. if ($escapeonlyhtmltags) {
  1010. $tmp = htmlspecialchars_decode($stringtoescape, ENT_COMPAT);
  1011. } else {
  1012. $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');
  1013. }
  1014. if (!$keepb) $tmp = strtr($tmp, array("<b>"=>'', '</b>'=>''));
  1015. if (!$keepn) $tmp = strtr($tmp, array("\r"=>'\\r', "\n"=>'\\n'));
  1016. if ($escapeonlyhtmltags) {
  1017. return htmlspecialchars($tmp, ENT_COMPAT, 'UTF-8');
  1018. } else {
  1019. return htmlentities($tmp, ENT_COMPAT, 'UTF-8');
  1020. }
  1021. }
  1022. /**
  1023. * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
  1024. *
  1025. * @param string $string String to encode
  1026. * @param string $encoding Character set encoding
  1027. * @return string String converted
  1028. */
  1029. function dol_strtolower($string, $encoding = "UTF-8")
  1030. {
  1031. if (function_exists('mb_strtolower')) {
  1032. return mb_strtolower($string, $encoding);
  1033. } else {
  1034. return strtolower($string);
  1035. }
  1036. }
  1037. /**
  1038. * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
  1039. *
  1040. * @param string $string String to encode
  1041. * @param string $encoding Character set encoding
  1042. * @return string String converted
  1043. */
  1044. function dol_strtoupper($string, $encoding = "UTF-8")
  1045. {
  1046. if (function_exists('mb_strtoupper')) {
  1047. return mb_strtoupper($string, $encoding);
  1048. } else {
  1049. return strtoupper($string);
  1050. }
  1051. }
  1052. /**
  1053. * Convert first character of the first word of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1054. *
  1055. * @param string $string String to encode
  1056. * @param string $encoding Character set encodign
  1057. * @return string String converted
  1058. */
  1059. function dol_ucfirst($string, $encoding = "UTF-8")
  1060. {
  1061. if (function_exists('mb_substr')) {
  1062. return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding);
  1063. } else {
  1064. return ucfirst($string);
  1065. }
  1066. }
  1067. /**
  1068. * Convert first character of all the words of a string to upper. Never use ucfirst because it does not works with UTF8 strings.
  1069. *
  1070. * @param string $string String to encode
  1071. * @param string $encoding Character set encodign
  1072. * @return string String converted
  1073. */
  1074. function dol_ucwords($string, $encoding = "UTF-8")
  1075. {
  1076. if (function_exists('mb_convert_case')) {
  1077. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  1078. } else {
  1079. return ucwords($string);
  1080. }
  1081. }
  1082. /**
  1083. * Write log message into outputs. Possible outputs can be:
  1084. * SYSLOG_HANDLERS = ["mod_syslog_file"] file name is then defined by SYSLOG_FILE
  1085. * SYSLOG_HANDLERS = ["mod_syslog_syslog"] facility is then defined by SYSLOG_FACILITY
  1086. * Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
  1087. * this, use logging to files instead of syslog (see setup of module).
  1088. * Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
  1089. * Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
  1090. * This function works only if syslog module is enabled.
  1091. * This must not use any call to other function calling dol_syslog (avoid infinite loop).
  1092. *
  1093. * @param string $message Line to log. ''=Show nothing
  1094. * @param int $level Log level
  1095. * 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
  1096. * On Linux LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
  1097. * @param int $ident 1=Increase ident of 1, -1=Decrease ident of 1
  1098. * @param string $suffixinfilename When output is a file, append this suffix into default log filename.
  1099. * @param string $restricttologhandler Force output of log only to this log handler
  1100. * @param array|null $logcontext If defined, an array with extra informations (can be used by some log handlers)
  1101. * @return void
  1102. */
  1103. function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '', $logcontext = null)
  1104. {
  1105. global $conf, $user, $debugbar;
  1106. // If syslog module enabled
  1107. if (empty($conf->syslog->enabled)) return;
  1108. // Check if we are into execution of code of a website
  1109. if (defined('USEEXTERNALSERVER') && !defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) {
  1110. global $website, $websitekey;
  1111. if (is_object($website) && !empty($website->ref)) $suffixinfilename .= '_website_'.$website->ref;
  1112. elseif (!empty($websitekey)) $suffixinfilename .= '_website_'.$websitekey;
  1113. }
  1114. if ($ident < 0)
  1115. {
  1116. foreach ($conf->loghandlers as $loghandlerinstance)
  1117. {
  1118. $loghandlerinstance->setIdent($ident);
  1119. }
  1120. }
  1121. if (!empty($message))
  1122. {
  1123. // Test log level
  1124. $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');
  1125. if (!array_key_exists($level, $logLevels))
  1126. {
  1127. throw new Exception('Incorrect log level');
  1128. }
  1129. if ($level > $conf->global->SYSLOG_LEVEL) return;
  1130. $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
  1131. // If adding log inside HTML page is required
  1132. if ((!empty($_REQUEST['logtohtml']) && !empty($conf->global->MAIN_ENABLE_LOG_TO_HTML))
  1133. || (!empty($user->rights->debugbar->read) && is_object($debugbar)))
  1134. {
  1135. $conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$logLevels[$level]." ".$message;
  1136. }
  1137. //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
  1138. // If html log tag enabled and url parameter log defined, we show output log on HTML comments
  1139. if (!empty($conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"]))
  1140. {
  1141. print "\n\n<!-- Log start\n";
  1142. print $message."\n";
  1143. print "Log end -->\n";
  1144. }
  1145. $data = array(
  1146. 'message' => $message,
  1147. 'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
  1148. 'level' => $level,
  1149. 'user' => ((is_object($user) && $user->id) ? $user->login : false),
  1150. 'ip' => false
  1151. );
  1152. $remoteip = getUserRemoteIP(); // Get ip when page run on a web server
  1153. if (!empty($remoteip)) {
  1154. $data['ip'] = $remoteip;
  1155. // This is when server run behind a reverse proxy
  1156. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != $remoteip) $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].' -> '.$data['ip'];
  1157. elseif (!empty($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != $remoteip) $data['ip'] = $_SERVER['HTTP_CLIENT_IP'].' -> '.$data['ip'];
  1158. } // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
  1159. elseif (!empty($_SERVER['SERVER_ADDR'])) $data['ip'] = $_SERVER['SERVER_ADDR'];
  1160. // 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).
  1161. elseif (!empty($_SERVER['COMPUTERNAME'])) $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
  1162. // 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).
  1163. elseif (!empty($_SERVER['LOGNAME'])) $data['ip'] = '???@'.$_SERVER['LOGNAME'];
  1164. // Loop on each log handler and send output
  1165. foreach ($conf->loghandlers as $loghandlerinstance)
  1166. {
  1167. if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) continue;
  1168. $loghandlerinstance->export($data, $suffixinfilename);
  1169. }
  1170. unset($data);
  1171. }
  1172. if ($ident > 0)
  1173. {
  1174. foreach ($conf->loghandlers as $loghandlerinstance)
  1175. {
  1176. $loghandlerinstance->setIdent($ident);
  1177. }
  1178. }
  1179. }
  1180. /**
  1181. * Return HTML code to output a button to open a dialog popup box.
  1182. * Such buttons must be included inside a HTML form.
  1183. *
  1184. * @param string $name A name for the html component
  1185. * @param string $label Label of button
  1186. * @param string $buttonstring button string
  1187. * @param string $url Url to open
  1188. * @param string $disabled Disabled text
  1189. * @return string HTML component with button
  1190. */
  1191. function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '')
  1192. {
  1193. if (strpos($url, '?') > 0) {
  1194. $url .= '&dol_hide_topmenu=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1195. } else {
  1196. $url .= '?dol_hide_menuinpopup=1&dol_hide_leftmenu=1&dol_openinpopup=1';
  1197. }
  1198. //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("MediaFiles")).'" name="file_manager">';
  1199. $out = '<a class="button bordertransp button_'.$name.'"'.$disabled.' title="'.dol_escape_htmltag($label).'">'.$buttonstring.'</a>';
  1200. $out .= '<script language="javascript">
  1201. jQuery(document).ready(function () {
  1202. jQuery(".button_'.$name.'").click(function () {
  1203. var $dialog = $(\'<div></div>\').html(\'<iframe class="iframedialog" style="border: 0px;" src="'.DOL_URL_ROOT.$url.'" width="100%" height="98%"></iframe>\')
  1204. .dialog({
  1205. autoOpen: false,
  1206. modal: true,
  1207. height: (window.innerHeight - 150),
  1208. width: \'80%\',
  1209. title: "'.dol_escape_js($label).'"
  1210. });
  1211. $dialog.dialog(\'open\');
  1212. });
  1213. });
  1214. </script>';
  1215. return $out;
  1216. }
  1217. /**
  1218. * Show tab header of a card
  1219. *
  1220. * @param array $links Array of tabs. Currently initialized by calling a function xxx_admin_prepare_head
  1221. * @param string $active Active tab name (document', 'info', 'ldap', ....)
  1222. * @param string $title Title
  1223. * @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)
  1224. * @param string $picto Add a picto on tab title
  1225. * @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.
  1226. * @param string $morehtmlright Add more html content on right of tabs title
  1227. * @param string $morecss More Css
  1228. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1229. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1230. * @return void
  1231. * @deprecated Use print dol_get_fiche_head() instead
  1232. */
  1233. function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1234. {
  1235. print dol_get_fiche_head($links, $active, $title, $notab, $picto, $pictoisfullpath, $morehtmlright, $morecss, $limittoshow, $moretabssuffix);
  1236. }
  1237. /**
  1238. * Show tabs of a record
  1239. *
  1240. * @param array $links Array of tabs
  1241. * @param string $active Active tab name
  1242. * @param string $title Title
  1243. * @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)
  1244. * @param string $picto Add a picto on tab title
  1245. * @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.
  1246. * @param string $morehtmlright Add more html content on right of tabs title
  1247. * @param string $morecss More Css
  1248. * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value.
  1249. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page
  1250. * @return string
  1251. */
  1252. function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '')
  1253. {
  1254. global $conf, $langs, $hookmanager;
  1255. // Show title
  1256. $showtitle = 1;
  1257. if (!empty($conf->dol_optimize_smallscreen)) $showtitle = 0;
  1258. $out = "\n".'<!-- dol_fiche_head - dol_get_fiche_head -->';
  1259. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1260. $out .= '<div class="tabs'.($picto ? '' : ' nopaddingleft').'" data-role="controlgroup" data-type="horizontal">'."\n";
  1261. }
  1262. // Show right part
  1263. if ($morehtmlright) $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.
  1264. // Show title
  1265. if (!empty($title) && $showtitle && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1266. {
  1267. $limittitle = 30;
  1268. $out .= '<a class="tabTitle">';
  1269. if ($picto) $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath, 0, 0, '', 'imgTabTitle').' ';
  1270. $out .= '<span class="tabTitleText">'.dol_trunc($title, $limittitle).'</span>';
  1271. $out .= '</a>';
  1272. }
  1273. // Show tabs
  1274. // Define max of key (max may be higher than sizeof because of hole due to module disabling some tabs).
  1275. $maxkey = -1;
  1276. if (is_array($links) && !empty($links))
  1277. {
  1278. $keys = array_keys($links);
  1279. if (count($keys)) $maxkey = max($keys);
  1280. }
  1281. // Show tabs
  1282. // if =0 we don't use the feature
  1283. if (empty($limittoshow)) {
  1284. $limittoshow = (empty($conf->global->MAIN_MAXTABS_IN_CARD) ? 99 : $conf->global->MAIN_MAXTABS_IN_CARD);
  1285. }
  1286. if (!empty($conf->dol_optimize_smallscreen)) $limittoshow = 2;
  1287. $displaytab = 0;
  1288. $nbintab = 0;
  1289. $popuptab = 0;
  1290. $outmore = '';
  1291. for ($i = 0; $i <= $maxkey; $i++)
  1292. {
  1293. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1294. // If active tab is already present
  1295. if ($i >= $limittoshow) $limittoshow--;
  1296. }
  1297. }
  1298. for ($i = 0; $i <= $maxkey; $i++)
  1299. {
  1300. if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
  1301. $isactive = true;
  1302. } else {
  1303. $isactive = false;
  1304. }
  1305. if ($i < $limittoshow || $isactive)
  1306. {
  1307. $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty($conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : $links[$i][2]).' -->';
  1308. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1309. {
  1310. if (!empty($links[$i][0]))
  1311. {
  1312. $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1313. } else {
  1314. $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1315. }
  1316. } elseif (!empty($links[$i][1]))
  1317. {
  1318. //print "x $i $active ".$links[$i][2]." z";
  1319. if ($isactive)
  1320. {
  1321. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1322. $out .= $links[$i][1];
  1323. $out .= '</a>'."\n";
  1324. } else {
  1325. $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabunactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1326. $out .= $links[$i][1];
  1327. $out .= '</a>'."\n";
  1328. }
  1329. }
  1330. $out .= '</div>';
  1331. } else {
  1332. // The popup with the other tabs
  1333. if (!$popuptab)
  1334. {
  1335. $popuptab = 1;
  1336. $outmore .= '<div class="popuptabset wordwrap">'; // The css used to hide/show popup
  1337. }
  1338. $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
  1339. if (isset($links[$i][2]) && $links[$i][2] == 'image')
  1340. {
  1341. if (!empty($links[$i][0]))
  1342. $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
  1343. else $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
  1344. } elseif (!empty($links[$i][1]))
  1345. {
  1346. $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
  1347. $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.
  1348. $outmore .= '</a>'."\n";
  1349. }
  1350. $outmore .= '</div>';
  1351. $nbintab++;
  1352. }
  1353. $displaytab = $i;
  1354. }
  1355. if ($popuptab) $outmore .= '</div>';
  1356. if ($popuptab) // If there is some tabs not shown
  1357. {
  1358. $left = ($langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
  1359. $right = ($langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
  1360. $widthofpopup = 200;
  1361. $tabsname = $moretabssuffix;
  1362. if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); }
  1363. $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
  1364. $out .= '<a href="#" class="tab moretab inline-block tabunactive">'.$langs->trans("More").'... ('.$nbintab.')</a>'; // Do not use "reposition" class in the "More".
  1365. $out .= '<div id="moretabsList'.$tabsname.'" style="width: '.$widthofpopup.'px; position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px; z-index:10;">';
  1366. $out .= $outmore;
  1367. $out .= '</div>';
  1368. $out .= '<div></div>';
  1369. $out .= "</div>\n";
  1370. $out .= "<script>";
  1371. $out .= "$('#moretabs".$tabsname."').mouseenter( function() {
  1372. var x = this.offsetLeft, y = this.offsetTop;
  1373. console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth);
  1374. if ((window.innerWidth - x) < ".($widthofpopup + 10).") {
  1375. $('#moretabsList".$tabsname."').css('".$right."','8px');
  1376. }
  1377. $('#moretabsList".$tabsname."').css('".$left."','auto');
  1378. });
  1379. ";
  1380. $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
  1381. $out .= "</script>";
  1382. }
  1383. if ((!empty($title) && $showtitle) || $morehtmlright || !empty($links)) {
  1384. $out .= "</div>\n";
  1385. }
  1386. if (!$notab || $notab == -1 || $notab == -2) $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ($notab == -2 ? ' tabBarNoTop' : ' tabBarWithBottom')).'">'."\n";
  1387. $parameters = array('tabname' => $active, 'out' => $out);
  1388. $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
  1389. if ($reshook > 0)
  1390. {
  1391. $out = $hookmanager->resPrint;
  1392. }
  1393. return $out;
  1394. }
  1395. /**
  1396. * Show tab footer of a card
  1397. *
  1398. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1399. * @return void
  1400. * @deprecated Use print dol_get_fiche_end() instead
  1401. */
  1402. function dol_fiche_end($notab = 0)
  1403. {
  1404. print dol_get_fiche_end($notab);
  1405. }
  1406. /**
  1407. * Return tab footer of a card
  1408. *
  1409. * @param int $notab -1 or 0=Add tab footer, 1=no tab footer
  1410. * @return string
  1411. */
  1412. function dol_get_fiche_end($notab = 0)
  1413. {
  1414. if (!$notab || $notab == -1) return "\n</div>\n";
  1415. else return '';
  1416. }
  1417. /**
  1418. * Show tab footer of a card.
  1419. * Note: $object->next_prev_filter can be set to restrict select to find next or previous record by $form->showrefnav.
  1420. *
  1421. * @param Object $object Object to show
  1422. * @param string $paramid Name of parameter to use to name the id into the URL next/previous link
  1423. * @param string $morehtml More html content to output just before the nav bar
  1424. * @param int $shownav Show Condition (navigation is shown if value is 1)
  1425. * @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.
  1426. * @param string $fieldref Nom du champ objet ref (object->ref) a utiliser pour select next et previous
  1427. * @param string $morehtmlref More html to show after ref
  1428. * @param string $moreparam More param to add in nav link url.
  1429. * @param int $nodbprefix Do not include DB prefix to forge table name
  1430. * @param string $morehtmlleft More html code to show before ref
  1431. * @param string $morehtmlstatus More html code to show under navigation arrows
  1432. * @param int $onlybanner Put this to 1, if the card will contains only a banner (this add css 'arearefnobottom' on div)
  1433. * @param string $morehtmlright More html code to show before navigation arrows
  1434. * @return void
  1435. */
  1436. function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
  1437. {
  1438. global $conf, $form, $user, $langs;
  1439. $error = 0;
  1440. $maxvisiblephotos = 1;
  1441. $showimage = 1;
  1442. $entity = (empty($object->entity) ? $conf->entity : $object->entity);
  1443. $showbarcode = empty($conf->barcode->enabled) ? 0 : ($object->barcode ? 1 : 0);
  1444. if (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) $showbarcode = 0;
  1445. $modulepart = 'unknown';
  1446. if ($object->element == 'societe') $modulepart = 'societe';
  1447. if ($object->element == 'contact') $modulepart = 'contact';
  1448. if ($object->element == 'member') $modulepart = 'memberphoto';
  1449. if ($object->element == 'user') $modulepart = 'userphoto';
  1450. if ($object->element == 'product') $modulepart = 'product';
  1451. if ($object->element == 'ticket') $modulepart = 'ticket';
  1452. if (class_exists("Imagick"))
  1453. {
  1454. if ($object->element == 'propal') $modulepart = 'propal';
  1455. if ($object->element == 'commande') $modulepart = 'commande';
  1456. if ($object->element == 'facture') $modulepart = 'facture';
  1457. if ($object->element == 'fichinter') $modulepart = 'ficheinter';
  1458. if ($object->element == 'contrat') $modulepart = 'contract';
  1459. if ($object->element == 'supplier_proposal') $modulepart = 'supplier_proposal';
  1460. if ($object->element == 'order_supplier') $modulepart = 'supplier_order';
  1461. if ($object->element == 'invoice_supplier') $modulepart = 'supplier_invoice';
  1462. if ($object->element == 'expensereport') $modulepart = 'expensereport';
  1463. }
  1464. if ($object->element == 'product')
  1465. {
  1466. $width = 80; $cssclass = 'photoref';
  1467. $showimage = $object->is_photo_available($conf->product->multidir_output[$entity]);
  1468. $maxvisiblephotos = (isset($conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? $conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
  1469. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1470. if ($showimage) {
  1471. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', $conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'</div>';
  1472. } else {
  1473. if (!empty($conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
  1474. $nophoto = '';
  1475. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1476. } else { // Show no photo link
  1477. $nophoto = '/public/theme/common/nophoto.png';
  1478. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1479. }
  1480. }
  1481. } elseif ($object->element == 'ticket') {
  1482. $width = 80; $cssclass = 'photoref';
  1483. $showimage = $object->is_photo_available($conf->ticket->multidir_output[$entity].'/'.$object->ref);
  1484. $maxvisiblephotos = (isset($conf->global->TICKET_MAX_VISIBLE_PHOTO) ? $conf->global->TICKET_MAX_VISIBLE_PHOTO : 2);
  1485. if ($conf->browser->layout == 'phone') $maxvisiblephotos = 1;
  1486. if ($showimage)
  1487. {
  1488. $showphoto = $object->show_photos('ticket', $conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0);
  1489. if ($object->nbphoto > 0)
  1490. {
  1491. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$showphoto.'</div>';
  1492. } else {
  1493. $showimage = 0;
  1494. }
  1495. }
  1496. if (!$showimage)
  1497. {
  1498. if (!empty($conf->global->TICKET_NODISPLAYIFNOPHOTO)) {
  1499. $nophoto = '';
  1500. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
  1501. } else { // Show no photo link
  1502. $nophoto = '/public/theme/common/nophoto.png';
  1503. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" border="0"'.($width ? ' style="width: '.$width.'px"' : '').' src="'.DOL_URL_ROOT.$nophoto.'"></div>';
  1504. }
  1505. }
  1506. } else {
  1507. if ($showimage)
  1508. {
  1509. if ($modulepart != 'unknown')
  1510. {
  1511. $phototoshow = '';
  1512. // Check if a preview file is available
  1513. if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick"))
  1514. {
  1515. $objectref = dol_sanitizeFileName($object->ref);
  1516. $dir_output = (empty($conf->$modulepart->multidir_output[$entity]) ? $conf->$modulepart->dir_output : $conf->$modulepart->multidir_output[$entity])."/";
  1517. if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice')))
  1518. {
  1519. $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
  1520. $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
  1521. } else {
  1522. $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
  1523. }
  1524. if (empty($subdir)) $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
  1525. $filepath = $dir_output.$subdir."/";
  1526. $filepdf = $filepath.$objectref.".pdf";
  1527. $relativepath = $subdir.'/'.$objectref.'.pdf';
  1528. // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
  1529. $fileimage = $filepdf.'_preview.png';
  1530. $relativepathimage = $relativepath.'_preview.png';
  1531. $pdfexists = file_exists($filepdf);
  1532. // If PDF file exists
  1533. if ($pdfexists)
  1534. {
  1535. // Conversion du PDF en image png si fichier png non existant
  1536. if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf)))
  1537. {
  1538. if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here.
  1539. {
  1540. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1541. $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png
  1542. if ($ret < 0) $error++;
  1543. }
  1544. }
  1545. }
  1546. if ($pdfexists && !$error)
  1547. {
  1548. $heightforphotref = 80;
  1549. if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60;
  1550. // If the preview file is found
  1551. if (file_exists($fileimage))
  1552. {
  1553. $phototoshow = '<div class="photoref">';
  1554. $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
  1555. $phototoshow .= '</div>';
  1556. }
  1557. }
  1558. } elseif (!$phototoshow) {
  1559. $phototoshow .= $form->showphoto($modulepart, $object, 0, 0, 0, 'photoref', 'small', 1, 0, $maxvisiblephotos);
  1560. }
  1561. if ($phototoshow) {
  1562. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1563. $morehtmlleft .= $phototoshow;
  1564. $morehtmlleft .= '</div>';
  1565. }
  1566. }
  1567. if (!$phototoshow) // Show No photo link (picto of object)
  1568. {
  1569. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">';
  1570. if ($object->element == 'action')
  1571. {
  1572. $width = 80;
  1573. $cssclass = 'photorefcenter';
  1574. $nophoto = img_picto('No photo', 'title_agenda');
  1575. } else {
  1576. $width = 14; $cssclass = 'photorefcenter';
  1577. $picto = $object->picto;
  1578. if ($object->element == 'project' && !$object->public) $picto = 'project'; // instead of projectpub
  1579. $nophoto = img_picto('No photo', 'object_'.$picto);
  1580. }
  1581. $morehtmlleft .= '<!-- No photo to show -->';
  1582. $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
  1583. $morehtmlleft .= $nophoto;
  1584. $morehtmlleft .= '</div></div>';
  1585. $morehtmlleft .= '</div>';
  1586. }
  1587. }
  1588. }
  1589. if ($showbarcode) $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
  1590. if ($object->element == 'societe')
  1591. {
  1592. if (!empty($conf->use_javascript_ajax) && $user->rights->societe->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE))
  1593. {
  1594. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'status', 'InActivity', 'ActivityCeased');
  1595. } else {
  1596. $morehtmlstatus .= $object->getLibStatut(6);
  1597. }
  1598. } elseif ($object->element == 'product')
  1599. {
  1600. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Sell").') ';
  1601. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1602. $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
  1603. } else {
  1604. $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(6, 0).'</span>';
  1605. }
  1606. $morehtmlstatus .= ' &nbsp; ';
  1607. //$morehtmlstatus.=$langs->trans("Status").' ('.$langs->trans("Buy").') ';
  1608. if (!empty($conf->use_javascript_ajax) && $user->rights->produit->creer && !empty($conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
  1609. $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
  1610. } else {
  1611. $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(6, 1).'</span>';
  1612. }
  1613. } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan')))
  1614. {
  1615. $tmptxt = $object->getLibStatut(6, $object->totalpaye);
  1616. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5, $object->totalpaye);
  1617. $morehtmlstatus .= $tmptxt;
  1618. } elseif ($object->element == 'contrat' || $object->element == 'contract')
  1619. {
  1620. if ($object->statut == 0) $morehtmlstatus .= $object->getLibStatut(5);
  1621. else $morehtmlstatus .= $object->getLibStatut(4);
  1622. } elseif ($object->element == 'facturerec')
  1623. {
  1624. if ($object->frequency == 0) $morehtmlstatus .= $object->getLibStatut(2);
  1625. else $morehtmlstatus .= $object->getLibStatut(5);
  1626. } elseif ($object->element == 'project_task')
  1627. {
  1628. $object->fk_statut = 1;
  1629. if ($object->progress > 0) $object->fk_statut = 2;
  1630. if ($object->progress >= 100) $object->fk_statut = 3;
  1631. $tmptxt = $object->getLibStatut(5);
  1632. $morehtmlstatus .= $tmptxt; // No status on task
  1633. } else { // Generic case
  1634. $tmptxt = $object->getLibStatut(6);
  1635. if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3)) $tmptxt = $object->getLibStatut(5);
  1636. $morehtmlstatus .= $tmptxt;
  1637. }
  1638. // Add if object was dispatched "into accountancy"
  1639. if (!empty($conf->accounting->enabled) && in_array($object->element, array('bank', 'facture', 'invoice', 'invoice_supplier', 'expensereport', 'payment_various')))
  1640. {
  1641. if (method_exists($object, 'getVentilExportCompta'))
  1642. {
  1643. $accounted = $object->getVentilExportCompta();
  1644. $langs->load("accountancy");
  1645. $morehtmlstatus .= '</div><div class="statusref statusrefbis"><span class="opacitymedium">'.($accounted > 0 ? $langs->trans("Accounted") : $langs->trans("NotYetAccounted")).'</span>';
  1646. }
  1647. }
  1648. // Add alias for thirdparty
  1649. if (!empty($object->name_alias)) $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
  1650. // Add label
  1651. if (in_array($object->element, array('product', 'bank_account', 'project_task')))
  1652. {
  1653. if (!empty($object->label)) $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
  1654. }
  1655. if (method_exists($object, 'getBannerAddress') && !in_array($object->element, array('product', 'bookmark', 'ecm_directories', 'ecm_files')))
  1656. {
  1657. $moreaddress = $object->getBannerAddress('refaddress', $object);
  1658. if ($moreaddress) {
  1659. $morehtmlref .= '<div class="refidno">';
  1660. $morehtmlref .= $moreaddress;
  1661. $morehtmlref .= '</div>';
  1662. }
  1663. }
  1664. 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))
  1665. {
  1666. $morehtmlref .= '<div style="clear: both;"></div>';
  1667. $morehtmlref .= '<div class="refidno">';
  1668. $morehtmlref .= $langs->trans("TechnicalID").': '.$object->id;
  1669. $morehtmlref .= '</div>';
  1670. }
  1671. print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle centpercent">';
  1672. print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
  1673. print '</div>';
  1674. print '<div class="underrefbanner clearboth"></div>';
  1675. }
  1676. /**
  1677. * Show a string with the label tag dedicated to the HTML edit field.
  1678. *
  1679. * @param string $langkey Translation key
  1680. * @param string $fieldkey Key of the html select field the text refers to
  1681. * @param int $fieldrequired 1=Field is mandatory
  1682. * @return string
  1683. * @deprecated Form::editfieldkey
  1684. */
  1685. function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
  1686. {
  1687. global $langs;
  1688. $ret = '';
  1689. if ($fieldrequired) $ret .= '<span class="fieldrequired">';
  1690. $ret .= '<label for="'.$fieldkey.'">';
  1691. $ret .= $langs->trans($langkey);
  1692. $ret .= '</label>';
  1693. if ($fieldrequired) $ret .= '</span>';
  1694. return $ret;
  1695. }
  1696. /**
  1697. * Return string to add class property on html element with pair/impair.
  1698. *
  1699. * @param string $var 0 or 1
  1700. * @param string $moreclass More class to add
  1701. * @return string String to add class onto HTML element
  1702. */
  1703. function dol_bc($var, $moreclass = '')
  1704. {
  1705. global $bc;
  1706. $ret = ' '.$bc[$var];
  1707. if ($moreclass) $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
  1708. return $ret;
  1709. }
  1710. /**
  1711. * Return a formated address (part address/zip/town/state) according to country rules.
  1712. * See https://en.wikipedia.org/wiki/Address
  1713. *
  1714. * @param Object $object A company or contact object
  1715. * @param int $withcountry 1=Add country into address string
  1716. * @param string $sep Separator to use to build string
  1717. * @param Translate $outputlangs Object lang that contains language for text translation.
  1718. * @param int $mode 0=Standard output, 1=Remove address
  1719. * @param string $extralangcode User extralanguage $langcode as values for address, town
  1720. * @return string Formated string
  1721. * @see dol_print_address()
  1722. */
  1723. function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0, $extralangcode = '')
  1724. {
  1725. global $conf, $langs;
  1726. $ret = '';
  1727. $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
  1728. // See format of addresses on https://en.wikipedia.org/wiki/Address
  1729. // Address
  1730. if (empty($mode)) {
  1731. $ret .= ($extralangcode ? $object->array_languages['address'][$extralangcode] : $object->address);
  1732. }
  1733. // Zip/Town/State
  1734. if (in_array($object->country_code, array('AU', 'CA', 'US')) || !empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) // US: title firstname name \n address lines \n town, state, zip \n country
  1735. {
  1736. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1737. $ret .= ($ret ? $sep : '').$town;
  1738. if ($object->state)
  1739. {
  1740. $ret .= ($ret ? ", " : '').$object->state;
  1741. }
  1742. if ($object->zip) $ret .= ($ret ? ", " : '').$object->zip;
  1743. } elseif (in_array($object->country_code, array('GB', 'UK'))) // UK: title firstname name \n address lines \n town state \n zip \n country
  1744. {
  1745. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1746. $ret .= ($ret ? $sep : '').$town;
  1747. if ($object->state)
  1748. {
  1749. $ret .= ($ret ? ", " : '').$object->state;
  1750. }
  1751. if ($object->zip) $ret .= ($ret ? $sep : '').$object->zip;
  1752. } elseif (in_array($object->country_code, array('ES', 'TR'))) // ES: title firstname name \n address lines \n zip town \n state \n country
  1753. {
  1754. $ret .= ($ret ? $sep : '').$object->zip;
  1755. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1756. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1757. if ($object->state)
  1758. {
  1759. $ret .= "\n".$object->state;
  1760. }
  1761. } elseif (in_array($object->country_code, array('IT'))) // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
  1762. {
  1763. $ret .= ($ret ? $sep : '').$object->zip;
  1764. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1765. $ret .= ($town ? (($object->zip ? ' ' : '').$town) : '');
  1766. $ret .= ($object->state_code ? (' '.($object->state_code)) : '');
  1767. } else // Other: title firstname name \n address lines \n zip town \n country
  1768. {
  1769. $town = ($extralangcode ? $object->array_languages['town'][$extralangcode] : $object->town);
  1770. $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : '';
  1771. $ret .= ($town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$town) : '');
  1772. if ($object->state && in_array($object->country_code, $countriesusingstate))
  1773. {
  1774. $ret .= ($ret ? ", " : '').$object->state;
  1775. }
  1776. }
  1777. if (!is_object($outputlangs)) $outputlangs = $langs;
  1778. if ($withcountry)
  1779. {
  1780. $langs->load("dict");
  1781. $ret .= ($object->country_code ? ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)) : '');
  1782. }
  1783. return $ret;
  1784. }
  1785. /**
  1786. * Format a string.
  1787. *
  1788. * @param string $fmt Format of strftime function (http://php.net/manual/fr/function.strftime.php)
  1789. * @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)
  1790. * @param int $is_gmt See comment of timestamp parameter
  1791. * @return string A formatted string
  1792. */
  1793. function dol_strftime($fmt, $ts = false, $is_gmt = false)
  1794. {
  1795. if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
  1796. return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
  1797. } else return 'Error date into a not supported range';
  1798. }
  1799. /**
  1800. * Output date in a string format according to outputlangs (or langs if not defined).
  1801. * Return charset is always UTF-8, except if encodetoouput is defined. In this case charset is output charset
  1802. *
  1803. * @param int $time GM Timestamps date
  1804. * @param string $format Output date format (tag of strftime function)
  1805. * "%d %b %Y",
  1806. * "%d/%m/%Y %H:%M",
  1807. * "%d/%m/%Y %H:%M:%S",
  1808. * "%B"=Long text of month, "%A"=Long text of day, "%b"=Short text of month, "%a"=Short text of day
  1809. * "day", "daytext", "dayhour", "dayhourldap", "dayhourtext", "dayrfc", "dayhourrfc", "...reduceformat"
  1810. * @param string $tzoutput true or 'gmt' => string is for Greenwich location
  1811. * false or 'tzserver' => output string is for local PHP server TZ usage
  1812. * 'tzuser' => output string is for user TZ (current browser TZ with current dst) => In a future, we should have same behaviour than 'tzuserrel'
  1813. * 'tzuserrel' => output string is for user TZ (current browser TZ with dst or not, depending on date position) (TODO not implemented yet)
  1814. * @param Translate $outputlangs Object lang that contains language for text translation.
  1815. * @param boolean $encodetooutput false=no convert into output pagecode
  1816. * @return string Formated date or '' if time is null
  1817. *
  1818. * @see dol_mktime(), dol_stringtotime(), dol_getdate()
  1819. */
  1820. function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlangs = '', $encodetooutput = false)
  1821. {
  1822. global $conf, $langs;
  1823. // Clean parameters
  1824. $to_gmt = false;
  1825. $offsettz = $offsetdst = 0;
  1826. if ($tzoutput)
  1827. {
  1828. $to_gmt = true; // For backward compatibility
  1829. if (is_string($tzoutput))
  1830. {
  1831. if ($tzoutput == 'tzserver')
  1832. {
  1833. $to_gmt = false;
  1834. $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1835. $offsettz = 0;
  1836. $offsetdst = 0;
  1837. } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel')
  1838. {
  1839. $to_gmt = true;
  1840. $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
  1841. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
  1842. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
  1843. }
  1844. }
  1845. }
  1846. if (!is_object($outputlangs)) $outputlangs = $langs;
  1847. if (!$format) $format = 'daytextshort';
  1848. $reduceformat = (!empty($conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0;
  1849. $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
  1850. if ($formatwithoutreduce != $format) { $format = $formatwithoutreduce; $reduceformat = 1; } // so format 'dayreduceformat' is processed like day
  1851. // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
  1852. // TODO Add format daysmallyear and dayhoursmallyear
  1853. if ($format == 'day') $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : $conf->format_date_short);
  1854. elseif ($format == 'hour') $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : $conf->format_hour_short);
  1855. elseif ($format == 'hourduration') $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : $conf->format_hour_short_duration);
  1856. elseif ($format == 'daytext') $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : $conf->format_date_text);
  1857. elseif ($format == 'daytextshort') $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : $conf->format_date_text_short);
  1858. elseif ($format == 'dayhour') $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : $conf->format_date_hour_short);
  1859. elseif ($format == 'dayhoursec') $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : $conf->format_date_hour_sec_short);
  1860. elseif ($format == 'dayhourtext') $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : $conf->format_date_hour_text);
  1861. elseif ($format == 'dayhourtextshort') $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : $conf->format_date_hour_text_short);
  1862. // Format not sensitive to language
  1863. elseif ($format == 'dayhourlog') $format = '%Y%m%d%H%M%S';
  1864. elseif ($format == 'dayhourldap') $format = '%Y%m%d%H%M%SZ';
  1865. elseif ($format == 'dayhourxcard') $format = '%Y%m%dT%H%M%SZ';
  1866. elseif ($format == 'dayxcard') $format = '%Y%m%d';
  1867. elseif ($format == 'dayrfc') $format = '%Y-%m-%d'; // DATE_RFC3339
  1868. elseif ($format == 'dayhourrfc') $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
  1869. elseif ($format == 'standard') $format = '%Y-%m-%d %H:%M:%S';
  1870. if ($reduceformat)
  1871. {
  1872. $format = str_replace('%Y', '%y', $format);
  1873. $format = str_replace('yyyy', 'yy', $format);
  1874. }
  1875. // If date undefined or "", we return ""
  1876. if (dol_strlen($time) == 0) return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
  1877. // Clean format
  1878. if (preg_match('/%b/i', $format)) // There is some text to translate
  1879. {
  1880. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1881. $format = str_replace('%b', '__b__', $format);
  1882. $format = str_replace('%B', '__B__', $format);
  1883. }
  1884. if (preg_match('/%a/i', $format)) // There is some text to translate
  1885. {
  1886. // We inhibate translation to text made by strftime functions. We will use trans instead later.
  1887. $format = str_replace('%a', '__a__', $format);
  1888. $format = str_replace('%A', '__A__', $format);
  1889. }
  1890. // Analyze date
  1891. $reg = array();
  1892. 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
  1893. {
  1894. dol_print_error("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"]);
  1895. return '';
  1896. } 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
  1897. {
  1898. // This part of code should not be used.
  1899. dol_syslog("Functions.lib::dol_print_date function called with a bad value from page ".$_SERVER["PHP_SELF"], LOG_WARNING);
  1900. //if (function_exists('debug_print_backtrace')) debug_print_backtrace();
  1901. // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
  1902. $syear = (!empty($reg[1]) ? $reg[1] : '');
  1903. $smonth = (!empty($reg[2]) ? $reg[2] : '');
  1904. $sday = (!empty($reg[3]) ? $reg[3] : '');
  1905. $shour = (!empty($reg[4]) ? $reg[4] : '');
  1906. $smin = (!empty($reg[5]) ? $reg[5] : '');
  1907. $ssec = (!empty($reg[6]) ? $reg[6] : '');
  1908. $time = dol_mktime($shour, $smin, $ssec, $smonth, $sday, $syear, true);
  1909. $ret = adodb_strftime($format, $time + $offsettz + $offsetdst, $to_gmt);
  1910. } else {
  1911. // Date is a timestamps
  1912. if ($time < 100000000000) // Protection against bad date values
  1913. {
  1914. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1915. $ret = adodb_strftime($format, $timetouse, $to_gmt);
  1916. } else $ret = 'Bad value '.$time.' for date';
  1917. }
  1918. if (preg_match('/__b__/i', $format))
  1919. {
  1920. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1921. // Here ret is string in PHP setup language (strftime was used). Now we convert to $outputlangs.
  1922. $month = adodb_strftime('%m', $timetouse);
  1923. $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
  1924. if ($encodetooutput)
  1925. {
  1926. $monthtext = $outputlangs->transnoentities('Month'.$month);
  1927. $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
  1928. } else {
  1929. $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
  1930. $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
  1931. }
  1932. //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
  1933. $ret = str_replace('__b__', $monthtextshort, $ret);
  1934. $ret = str_replace('__B__', $monthtext, $ret);
  1935. //print 'x'.$outputlangs->charset_output.'-'.$ret.'x';
  1936. //return $ret;
  1937. }
  1938. if (preg_match('/__a__/i', $format))
  1939. {
  1940. $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1941. $w = adodb_strftime('%w', $timetouse); // TODO Replace this with function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
  1942. $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
  1943. $ret = str_replace('__A__', $dayweek, $ret);
  1944. $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
  1945. }
  1946. return $ret;
  1947. }
  1948. /**
  1949. * Return an array with locale date info.
  1950. * WARNING: This function use PHP server timezone by default to return locale informations.
  1951. * Be aware to add the third parameter to "UTC" if you need to work on UTC.
  1952. *
  1953. * @param int $timestamp Timestamp
  1954. * @param boolean $fast Fast mode. deprecated.
  1955. * @param string $forcetimezone '' to use the PHP server timezone. Or use a form like 'Europe/Paris' or '+0200' to force timezone.
  1956. * @return array Array of informations
  1957. * 'seconds' => $secs,
  1958. * 'minutes' => $min,
  1959. * 'hours' => $hour,
  1960. * 'mday' => $day,
  1961. * 'wday' => $dow, 0=sunday, 6=saturday
  1962. * 'mon' => $month,
  1963. * 'year' => $year,
  1964. * 'yday' => floor($secsInYear/$_day_power)
  1965. * '0' => original timestamp
  1966. * @see dol_print_date(), dol_stringtotime(), dol_mktime()
  1967. */
  1968. function dol_getdate($timestamp, $fast = false, $forcetimezone = '')
  1969. {
  1970. global $conf;
  1971. if (empty($conf->global->MAIN_USE_OLD_FUNCTIONS_FOR_GETDATE)) {
  1972. //$datetimeobj = new DateTime('@'.$timestamp);
  1973. $datetimeobj = new DateTime();
  1974. $datetimeobj->setTimestamp($timestamp); // Use local PHP server timezone
  1975. if ($forcetimezone) $datetimeobj->setTimezone(new DateTimeZone($forcetimezone)); // (add timezone relative to the date entered)
  1976. $arrayinfo = array(
  1977. 'year'=>((int) date_format($datetimeobj, 'Y')),
  1978. 'mon'=>((int) date_format($datetimeobj, 'm')),
  1979. 'mday'=>((int) date_format($datetimeobj, 'd')),
  1980. 'wday'=>((int) date_format($datetimeobj, 'w')),
  1981. 'yday'=>((int) date_format($datetimeobj, 'z')),
  1982. 'hours'=>((int) date_format($datetimeobj, 'H')),
  1983. 'minutes'=>((int) date_format($datetimeobj, 'i')),
  1984. 'seconds'=>((int) date_format($datetimeobj, 's')),
  1985. '0'=>$timestamp
  1986. );
  1987. } else {
  1988. // PHP getdate is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  1989. $usealternatemethod = false;
  1990. if ($timestamp <= 0) $usealternatemethod = true; // <= 1970
  1991. if ($timestamp >= 2145913200) $usealternatemethod = true; // >= 2038
  1992. if ($usealternatemethod)
  1993. {
  1994. $arrayinfo = adodb_getdate($timestamp, $fast);
  1995. } else {
  1996. $arrayinfo = getdate($timestamp);
  1997. }
  1998. }
  1999. return $arrayinfo;
  2000. }
  2001. /**
  2002. * Return a timestamp date built from detailed informations (by default a local PHP server timestamp)
  2003. * Replace function mktime not available under Windows if year < 1970
  2004. * PHP mktime is restricted to the years 1901-2038 on Unix and 1970-2038 on Windows
  2005. *
  2006. * @param int $hour Hour (can be -1 for undefined)
  2007. * @param int $minute Minute (can be -1 for undefined)
  2008. * @param int $second Second (can be -1 for undefined)
  2009. * @param int $month Month (1 to 12)
  2010. * @param int $day Day (1 to 31)
  2011. * @param int $year Year
  2012. * @param mixed $gm True or 1 or 'gmt'=Input informations are GMT values
  2013. * False or 0 or 'server' = local to server TZ
  2014. * 'user' = local to user TZ
  2015. * 'tz,TimeZone' = use specified timezone
  2016. * @param int $check 0=No check on parameters (Can use day 32, etc...)
  2017. * @return int|string Date as a timestamp, '' or false if error
  2018. * @see dol_print_date(), dol_stringtotime(), dol_getdate()
  2019. */
  2020. function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $check = 1)
  2021. {
  2022. global $conf;
  2023. //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
  2024. // Clean parameters
  2025. if ($hour == -1 || empty($hour)) $hour = 0;
  2026. if ($minute == -1 || empty($minute)) $minute = 0;
  2027. if ($second == -1 || empty($second)) $second = 0;
  2028. // Check parameters
  2029. if ($check)
  2030. {
  2031. if (!$month || !$day) return '';
  2032. if ($day > 31) return '';
  2033. if ($month > 12) return '';
  2034. if ($hour < 0 || $hour > 24) return '';
  2035. if ($minute < 0 || $minute > 60) return '';
  2036. if ($second < 0 || $second > 60) return '';
  2037. }
  2038. if (empty($gm) || $gm === 'server')
  2039. {
  2040. $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
  2041. $localtz = new DateTimeZone($default_timezone);
  2042. } elseif ($gm === 'user')
  2043. {
  2044. // We use dol_tz_string first because it is more reliable.
  2045. $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
  2046. try {
  2047. $localtz = new DateTimeZone($default_timezone);
  2048. } catch (Exception $e)
  2049. {
  2050. dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
  2051. $default_timezone = @date_default_timezone_get();
  2052. }
  2053. } elseif (strrpos($gm, "tz,") !== false)
  2054. {
  2055. $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
  2056. try {
  2057. $localtz = new DateTimeZone($timezone);
  2058. } catch (Exception $e)
  2059. {
  2060. dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
  2061. }
  2062. }
  2063. if (empty($localtz)) {
  2064. $localtz = new DateTimeZone('UTC');
  2065. }
  2066. //var_dump($localtz);
  2067. //var_dump($year.'-'.$month.'-'.$day.'-'.$hour.'-'.$minute);
  2068. $dt = new DateTime(null, $localtz);
  2069. $dt->setDate((int) $year, (int) $month, (int) $day);
  2070. $dt->setTime((int) $hour, (int) $minute, (int) $second);
  2071. $date = $dt->getTimestamp(); // should include daylight saving time
  2072. //var_dump($date);
  2073. return $date;
  2074. }
  2075. /**
  2076. * Return date for now. In most cases, we use this function without parameters (that means GMT time).
  2077. *
  2078. * @param string $mode 'gmt' => we return GMT timestamp,
  2079. * 'tzserver' => we add the PHP server timezone
  2080. * 'tzref' => we add the company timezone
  2081. * 'tzuser' => we add the user timezone
  2082. * @return int $date Timestamp
  2083. */
  2084. function dol_now($mode = 'gmt')
  2085. {
  2086. $ret = 0;
  2087. if ($mode == 'gmt') $ret = time(); // Time for now at greenwich.
  2088. elseif ($mode == 'tzserver') // Time for now with PHP server timezone added
  2089. {
  2090. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2091. $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
  2092. $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
  2093. } /*elseif ($mode == 'tzref') // Time for now with parent company timezone is added
  2094. {
  2095. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  2096. $tzsecond=getParentCompanyTimeZoneInt(); // Contains tz+dayling saving time
  2097. $ret=dol_now('gmt')+($tzsecond*3600);
  2098. }*/
  2099. elseif ($mode == 'tzuser') // Time for now with user timezone added
  2100. {
  2101. //print 'time: '.time();
  2102. $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;
  2103. $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60;
  2104. $ret = (int) (dol_now('gmt') + ($offsettz + $offsetdst));
  2105. }
  2106. return $ret;
  2107. }
  2108. /**
  2109. * Return string with formated size
  2110. *
  2111. * @param int $size Size to print
  2112. * @param int $shortvalue Tell if we want long value to use another unit (Ex: 1.5Kb instead of 1500b)
  2113. * @param int $shortunit Use short label of size unit (for example 'b' instead of 'bytes')
  2114. * @return string Link
  2115. */
  2116. function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
  2117. {
  2118. global $conf, $langs;
  2119. $level = 1024;
  2120. if (!empty($conf->dol_optimize_smallscreen)) $shortunit = 1;
  2121. // Set value text
  2122. if (empty($shortvalue) || $size < ($level * 10))
  2123. {
  2124. $ret = $size;
  2125. $textunitshort = $langs->trans("b");
  2126. $textunitlong = $langs->trans("Bytes");
  2127. } else {
  2128. $ret = round($size / $level, 0);
  2129. $textunitshort = $langs->trans("Kb");
  2130. $textunitlong = $langs->trans("KiloBytes");
  2131. }
  2132. // Use long or short text unit
  2133. if (empty($shortunit)) { $ret .= ' '.$textunitlong; } else { $ret .= ' '.$textunitshort; }
  2134. return $ret;
  2135. }
  2136. /**
  2137. * Show Url link
  2138. *
  2139. * @param string $url Url to show
  2140. * @param string $target Target for link
  2141. * @param int $max Max number of characters to show
  2142. * @param int $withpicto With picto
  2143. * @return string HTML Link
  2144. */
  2145. function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
  2146. {
  2147. global $langs;
  2148. if (empty($url)) return '';
  2149. $link = '<a href="';
  2150. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2151. $link .= $url;
  2152. $link .= '"';
  2153. if ($target) $link .= ' target="'.$target.'"';
  2154. $link .= '>';
  2155. if (!preg_match('/^http/i', $url)) $link .= 'http://';
  2156. $link .= dol_trunc($url, $max);
  2157. $link .= '</a>';
  2158. return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ?img_picto($langs->trans("Url"), 'globe').' ' : '').$link.'</div>';
  2159. }
  2160. /**
  2161. * Show EMail link formatted for HTML output.
  2162. *
  2163. * @param string $email EMail to show (only email, without 'Name of recipient' before)
  2164. * @param int $cid Id of contact if known
  2165. * @param int $socid Id of third party if known
  2166. * @param int $addlink 0=no link, 1=email has a html email link (+ link to create action if constant AGENDA_ADDACTIONFOREMAIL is on)
  2167. * @param int $max Max number of characters to show
  2168. * @param int $showinvalid 1=Show warning if syntax email is wrong
  2169. * @param int $withpicto Show picto
  2170. * @return string HTML Link
  2171. */
  2172. function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
  2173. {
  2174. global $conf, $user, $langs, $hookmanager;
  2175. $newemail = dol_escape_htmltag($email);
  2176. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $withpicto) $withpicto = 0;
  2177. if (empty($email)) return '&nbsp;';
  2178. if (!empty($addlink))
  2179. {
  2180. $newemail = '<a style="text-overflow: ellipsis;" href="';
  2181. if (!preg_match('/^mailto:/i', $email)) $newemail .= 'mailto:';
  2182. $newemail .= $email;
  2183. $newemail .= '">';
  2184. $newemail .= dol_trunc($email, $max);
  2185. $newemail .= '</a>';
  2186. if ($showinvalid && !isValidEmail($email))
  2187. {
  2188. $langs->load("errors");
  2189. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2190. }
  2191. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2192. {
  2193. $type = 'AC_EMAIL'; $link = '';
  2194. if (!empty($conf->global->AGENDA_ADDACTIONFOREMAIL)) $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>';
  2195. if ($link) $newemail = '<div>'.$newemail.' '.$link.'</div>';
  2196. }
  2197. } else {
  2198. if ($showinvalid && !isValidEmail($email))
  2199. {
  2200. $langs->load("errors");
  2201. $newemail .= img_warning($langs->trans("ErrorBadEMail", $email));
  2202. }
  2203. }
  2204. //$rep = '<div class="nospan" style="margin-right: 10px">';
  2205. $rep = ($withpicto ? img_picto($langs->trans("EMail").' : '.$email, 'object_email.png').' ' : '').$newemail;
  2206. //$rep .= '</div>';
  2207. if ($hookmanager) {
  2208. $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
  2209. $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
  2210. if ($reshook > 0) {
  2211. $rep = '';
  2212. }
  2213. $rep .= $hookmanager->resPrint;
  2214. }
  2215. return $rep;
  2216. }
  2217. /**
  2218. * Get array of social network dictionary
  2219. *
  2220. * @return array Array of Social Networks Dictionary
  2221. */
  2222. function getArrayOfSocialNetworks()
  2223. {
  2224. global $conf, $db;
  2225. $sql = "SELECT rowid, code, label, url, icon, active FROM ".MAIN_DB_PREFIX."c_socialnetworks";
  2226. $sql .= " WHERE entity=".$conf->entity;
  2227. $socialnetworks = array();
  2228. $resql = $db->query($sql);
  2229. if ($resql) {
  2230. while ($obj = $db->fetch_object($resql)) {
  2231. $socialnetworks[$obj->code] = array(
  2232. 'rowid' => $obj->rowid,
  2233. 'label' => $obj->label,
  2234. 'url' => $obj->url,
  2235. 'icon' => $obj->icon,
  2236. 'active' => $obj->active,
  2237. );
  2238. }
  2239. }
  2240. return $socialnetworks;
  2241. }
  2242. /**
  2243. * Show social network link
  2244. *
  2245. * @param string $value Skype to show (only skype, without 'Name of recipient' before)
  2246. * @param int $cid Id of contact if known
  2247. * @param int $socid Id of third party if known
  2248. * @param string $type 'skype','facebook',...
  2249. * @return string HTML Link
  2250. */
  2251. function dol_print_socialnetworks($value, $cid, $socid, $type)
  2252. {
  2253. global $conf, $user, $langs;
  2254. $htmllink = $value;
  2255. if (empty($value)) return '&nbsp;';
  2256. if (!empty($type))
  2257. {
  2258. $htmllink = '<div class="divsocialnetwork inline-block valignmiddle">';
  2259. $htmllink .= img_picto($langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright', 0);
  2260. $htmllink .= $value;
  2261. if ($type == 'skype')
  2262. {
  2263. $htmllink .= '&nbsp;';
  2264. $htmllink .= '<a href="skype:';
  2265. $htmllink .= $value;
  2266. $htmllink .= '?call" alt="'.$langs->trans("Call").'&nbsp;'.$value.'" title="'.$langs->trans("Call").'&nbsp;'.$value.'">';
  2267. $htmllink .= '<img src="'.DOL_URL_ROOT.'/theme/common/skype_callbutton.png" border="0">';
  2268. $htmllink .= '</a><a href="skype:';
  2269. $htmllink .= $value;
  2270. $htmllink .= '?chat" alt="'.$langs->trans("Chat").'&nbsp;'.$value.'" title="'.$langs->trans("Chat").'&nbsp;'.$value.'">';
  2271. $htmllink .= '<img class="paddingleft" src="'.DOL_URL_ROOT.'/theme/common/skype_chatbutton.png" border="0">';
  2272. $htmllink .= '</a>';
  2273. }
  2274. if (($cid || $socid) && !empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype')
  2275. {
  2276. $addlink = 'AC_SKYPE';
  2277. $link = '';
  2278. if (!empty($conf->global->AGENDA_ADDACTIONFORSKYPE)) $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>';
  2279. $htmllink .= ($link ? ' '.$link : '');
  2280. }
  2281. $htmllink .= '</div>';
  2282. } else {
  2283. $langs->load("errors");
  2284. $htmllink .= img_warning($langs->trans("ErrorBadSocialNetworkValue", $value));
  2285. }
  2286. return $htmllink;
  2287. }
  2288. /**
  2289. * Format phone numbers according to country
  2290. *
  2291. * @param string $phone Phone number to format
  2292. * @param string $countrycode Country code to use for formatting
  2293. * @param int $cid Id of contact if known
  2294. * @param int $socid Id of third party if known
  2295. * @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)
  2296. * @param string $separ Separation between numbers for a better visibility example : xx.xx.xx.xx.xx
  2297. * @param string $withpicto Show picto
  2298. * @param string $titlealt Text to show on alt
  2299. * @param int $adddivfloat Add div float around phone.
  2300. * @return string Formated phone number
  2301. */
  2302. function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
  2303. {
  2304. global $conf, $user, $langs, $mysoc, $hookmanager;
  2305. // Clean phone parameter
  2306. $phone = preg_replace("/[\s.-]/", "", trim($phone));
  2307. if (empty($phone)) { return ''; }
  2308. if (!empty($conf->global->MAIN_PHONE_SEPAR)) $separ = $conf->global->MAIN_PHONE_SEPAR;
  2309. if (empty($countrycode)) $countrycode = $mysoc->country_code;
  2310. // Short format for small screens
  2311. if ($conf->dol_optimize_smallscreen) $separ = '';
  2312. $newphone = $phone;
  2313. if (strtoupper($countrycode) == "FR")
  2314. {
  2315. // France
  2316. if (dol_strlen($phone) == 10) {
  2317. $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);
  2318. } elseif (dol_strlen($phone) == 7)
  2319. {
  2320. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
  2321. } elseif (dol_strlen($phone) == 9)
  2322. {
  2323. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
  2324. } elseif (dol_strlen($phone) == 11)
  2325. {
  2326. $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);
  2327. } elseif (dol_strlen($phone) == 12)
  2328. {
  2329. $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);
  2330. }
  2331. } elseif (strtoupper($countrycode) == "CA")
  2332. {
  2333. if (dol_strlen($phone) == 10) {
  2334. $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
  2335. }
  2336. } elseif (strtoupper($countrycode) == "PT")
  2337. {//Portugal
  2338. if (dol_strlen($phone) == 13)
  2339. {//ex: +351_ABC_DEF_GHI
  2340. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2341. }
  2342. } elseif (strtoupper($countrycode) == "SR")
  2343. {//Suriname
  2344. if (dol_strlen($phone) == 10)
  2345. {//ex: +597_ABC_DEF
  2346. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
  2347. } elseif (dol_strlen($phone) == 11)
  2348. {//ex: +597_ABC_DEFG
  2349. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
  2350. }
  2351. } elseif (strtoupper($countrycode) == "DE")
  2352. {//Allemagne
  2353. if (dol_strlen($phone) == 14)
  2354. {//ex: +49_ABCD_EFGH_IJK
  2355. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
  2356. } elseif (dol_strlen($phone) == 13)
  2357. {//ex: +49_ABC_DEFG_HIJ
  2358. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
  2359. }
  2360. } elseif (strtoupper($countrycode) == "ES")
  2361. {//Espagne
  2362. if (dol_strlen($phone) == 12)
  2363. {//ex: +34_ABC_DEF_GHI
  2364. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2365. }
  2366. } elseif (strtoupper($countrycode) == "BF")
  2367. {// Burkina Faso
  2368. if (dol_strlen($phone) == 12)
  2369. {//ex : +22 A BC_DE_FG_HI
  2370. $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);
  2371. }
  2372. } elseif (strtoupper($countrycode) == "RO")
  2373. {// Roumanie
  2374. if (dol_strlen($phone) == 12)
  2375. {//ex : +40 AB_CDE_FG_HI
  2376. $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);
  2377. }
  2378. } elseif (strtoupper($countrycode) == "TR")
  2379. {//Turquie
  2380. if (dol_strlen($phone) == 13)
  2381. {//ex : +90 ABC_DEF_GHIJ
  2382. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2383. }
  2384. } elseif (strtoupper($countrycode) == "US")
  2385. {//Etat-Unis
  2386. if (dol_strlen($phone) == 12)
  2387. {//ex: +1 ABC_DEF_GHIJ
  2388. $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2389. }
  2390. } elseif (strtoupper($countrycode) == "MX")
  2391. {//Mexique
  2392. if (dol_strlen($phone) == 12)
  2393. {//ex: +52 ABCD_EFG_HI
  2394. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2395. } elseif (dol_strlen($phone) == 11)
  2396. {//ex: +52 AB_CD_EF_GH
  2397. $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);
  2398. } elseif (dol_strlen($phone) == 13)
  2399. {//ex: +52 ABC_DEF_GHIJ
  2400. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
  2401. }
  2402. } elseif (strtoupper($countrycode) == "ML")
  2403. {//Mali
  2404. if (dol_strlen($phone) == 12)
  2405. {//ex: +223 AB_CD_EF_GH
  2406. $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);
  2407. }
  2408. } elseif (strtoupper($countrycode) == "TH")
  2409. {//Thaïlande
  2410. if (dol_strlen($phone) == 11)
  2411. {//ex: +66_ABC_DE_FGH
  2412. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2413. } elseif (dol_strlen($phone) == 12)
  2414. {//ex: +66_A_BCD_EF_GHI
  2415. $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);
  2416. }
  2417. } elseif (strtoupper($countrycode) == "MU")
  2418. {
  2419. //Maurice
  2420. if (dol_strlen($phone) == 11)
  2421. {//ex: +230_ABC_DE_FG
  2422. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
  2423. } elseif (dol_strlen($phone) == 12)
  2424. {//ex: +230_ABCD_EF_GH
  2425. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
  2426. }
  2427. } elseif (strtoupper($countrycode) == "ZA")
  2428. {//Afrique du sud
  2429. if (dol_strlen($phone) == 12)
  2430. {//ex: +27_AB_CDE_FG_HI
  2431. $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);
  2432. }
  2433. } elseif (strtoupper($countrycode) == "SY")
  2434. {//Syrie
  2435. if (dol_strlen($phone) == 12)
  2436. {//ex: +963_AB_CD_EF_GH
  2437. $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);
  2438. } elseif (dol_strlen($phone) == 13)
  2439. {//ex: +963_AB_CD_EF_GHI
  2440. $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);
  2441. }
  2442. } elseif (strtoupper($countrycode) == "AE")
  2443. {//Emirats Arabes Unis
  2444. if (dol_strlen($phone) == 12)
  2445. {//ex: +971_ABC_DEF_GH
  2446. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
  2447. } elseif (dol_strlen($phone) == 13)
  2448. {//ex: +971_ABC_DEF_GHI
  2449. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2450. } elseif (dol_strlen($phone) == 14)
  2451. {//ex: +971_ABC_DEF_GHIK
  2452. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
  2453. }
  2454. } elseif (strtoupper($countrycode) == "DZ")
  2455. {//Algérie
  2456. if (dol_strlen($phone) == 13)
  2457. {//ex: +213_ABC_DEF_GHI
  2458. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2459. }
  2460. } elseif (strtoupper($countrycode) == "BE")
  2461. {//Belgique
  2462. if (dol_strlen($phone) == 11)
  2463. {//ex: +32_ABC_DE_FGH
  2464. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
  2465. } elseif (dol_strlen($phone) == 12)
  2466. {//ex: +32_ABC_DEF_GHI
  2467. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2468. }
  2469. } elseif (strtoupper($countrycode) == "PF")
  2470. {//Polynésie française
  2471. if (dol_strlen($phone) == 12)
  2472. {//ex: +689_AB_CD_EF_GH
  2473. $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);
  2474. }
  2475. } elseif (strtoupper($countrycode) == "CO")
  2476. {//Colombie
  2477. if (dol_strlen($phone) == 13)
  2478. {//ex: +57_ABC_DEF_GH_IJ
  2479. $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);
  2480. }
  2481. } elseif (strtoupper($countrycode) == "JO")
  2482. {//Jordanie
  2483. if (dol_strlen($phone) == 12)
  2484. {//ex: +962_A_BCD_EF_GH
  2485. $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);
  2486. }
  2487. } elseif (strtoupper($countrycode) == "JM")
  2488. {//Jamaïque
  2489. if (dol_strlen($newphone) == 12)
  2490. {//ex: +1867_ABC_DEFG
  2491. $newphone = substr($newphone, 0, 5).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
  2492. }
  2493. } elseif (strtoupper($countrycode) == "MG")
  2494. {//Madagascar
  2495. if (dol_strlen($phone) == 13)
  2496. {//ex: +261_AB_CD_EF_GHI
  2497. $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);
  2498. }
  2499. } elseif (strtoupper($countrycode) == "GB")
  2500. {//Royaume uni
  2501. if (dol_strlen($phone) == 13)
  2502. {//ex: +44_ABCD_EFG_HIJ
  2503. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
  2504. }
  2505. } elseif (strtoupper($countrycode) == "CH")
  2506. {//Suisse
  2507. if (dol_strlen($phone) == 12)
  2508. {//ex: +41_AB_CDE_FG_HI
  2509. $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);
  2510. } elseif (dol_strlen($phone) == 15)
  2511. {// +41_AB_CDE_FGH_IJKL
  2512. $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);
  2513. }
  2514. } elseif (strtoupper($countrycode) == "TN")
  2515. {//Tunisie
  2516. if (dol_strlen($phone) == 12)
  2517. {//ex: +216_AB_CDE_FGH
  2518. $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2519. }
  2520. } elseif (strtoupper($countrycode) == "GF")
  2521. {//Guyane francaise
  2522. if (dol_strlen($phone) == 13)
  2523. {//ex: +594_ABC_DE_FG_HI (ABC=594 de nouveau)
  2524. $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);
  2525. }
  2526. } elseif (strtoupper($countrycode) == "GP")
  2527. {//Guadeloupe
  2528. if (dol_strlen($phone) == 13)
  2529. {//ex: +590_ABC_DE_FG_HI (ABC=590 de nouveau)
  2530. $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);
  2531. }
  2532. } elseif (strtoupper($countrycode) == "MQ")
  2533. {//Martinique
  2534. if (dol_strlen($phone) == 13)
  2535. {//ex: +596_ABC_DE_FG_HI (ABC=596 de nouveau)
  2536. $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);
  2537. }
  2538. } elseif (strtoupper($countrycode) == "IT")
  2539. {//Italie
  2540. if (dol_strlen($phone) == 12)
  2541. {//ex: +39_ABC_DEF_GHI
  2542. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
  2543. } elseif (dol_strlen($phone) == 13)
  2544. {//ex: +39_ABC_DEF_GH_IJ
  2545. $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);
  2546. }
  2547. } elseif (strtoupper($countrycode) == "AU")
  2548. {
  2549. //Australie
  2550. if (dol_strlen($phone) == 12)
  2551. {
  2552. //ex: +61_A_BCDE_FGHI
  2553. $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
  2554. }
  2555. }
  2556. if (!empty($addlink)) // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
  2557. {
  2558. if ($conf->browser->layout == 'phone' || (!empty($conf->clicktodial->enabled) && !empty($conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) // If phone or option for, we use link of phone
  2559. {
  2560. $newphoneform = $newphone;
  2561. $newphone = '<a href="tel:'.$phone.'"';
  2562. $newphone .= '>'.$newphoneform.'</a>';
  2563. } elseif (!empty($conf->clicktodial->enabled) && $addlink == 'AC_TEL') // If click to dial, we use click to dial url
  2564. {
  2565. if (empty($user->clicktodial_loaded)) $user->fetch_clicktodial();
  2566. // Define urlmask
  2567. $urlmask = 'ErrorClickToDialModuleNotConfigured';
  2568. if (!empty($conf->global->CLICKTODIAL_URL)) $urlmask = $conf->global->CLICKTODIAL_URL;
  2569. if (!empty($user->clicktodial_url)) $urlmask = $user->clicktodial_url;
  2570. $clicktodial_poste = (!empty($user->clicktodial_poste) ?urlencode($user->clicktodial_poste) : '');
  2571. $clicktodial_login = (!empty($user->clicktodial_login) ?urlencode($user->clicktodial_login) : '');
  2572. $clicktodial_password = (!empty($user->clicktodial_password) ?urlencode($user->clicktodial_password) : '');
  2573. // This line is for backward compatibility
  2574. $url = sprintf($urlmask, urlencode($phone), $clicktodial_poste, $clicktodial_login, $clicktodial_password);
  2575. // Thoose lines are for substitution
  2576. $substitarray = array('__PHONEFROM__'=>$clicktodial_poste,
  2577. '__PHONETO__'=>urlencode($phone),
  2578. '__LOGIN__'=>$clicktodial_login,
  2579. '__PASS__'=>$clicktodial_password);
  2580. $url = make_substitutions($url, $substitarray);
  2581. $newphonesav = $newphone;
  2582. $newphone = '<a href="'.$url.'"';
  2583. if (!empty($conf->global->CLICKTODIAL_FORCENEWTARGET)) $newphone .= ' target="_blank"';
  2584. $newphone .= '>'.$newphonesav.'</a>';
  2585. }
  2586. //if (($cid || $socid) && ! empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2587. if (!empty($conf->agenda->enabled) && $user->rights->agenda->myactions->create)
  2588. {
  2589. $type = 'AC_TEL'; $link = '';
  2590. if ($addlink == 'AC_FAX') $type = 'AC_FAX';
  2591. if (!empty($conf->global->AGENDA_ADDACTIONFORPHONE)) $link = '<a href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object($langs->trans("AddAction"), "calendar").'</a>';
  2592. if ($link) $newphone = '<div>'.$newphone.' '.$link.'</div>';
  2593. }
  2594. }
  2595. if (empty($titlealt))
  2596. {
  2597. $titlealt = ($withpicto == 'fax' ? $langs->trans("Fax") : $langs->trans("Phone"));
  2598. }
  2599. $rep = '';
  2600. if ($hookmanager) {
  2601. $parameters = array('countrycode' => $countrycode, 'cid' => $cid, 'socid' => $socid, 'titlealt' => $titlealt, 'picto' => $withpicto);
  2602. $reshook = $hookmanager->executeHooks('printPhone', $parameters, $phone);
  2603. $rep .= $hookmanager->resPrint;
  2604. }
  2605. if (empty($reshook))
  2606. {
  2607. $picto = '';
  2608. if ($withpicto) {
  2609. if ($withpicto == 'fax') {
  2610. $picto = 'phoning_fax';
  2611. } elseif ($withpicto == 'phone') {
  2612. $picto = 'phoning';
  2613. } elseif ($withpicto == 'mobile') {
  2614. $picto = 'phoning_mobile';
  2615. } else {
  2616. $picto = '';
  2617. }
  2618. }
  2619. if ($adddivfloat) $rep .= '<div class="nospan float" style="margin-right: 10px">';
  2620. else $rep .= '<span style="margin-right: 10px;">';
  2621. $rep .= ($withpicto ?img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
  2622. if ($adddivfloat) $rep .= '</div>';
  2623. else $rep .= '</span>';
  2624. }
  2625. return $rep;
  2626. }
  2627. /**
  2628. * Return an IP formated to be shown on screen
  2629. *
  2630. * @param string $ip IP
  2631. * @param int $mode 0=return IP + country/flag, 1=return only country/flag, 2=return only IP
  2632. * @return string Formated IP, with country if GeoIP module is enabled
  2633. */
  2634. function dol_print_ip($ip, $mode = 0)
  2635. {
  2636. global $conf, $langs;
  2637. $ret = '';
  2638. if (empty($mode)) $ret .= $ip;
  2639. if ($mode != 2)
  2640. {
  2641. $countrycode = dolGetCountryCodeFromIp($ip);
  2642. if ($countrycode) // If success, countrycode is us, fr, ...
  2643. {
  2644. if (file_exists(DOL_DOCUMENT_ROOT.'/theme/common/flags/'.$countrycode.'.png'))
  2645. {
  2646. $ret .= ' '.img_picto($countrycode.' '.$langs->trans("AccordingToGeoIPDatabase"), DOL_URL_ROOT.'/theme/common/flags/'.$countrycode.'.png', '', 1);
  2647. } else $ret .= ' ('.$countrycode.')';
  2648. } else {
  2649. // Nothing
  2650. }
  2651. }
  2652. return $ret;
  2653. }
  2654. /**
  2655. * Return the IP of remote user.
  2656. * Take HTTP_X_FORWARDED_FOR (defined when using proxy)
  2657. * Then HTTP_CLIENT_IP if defined (rare)
  2658. * Then REMOTE_ADDR (no way to be modified by user but may be wrong if user is using a proxy)
  2659. *
  2660. * @return string Ip of remote user.
  2661. */
  2662. function getUserRemoteIP()
  2663. {
  2664. if (empty($_SERVER['HTTP_X_FORWARDED_FOR']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_X_FORWARDED_FOR'])) {
  2665. if (empty($_SERVER['HTTP_CLIENT_IP']) || preg_match('/[^0-9\.\:,\[\]]/', $_SERVER['HTTP_CLIENT_IP'])) {
  2666. $ip = (empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']);
  2667. } else {
  2668. $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here
  2669. }
  2670. } else {
  2671. $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here
  2672. }
  2673. return $ip;
  2674. }
  2675. /**
  2676. * Return a country code from IP. Empty string if not found.
  2677. *
  2678. * @param string $ip IP
  2679. * @return string Country code ('us', 'fr', ...)
  2680. */
  2681. function dolGetCountryCodeFromIp($ip)
  2682. {
  2683. global $conf;
  2684. $countrycode = '';
  2685. if (!empty($conf->geoipmaxmind->enabled))
  2686. {
  2687. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2688. //$ip='24.24.24.24';
  2689. //$datafile='/usr/share/GeoIP/GeoIP.dat'; Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
  2690. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2691. $geoip = new DolGeoIP('country', $datafile);
  2692. //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
  2693. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2694. }
  2695. return $countrycode;
  2696. }
  2697. /**
  2698. * Return country code for current user.
  2699. * If software is used inside a local network, detection may fails (we need a public ip)
  2700. *
  2701. * @return string Country code (fr, es, it, us, ...)
  2702. */
  2703. function dol_user_country()
  2704. {
  2705. global $conf, $langs, $user;
  2706. //$ret=$user->xxx;
  2707. $ret = '';
  2708. if (!empty($conf->geoipmaxmind->enabled))
  2709. {
  2710. $ip = getUserRemoteIP();
  2711. $datafile = $conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
  2712. //$ip='24.24.24.24';
  2713. //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
  2714. include_once DOL_DOCUMENT_ROOT.'/core/class/dolgeoip.class.php';
  2715. $geoip = new DolGeoIP('country', $datafile);
  2716. $countrycode = $geoip->getCountryCodeFromIP($ip);
  2717. $ret = $countrycode;
  2718. }
  2719. return $ret;
  2720. }
  2721. /**
  2722. * Format address string
  2723. *
  2724. * @param string $address Address string, already formatted with dol_format_address()
  2725. * @param int $htmlid Html ID (for example 'gmap')
  2726. * @param int $element 'thirdparty'|'contact'|'member'|'other'
  2727. * @param int $id Id of object
  2728. * @param int $noprint No output. Result is the function return
  2729. * @param string $charfornl Char to use instead of nl2br. '' means we use a standad nl2br.
  2730. * @return string|void Nothing if noprint is 0, formatted address if noprint is 1
  2731. * @see dol_format_address()
  2732. */
  2733. function dol_print_address($address, $htmlid, $element, $id, $noprint = 0, $charfornl = '')
  2734. {
  2735. global $conf, $user, $langs, $hookmanager;
  2736. $out = '';
  2737. if ($address)
  2738. {
  2739. if ($hookmanager) {
  2740. $parameters = array('element' => $element, 'id' => $id);
  2741. $reshook = $hookmanager->executeHooks('printAddress', $parameters, $address);
  2742. $out .= $hookmanager->resPrint;
  2743. }
  2744. if (empty($reshook))
  2745. {
  2746. if (empty($charfornl)) $out .= nl2br($address);
  2747. else $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
  2748. // TODO Remove this block, we can add this using the hook now
  2749. $showgmap = $showomap = 0;
  2750. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS)) $showgmap = 1;
  2751. if ($element == 'contact' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) $showgmap = 1;
  2752. if ($element == 'member' && !empty($conf->google->enabled) && !empty($conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) $showgmap = 1;
  2753. if (($element == 'thirdparty' || $element == 'societe') && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS)) $showomap = 1;
  2754. if ($element == 'contact' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) $showomap = 1;
  2755. if ($element == 'member' && !empty($conf->openstreetmap->enabled) && !empty($conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) $showomap = 1;
  2756. if ($showgmap)
  2757. {
  2758. $url = dol_buildpath('/google/gmaps.php?mode='.$element.'&id='.$id, 1);
  2759. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2760. }
  2761. if ($showomap)
  2762. {
  2763. $url = dol_buildpath('/openstreetmap/maps.php?mode='.$element.'&id='.$id, 1);
  2764. $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_URL_ROOT.'/theme/common/gmap.png"></a>';
  2765. }
  2766. }
  2767. }
  2768. if ($noprint) return $out;
  2769. else print $out;
  2770. }
  2771. /**
  2772. * Return true if email syntax is ok.
  2773. *
  2774. * @param string $address email (Ex: "toto@examle.com", "John Do <johndo@example.com>")
  2775. * @param int $acceptsupervisorkey If 1, the special string '__SUPERVISOREMAIL__' is also accepted as valid
  2776. * @return boolean true if email syntax is OK, false if KO or empty string
  2777. * @see isValidMXRecord()
  2778. */
  2779. function isValidEmail($address, $acceptsupervisorkey = 0)
  2780. {
  2781. if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') return true;
  2782. if (filter_var($address, FILTER_VALIDATE_EMAIL)) return true;
  2783. return false;
  2784. }
  2785. /**
  2786. * Return if the domain name has a valid MX record.
  2787. * WARNING: This need function idn_to_ascii, checkdnsrr and getmxrr
  2788. *
  2789. * @param string $domain Domain name (Ex: "yahoo.com", "yhaoo.com", "dolibarr.fr")
  2790. * @return int -1 if error (function not available), 0=Not valid, 1=Valid
  2791. * @see isValidEmail()
  2792. */
  2793. function isValidMXRecord($domain)
  2794. {
  2795. if (function_exists('idn_to_ascii') && function_exists('checkdnsrr'))
  2796. {
  2797. if (!checkdnsrr(idn_to_ascii($domain), 'MX'))
  2798. {
  2799. return 0;
  2800. }
  2801. if (function_exists('getmxrr'))
  2802. {
  2803. $mxhosts = array();
  2804. $weight = array();
  2805. getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
  2806. if (count($mxhosts) > 1) return 1;
  2807. if (count($mxhosts) == 1 && !empty($mxhosts[0])) return 1;
  2808. return 0;
  2809. }
  2810. }
  2811. return -1;
  2812. }
  2813. /**
  2814. * Return true if phone number syntax is ok
  2815. * TODO Decide what to do with this
  2816. *
  2817. * @param string $phone phone (Ex: "0601010101")
  2818. * @return boolean true if phone syntax is OK, false if KO or empty string
  2819. */
  2820. function isValidPhone($phone)
  2821. {
  2822. return true;
  2823. }
  2824. /**
  2825. * Make a strlen call. Works even if mbstring module not enabled
  2826. *
  2827. * @param string $string String to calculate length
  2828. * @param string $stringencoding Encoding of string
  2829. * @return int Length of string
  2830. */
  2831. function dol_strlen($string, $stringencoding = 'UTF-8')
  2832. {
  2833. if (function_exists('mb_strlen')) return mb_strlen($string, $stringencoding);
  2834. else return strlen($string);
  2835. }
  2836. /**
  2837. * Make a substring. Works even if mbstring module is not enabled for better compatibility.
  2838. *
  2839. * @param string $string String to scan
  2840. * @param string $start Start position
  2841. * @param int $length Length (in nb of characters or nb of bytes depending on trunconbytes param)
  2842. * @param string $stringencoding Page code used for input string encoding
  2843. * @param int $trunconbytes 1=Length is max of bytes instead of max of characters
  2844. * @return string substring
  2845. */
  2846. function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
  2847. {
  2848. global $langs;
  2849. if (empty($stringencoding)) $stringencoding = $langs->charset_output;
  2850. $ret = '';
  2851. if (empty($trunconbytes))
  2852. {
  2853. if (function_exists('mb_substr'))
  2854. {
  2855. $ret = mb_substr($string, $start, $length, $stringencoding);
  2856. } else {
  2857. $ret = substr($string, $start, $length);
  2858. }
  2859. } else {
  2860. if (function_exists('mb_strcut'))
  2861. {
  2862. $ret = mb_strcut($string, $start, $length, $stringencoding);
  2863. } else {
  2864. $ret = substr($string, $start, $length);
  2865. }
  2866. }
  2867. return $ret;
  2868. }
  2869. /**
  2870. * Truncate a string to a particular length adding '...' if string larger than length.
  2871. * If length = max length+1, we do no truncate to avoid having just 1 char replaced with '...'.
  2872. * MAIN_DISABLE_TRUNC=1 can disable all truncings
  2873. *
  2874. * @param string $string String to truncate
  2875. * @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 or max+2 or max+3 so it does not worse to replace with ...)
  2876. * @param string $trunc Where to trunc: 'right', 'left', 'middle' (size must be a 2 power), 'wrap'
  2877. * @param string $stringencoding Tell what is source string encoding
  2878. * @param int $nodot Truncation do not add ... after truncation. So it's an exact truncation.
  2879. * @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)
  2880. * @return string Truncated string. WARNING: length is never higher than $size if $nodot is set, but can be 3 chars higher otherwise.
  2881. */
  2882. function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
  2883. {
  2884. global $conf;
  2885. if ($size == 0 || !empty($conf->global->MAIN_DISABLE_TRUNC)) return $string;
  2886. if (empty($stringencoding)) $stringencoding = 'UTF-8';
  2887. // reduce for small screen
  2888. if ($conf->dol_optimize_smallscreen == 1 && $display == 1) $size = round($size / 3);
  2889. // We go always here
  2890. if ($trunc == 'right')
  2891. {
  2892. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2893. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
  2894. return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...');
  2895. else //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
  2896. return $string;
  2897. } elseif ($trunc == 'middle')
  2898. {
  2899. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2900. if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1))
  2901. {
  2902. $size1 = round($size / 2);
  2903. $size2 = round($size / 2);
  2904. return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
  2905. } else return $string;
  2906. } elseif ($trunc == 'left')
  2907. {
  2908. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2909. if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
  2910. return '...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
  2911. else return $string;
  2912. } elseif ($trunc == 'wrap')
  2913. {
  2914. $newstring = dol_textishtml($string) ?dol_string_nohtmltag($string, 1) : $string;
  2915. if (dol_strlen($newstring, $stringencoding) > ($size + 1))
  2916. return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
  2917. else return $string;
  2918. } else return 'BadParam3CallingDolTrunc';
  2919. }
  2920. /**
  2921. * Show picto whatever it's its name (generic function)
  2922. *
  2923. * @param string $titlealt Text on title tag for tooltip. Not used if param notitle is set to 1.
  2924. * @param string $picto Name of image file to show ('filenew', ...)
  2925. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  2926. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  2927. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  2928. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  2929. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  2930. * @param boolean|int $pictoisfullpath If true or 1, image path is a full path
  2931. * @param int $srconly Return only content of the src attribute of img.
  2932. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  2933. * @param string $alt Force alt for bind people
  2934. * @param string $morecss Add more class css on img tag (For example 'myclascss').
  2935. * @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.
  2936. * @return string Return img tag
  2937. * @see img_object(), img_picto_common()
  2938. */
  2939. function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '', $marginleftonlyshort = 2)
  2940. {
  2941. global $conf, $langs;
  2942. // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_URL_ROOT/theme/$conf->theme/img/$picto
  2943. $url = DOL_URL_ROOT;
  2944. $theme = $conf->theme;
  2945. $path = 'theme/'.$theme;
  2946. // Define fullpathpicto to use into src
  2947. if ($pictoisfullpath) {
  2948. // Clean parameters
  2949. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  2950. $picto .= '.png';
  2951. }
  2952. $fullpathpicto = $picto;
  2953. $reg = array();
  2954. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  2955. $morecss .= ($morecss ? ' ' : '').$reg[1];
  2956. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  2957. }
  2958. } else {
  2959. $pictowithouttext = preg_replace('/(\.png|\.gif|\.svg)$/', '', $picto);
  2960. if (empty($srconly) && in_array($pictowithouttext, array(
  2961. '1downarrow', '1uparrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected',
  2962. 'accountancy', 'account', 'accountline', 'action', 'add', 'address', 'bank_account', 'barcode', 'bank', 'bill', 'billa', 'billr', 'billd', 'bookmark', 'bom', 'building',
  2963. 'cash-register', 'category', 'check', 'clock', 'close_title', 'company', 'contact', 'contract', 'cubes',
  2964. 'delete', 'dolly', 'dollyrevert', 'donation', 'edit', 'ellipsis-h', 'email', 'eraser', 'external-link-alt', 'external-link-square-alt',
  2965. 'filter', 'file-code', 'file-export', 'file-import', 'file-upload', 'folder', 'folder-open', 'globe', 'globe-americas', 'grip', 'grip_title', 'group',
  2966. 'help', 'holiday',
  2967. 'intervention', 'label', 'language', 'list', 'listlight', 'lot',
  2968. 'map-marker-alt', 'member', 'money-bill-alt', 'mrp', 'note', 'next',
  2969. 'object_accounting', 'object_account', 'object_accountline', 'object_action', 'object_barcode', 'object_bill', 'object_billa', 'object_billd', 'object_bom',
  2970. 'object_category', 'object_conversation', 'object_bookmark', 'object_bug', 'object_dolly', 'object_dollyrevert', 'object_generic', 'object_folder',
  2971. 'object_list-alt', 'object_calendar', 'object_calendarweek', 'object_calendarmonth', 'object_calendarday', 'object_calendarperuser',
  2972. 'object_cash-register', 'object_company', 'object_contact', 'object_contract', 'object_donation', 'object_dynamicprice',
  2973. 'object_globe', 'object_holiday', 'object_hrm', 'object_invoice', 'object_intervention', 'object_label',
  2974. 'object_margin', 'object_money-bill-alt', 'object_multicurrency', 'object_order', 'object_payment',
  2975. 'object_lot', 'object_mrp', 'object_payment', 'object_product', 'object_propal',
  2976. 'object_other', 'object_paragraph', 'object_poll', 'object_printer', 'object_project', 'object_projectpub', 'object_propal', 'object_resource', 'object_rss', 'object_projecttask',
  2977. 'object_recruitmentjobposition', 'object_recruitmentcandidature',
  2978. 'object_shipment', 'object_share-alt', 'object_supplier_invoice', 'object_supplier_invoicea', 'object_supplier_invoiced', 'object_supplier_order', 'object_supplier_proposal', 'object_service', 'object_stock',
  2979. 'object_technic', 'object_ticket', 'object_trip', 'object_user', 'object_group', 'object_member',
  2980. 'object_phoning', 'object_phoning_mobile', 'object_phoning_fax', 'object_email', 'object_website',
  2981. 'off', 'on', 'order',
  2982. 'paiment', 'play', 'playdisabled', 'previous', 'poll', 'printer', 'product', 'propal', 'projecttask', 'stock', 'resize', 'service', 'stats', 'trip',
  2983. 'setup', 'share-alt', 'sign-out', 'split', 'stripe-s', 'switch_off', 'switch_on', 'tools', 'unlink', 'uparrow', 'user', 'vcard', 'wrench',
  2984. 'jabber', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'youtube', 'google-plus-g', 'whatsapp',
  2985. 'chevron-left', 'chevron-right', 'chevron-down', 'chevron-top', 'commercial', 'companies',
  2986. 'generic', 'home', 'hrm', 'members', 'products', 'invoicing',
  2987. 'payment', 'pencil-ruler', 'preview', 'project', 'projectpub', 'refresh', 'supplier_invoice', 'ticket',
  2988. 'error', 'warning',
  2989. 'recruitmentcandidature', 'recruitmentjobposition', 'resource',
  2990. 'supplier_proposal', 'supplier_order', 'supplier_invoice',
  2991. 'title_setup', 'title_accountancy', 'title_bank', 'title_hrm', 'title_agenda'
  2992. )
  2993. )) {
  2994. $fakey = $pictowithouttext;
  2995. $facolor = ''; $fasize = '';
  2996. $fa = 'fas';
  2997. if (in_array($pictowithouttext, array('clock', 'object_generic', 'note', 'off', 'on', 'object_bookmark', 'bookmark', 'vcard'))) {
  2998. $fa = 'far';
  2999. }
  3000. if (in_array($pictowithouttext, array('black-tie', 'skype', 'twitter', 'facebook', 'linkedin', 'instagram', 'snapchat', 'stripe-s', 'youtube', 'google-plus-g', 'whatsapp'))) {
  3001. $fa = 'fab';
  3002. }
  3003. $pictowithouttext = str_replace('object_', '', $pictowithouttext);
  3004. $arrayconvpictotofa = array(
  3005. 'account'=>'university', 'accountline'=>'receipt', 'accountancy'=>'money-check-alt', 'action'=>'calendar-alt', 'add'=>'plus-circle', 'address'=> 'address-book',
  3006. 'bank_account'=>'university', 'bill'=>'file-invoice-dollar', 'billa'=>'file-excel', 'supplier_invoicea'=>'file-excel', 'billd'=>'file-medical', 'supplier_invoiced'=>'file-medical', 'bom'=>'cubes',
  3007. 'company'=>'building', 'contact'=>'address-book', 'contract'=>'suitcase', 'conversation'=>'comments', 'donation'=>'file-alt', 'dynamicprice'=>'hand-holding-usd',
  3008. 'setup'=>'cog', 'companies'=>'building', 'products'=>'cube', 'commercial'=>'suitcase', 'invoicing'=>'coins',
  3009. 'accounting'=>'chart-line', 'category'=>'tag', 'dollyrevert'=>'dolly',
  3010. 'hrm'=>'user-tie', 'margin'=>'calculator', 'members'=>'users', 'ticket'=>'ticket-alt', 'globe'=>'external-link-alt', 'lot'=>'barcode',
  3011. 'email'=>'at',
  3012. 'edit'=>'pencil-alt', 'grip_title'=>'arrows-alt', 'grip'=>'arrows-alt', 'help'=>'question-circle',
  3013. 'generic'=>'file', 'holiday'=>'umbrella-beach', 'label'=>'layer-group',
  3014. 'member'=>'users', 'mrp'=>'cubes', 'next'=>'arrow-alt-circle-right',
  3015. 'trip'=>'wallet', 'group'=>'users',
  3016. 'sign-out'=>'sign-out-alt',
  3017. 'switch_off'=>'toggle-off', 'switch_on'=>'toggle-on', 'check'=>'check', 'bookmark'=>'star', 'bookmark'=>'star',
  3018. 'bank'=>'university', 'close_title'=>'times', 'delete'=>'trash', 'edit'=>'pencil-alt', 'filter'=>'filter',
  3019. 'list-alt'=>'list-alt', 'calendar'=>'calendar-alt', 'calendarweek'=>'calendar-week', 'calendarmonth'=>'calendar-alt', 'calendarday'=>'calendar-day', 'calendarperuser'=>'table',
  3020. 'intervention'=>'ambulance', 'invoice'=>'file-invoice-dollar', 'multicurrency'=>'dollar-sign', 'order'=>'file-invoice',
  3021. 'error'=>'exclamation-triangle', 'warning'=>'exclamation-triangle',
  3022. 'other'=>'square',
  3023. 'playdisabled'=>'play', 'poll'=>'check-double', 'preview'=>'binoculars', 'project'=>'sitemap', 'projectpub'=>'sitemap', 'projecttask'=>'tasks', 'propal'=>'file-signature',
  3024. 'recruitmentjobposition'=>'id-card-alt', 'recruitmentcandidature'=>'id-badge',
  3025. 'resize'=>'crop', 'supplier_order'=>'dol-order_supplier', 'supplier_proposal'=>'file-signature',
  3026. 'payment'=>'money-check-alt', 'phoning'=>'phone', 'phoning_mobile'=>'mobile-alt', 'phoning_fax'=>'fax', 'previous'=>'arrow-alt-circle-left', 'printer'=>'print', 'product'=>'cube', 'service'=>'concierge-bell',
  3027. 'refresh'=>'redo', 'resource'=>'laptop-house',
  3028. 'shipment'=>'dolly', 'stock'=>'box-open', 'stats' => 'chart-bar', 'split'=>'code-branch', 'supplier_invoice'=>'file-invoice-dollar', 'technic'=>'cogs', 'ticket'=>'ticket-alt',
  3029. 'title_setup'=>'tools', 'title_accountancy'=>'money-check-alt', 'title_bank'=>'university', 'title_hrm'=>'umbrella-beach',
  3030. 'title_agenda'=>'calendar-alt',
  3031. 'uparrow'=>'mail-forward', 'vcard'=>'address-card',
  3032. 'jabber'=>'comment-o',
  3033. 'website'=>'globe-americas'
  3034. );
  3035. if ($pictowithouttext == 'off') {
  3036. $fakey = 'fa-square';
  3037. $fasize = '1.3em';
  3038. } elseif ($pictowithouttext == 'on') {
  3039. $fakey = 'fa-check-square';
  3040. $fasize = '1.3em';
  3041. } elseif ($pictowithouttext == 'listlight') {
  3042. $fakey = 'fa-download';
  3043. $marginleftonlyshort = 1;
  3044. } elseif ($pictowithouttext == 'printer') {
  3045. $fakey = 'fa-print';
  3046. $fasize = '1.2em';
  3047. } elseif ($pictowithouttext == 'note') {
  3048. $fakey = 'fa-sticky-note';
  3049. $marginleftonlyshort = 1;
  3050. } elseif (in_array($pictowithouttext, array('1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'))) {
  3051. $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');
  3052. $fakey = 'fa-'.$convertarray[$pictowithouttext];
  3053. if (preg_match('/selected/', $pictowithouttext)) $facolor = '#888';
  3054. $marginleftonlyshort = 1;
  3055. } elseif (!empty($arrayconvpictotofa[$pictowithouttext]))
  3056. {
  3057. $fakey = 'fa-'.$arrayconvpictotofa[$pictowithouttext];
  3058. } else {
  3059. $fakey = 'fa-'.$pictowithouttext;
  3060. }
  3061. // Define $marginleftonlyshort
  3062. $arrayconvpictotomarginleftonly = array(
  3063. 'bank', 'check', 'delete', 'generic', 'grip', 'grip_title', 'jabber',
  3064. 'grip_title', 'grip', 'listlight', 'note', 'on', 'off', 'playdisabled', 'printer', 'resize', 'sign-out', 'stats', 'switch_on', 'switch_off',
  3065. 'uparrow', '1uparrow', '1downarrow', '1leftarrow', '1rightarrow', '1uparrow_selected', '1downarrow_selected', '1leftarrow_selected', '1rightarrow_selected'
  3066. );
  3067. if (!isset($arrayconvpictotomarginleftonly[$pictowithouttext])) {
  3068. $marginleftonlyshort = 0;
  3069. }
  3070. // Add CSS
  3071. $arrayconvpictotomorcess = array(
  3072. 'action'=>'infobox-action', 'account'=>'infobox-bank_account', 'accountline'=>'infobox-bank_account', 'accountancy'=>'infobox-bank_account',
  3073. 'bank_account'=>'bg-infobox-bank_account',
  3074. 'bill'=>'infobox-commande', 'billa'=>'infobox-commande', 'billd'=>'infobox-commande',
  3075. 'cash-register'=>'infobox-bank_account', 'contract'=>'infobox-contrat', 'check'=>'font-status4', 'conversation'=>'infobox-contrat',
  3076. 'donation'=>'infobox-commande', 'dollyrevert'=>'flip', 'ecm'=>'infobox-action',
  3077. 'hrm'=>'infobox-adherent', 'group'=>'infobox-adherent', 'intervention'=>'infobox-contrat',
  3078. 'multicurrency'=>'infobox-bank_account',
  3079. 'members'=>'infobox-adherent', 'member'=>'infobox-adherent', 'money-bill-alt'=>'infobox-bank_account',
  3080. 'order'=>'infobox-commande',
  3081. 'user'=>'infobox-adherent', 'users'=>'infobox-adherent',
  3082. 'error'=>'pictoerror', 'warning'=>'pictowarning', 'switch_on'=>'font-status4',
  3083. 'holiday'=>'infobox-holiday', 'invoice'=>'infobox-commande',
  3084. 'payment'=>'infobox-bank_account', 'poll'=>'infobox-adherent', 'project'=>'infobox-project', 'projecttask'=>'infobox-project', 'propal'=>'infobox-propal',
  3085. 'recruitmentjobposition'=>'infobox-adherent', 'recruitmentcandidature'=>'infobox-adherent',
  3086. 'resource'=>'infobox-action',
  3087. 'supplier_invoice'=>'infobox-order_supplier', 'supplier_invoicea'=>'infobox-order_supplier', 'supplier_invoiced'=>'infobox-order_supplier',
  3088. 'supplier_order'=>'infobox-order_supplier', 'supplier_proposal'=>'infobox-supplier_proposal',
  3089. 'ticket'=>'infobox-contrat', 'title_accountancy'=>'infobox-bank_account', 'title_hrm'=>'infobox-holiday', 'trip'=>'infobox-expensereport', 'title_agenda'=>'infobox-action',
  3090. //'title_setup'=>'infobox-action', 'tools'=>'infobox-action',
  3091. 'list-alt'=>'imgforviewmode', 'calendar'=>'imgforviewmode', 'calendarweek'=>'imgforviewmode', 'calendarmonth'=>'imgforviewmode', 'calendarday'=>'imgforviewmode', 'calendarperuser'=>'imgforviewmode'
  3092. );
  3093. if (!empty($arrayconvpictotomorcess[$pictowithouttext])) {
  3094. $morecss .= ($morecss ? ' ' : '').$arrayconvpictotomorcess[$pictowithouttext];
  3095. }
  3096. // Define $color
  3097. $arrayconvpictotocolor = array(
  3098. 'address'=>'#6c6aa8', 'building'=>'#6c6aa8', 'bom'=>'#a69944',
  3099. 'companies'=>'#6c6aa8', 'company'=>'#6c6aa8', 'contact'=>'#37a', 'dynamicprice'=>'#a69944',
  3100. 'edit'=>'#444', 'note'=>'#999', 'error'=>'', 'help'=>'#bbb', 'listlight'=>'#999',
  3101. 'dolly'=>'#a69944', 'dollyrevert'=>'#a69944', 'lot'=>'#a69944',
  3102. 'map-marker-alt'=>'#aaa', 'mrp'=>'#a69944', 'product'=>'#a69944', 'service'=>'#a69944', 'stock'=>'#a69944',
  3103. 'other'=>'#ddd',
  3104. 'playdisabled'=>'#ccc', 'printer'=>'#444', 'projectpub'=>'#986c6a', 'resize'=>'#444', 'rss'=>'#cba',
  3105. 'shipment'=>'#a69944', 'stats'=>'#444', 'switch_off'=>'#999', 'uparrow'=>'#555', 'globe-americas'=>'#aaa',
  3106. 'website'=>'#304'
  3107. );
  3108. if (isset($arrayconvpictotocolor[$pictowithouttext])) {
  3109. $facolor = $arrayconvpictotocolor[$pictowithouttext];
  3110. }
  3111. // This snippet only needed since function img_edit accepts only one additional parameter: no separate one for css only.
  3112. // class/style need to be extracted to avoid duplicate class/style validation errors when $moreatt is added to the end of the attributes.
  3113. $morestyle = '';
  3114. $reg = array();
  3115. if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
  3116. $morecss .= ($morecss ? ' ' : '').$reg[1];
  3117. $moreatt = str_replace('class="'.$reg[1].'"', '', $moreatt);
  3118. }
  3119. if (preg_match('/style="([^"]+)"/', $moreatt, $reg)) {
  3120. $morestyle = $reg[1];
  3121. $moreatt = str_replace('style="'.$reg[1].'"', '', $moreatt);
  3122. }
  3123. $moreatt = trim($moreatt);
  3124. $enabledisablehtml = '<span class="'.$fa.' '.$fakey.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? ' marginleftonlyshort' : ' marginleftonly') : '');
  3125. $enabledisablehtml .= ($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').($morestyle ? ' '.$morestyle : '').'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : '').'>';
  3126. /*if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  3127. $enabledisablehtml .= $titlealt;
  3128. }*/
  3129. $enabledisablehtml .= '</span>';
  3130. return $enabledisablehtml;
  3131. }
  3132. if (!empty($conf->global->MAIN_OVERWRITE_THEME_PATH)) {
  3133. $path = $conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
  3134. } elseif (!empty($conf->global->MAIN_OVERWRITE_THEME_RES)) {
  3135. $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
  3136. } elseif (!empty($conf->modules_parts['theme']) && array_key_exists($theme, $conf->modules_parts['theme'])) {
  3137. $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
  3138. }
  3139. // If we ask an image into $url/$mymodule/img (instead of default path)
  3140. $regs = array();
  3141. if (preg_match('/^([^@]+)@([^@]+)$/i', $picto, $regs)) {
  3142. $picto = $regs[1];
  3143. $path = $regs[2]; // $path is $mymodule
  3144. }
  3145. // Clean parameters
  3146. if (!preg_match('/(\.png|\.gif|\.svg)$/i', $picto)) {
  3147. $picto .= '.png';
  3148. }
  3149. // If alt path are defined, define url where img file is, according to physical path
  3150. // ex: array(["main"]=>"/home/maindir/htdocs", ["alt0"]=>"/home/moddir0/htdocs", ...)
  3151. foreach ($conf->file->dol_document_root as $type => $dirroot) {
  3152. if ($type == 'main') {
  3153. continue;
  3154. }
  3155. // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
  3156. if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
  3157. $url = DOL_URL_ROOT.$conf->file->dol_url_root[$type];
  3158. break;
  3159. }
  3160. }
  3161. // $url is '' or '/custom', $path is current theme or
  3162. $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
  3163. }
  3164. if ($srconly) {
  3165. return $fullpathpicto;
  3166. }
  3167. // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for blind people
  3168. return '<img src="'.$fullpathpicto.'" 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
  3169. }
  3170. /**
  3171. * Show a picto called object_picto (generic function)
  3172. *
  3173. * @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.
  3174. * @param string $picto Name of image to show object_picto (example: user, group, action, bill, contract, propal, product, ...)
  3175. * For external modules use imagename@mymodule to search into directory "img" of module.
  3176. * @param string $moreatt Add more attribute on img tag (ie: class="datecallink")
  3177. * @param int $pictoisfullpath If 1, image path is a full path
  3178. * @param int $srconly Return only content of the src attribute of img.
  3179. * @param int $notitle 1=Disable tag title. Use it if you add js tooltip, to avoid duplicate tooltip.
  3180. * @return string Return img tag
  3181. * @see img_picto(), img_picto_common()
  3182. */
  3183. function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
  3184. {
  3185. if (strpos($picto, '^') === 0) return img_picto($titlealt, str_replace('^', '', $picto), $moreatt, $pictoisfullpath, $srconly, $notitle);
  3186. else return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
  3187. }
  3188. /**
  3189. * Show weather picto
  3190. *
  3191. * @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.
  3192. * @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).
  3193. * @param string $moreatt Add more attribute on img tag
  3194. * @param int $pictoisfullpath If 1, image path is a full path
  3195. * @param string $morecss More CSS
  3196. * @return string Return img tag
  3197. * @see img_object(), img_picto()
  3198. */
  3199. function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0, $morecss = '')
  3200. {
  3201. global $conf;
  3202. if (is_numeric($picto)) {
  3203. //$leveltopicto = array(0=>'weather-clear.png', 1=>'weather-few-clouds.png', 2=>'weather-clouds.png', 3=>'weather-many-clouds.png', 4=>'weather-storm.png');
  3204. //$picto = $leveltopicto[$picto];
  3205. return '<i class="fa fa-weather-level'.$picto.'"></i>';
  3206. } elseif (!preg_match('/(\.png|\.gif)$/i', $picto)) {
  3207. $picto .= '.png';
  3208. }
  3209. $path = DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/weather/'.$picto;
  3210. return img_picto($titlealt, $path, $moreatt, 1, 0, 0, '', $morecss);
  3211. }
  3212. /**
  3213. * Show picto (generic function)
  3214. *
  3215. * @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.
  3216. * @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.
  3217. * @param string $moreatt Add more attribute on img tag
  3218. * @param int $pictoisfullpath If 1, image path is a full path
  3219. * @return string Return img tag
  3220. * @see img_object(), img_picto()
  3221. */
  3222. function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
  3223. {
  3224. global $conf;
  3225. if (!preg_match('/(\.png|\.gif)$/i', $picto)) $picto .= '.png';
  3226. if ($pictoisfullpath) $path = $picto;
  3227. else {
  3228. $path = DOL_URL_ROOT.'/theme/common/'.$picto;
  3229. if (!empty($conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS))
  3230. {
  3231. $themepath = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/img/'.$picto;
  3232. if (file_exists($themepath)) $path = $themepath;
  3233. }
  3234. }
  3235. return img_picto($titlealt, $path, $moreatt, 1);
  3236. }
  3237. /**
  3238. * Show logo action
  3239. *
  3240. * @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.
  3241. * @param string $numaction Action id or code to show
  3242. * @param string $picto Name of image file to show ('filenew', ...)
  3243. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  3244. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  3245. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  3246. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  3247. * @return string Return an img tag
  3248. */
  3249. function img_action($titlealt, $numaction, $picto = '')
  3250. {
  3251. global $langs;
  3252. if (empty($titlealt) || $titlealt == 'default')
  3253. {
  3254. if ($numaction == '-1' || $numaction == 'ST_NO') {
  3255. $numaction = -1;
  3256. $titlealt = $langs->transnoentitiesnoconv('ChangeDoNotContact');
  3257. } elseif ($numaction == '0' || $numaction == 'ST_NEVER') {
  3258. $numaction = 0;
  3259. $titlealt = $langs->transnoentitiesnoconv('ChangeNeverContacted');
  3260. } elseif ($numaction == '1' || $numaction == 'ST_TODO') {
  3261. $numaction = 1;
  3262. $titlealt = $langs->transnoentitiesnoconv('ChangeToContact');
  3263. } elseif ($numaction == '2' || $numaction == 'ST_PEND') {
  3264. $numaction = 2;
  3265. $titlealt = $langs->transnoentitiesnoconv('ChangeContactInProcess');
  3266. } elseif ($numaction == '3' || $numaction == 'ST_DONE') {
  3267. $numaction = 3;
  3268. $titlealt = $langs->transnoentitiesnoconv('ChangeContactDone');
  3269. } else {
  3270. $titlealt = $langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
  3271. $numaction = 0;
  3272. }
  3273. }
  3274. if (!is_numeric($numaction)) $numaction = 0;
  3275. return img_picto($titlealt, !empty($picto) ? $picto : 'stcomm'.$numaction.'.png');
  3276. }
  3277. /**
  3278. * Show pdf logo
  3279. *
  3280. * @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.
  3281. * @param int $size Taille de l'icone : 3 = 16x16px , 2 = 14x14px
  3282. * @return string Retourne tag img
  3283. */
  3284. function img_pdf($titlealt = 'default', $size = 3)
  3285. {
  3286. global $langs;
  3287. if ($titlealt == 'default') $titlealt = $langs->trans('Show');
  3288. return img_picto($titlealt, 'pdf'.$size.'.png');
  3289. }
  3290. /**
  3291. * Show logo +
  3292. *
  3293. * @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.
  3294. * @param string $other Add more attributes on img
  3295. * @return string Return tag img
  3296. */
  3297. function img_edit_add($titlealt = 'default', $other = '')
  3298. {
  3299. global $langs;
  3300. if ($titlealt == 'default') $titlealt = $langs->trans('Add');
  3301. return img_picto($titlealt, 'edit_add.png', $other);
  3302. }
  3303. /**
  3304. * Show logo -
  3305. *
  3306. * @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.
  3307. * @param string $other Add more attributes on img
  3308. * @return string Return tag img
  3309. */
  3310. function img_edit_remove($titlealt = 'default', $other = '')
  3311. {
  3312. global $langs;
  3313. if ($titlealt == 'default') $titlealt = $langs->trans('Remove');
  3314. return img_picto($titlealt, 'edit_remove.png', $other);
  3315. }
  3316. /**
  3317. * Show logo editer/modifier fiche
  3318. *
  3319. * @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.
  3320. * @param integer $float If you have to put the style "float: right"
  3321. * @param string $other Add more attributes on img
  3322. * @return string Return tag img
  3323. */
  3324. function img_edit($titlealt = 'default', $float = 0, $other = '')
  3325. {
  3326. global $langs;
  3327. if ($titlealt == 'default') $titlealt = $langs->trans('Modify');
  3328. return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.($langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
  3329. }
  3330. /**
  3331. * Show logo view card
  3332. *
  3333. * @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.
  3334. * @param integer $float If you have to put the style "float: right"
  3335. * @param string $other Add more attributes on img
  3336. * @return string Return tag img
  3337. */
  3338. function img_view($titlealt = 'default', $float = 0, $other = '')
  3339. {
  3340. global $langs;
  3341. if ($titlealt == 'default') $titlealt = $langs->trans('View');
  3342. $moreatt = ($float ? 'style="float: right" ' : '').$other;
  3343. return img_picto($titlealt, 'view.png', $moreatt);
  3344. }
  3345. /**
  3346. * Show delete logo
  3347. *
  3348. * @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.
  3349. * @param string $other Add more attributes on img
  3350. * @param string $morecss More CSS
  3351. * @return string Retourne tag img
  3352. */
  3353. function img_delete($titlealt = 'default', $other = 'class="pictodelete"', $morecss = '')
  3354. {
  3355. global $langs;
  3356. if ($titlealt == 'default') $titlealt = $langs->trans('Delete');
  3357. return img_picto($titlealt, 'delete.png', $other, false, 0, 0, '', $morecss);
  3358. }
  3359. /**
  3360. * Show printer logo
  3361. *
  3362. * @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.
  3363. * @param string $other Add more attributes on img
  3364. * @return string Retourne tag img
  3365. */
  3366. function img_printer($titlealt = "default", $other = '')
  3367. {
  3368. global $langs;
  3369. if ($titlealt == "default") $titlealt = $langs->trans("Print");
  3370. return img_picto($titlealt, 'printer.png', $other);
  3371. }
  3372. /**
  3373. * Show split logo
  3374. *
  3375. * @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.
  3376. * @param string $other Add more attributes on img
  3377. * @return string Retourne tag img
  3378. */
  3379. function img_split($titlealt = 'default', $other = 'class="pictosplit"')
  3380. {
  3381. global $langs;
  3382. if ($titlealt == 'default') $titlealt = $langs->trans('Split');
  3383. return img_picto($titlealt, 'split.png', $other);
  3384. }
  3385. /**
  3386. * Show help logo with cursor "?"
  3387. *
  3388. * @param int $usehelpcursor 1=Use help cursor, 2=Use click pointer cursor, 0=No specific cursor
  3389. * @param int|string $usealttitle Text to use as alt title
  3390. * @return string Return tag img
  3391. */
  3392. function img_help($usehelpcursor = 1, $usealttitle = 1)
  3393. {
  3394. global $langs;
  3395. if ($usealttitle)
  3396. {
  3397. if (is_string($usealttitle)) $usealttitle = dol_escape_htmltag($usealttitle);
  3398. else $usealttitle = $langs->trans('Info');
  3399. }
  3400. return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
  3401. }
  3402. /**
  3403. * Show info logo
  3404. *
  3405. * @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.
  3406. * @return string Return img tag
  3407. */
  3408. function img_info($titlealt = 'default')
  3409. {
  3410. global $langs;
  3411. if ($titlealt == 'default') $titlealt = $langs->trans('Informations');
  3412. return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
  3413. }
  3414. /**
  3415. * Show warning logo
  3416. *
  3417. * @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.
  3418. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"'). If 1, add float: right. Can't be "class" attribute.
  3419. * @param string $morecss Add more CSS
  3420. * @return string Return img tag
  3421. */
  3422. function img_warning($titlealt = 'default', $moreatt = '', $morecss = 'pictowarning')
  3423. {
  3424. global $langs;
  3425. if ($titlealt == 'default') $titlealt = $langs->trans('Warning');
  3426. //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
  3427. return img_picto($titlealt, 'warning.png', 'class="'.$morecss.'"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
  3428. }
  3429. /**
  3430. * Show error logo
  3431. *
  3432. * @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.
  3433. * @return string Return img tag
  3434. */
  3435. function img_error($titlealt = 'default')
  3436. {
  3437. global $langs;
  3438. if ($titlealt == 'default') $titlealt = $langs->trans('Error');
  3439. return img_picto($titlealt, 'error.png');
  3440. }
  3441. /**
  3442. * Show next logo
  3443. *
  3444. * @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.
  3445. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3446. * @return string Return img tag
  3447. */
  3448. function img_next($titlealt = 'default', $moreatt = '')
  3449. {
  3450. global $langs;
  3451. if ($titlealt == 'default') $titlealt = $langs->trans('Next');
  3452. //return img_picto($titlealt, 'next.png', $moreatt);
  3453. return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3454. }
  3455. /**
  3456. * Show previous logo
  3457. *
  3458. * @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.
  3459. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3460. * @return string Return img tag
  3461. */
  3462. function img_previous($titlealt = 'default', $moreatt = '')
  3463. {
  3464. global $langs;
  3465. if ($titlealt == 'default') $titlealt = $langs->trans('Previous');
  3466. //return img_picto($titlealt, 'previous.png', $moreatt);
  3467. return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
  3468. }
  3469. /**
  3470. * Show down arrow logo
  3471. *
  3472. * @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.
  3473. * @param int $selected Selected
  3474. * @param string $moreclass Add more CSS classes
  3475. * @return string Return img tag
  3476. */
  3477. function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
  3478. {
  3479. global $langs;
  3480. if ($titlealt == 'default') $titlealt = $langs->trans('Down');
  3481. return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
  3482. }
  3483. /**
  3484. * Show top arrow logo
  3485. *
  3486. * @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.
  3487. * @param int $selected Selected
  3488. * @param string $moreclass Add more CSS classes
  3489. * @return string Return img tag
  3490. */
  3491. function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
  3492. {
  3493. global $langs;
  3494. if ($titlealt == 'default') $titlealt = $langs->trans('Up');
  3495. return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
  3496. }
  3497. /**
  3498. * Show left arrow logo
  3499. *
  3500. * @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.
  3501. * @param int $selected Selected
  3502. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3503. * @return string Return img tag
  3504. */
  3505. function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
  3506. {
  3507. global $langs;
  3508. if ($titlealt == 'default') {
  3509. $titlealt = $langs->trans('Left');
  3510. }
  3511. return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
  3512. }
  3513. /**
  3514. * Show right arrow logo
  3515. *
  3516. * @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.
  3517. * @param int $selected Selected
  3518. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"')
  3519. * @return string Return img tag
  3520. */
  3521. function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
  3522. {
  3523. global $langs;
  3524. if ($titlealt == 'default') $titlealt = $langs->trans('Right');
  3525. return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
  3526. }
  3527. /**
  3528. * Show tick logo if allowed
  3529. *
  3530. * @param string $allow Allow
  3531. * @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.
  3532. * @return string Return img tag
  3533. */
  3534. function img_allow($allow, $titlealt = 'default')
  3535. {
  3536. global $langs;
  3537. if ($titlealt == 'default') $titlealt = $langs->trans('Active');
  3538. if ($allow == 1) return img_picto($titlealt, 'tick.png');
  3539. return '-';
  3540. }
  3541. /**
  3542. * Return image of a credit card according to its brand name
  3543. *
  3544. * @param string $brand Brand name of credit card
  3545. * @param string $morecss More CSS
  3546. * @return string Return img tag
  3547. */
  3548. function img_credit_card($brand, $morecss = null)
  3549. {
  3550. if (is_null($morecss)) $morecss = 'fa-2x';
  3551. if ($brand == 'visa' || $brand == 'Visa') {
  3552. $brand = 'cc-visa';
  3553. } elseif ($brand == 'mastercard' || $brand == 'MasterCard') {
  3554. $brand = 'cc-mastercard';
  3555. } elseif ($brand == 'amex' || $brand == 'American Express') {
  3556. $brand = 'cc-amex';
  3557. } elseif ($brand == 'discover' || $brand == 'Discover') {
  3558. $brand = 'cc-discover';
  3559. } elseif ($brand == 'jcb' || $brand == 'JCB') {
  3560. $brand = 'cc-jcb';
  3561. } elseif ($brand == 'diners' || $brand == 'Diners club') {
  3562. $brand = 'cc-diners-club';
  3563. } elseif (!in_array($brand, array('cc-visa', 'cc-mastercard', 'cc-amex', 'cc-discover', 'cc-jcb', 'cc-diners-club'))) {
  3564. $brand = 'credit-card';
  3565. }
  3566. return '<span class="fa fa-'.$brand.' fa-fw'.($morecss ? ' '.$morecss : '').'"></span>';
  3567. }
  3568. /**
  3569. * Show MIME img of a file
  3570. *
  3571. * @param string $file Filename
  3572. * @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.
  3573. * @param string $morecss More css
  3574. * @return string Return img tag
  3575. */
  3576. function img_mime($file, $titlealt = '', $morecss = '')
  3577. {
  3578. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  3579. $mimetype = dol_mimetype($file, '', 1);
  3580. $mimeimg = dol_mimetype($file, '', 2);
  3581. $mimefa = dol_mimetype($file, '', 4);
  3582. if (empty($titlealt)) $titlealt = 'Mime type: '.$mimetype;
  3583. //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
  3584. return '<i class="fa fa-'.$mimefa.' paddingright"'.($titlealt ? ' title="'.$titlealt.'"' : '').'></i>';
  3585. }
  3586. /**
  3587. * Show search logo
  3588. *
  3589. * @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.
  3590. * @param string $other Add more attributes on img
  3591. * @return string Retourne tag img
  3592. */
  3593. function img_search($titlealt = 'default', $other = '')
  3594. {
  3595. global $conf, $langs;
  3596. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3597. $img = img_picto($titlealt, 'search.png', $other, false, 1);
  3598. $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
  3599. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3600. return $input;
  3601. }
  3602. /**
  3603. * Show search logo
  3604. *
  3605. * @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.
  3606. * @param string $other Add more attributes on img
  3607. * @return string Retourne tag img
  3608. */
  3609. function img_searchclear($titlealt = 'default', $other = '')
  3610. {
  3611. global $conf, $langs;
  3612. if ($titlealt == 'default') $titlealt = $langs->trans('Search');
  3613. $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
  3614. $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
  3615. $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
  3616. return $input;
  3617. }
  3618. /**
  3619. * Show information for admin users or standard users
  3620. *
  3621. * @param string $text Text info
  3622. * @param integer $infoonimgalt Info is shown only on alt of star picto, otherwise it is show on output after the star picto
  3623. * @param int $nodiv No div
  3624. * @param string $admin '1'=Info for admin users. '0'=Info for standard users (change only the look), 'error','xxx'=Other
  3625. * @param string $morecss More CSS ('', 'warning', 'error')
  3626. * @param string $textfordropdown Show a text to click to dropdown the info box.
  3627. * @return string String with info text
  3628. */
  3629. function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '', $textfordropdown = '')
  3630. {
  3631. global $conf, $langs;
  3632. if ($infoonimgalt)
  3633. {
  3634. $result = img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
  3635. } else {
  3636. if (empty($conf->use_javascript_ajax)) $textfordropdown = '';
  3637. $class = (empty($admin) ? 'undefined' : ($admin == '1' ? 'info' : $admin));
  3638. $result = ($nodiv ? '' : '<div class="'.$class.' hideonsmartphone'.($morecss ? ' '.$morecss : '').($textfordropdown ? ' hidden' : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? $langs->trans('InfoAdmin') : $langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
  3639. if ($textfordropdown) {
  3640. $tmpresult .= '<span class="'.$class.'text opacitymedium cursorpointer">'.$langs->trans($textfordropdown).' '.img_picto($langs->trans($textfordropdown), '1downarrow').'</span>';
  3641. $tmpresult .= '<script type="text/javascript" language="javascript">
  3642. jQuery(document).ready(function() {
  3643. jQuery(".'.$class.'text").click(function() {
  3644. console.log("toggle text");
  3645. jQuery(".'.$class.'").toggle();
  3646. });
  3647. });
  3648. </script>';
  3649. $result = $tmpresult.$result;
  3650. }
  3651. }
  3652. return $result;
  3653. }
  3654. /**
  3655. * Displays error message system with all the information to facilitate the diagnosis and the escalation of the bugs.
  3656. * This function must be called when a blocking technical error is encountered.
  3657. * However, one must try to call it only within php pages, classes must return their error through their property "error".
  3658. *
  3659. * @param DoliDB $db Database handler
  3660. * @param string|string[] $error String or array of errors strings to show
  3661. * @param array $errors Array of errors
  3662. * @return void
  3663. * @see dol_htmloutput_errors()
  3664. */
  3665. function dol_print_error($db = '', $error = '', $errors = null)
  3666. {
  3667. global $conf, $langs, $argv;
  3668. global $dolibarr_main_prod;
  3669. $out = '';
  3670. $syslog = '';
  3671. // If error occurs before the $lang object was loaded
  3672. if (!$langs)
  3673. {
  3674. require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
  3675. $langs = new Translate('', $conf);
  3676. $langs->load("main");
  3677. }
  3678. // Load translation files required by the error messages
  3679. $langs->loadLangs(array('main', 'errors'));
  3680. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3681. {
  3682. $out .= $langs->trans("DolibarrHasDetectedError").".<br>\n";
  3683. if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $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";
  3684. $out .= $langs->trans("InformationToHelpDiagnose").":<br>\n";
  3685. $out .= "<b>".$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
  3686. $out .= "<b>".$langs->trans("Dolibarr").":</b> ".DOL_VERSION." - https://www.dolibarr.org<br>\n";
  3687. if (isset($conf->global->MAIN_FEATURES_LEVEL)) $out .= "<b>".$langs->trans("LevelOfFeature").":</b> ".$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
  3688. if (function_exists("phpversion"))
  3689. {
  3690. $out .= "<b>".$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
  3691. }
  3692. $out .= "<b>".$langs->trans("Server").":</b> ".dol_htmlentities($_SERVER["SERVER_SOFTWARE"])."<br>\n";
  3693. if (function_exists("php_uname"))
  3694. {
  3695. $out .= "<b>".$langs->trans("OS").":</b> ".php_uname()."<br>\n";
  3696. }
  3697. $out .= "<b>".$langs->trans("UserAgent").":</b> ".dol_htmlentities($_SERVER["HTTP_USER_AGENT"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3698. $out .= "<br>\n";
  3699. $out .= "<b>".$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."<br>\n";
  3700. $out .= "<b>".$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '')."<br>\n";
  3701. $out .= "<b>".$langs->trans("MenuManager").":</b> ".(isset($conf->standard_menu) ? dol_htmlentities($conf->standard_menu) : '')."<br>\n";
  3702. $out .= "<br>\n";
  3703. $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
  3704. $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
  3705. } else // Mode CLI
  3706. {
  3707. $out .= '> '.$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
  3708. $syslog .= "pid=".dol_getmypid();
  3709. }
  3710. if (!empty($conf->modules))
  3711. {
  3712. $out .= "<b>".$langs->trans("Modules").":</b> ".join(', ', $conf->modules)."<br>\n";
  3713. }
  3714. if (is_object($db))
  3715. {
  3716. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3717. {
  3718. $out .= "<b>".$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
  3719. $out .= "<b>".$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3720. $out .= "<b>".$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3721. $out .= "<b>".$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : $langs->trans("ErrorNoRequestInError"))."<br>\n";
  3722. $out .= "<br>\n";
  3723. } else // Mode CLI
  3724. {
  3725. // No dol_escape_htmltag for output, we are in CLI mode
  3726. $out .= '> '.$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
  3727. $out .= '> '.$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3728. $out .= '> '.$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3729. $out .= '> '.$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : $langs->transnoentities("ErrorNoRequestInError"))."\n";
  3730. }
  3731. $syslog .= ", sql=".$db->lastquery();
  3732. $syslog .= ", db_error=".$db->lasterror();
  3733. }
  3734. if ($error || $errors)
  3735. {
  3736. $langs->load("errors");
  3737. // Merge all into $errors array
  3738. if (is_array($error) && is_array($errors)) $errors = array_merge($error, $errors);
  3739. elseif (is_array($error)) $errors = $error;
  3740. elseif (is_array($errors)) $errors = array_merge(array($error), $errors);
  3741. else $errors = array_merge(array($error));
  3742. foreach ($errors as $msg)
  3743. {
  3744. if (empty($msg)) continue;
  3745. if ($_SERVER['DOCUMENT_ROOT']) // Mode web
  3746. {
  3747. $out .= "<b>".$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
  3748. } else // Mode CLI
  3749. {
  3750. $out .= '> '.$langs->transnoentities("Message").":\n".$msg."\n";
  3751. }
  3752. $syslog .= ", msg=".$msg;
  3753. }
  3754. }
  3755. if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file'))
  3756. {
  3757. xdebug_print_function_stack();
  3758. $out .= '<b>XDebug informations:</b>'."<br>\n";
  3759. $out .= 'File: '.xdebug_call_file()."<br>\n";
  3760. $out .= 'Line: '.xdebug_call_line()."<br>\n";
  3761. $out .= 'Function: '.xdebug_call_function()."<br>\n";
  3762. $out .= "<br>\n";
  3763. }
  3764. // Return a http error code if possible
  3765. if (!headers_sent()) {
  3766. http_response_code(500);
  3767. }
  3768. if (empty($dolibarr_main_prod)) {
  3769. print $out;
  3770. } else {
  3771. if (empty($langs->defaultlang)) $langs->setDefaultLang();
  3772. $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.
  3773. // This should not happen, except if there is a bug somewhere. Enabled and check log in such case.
  3774. 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 are on next line...<br><br>'."\n";
  3775. print $langs->trans("DolibarrHasDetectedError").'. ';
  3776. print $langs->trans("YouCanSetOptionDolibarrMainProdToZero");
  3777. define("MAIN_CORE_ERROR", 1);
  3778. }
  3779. dol_syslog("Error ".$syslog, LOG_ERR);
  3780. }
  3781. /**
  3782. * Show a public email and error code to contact if technical error
  3783. *
  3784. * @param string $prefixcode Prefix of public error code
  3785. * @param string $errormessage Complete error message
  3786. * @param array $errormessages Array of error messages
  3787. * @param string $morecss More css
  3788. * @param string $email Email
  3789. * @return void
  3790. */
  3791. function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
  3792. {
  3793. global $langs, $conf;
  3794. if (empty($email)) $email = $conf->global->MAIN_INFO_SOCIETE_MAIL;
  3795. $langs->load("errors");
  3796. $now = dol_now();
  3797. print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
  3798. print $langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d%H%M%S'));
  3799. if ($errormessage) print '<br><br>'.$errormessage;
  3800. if (is_array($errormessages) && count($errormessages))
  3801. {
  3802. foreach ($errormessages as $mesgtoshow)
  3803. {
  3804. print '<br><br>'.$mesgtoshow;
  3805. }
  3806. }
  3807. print '</div></div>';
  3808. }
  3809. /**
  3810. * Show title line of an array
  3811. *
  3812. * @param string $name Label of field
  3813. * @param string $file Url used when we click on sort picto
  3814. * @param string $field Field to use for new sorting
  3815. * @param string $begin ("" by defaut)
  3816. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3817. * @param string $moreattrib Options of attribute td ("" by defaut, example: 'align="center"')
  3818. * @param string $sortfield Current field used to sort
  3819. * @param string $sortorder Current sort order
  3820. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag.
  3821. * @param string $tooltip Tooltip
  3822. * @return void
  3823. */
  3824. function print_liste_field_titre($name, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $tooltip = "")
  3825. {
  3826. print getTitleFieldOfList($name, 0, $file, $field, $begin, $moreparam, $moreattrib, $sortfield, $sortorder, $prefix, 0, $tooltip);
  3827. }
  3828. /**
  3829. * Get title line of an array
  3830. *
  3831. * @param string $name Translation key of field
  3832. * @param int $thead 0=To use with standard table format, 1=To use inside <thead><tr>, 2=To use with <div>
  3833. * @param string $file Url used when we click on sort picto
  3834. * @param string $field Field to use for new sorting. Empty if this field is not sortable. Example "t.abc" or "t.abc,t.def"
  3835. * @param string $begin ("" by defaut)
  3836. * @param string $moreparam Add more parameters on sort url links ("" by default)
  3837. * @param string $moreattrib Add more attributes on th ("" by defaut, example: 'align="center"'). To add more css class, use param $prefix.
  3838. * @param string $sortfield Current field used to sort (Ex: 'd.datep,d.id')
  3839. * @param string $sortorder Current sort order (Ex: 'asc,desc')
  3840. * @param string $prefix Prefix for css. Use space after prefix to add your own CSS tag, for example 'mycss '.
  3841. * @param string $disablesortlink 1=Disable sort link
  3842. * @param string $tooltip Tooltip
  3843. * @return string
  3844. */
  3845. function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '')
  3846. {
  3847. global $conf, $langs, $form;
  3848. //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
  3849. if ($moreattrib == 'class="right"') $prefix .= 'right '; // For backward compatibility
  3850. $sortorder = strtoupper($sortorder);
  3851. $out = '';
  3852. $sortimg = '';
  3853. $tag = 'th';
  3854. if ($thead == 2) $tag = 'div';
  3855. $tmpsortfield = explode(',', $sortfield);
  3856. $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
  3857. $tmpfield = explode(',', $field);
  3858. $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
  3859. if (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE)) {
  3860. $prefix = 'wrapcolumntitle '.$prefix;
  3861. }
  3862. //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
  3863. // If field is used as sort criteria we use a specific css class liste_titre_sel
  3864. // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
  3865. $liste_titre = 'liste_titre';
  3866. if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
  3867. $liste_titre = 'liste_titre_sel';
  3868. }
  3869. $out .= '<'.$tag.' class="'.$prefix.$liste_titre.'" '.$moreattrib;
  3870. //$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)).'"' : '');
  3871. $out .= (($field && empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE)) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3872. $out .= '>';
  3873. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3874. {
  3875. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  3876. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3877. $options = preg_replace('/&+/i', '&', $options);
  3878. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3879. $sortordertouseinlink = '';
  3880. if ($field1 != $sortfield1) // We are on another field than current sorted field
  3881. {
  3882. if (preg_match('/^DESC/i', $sortorder))
  3883. {
  3884. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3885. } else // We reverse the var $sortordertouseinlink
  3886. {
  3887. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3888. }
  3889. } else // We are on field that is the first current sorting criteria
  3890. {
  3891. if (preg_match('/^ASC/i', $sortorder)) // We reverse the var $sortordertouseinlink
  3892. {
  3893. $sortordertouseinlink .= str_repeat('desc,', count(explode(',', $field)));
  3894. } else {
  3895. $sortordertouseinlink .= str_repeat('asc,', count(explode(',', $field)));
  3896. }
  3897. }
  3898. $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
  3899. $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'"';
  3900. //$out .= (empty($conf->global->MAIN_DISABLE_WRAPPING_ON_COLUMN_TITLE) ? ' title="'.dol_escape_htmltag($langs->trans($name)).'"' : '');
  3901. $out .= '>';
  3902. }
  3903. if ($tooltip) $out .= $form->textwithpicto($langs->trans($name), $langs->trans($tooltip));
  3904. else $out .= $langs->trans($name);
  3905. if (empty($thead) && $field && empty($disablesortlink)) // If this is a sort field
  3906. {
  3907. $out .= '</a>';
  3908. }
  3909. if (empty($thead) && $field) // If this is a sort field
  3910. {
  3911. $options = preg_replace('/sortfield=([a-zA-Z0-9,\s\.]+)/i', '', (is_scalar($moreparam) ? $moreparam : ''));
  3912. $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
  3913. $options = preg_replace('/&+/i', '&', $options);
  3914. if (!preg_match('/^&/', $options)) $options = '&'.$options;
  3915. if (!$sortorder || $field1 != $sortfield1)
  3916. {
  3917. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3918. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3919. } else {
  3920. if (preg_match('/^DESC/', $sortorder)) {
  3921. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
  3922. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
  3923. $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0, 'paddingleft').'</span>';
  3924. }
  3925. if (preg_match('/^ASC/', $sortorder)) {
  3926. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
  3927. //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
  3928. $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0, 'paddingleft').'</span>';
  3929. }
  3930. }
  3931. }
  3932. $out .= $sortimg;
  3933. $out .= '</'.$tag.'>';
  3934. return $out;
  3935. }
  3936. /**
  3937. * Show a title.
  3938. *
  3939. * @param string $title Title to show
  3940. * @return string Title to show
  3941. * @deprecated Use load_fiche_titre instead
  3942. * @see load_fiche_titre()
  3943. */
  3944. function print_titre($title)
  3945. {
  3946. dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
  3947. print '<div class="titre">'.$title.'</div>';
  3948. }
  3949. /**
  3950. * Show a title with picto
  3951. *
  3952. * @param string $title Title to show
  3953. * @param string $mesg Added message to show on right
  3954. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3955. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3956. * @param int $id To force an id on html objects
  3957. * @return void
  3958. * @deprecated Use print load_fiche_titre instead
  3959. */
  3960. function print_fiche_titre($title, $mesg = '', $picto = 'generic', $pictoisfullpath = 0, $id = '')
  3961. {
  3962. print load_fiche_titre($title, $mesg, $picto, $pictoisfullpath, $id);
  3963. }
  3964. /**
  3965. * Load a title with picto
  3966. *
  3967. * @param string $titre Title to show
  3968. * @param string $morehtmlright Added message to show on right
  3969. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  3970. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  3971. * @param string $id To force an id on html objects
  3972. * @param string $morecssontable More css on table
  3973. * @param string $morehtmlcenter Added message to show on center
  3974. * @return string
  3975. * @see print_barre_liste()
  3976. */
  3977. function load_fiche_titre($titre, $morehtmlright = '', $picto = 'generic', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
  3978. {
  3979. global $conf;
  3980. $return = '';
  3981. if ($picto == 'setup') $picto = 'generic';
  3982. $return .= "\n";
  3983. $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'class="centpercent notopnoleftnoright table-fiche-title'.($morecssontable ? ' '.$morecssontable : '').'">'; // maring bottom must be same than into print_barre_list
  3984. $return .= '<tr class="titre">';
  3985. if ($picto) $return .= '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
  3986. $return .= '<td class="nobordernopadding valignmiddle col-title">';
  3987. $return .= '<div class="titre inline-block">'.$titre.'</div>';
  3988. $return .= '</td>';
  3989. if (dol_strlen($morehtmlcenter))
  3990. {
  3991. $return .= '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  3992. }
  3993. if (dol_strlen($morehtmlright))
  3994. {
  3995. $return .= '<td class="nobordernopadding titre_right wordbreakimp right valignmiddle">'.$morehtmlright.'</td>';
  3996. }
  3997. $return .= '</tr></table>'."\n";
  3998. return $return;
  3999. }
  4000. /**
  4001. * Print a title with navigation controls for pagination
  4002. *
  4003. * @param string $titre Title to show (required)
  4004. * @param int $page Numero of page to show in navigation links (required)
  4005. * @param string $file Url of page (required)
  4006. * @param string $options More parameters for links ('' by default, does not include sortfield neither sortorder). Value must be 'urlencoded' before calling function.
  4007. * @param string $sortfield Field to sort on ('' by default)
  4008. * @param string $sortorder Order to sort ('' by default)
  4009. * @param string $morehtmlcenter String in the middle ('' by default). We often find here string $massaction comming from $form->selectMassAction()
  4010. * @param int $num Number of records found by select with limit+1
  4011. * @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.
  4012. * @param string $picto Icon to use before title (should be a 32x32 transparent png file)
  4013. * @param int $pictoisfullpath 1=Icon name is a full absolute url of image
  4014. * @param string $morehtmlright More html to show (after arrows)
  4015. * @param string $morecss More css to the table
  4016. * @param int $limit Max number of lines (-1 = use default, 0 = no limit, > 0 = limit).
  4017. * @param int $hideselectlimit Force to hide select limit
  4018. * @param int $hidenavigation Force to hide all navigation tools
  4019. * @param int $pagenavastextinput 1=Do not suggest list of pages to navigate but suggest the page number into an input field.
  4020. * @param string $morehtmlrightbeforearrow More html to show (before arrows)
  4021. * @return void
  4022. */
  4023. 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 = '')
  4024. {
  4025. global $conf, $langs;
  4026. $savlimit = $limit;
  4027. $savtotalnboflines = $totalnboflines;
  4028. $totalnboflines = abs($totalnboflines);
  4029. if ($picto == 'setup') $picto = 'title_setup.png';
  4030. if (($conf->browser->name == 'ie') && $picto == 'generic') $picto = 'title.gif';
  4031. if ($limit < 0) $limit = $conf->liste_limit;
  4032. if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0)))
  4033. {
  4034. $nextpage = 1;
  4035. } else {
  4036. $nextpage = 0;
  4037. }
  4038. //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
  4039. print "\n";
  4040. print "<!-- Begin title '".$titre."' -->\n";
  4041. print '<table class="centpercent notopnoleftnoright table-fiche-title'.($morecss ? ' '.$morecss : '').'"><tr>'; // maring bottom must be same than into load_fiche_tire
  4042. // Left
  4043. if ($picto && $titre) print '<td class="nobordernopadding widthpictotitle valignmiddle col-picto">'.img_picto('', $picto, 'class="valignmiddle pictotitle widthpictotitle"', $pictoisfullpath).'</td>';
  4044. print '<td class="nobordernopadding valignmiddle col-title">';
  4045. print '<div class="titre inline-block">'.$titre;
  4046. if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') print '<span class="opacitymedium colorblack paddingleft">('.$totalnboflines.')</span>';
  4047. print '</div></td>';
  4048. // Center
  4049. if ($morehtmlcenter)
  4050. {
  4051. print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
  4052. }
  4053. // Right
  4054. print '<td class="nobordernopadding valignmiddle right">';
  4055. print '<input type="hidden" name="pageplusoneold" value="'.((int) $page + 1).'">';
  4056. if ($sortfield) $options .= "&sortfield=".urlencode($sortfield);
  4057. if ($sortorder) $options .= "&sortorder=".urlencode($sortorder);
  4058. // Show navigation bar
  4059. $pagelist = '';
  4060. if ($savlimit != 0 && ($page > 0 || $num > $limit))
  4061. {
  4062. if ($totalnboflines) // If we know total nb of lines
  4063. {
  4064. // Define nb of extra page links before and after selected page + ... + first or last
  4065. $maxnbofpage = (empty($conf->dol_optimize_smallscreen) ? 4 : 0);
  4066. if ($limit > 0) $nbpages = ceil($totalnboflines / $limit);
  4067. else $nbpages = 1;
  4068. $cpt = ($page - $maxnbofpage);
  4069. if ($cpt < 0) { $cpt = 0; }
  4070. if ($cpt >= 1)
  4071. {
  4072. if (empty($pagenavastextinput)) {
  4073. $pagelist .= '<li class="pagination"><a href="'.$file.'?page=0'.$options.'">1</a></li>';
  4074. if ($cpt > 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4075. elseif ($cpt == 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page=1'.$options.'">2</a></li>';
  4076. }
  4077. }
  4078. do {
  4079. if ($pagenavastextinput) {
  4080. if ($cpt == $page)
  4081. {
  4082. $pagelist .= '<li class="pagination"><input type="text" class="width25 center pageplusone" name="pageplusone" value="'.($page + 1).'"></li>';
  4083. $pagelist .= '/';
  4084. //if (($cpt + 1) < $nbpages) $pagelist .= '/';
  4085. }
  4086. } else {
  4087. if ($cpt == $page)
  4088. {
  4089. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1).'</span></li>';
  4090. } else {
  4091. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
  4092. }
  4093. }
  4094. $cpt++;
  4095. } while ($cpt < $nbpages && $cpt <= ($page + $maxnbofpage));
  4096. if (empty($pagenavastextinput)) {
  4097. if ($cpt < $nbpages)
  4098. {
  4099. if ($cpt < $nbpages - 2) $pagelist .= '<li class="pagination"><span class="inactive">...</span></li>';
  4100. elseif ($cpt == $nbpages - 2) $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
  4101. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4102. }
  4103. } else {
  4104. //var_dump($page.' '.$cpt.' '.$nbpages);
  4105. //if (($page + 1) < $nbpages) {
  4106. $pagelist .= '<li class="pagination"><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
  4107. //}
  4108. }
  4109. } else {
  4110. $pagelist .= '<li class="pagination"><span class="active">'.($page + 1)."</li>";
  4111. }
  4112. }
  4113. if ($savlimit || $morehtmlright || $morehtmlrightbeforearrow) {
  4114. print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit, $morehtmlrightbeforearrow); // output the div and ul for previous/last completed with page numbers into $pagelist
  4115. }
  4116. // js to autoselect page field on focus
  4117. if ($pagenavastextinput) {
  4118. print ajax_autoselect('.pageplusone');
  4119. }
  4120. print '</td>';
  4121. print '</tr></table>'."\n";
  4122. print "<!-- End title -->\n\n";
  4123. }
  4124. /**
  4125. * Function to show navigation arrows into lists
  4126. *
  4127. * @param int $page Number of page
  4128. * @param string $file Page URL (in most cases provided with $_SERVER["PHP_SELF"])
  4129. * @param string $options Other url parameters to propagate ("" by default, may include sortfield and sortorder)
  4130. * @param integer $nextpage Do we show a next page button
  4131. * @param string $betweenarrows HTML content to show between arrows. MUST contains '<li> </li>' tags or '<li><span> </span></li>'.
  4132. * @param string $afterarrows HTML content to show after arrows. Must NOT contains '<li> </li>' tags.
  4133. * @param int $limit Max nb of record to show (-1 = no combo with limit, 0 = no limit, > 0 = limit)
  4134. * @param int $totalnboflines Total number of records/lines for all pages (if known)
  4135. * @param int $hideselectlimit Force to hide select limit
  4136. * @param string $beforearrows HTML content to show before arrows. Must NOT contains '<li> </li>' tags.
  4137. * @return void
  4138. */
  4139. function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0, $beforearrows = '')
  4140. {
  4141. global $conf, $langs;
  4142. print '<div class="pagination"><ul>';
  4143. if ($beforearrows)
  4144. {
  4145. print '<li class="paginationbeforearrows">';
  4146. print $beforearrows;
  4147. print '</li>';
  4148. }
  4149. if ((int) $limit > 0 && empty($hideselectlimit))
  4150. {
  4151. $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
  4152. //$pagesizechoices.=',0:'.$langs->trans("All"); // Not yet supported
  4153. //$pagesizechoices.=',2:2';
  4154. if (!empty($conf->global->MAIN_PAGESIZE_CHOICES)) $pagesizechoices = $conf->global->MAIN_PAGESIZE_CHOICES;
  4155. print '<li class="pagination">';
  4156. print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag($langs->trans("MaxNbOfRecordPerPage")).'">';
  4157. $tmpchoice = explode(',', $pagesizechoices);
  4158. $tmpkey = $limit.':'.$limit;
  4159. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4160. $tmpkey = $conf->liste_limit.':'.$conf->liste_limit;
  4161. if (!in_array($tmpkey, $tmpchoice)) $tmpchoice[] = $tmpkey;
  4162. asort($tmpchoice, SORT_NUMERIC);
  4163. foreach ($tmpchoice as $val)
  4164. {
  4165. $selected = '';
  4166. $tmp = explode(':', $val);
  4167. $key = $tmp[0];
  4168. $val = $tmp[1];
  4169. if ($key != '' && $val != '')
  4170. {
  4171. if ((int) $key == (int) $limit)
  4172. {
  4173. $selected = ' selected="selected"';
  4174. }
  4175. print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
  4176. }
  4177. }
  4178. print '</select>';
  4179. if ($conf->use_javascript_ajax)
  4180. {
  4181. print '<!-- JS CODE TO ENABLE select limit to launch submit of page -->
  4182. <script>
  4183. jQuery(document).ready(function () {
  4184. jQuery(".selectlimit").change(function() {
  4185. console.log("Change limit. Send submit");
  4186. $(this).parents(\'form:first\').submit();
  4187. });
  4188. });
  4189. </script>
  4190. ';
  4191. }
  4192. print '</li>';
  4193. }
  4194. if ($page > 0)
  4195. {
  4196. 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>';
  4197. }
  4198. if ($betweenarrows)
  4199. {
  4200. print '<!--<div class="betweenarrows nowraponall inline-block">-->';
  4201. print $betweenarrows;
  4202. print '<!--</div>-->';
  4203. }
  4204. if ($nextpage > 0)
  4205. {
  4206. 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>';
  4207. }
  4208. if ($afterarrows)
  4209. {
  4210. print '<li class="paginationafterarrows">';
  4211. print $afterarrows;
  4212. print '</li>';
  4213. }
  4214. print '</ul></div>'."\n";
  4215. }
  4216. /**
  4217. * Return a string with VAT rate label formated for view output
  4218. * Used into pdf and HTML pages
  4219. *
  4220. * @param string $rate Rate value to format ('19.6', '19,6', '19.6%', '19,6%', '19.6 (CODEX)', ...)
  4221. * @param boolean $addpercent Add a percent % sign in output
  4222. * @param int $info_bits Miscellaneous information on vat (0=Default, 1=French NPR vat)
  4223. * @param int $usestarfornpr -1=Never show, 0 or 1=Use '*' for NPR vat rates
  4224. * @return string String with formated amounts ('19,6' or '19,6%' or '8.5% (NPR)' or '8.5% *' or '19,6 (CODEX)')
  4225. */
  4226. function vatrate($rate, $addpercent = false, $info_bits = 0, $usestarfornpr = 0)
  4227. {
  4228. $morelabel = '';
  4229. if (preg_match('/%/', $rate))
  4230. {
  4231. $rate = str_replace('%', '', $rate);
  4232. $addpercent = true;
  4233. }
  4234. if (preg_match('/\((.*)\)/', $rate, $reg))
  4235. {
  4236. $morelabel = ' ('.$reg[1].')';
  4237. $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
  4238. }
  4239. if (preg_match('/\*/', $rate))
  4240. {
  4241. $rate = str_replace('*', '', $rate);
  4242. $info_bits |= 1;
  4243. }
  4244. // If rate is '9/9/9' we don't change it. If rate is '9.000' we apply price()
  4245. if (!preg_match('/\//', $rate)) $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
  4246. else {
  4247. // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
  4248. $ret = $rate.($addpercent ? '%' : '');
  4249. }
  4250. if (($info_bits & 1) && $usestarfornpr >= 0) $ret .= ' *';
  4251. $ret .= $morelabel;
  4252. return $ret;
  4253. }
  4254. /**
  4255. * Function to format a value into an amount for visual output
  4256. * Function used into PDF and HTML pages
  4257. *
  4258. * @param float $amount Amount to format
  4259. * @param integer $form Type of format, HTML or not (not by default)
  4260. * @param Translate $outlangs Object langs for output
  4261. * @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.
  4262. * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  4263. * @param int $forcerounding Force the number of decimal to forcerounding decimal (-1=do not force)
  4264. * @param string $currency_code To add currency symbol (''=add nothing, 'auto'=Use default currency, 'XXX'=add currency symbols for XXX currency)
  4265. * @return string Chaine avec montant formate
  4266. *
  4267. * @see price2num() Revert function of price
  4268. */
  4269. function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
  4270. {
  4271. global $langs, $conf;
  4272. // Clean parameters
  4273. if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = ''
  4274. $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
  4275. if ($rounding < 0) $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4276. $nbdecimal = $rounding;
  4277. // Output separators by default (french)
  4278. $dec = ','; $thousand = ' ';
  4279. // If $outlangs not forced, we use use language
  4280. if (!is_object($outlangs)) $outlangs = $langs;
  4281. if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
  4282. if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
  4283. if ($thousand == 'None') $thousand = '';
  4284. elseif ($thousand == 'Space') $thousand = ' ';
  4285. //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4286. //print "amount=".$amount."-";
  4287. $amount = str_replace(',', '.', $amount); // should be useless
  4288. //print $amount."-";
  4289. $datas = explode('.', $amount);
  4290. $decpart = isset($datas[1]) ? $datas[1] : '';
  4291. $decpart = preg_replace('/0+$/i', '', $decpart); // Supprime les 0 de fin de partie decimale
  4292. //print "decpart=".$decpart."<br>";
  4293. $end = '';
  4294. // We increase nbdecimal if there is more decimal than asked (to not loose information)
  4295. if (dol_strlen($decpart) > $nbdecimal) $nbdecimal = dol_strlen($decpart);
  4296. // Si on depasse max
  4297. if ($trunc && $nbdecimal > $conf->global->MAIN_MAX_DECIMALS_SHOWN)
  4298. {
  4299. $nbdecimal = $conf->global->MAIN_MAX_DECIMALS_SHOWN;
  4300. if (preg_match('/\.\.\./i', $conf->global->MAIN_MAX_DECIMALS_SHOWN))
  4301. {
  4302. // Si un affichage est tronque, on montre des ...
  4303. $end = '...';
  4304. }
  4305. }
  4306. // If force rounding
  4307. if ($forcerounding >= 0) $nbdecimal = $forcerounding;
  4308. // Format number
  4309. $output = number_format($amount, $nbdecimal, $dec, $thousand);
  4310. if ($form)
  4311. {
  4312. $output = preg_replace('/\s/', '&nbsp;', $output);
  4313. $output = preg_replace('/\'/', '&#039;', $output);
  4314. }
  4315. // Add symbol of currency if requested
  4316. $cursymbolbefore = $cursymbolafter = '';
  4317. if ($currency_code)
  4318. {
  4319. if ($currency_code == 'auto') $currency_code = $conf->currency;
  4320. $listofcurrenciesbefore = array('AUD', 'CAD', 'CNY', 'COP', 'CLP', 'GBP', 'HKD', 'MXN', 'PEN', 'USD');
  4321. $listoflanguagesbefore = array('nl_NL');
  4322. if (in_array($currency_code, $listofcurrenciesbefore) || in_array($outlangs->defaultlang, $listoflanguagesbefore))
  4323. {
  4324. $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
  4325. } else {
  4326. $tmpcur = $outlangs->getCurrencySymbol($currency_code);
  4327. $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
  4328. }
  4329. }
  4330. $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
  4331. return $output;
  4332. }
  4333. /**
  4334. * Function that return a number with universal decimal format (decimal separator is '.') from an amount typed by a user.
  4335. * Function to use on each input amount before any numeric test or database insert. A better name for this function
  4336. * should be roundtext2num().
  4337. *
  4338. * @param string|float $amount Amount to convert/clean or round
  4339. * @param string $rounding ''=No rounding
  4340. * 'MU'=Round to Max unit price (MAIN_MAX_DECIMALS_UNIT)
  4341. * 'MT'=Round to Max for totals with Tax (MAIN_MAX_DECIMALS_TOT)
  4342. * 'MS'=Round to Max for stock quantity (MAIN_MAX_DECIMALS_STOCK)
  4343. * 'CR'=Currency rate
  4344. * Numeric = Nb of digits for rounding
  4345. * @param int $option Put 1 if you know that content is already universal format number (so no correction on decimal will be done)
  4346. * Put 2 if you know that number is a user input (so we know we don't have to fix decimal separator).
  4347. * @return string Amount with universal numeric format (Example: '99.99999').
  4348. * If conversion fails, it return text unchanged if $rounding = '' or '0' if $rounding is defined.
  4349. * If amount is null or '', it returns '' if $rounding = '' or '0' if $rounding is defined..
  4350. *
  4351. * @see price() Opposite function of price2num
  4352. */
  4353. function price2num($amount, $rounding = '', $option = 0)
  4354. {
  4355. global $langs, $conf;
  4356. // Round PHP function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
  4357. // Numbers must be '1234.56'
  4358. // Decimal delimiter for PHP and database SQL requests must be '.'
  4359. $dec = ','; $thousand = ' ';
  4360. if ($langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") $dec = $langs->transnoentitiesnoconv("SeparatorDecimal");
  4361. if ($langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") $thousand = $langs->transnoentitiesnoconv("SeparatorThousand");
  4362. if ($thousand == 'None') $thousand = '';
  4363. elseif ($thousand == 'Space') $thousand = ' ';
  4364. //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
  4365. // Convert value to universal number format (no thousand separator, '.' as decimal separator)
  4366. if ($option != 1) { // If not a PHP number or unknown, we change or clean format
  4367. //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
  4368. if (!is_numeric($amount)) {
  4369. $amount = preg_replace('/[a-zA-Z\/\\\*\(\)\<\>\-]/', '', $amount);
  4370. }
  4371. if ($option == 2 && $thousand == '.' && preg_match('/\.(\d\d\d)$/', (string) $amount)) { // It means the . is used as a thousand separator and string come frominput data, so 1.123 is 1123
  4372. $amount = str_replace($thousand, '', $amount);
  4373. }
  4374. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4375. // to format defined by LC_NUMERIC after a calculation and we want source format to be like defined by Dolibarr setup.
  4376. // So if number was already a good number, it is converted into local Dolibarr setup.
  4377. if (is_numeric($amount))
  4378. {
  4379. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4380. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4381. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4382. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4383. $amount = number_format($amount, $nbofdec, $dec, $thousand);
  4384. }
  4385. //print "QQ".$amount."<br>\n";
  4386. // Now make replace (the main goal of function)
  4387. if ($thousand != ',' && $thousand != '.') {
  4388. $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4389. }
  4390. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4391. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4392. $amount = str_replace($dec, '.', $amount);
  4393. }
  4394. // Now, make a rounding if required
  4395. if ($rounding)
  4396. {
  4397. $nbofdectoround = '';
  4398. if ($rounding == 'MU') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_UNIT;
  4399. elseif ($rounding == 'MT') $nbofdectoround = $conf->global->MAIN_MAX_DECIMALS_TOT;
  4400. elseif ($rounding == 'MS') $nbofdectoround = empty($conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : $conf->global->MAIN_MAX_DECIMALS_STOCK;
  4401. elseif ($rounding == 'CR') $nbofdectoround = 8;
  4402. elseif (is_numeric($rounding)) $nbofdectoround = $rounding;
  4403. //print "RR".$amount.' - '.$nbofdectoround.'<br>';
  4404. if (dol_strlen($nbofdectoround)) $amount = round($amount, $nbofdectoround); // $nbofdectoround can be 0.
  4405. else return 'ErrorBadParameterProvidedToFunction';
  4406. //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
  4407. // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
  4408. // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
  4409. if (is_numeric($amount))
  4410. {
  4411. // We put in temps value of decimal ("0.00001"). Works with 0 and 2.0E-5 and 9999.10
  4412. $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
  4413. $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
  4414. $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
  4415. $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
  4416. }
  4417. //print "TT".$amount.'<br>';
  4418. // Always make replace because each math function (like round) replace
  4419. // with local values and we want a number that has a SQL string format x.y
  4420. if ($thousand != ',' && $thousand != '.') $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
  4421. $amount = str_replace(' ', '', $amount); // To avoid spaces
  4422. $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
  4423. $amount = str_replace($dec, '.', $amount);
  4424. }
  4425. return $amount;
  4426. }
  4427. /**
  4428. * Output a dimension with best unit
  4429. *
  4430. * @param float $dimension Dimension
  4431. * @param int $unit Unit scale of dimension (Example: 0=kg, -3=g, -6=mg, 98=ounce, 99=pound, ...)
  4432. * @param string $type 'weight', 'volume', ...
  4433. * @param Translate $outputlangs Translate language object
  4434. * @param int $round -1 = non rounding, x = number of decimal
  4435. * @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)
  4436. * @return string String to show dimensions
  4437. */
  4438. function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
  4439. {
  4440. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4441. if (($forceunitoutput == 'no' && $dimension < 1 / 10000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -6))
  4442. {
  4443. $dimension = $dimension * 1000000;
  4444. $unit = $unit - 6;
  4445. } elseif (($forceunitoutput == 'no' && $dimension < 1 / 10 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == -3))
  4446. {
  4447. $dimension = $dimension * 1000;
  4448. $unit = $unit - 3;
  4449. } elseif (($forceunitoutput == 'no' && $dimension > 100000000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 6))
  4450. {
  4451. $dimension = $dimension / 1000000;
  4452. $unit = $unit + 6;
  4453. } elseif (($forceunitoutput == 'no' && $dimension > 100000 && $unit < 90) || (is_numeric($forceunitoutput) && $forceunitoutput == 3))
  4454. {
  4455. $dimension = $dimension / 1000;
  4456. $unit = $unit + 3;
  4457. }
  4458. // Special case when we want output unit into pound or ounce
  4459. /* TODO
  4460. if ($unit < 90 && $type == 'weight' && is_numeric($forceunitoutput) && (($forceunitoutput == 98) || ($forceunitoutput == 99))
  4461. {
  4462. $dimension = // convert dimension from standard unit into ounce or pound
  4463. $unit = $forceunitoutput;
  4464. }
  4465. if ($unit > 90 && $type == 'weight' && is_numeric($forceunitoutput) && $forceunitoutput < 90)
  4466. {
  4467. $dimension = // convert dimension from standard unit into ounce or pound
  4468. $unit = $forceunitoutput;
  4469. }*/
  4470. $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuringUnitString(0, $type, $unit);
  4471. return $ret;
  4472. }
  4473. /**
  4474. * Return localtax rate for a particular vat, when selling a product with vat $vatrate, from a $thirdparty_buyer to a $thirdparty_seller
  4475. * Note: This function applies same rules than get_default_tva
  4476. *
  4477. * @param float $vatrate Vat rate. Can be '8.5' or '8.5 (VATCODEX)' for example
  4478. * @param int $local Local tax to search and return (1 or 2 return only tax rate 1 or tax rate 2)
  4479. * @param Societe $thirdparty_buyer Object of buying third party
  4480. * @param Societe $thirdparty_seller Object of selling third party ($mysoc if not defined)
  4481. * @param int $vatnpr If vat rate is NPR or not
  4482. * @return mixed 0 if not found, localtax rate if found
  4483. * @see get_default_tva()
  4484. */
  4485. function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
  4486. {
  4487. global $db, $conf, $mysoc;
  4488. if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) $thirdparty_seller = $mysoc;
  4489. 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);
  4490. $vatratecleaned = $vatrate;
  4491. $reg = array();
  4492. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4493. {
  4494. $vatratecleaned = trim($reg[1]);
  4495. $vatratecode = $reg[2];
  4496. }
  4497. /*if ($thirdparty_buyer->country_code != $thirdparty_seller->country_code)
  4498. {
  4499. return 0;
  4500. }*/
  4501. // Some test to guess with no need to make database access
  4502. if ($mysoc->country_code == 'ES') // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
  4503. {
  4504. if ($local == 1)
  4505. {
  4506. if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") return 0;
  4507. if ($thirdparty_seller->id == $mysoc->id)
  4508. {
  4509. if (!$thirdparty_buyer->localtax1_assuj) return 0;
  4510. } else {
  4511. if (!$thirdparty_seller->localtax1_assuj) return 0;
  4512. }
  4513. }
  4514. if ($local == 2)
  4515. {
  4516. //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
  4517. if (!$mysoc->localtax2_assuj) return 0; // If main vat is 0, IRPF may be different than 0.
  4518. if ($thirdparty_seller->id == $mysoc->id)
  4519. {
  4520. if (!$thirdparty_buyer->localtax2_assuj) return 0;
  4521. } else {
  4522. if (!$thirdparty_seller->localtax2_assuj) return 0;
  4523. }
  4524. }
  4525. } else {
  4526. if ($local == 1 && !$thirdparty_seller->localtax1_assuj) return 0;
  4527. if ($local == 2 && !$thirdparty_seller->localtax2_assuj) return 0;
  4528. }
  4529. // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
  4530. if (in_array($mysoc->country_code, array('ES')))
  4531. {
  4532. $conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY = 1;
  4533. }
  4534. // Search local taxes
  4535. if (!empty($conf->global->MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY))
  4536. {
  4537. if ($local == 1)
  4538. {
  4539. if ($thirdparty_seller != $mysoc)
  4540. {
  4541. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4542. {
  4543. return $thirdparty_seller->localtax1_value;
  4544. }
  4545. } else // i am the seller
  4546. {
  4547. if (!isOnlyOneLocalTax($local)) // TODO If seller is me, why not always returning this, even if there is only one locatax vat.
  4548. {
  4549. return $conf->global->MAIN_INFO_VALUE_LOCALTAX1;
  4550. }
  4551. }
  4552. }
  4553. if ($local == 2)
  4554. {
  4555. if ($thirdparty_seller != $mysoc)
  4556. {
  4557. if (!isOnlyOneLocalTax($local)) // TODO We should provide $vatrate to search on correct line and not always on line with highest vat rate
  4558. // TODO We should also return value defined on thirdparty only if defined
  4559. {
  4560. return $thirdparty_seller->localtax2_value;
  4561. }
  4562. } else // i am the seller
  4563. {
  4564. if (in_array($mysoc->country_code, array('ES')))
  4565. {
  4566. return $thirdparty_buyer->localtax2_value;
  4567. } else {
  4568. return $conf->global->MAIN_INFO_VALUE_LOCALTAX2;
  4569. }
  4570. }
  4571. }
  4572. }
  4573. // By default, search value of local tax on line of common tax
  4574. $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  4575. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4576. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($thirdparty_seller->country_code)."'";
  4577. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4578. if ($vatratecode) $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; // If we have the code, we use it in priority
  4579. else $sql .= " AND t.recuperableonly ='".$db->escape($vatnpr)."'";
  4580. dol_syslog("get_localtax", LOG_DEBUG);
  4581. $resql = $db->query($sql);
  4582. if ($resql)
  4583. {
  4584. $obj = $db->fetch_object($resql);
  4585. if ($local == 1) return $obj->localtax1;
  4586. elseif ($local == 2) return $obj->localtax2;
  4587. }
  4588. return 0;
  4589. }
  4590. /**
  4591. * Return true if LocalTax (1 or 2) is unique.
  4592. * Example: If localtax1 is 5 on line with highest common vat rate, return true
  4593. * Example: If localtax1 is 5:8:15 on line with highest common vat rate, return false
  4594. *
  4595. * @param int $local Local tax to test (1 or 2)
  4596. * @return boolean True if LocalTax have multiple values, False if not
  4597. */
  4598. function isOnlyOneLocalTax($local)
  4599. {
  4600. $tax = get_localtax_by_third($local);
  4601. $valors = explode(":", $tax);
  4602. if (count($valors) > 1)
  4603. {
  4604. return false;
  4605. } else {
  4606. return true;
  4607. }
  4608. }
  4609. /**
  4610. * Get values of localtaxes (1 or 2) for company country for the common vat with the highest value
  4611. *
  4612. * @param int $local LocalTax to get
  4613. * @return number Values of localtax
  4614. */
  4615. function get_localtax_by_third($local)
  4616. {
  4617. global $db, $mysoc;
  4618. $sql = "SELECT t.localtax1, t.localtax2 ";
  4619. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
  4620. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND t.active = 1 AND t.taux=(";
  4621. $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";
  4622. $sql .= " WHERE c.code = '".$db->escape($mysoc->country_code)."' AND tt.active = 1";
  4623. $sql .= " )";
  4624. $resql = $db->query($sql);
  4625. if ($resql)
  4626. {
  4627. $obj = $db->fetch_object($resql);
  4628. if ($local == 1) return $obj->localtax1;
  4629. elseif ($local == 2) return $obj->localtax2;
  4630. }
  4631. return 0;
  4632. }
  4633. /**
  4634. * Get vat main information from Id.
  4635. * You can call getLocalTaxesFromRate after to get other fields.
  4636. *
  4637. * @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.
  4638. * @param Societe $buyer Company object
  4639. * @param Societe $seller Company object
  4640. * @param int $firstparamisid 1 if first param is id into table (use this if you can)
  4641. * @return array array('rowid'=> , 'code'=> ...)
  4642. * @see getLocalTaxesFromRate()
  4643. */
  4644. function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
  4645. {
  4646. global $db, $mysoc;
  4647. dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
  4648. // Search local taxes
  4649. $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
  4650. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4651. if ($firstparamisid) $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4652. else {
  4653. $vatratecleaned = $vatrate;
  4654. $vatratecode = '';
  4655. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "xx (yy)"
  4656. {
  4657. $vatratecleaned = $reg[1];
  4658. $vatratecode = $reg[2];
  4659. }
  4660. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4661. /*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 ??
  4662. else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";*/
  4663. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  4664. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4665. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4666. }
  4667. $resql = $db->query($sql);
  4668. if ($resql)
  4669. {
  4670. $obj = $db->fetch_object($resql);
  4671. if ($obj) return array('rowid'=>$obj->rowid, 'code'=>$obj->code, 'rate'=>$obj->rate, 'npr'=>$obj->npr, 'accountancy_code_sell'=>$obj->accountancy_code_sell, 'accountancy_code_buy'=>$obj->accountancy_code_buy);
  4672. else return array();
  4673. } else dol_print_error($db);
  4674. return array();
  4675. }
  4676. /**
  4677. * Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
  4678. * This does not take into account the seller setup if subject to vat or not, only country.
  4679. * TODO
  4680. * This function is ALSO called to retrieve type for building PDF. Such call of function must be removed.
  4681. * Instead this function must be called when adding a line to get the array of localtax and type, and then
  4682. * provide it to the function calcul_price_total.
  4683. *
  4684. * @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.
  4685. * @param int $local Number of localtax (1 or 2, or 0 to return 1 & 2)
  4686. * @param Societe $buyer Company object
  4687. * @param Societe $seller Company object
  4688. * @param int $firstparamisid 1 if first param is ID into table instead of Rate+code (use this if you can)
  4689. * @return array array(localtax_type1(1-6/0 if not found), rate localtax1, localtax_type2, rate localtax2, accountancycodecust, accountancycodesupp)
  4690. * @see getTaxesFromId()
  4691. */
  4692. function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
  4693. {
  4694. global $db, $mysoc;
  4695. dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
  4696. // Search local taxes
  4697. $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";
  4698. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
  4699. if ($firstparamisid) $sql .= " WHERE t.rowid = ".(int) $vatrate;
  4700. else {
  4701. $vatratecleaned = $vatrate;
  4702. $vatratecode = '';
  4703. $reg = array();
  4704. if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) // If vat is "x.x (yy)"
  4705. {
  4706. $vatratecleaned = $reg[1];
  4707. $vatratecode = $reg[2];
  4708. }
  4709. $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
  4710. if ($mysoc->country_code == 'ES') $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($buyer->country_code)."'"; // local tax in spain use the buyer country ??
  4711. else $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($seller->country_code)."'";
  4712. $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
  4713. if ($vatratecode) $sql .= " AND t.code = '".$db->escape($vatratecode)."'";
  4714. }
  4715. $resql = $db->query($sql);
  4716. if ($resql)
  4717. {
  4718. $obj = $db->fetch_object($resql);
  4719. $vateratestring = $obj->rate.($obj->code ? ' ('.$obj->code.')' : '');
  4720. if ($local == 1)
  4721. {
  4722. return array($obj->localtax1_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4723. } elseif ($local == 2)
  4724. {
  4725. return array($obj->localtax2_type, get_localtax($vateratestring, $local, $buyer, $seller), $obj->accountancy_code_sell, $obj->accountancy_code_buy);
  4726. } else {
  4727. 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);
  4728. }
  4729. }
  4730. return 0;
  4731. }
  4732. /**
  4733. * Return vat rate of a product in a particular selling country or default country vat if product is unknown
  4734. * Function called by get_default_tva
  4735. *
  4736. * @param int $idprod Id of product or 0 if not a predefined product
  4737. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4738. * @param int $idprodfournprice Id product_fournisseur_price (for "supplier" proposal/order/invoice)
  4739. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)'
  4740. * @see get_product_localtax_for_country()
  4741. */
  4742. function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice = 0)
  4743. {
  4744. global $db, $conf, $mysoc;
  4745. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4746. $ret = 0;
  4747. $found = 0;
  4748. if ($idprod > 0)
  4749. {
  4750. // Load product
  4751. $product = new Product($db);
  4752. $result = $product->fetch($idprod);
  4753. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4754. {
  4755. if ($idprodfournprice > 0) // We want vat for product for a "supplier" object
  4756. {
  4757. $product->get_buyprice($idprodfournprice, 0, 0, 0);
  4758. $ret = $product->vatrate_supplier;
  4759. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4760. } else {
  4761. $ret = $product->tva_tx; // Default vat of product we defined
  4762. if ($product->default_vat_code) $ret .= ' ('.$product->default_vat_code.')';
  4763. }
  4764. $found = 1;
  4765. } else {
  4766. // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
  4767. // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
  4768. }
  4769. }
  4770. if (!$found)
  4771. {
  4772. if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS))
  4773. {
  4774. // If vat of product for the country not found or not defined, we return the first higher vat of country.
  4775. $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
  4776. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4777. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4778. $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
  4779. $sql .= $db->plimit(1);
  4780. $resql = $db->query($sql);
  4781. if ($resql)
  4782. {
  4783. $obj = $db->fetch_object($resql);
  4784. if ($obj)
  4785. {
  4786. $ret = $obj->vat_rate;
  4787. if ($obj->default_vat_code) $ret .= ' ('.$obj->default_vat_code.')';
  4788. }
  4789. $db->free($sql);
  4790. } else dol_print_error($db);
  4791. } else $ret = $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
  4792. }
  4793. dol_syslog("get_product_vat_for_country: ret=".$ret);
  4794. return $ret;
  4795. }
  4796. /**
  4797. * Return localtax vat rate of a product in a particular selling country or default country vat if product is unknown
  4798. *
  4799. * @param int $idprod Id of product
  4800. * @param int $local 1 for localtax1, 2 for localtax 2
  4801. * @param Societe $thirdparty_seller Thirdparty with a ->country_code defined (FR, US, IT, ...)
  4802. * @return int <0 if KO, Vat rate if OK
  4803. * @see get_product_vat_for_country()
  4804. */
  4805. function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
  4806. {
  4807. global $db, $mysoc;
  4808. if (!class_exists('Product')) {
  4809. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4810. }
  4811. $ret = 0;
  4812. $found = 0;
  4813. if ($idprod > 0)
  4814. {
  4815. // Load product
  4816. $product = new Product($db);
  4817. $result = $product->fetch($idprod);
  4818. if ($mysoc->country_code == $thirdparty_seller->country_code) // If selling country is ours
  4819. {
  4820. /* Not defined yet, so we don't use this
  4821. if ($local==1) $ret=$product->localtax1_tx;
  4822. elseif ($local==2) $ret=$product->localtax2_tx;
  4823. $found=1;
  4824. */
  4825. } else {
  4826. // TODO Read default product vat according to countrycode and product
  4827. }
  4828. }
  4829. if (!$found)
  4830. {
  4831. // If vat of product for the country not found or not defined, we return higher vat of country.
  4832. $sql = "SELECT taux as vat_rate, localtax1, localtax2";
  4833. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4834. $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$db->escape($thirdparty_seller->country_code)."'";
  4835. $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
  4836. $sql .= $db->plimit(1);
  4837. $resql = $db->query($sql);
  4838. if ($resql)
  4839. {
  4840. $obj = $db->fetch_object($resql);
  4841. if ($obj)
  4842. {
  4843. if ($local == 1) $ret = $obj->localtax1;
  4844. elseif ($local == 2) $ret = $obj->localtax2;
  4845. }
  4846. } else dol_print_error($db);
  4847. }
  4848. dol_syslog("get_product_localtax_for_country: ret=".$ret);
  4849. return $ret;
  4850. }
  4851. /**
  4852. * Function that return vat rate of a product line (according to seller, buyer and product vat rate)
  4853. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4854. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4855. * Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  4856. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier ou entreprise sans num TVA intra) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4857. * Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise avec num TVA) intra alors TVA par defaut=0. Fin de regle
  4858. * Sinon TVA proposee par defaut=0. Fin de regle.
  4859. *
  4860. * @param Societe $thirdparty_seller Objet societe vendeuse
  4861. * @param Societe $thirdparty_buyer Objet societe acheteuse
  4862. * @param int $idprod Id product
  4863. * @param int $idprodfournprice Id product_fournisseur_price (for supplier order/invoice)
  4864. * @return float|string Vat rate to use with format 5.0 or '5.0 (XXX)', -1 if we can't guess it
  4865. * @see get_default_npr(), get_default_localtax()
  4866. */
  4867. function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4868. {
  4869. global $conf;
  4870. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  4871. // Note: possible values for tva_assuj are 0/1 or franchise/reel
  4872. $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;
  4873. $seller_country_code = $thirdparty_seller->country_code;
  4874. $seller_in_cee = isInEEC($thirdparty_seller);
  4875. $buyer_country_code = $thirdparty_buyer->country_code;
  4876. $buyer_in_cee = isInEEC($thirdparty_buyer);
  4877. 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 : ''));
  4878. // 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)
  4879. // we use the buyer VAT.
  4880. if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))
  4881. {
  4882. if ($seller_in_cee && $buyer_in_cee && !$thirdparty_buyer->isACompany())
  4883. {
  4884. //print 'VATRULE 0';
  4885. return get_product_vat_for_country($idprod, $thirdparty_buyer, $idprodfournprice);
  4886. }
  4887. }
  4888. // If seller does not use VAT
  4889. if (!$seller_use_vat)
  4890. {
  4891. //print 'VATRULE 1';
  4892. return 0;
  4893. }
  4894. // Le test ci-dessus ne devrait pas etre necessaire. Me signaler l'exemple du cas juridique concerne si le test suivant n'est pas suffisant.
  4895. // Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
  4896. if (($seller_country_code == $buyer_country_code)
  4897. || (in_array($seller_country_code, array('FR,MC')) && in_array($buyer_country_code, array('FR', 'MC')))) // Warning ->country_code not always defined
  4898. {
  4899. //print 'VATRULE 2';
  4900. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4901. }
  4902. // Si (vendeur et acheteur dans Communaute europeenne) et (bien vendu = moyen de transports neuf comme auto, bateau, avion) alors TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
  4903. // Not supported
  4904. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = entreprise) alors TVA par defaut=0. Fin de regle
  4905. // Si (vendeur et acheteur dans Communaute europeenne) et (acheteur = particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4906. if (($seller_in_cee && $buyer_in_cee))
  4907. {
  4908. $isacompany = $thirdparty_buyer->isACompany();
  4909. if ($isacompany)
  4910. {
  4911. //print 'VATRULE 3';
  4912. return 0;
  4913. } else {
  4914. //print 'VATRULE 4';
  4915. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4916. }
  4917. }
  4918. // Si (vendeur en France et acheteur hors Communaute europeenne et acheteur particulier) alors TVA par defaut=TVA du produit vendu. Fin de regle
  4919. if (!empty($conf->global->MAIN_USE_VAT_OF_PRODUCT_FOR_INDIVIDUAL_CUSTOMER_OUT_OF_EEC) && empty($buyer_in_cee) && !$thirdparty_buyer->isACompany()) {
  4920. return get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice);
  4921. }
  4922. // Sinon la TVA proposee par defaut=0. Fin de regle.
  4923. // Rem: Cela signifie qu'au moins un des 2 est hors Communaute europeenne et que le pays differe
  4924. //print 'VATRULE 5';
  4925. return 0;
  4926. }
  4927. /**
  4928. * Fonction qui renvoie si tva doit etre tva percue recuperable
  4929. *
  4930. * @param Societe $thirdparty_seller Thirdparty seller
  4931. * @param Societe $thirdparty_buyer Thirdparty buyer
  4932. * @param int $idprod Id product
  4933. * @param int $idprodfournprice Id supplier price for product
  4934. * @return float 0 or 1
  4935. * @see get_default_tva(), get_default_localtax()
  4936. */
  4937. function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
  4938. {
  4939. global $db;
  4940. if ($idprodfournprice > 0)
  4941. {
  4942. if (!class_exists('ProductFournisseur')) {
  4943. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  4944. }
  4945. $prodprice = new ProductFournisseur($db);
  4946. $prodprice->fetch_product_fournisseur_price($idprodfournprice);
  4947. return $prodprice->fourn_tva_npr;
  4948. } elseif ($idprod > 0)
  4949. {
  4950. if (!class_exists('Product')) {
  4951. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  4952. }
  4953. $prod = new Product($db);
  4954. $prod->fetch($idprod);
  4955. return $prod->tva_npr;
  4956. }
  4957. return 0;
  4958. }
  4959. /**
  4960. * Function that return localtax of a product line (according to seller, buyer and product vat rate)
  4961. * Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
  4962. * Si le (pays vendeur = pays acheteur) alors TVA par defaut=TVA du produit vendu. Fin de regle.
  4963. * Sinon TVA proposee par defaut=0. Fin de regle.
  4964. *
  4965. * @param Societe $thirdparty_seller Thirdparty seller
  4966. * @param Societe $thirdparty_buyer Thirdparty buyer
  4967. * @param int $local Localtax to process (1 or 2)
  4968. * @param int $idprod Id product
  4969. * @return integer localtax, -1 si ne peut etre determine
  4970. * @see get_default_tva(), get_default_npr()
  4971. */
  4972. function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
  4973. {
  4974. global $mysoc;
  4975. if (!is_object($thirdparty_seller)) return -1;
  4976. if (!is_object($thirdparty_buyer)) return -1;
  4977. if ($local == 1) // Localtax 1
  4978. {
  4979. if ($mysoc->country_code == 'ES')
  4980. {
  4981. if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) return 0;
  4982. } else {
  4983. // Si vendeur non assujeti a Localtax1, localtax1 par default=0
  4984. if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) return 0;
  4985. if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') return 0;
  4986. }
  4987. } elseif ($local == 2) //I Localtax 2
  4988. {
  4989. // Si vendeur non assujeti a Localtax2, localtax2 par default=0
  4990. if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) return 0;
  4991. if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') return 0;
  4992. }
  4993. if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code)
  4994. {
  4995. return get_product_localtax_for_country($idprod, $local, $thirdparty_seller);
  4996. }
  4997. return 0;
  4998. }
  4999. /**
  5000. * Return yes or no in current language
  5001. *
  5002. * @param string|int $yesno Value to test (1, 'yes', 'true' or 0, 'no', 'false')
  5003. * @param integer $case 1=Yes/No, 0=yes/no, 2=Disabled checkbox, 3=Disabled checkbox + Yes/No
  5004. * @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.
  5005. * @return string HTML string
  5006. */
  5007. function yn($yesno, $case = 1, $color = 0)
  5008. {
  5009. global $langs;
  5010. $result = 'unknown'; $classname = '';
  5011. if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') // A mettre avant test sur no a cause du == 0
  5012. {
  5013. $result = $langs->trans('yes');
  5014. if ($case == 1 || $case == 3) $result = $langs->trans("Yes");
  5015. if ($case == 2) $result = '<input type="checkbox" value="1" checked disabled>';
  5016. if ($case == 3) $result = '<input type="checkbox" value="1" checked disabled> '.$result;
  5017. $classname = 'ok';
  5018. } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false')
  5019. {
  5020. $result = $langs->trans("no");
  5021. if ($case == 1 || $case == 3) $result = $langs->trans("No");
  5022. if ($case == 2) $result = '<input type="checkbox" value="0" disabled>';
  5023. if ($case == 3) $result = '<input type="checkbox" value="0" disabled> '.$result;
  5024. if ($color == 2) $classname = 'ok';
  5025. else $classname = 'error';
  5026. }
  5027. if ($color) return '<font class="'.$classname.'">'.$result.'</font>';
  5028. return $result;
  5029. }
  5030. /**
  5031. * Return a path to have a the directory according to object where files are stored.
  5032. * New usage: $conf->module->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, '')
  5033. * or: $conf->module->dir_output.'/'.get_exdir(0, 0, 0, 1, $object, '') if multidir_output not defined.
  5034. * Example our with new usage: $object is invoice -> 'INYYMM-ABCD'
  5035. * Example our with old usage: '015' with level 3->"0/1/5/", '015' with level 1->"5/", 'ABC-1' with level 3 ->"0/0/1/"
  5036. *
  5037. * @param string|int $num Id of object (deprecated, $object will be used in future)
  5038. * @param int $level Level of subdirs to return (1, 2 or 3 levels). (deprecated, global option will be used in future)
  5039. * @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)
  5040. * @param int $withoutslash 0=With slash at end (except if '/', we return ''), 1=without slash at end
  5041. * @param Object $object Object to use to get ref to forge the path.
  5042. * @param string $modulepart Type of object ('invoice_supplier, 'donation', 'invoice', ...'). Use '' for autodetect from $object.
  5043. * @return string Dir to use ending. Example '' or '1/' or '1/2/'
  5044. */
  5045. function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart = '')
  5046. {
  5047. global $conf;
  5048. if (empty($modulepart) && !empty($object->module)) $modulepart = $object->module;
  5049. $path = '';
  5050. $arrayforoldpath = array('cheque', 'user', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
  5051. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) $arrayforoldpath[] = 'product';
  5052. if (!empty($level) && in_array($modulepart, $arrayforoldpath))
  5053. {
  5054. // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
  5055. if (empty($alpha)) $num = preg_replace('/([^0-9])/i', '', $num);
  5056. else $num = preg_replace('/^.*\-/i', '', $num);
  5057. $num = substr("000".$num, -$level);
  5058. if ($level == 1) $path = substr($num, 0, 1);
  5059. if ($level == 2) $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
  5060. if ($level == 3) $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
  5061. } else {
  5062. // We will enhance here a common way of forging path for document storage.
  5063. // In a future, we may distribut directories on several levels depending on setup and object.
  5064. // Here, $object->id, $object->ref and $modulepart are required.
  5065. //var_dump($modulepart);
  5066. if (! in_array($modulepart, array('product'))) { // Test to remove
  5067. $path = dol_sanitizeFileName(empty($object->ref) ? $object->id : $object->ref);
  5068. }
  5069. }
  5070. if (empty($withoutslash) && !empty($path)) $path .= '/';
  5071. return $path;
  5072. }
  5073. /**
  5074. * Creation of a directory (this can create recursive subdir)
  5075. *
  5076. * @param string $dir Directory to create (Separator must be '/'. Example: '/mydir/mysubdir')
  5077. * @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)
  5078. * @param string|null $newmask Mask for new file (Defaults to $conf->global->MAIN_UMASK or 0755 if unavailable). Example: '0444'
  5079. * @return int < 0 if KO, 0 = already exists, > 0 if OK
  5080. */
  5081. function dol_mkdir($dir, $dataroot = '', $newmask = null)
  5082. {
  5083. global $conf;
  5084. dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
  5085. $dir_osencoded = dol_osencode($dir);
  5086. if (@is_dir($dir_osencoded)) return 0;
  5087. $nberr = 0;
  5088. $nbcreated = 0;
  5089. $ccdir = '';
  5090. if (!empty($dataroot)) {
  5091. // Remove data root from loop
  5092. $dir = str_replace($dataroot.'/', '', $dir);
  5093. $ccdir = $dataroot.'/';
  5094. }
  5095. $cdir = explode("/", $dir);
  5096. $num = count($cdir);
  5097. for ($i = 0; $i < $num; $i++)
  5098. {
  5099. if ($i > 0) $ccdir .= '/'.$cdir[$i];
  5100. else $ccdir .= $cdir[$i];
  5101. if (preg_match("/^.:$/", $ccdir, $regs)) continue; // Si chemin Windows incomplet, on poursuit par rep suivant
  5102. // Attention, le is_dir() peut echouer bien que le rep existe.
  5103. // (ex selon config de open_basedir)
  5104. if ($ccdir)
  5105. {
  5106. $ccdir_osencoded = dol_osencode($ccdir);
  5107. if (!@is_dir($ccdir_osencoded))
  5108. {
  5109. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
  5110. umask(0);
  5111. $dirmaskdec = octdec($newmask);
  5112. if (empty($newmask)) {
  5113. $dirmaskdec = empty($conf->global->MAIN_UMASK) ? octdec('0755') : octdec($conf->global->MAIN_UMASK);
  5114. }
  5115. $dirmaskdec |= octdec('0111'); // Set x bit required for directories
  5116. if (!@mkdir($ccdir_osencoded, $dirmaskdec))
  5117. {
  5118. // Si le is_dir a renvoye une fausse info, alors on passe ici.
  5119. dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
  5120. $nberr++;
  5121. } else {
  5122. dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
  5123. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
  5124. $nbcreated++;
  5125. }
  5126. } else {
  5127. $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignores
  5128. }
  5129. }
  5130. }
  5131. return ($nberr ? -$nberr : $nbcreated);
  5132. }
  5133. /**
  5134. * Return picto saying a field is required
  5135. *
  5136. * @return string Chaine avec picto obligatoire
  5137. */
  5138. function picto_required()
  5139. {
  5140. return '<span class="fieldrequired">*</span>';
  5141. }
  5142. /**
  5143. * Clean a string from all HTML tags and entities.
  5144. * This function differs from strip_tags because:
  5145. * - <br> are replaced with \n if removelinefeed=0 or 1
  5146. * - if entities are found, they are decoded BEFORE the strip
  5147. * - you can decide to convert line feed into a space
  5148. *
  5149. * @param string $stringtoclean String to clean
  5150. * @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..."
  5151. * @param string $pagecodeto Encoding of input/output string
  5152. * @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)
  5153. * @param integer $removedoublespaces Replace double space into one space
  5154. * @return string String cleaned
  5155. *
  5156. * @see dol_escape_htmltag() strip_tags() dol_string_onlythesehtmltags() dol_string_neverthesehtmltags(), dolStripPhpCode()
  5157. */
  5158. function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0, $removedoublespaces = 1)
  5159. {
  5160. if ($removelinefeed == 2) $stringtoclean = preg_replace('/<br[^>]*>(\n|\r)+/ims', '<br>', $stringtoclean);
  5161. $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
  5162. // We remove entities BEFORE stripping (in case of a separator char is encoded and not the other, the strip will fails)
  5163. $temp = dol_html_entity_decode($temp, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5164. if ($strip_tags) {
  5165. $temp = strip_tags($temp);
  5166. } else {
  5167. $pattern = "/<[^<>]+>/";
  5168. // Example of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
  5169. $temp = preg_replace($pattern, "", $temp); // pass 1
  5170. // $temp after pass 1: <a href="/myurl" title="A title">0000-021
  5171. $temp = preg_replace($pattern, "", $temp); // pass 2
  5172. // $temp after pass 2: 0000-021
  5173. }
  5174. $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
  5175. // Remove also carriage returns
  5176. if ($removelinefeed == 1) $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
  5177. // And double quotes
  5178. if ($removedoublespaces) {
  5179. while (strpos($temp, " ")) {
  5180. $temp = str_replace(" ", " ", $temp);
  5181. }
  5182. }
  5183. return trim($temp);
  5184. }
  5185. /**
  5186. * Clean a string to keep only desirable HTML tags.
  5187. *
  5188. * @param string $stringtoclean String to clean
  5189. * @param int $cleanalsosomestyles Remove absolute/fixed positioning from inline styles
  5190. * @param int $removeclassattribute Remove the class attribute from tags
  5191. * @param int $cleanalsojavascript Remove also occurence of (javascript:'
  5192. * @return string String cleaned
  5193. *
  5194. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_neverthesehtmltags()
  5195. */
  5196. function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $removeclassattribute = 1, $cleanalsojavascript = 0)
  5197. {
  5198. $allowed_tags = array(
  5199. "html", "head", "meta", "body", "article", "a", "abbr", "b", "blockquote", "br", "cite", "div", "dl", "dd", "dt", "em", "font", "img", "ins", "hr", "i", "li", "link",
  5200. "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"
  5201. );
  5202. $allowed_tags_string = join("><", $allowed_tags);
  5203. $allowed_tags_string = '<'.$allowed_tags_string.'>';
  5204. $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0);
  5205. $stringtoclean = preg_replace('/&colon;/i', ':', $stringtoclean);
  5206. $temp = strip_tags($stringtoclean, $allowed_tags_string);
  5207. if ($cleanalsosomestyles) { // Clean for remaining html tags
  5208. $stringtoclean = 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
  5209. }
  5210. if ($removeclassattribute) { // Clean for remaining html tags
  5211. $stringtoclean = preg_replace('/(<[^>]+)\s+class=((["\']).*?\\3|\\w*)/i', '\\1', $temp);
  5212. }
  5213. // Remove 'javascript:' that we should not find into a text with
  5214. if ($cleanalsojavascript) {
  5215. $temp = preg_replace('/javascript\s*:/i', '', $temp);
  5216. }
  5217. return $temp;
  5218. }
  5219. /**
  5220. * Clean a string from some undesirable HTML tags.
  5221. * Note. Not as secured as dol_string_onlythesehtmltags().
  5222. *
  5223. * @param string $stringtoclean String to clean
  5224. * @param array $disallowed_tags Array of tags not allowed
  5225. * @param string $cleanalsosomestyles Clean also some tags
  5226. * @return string String cleaned
  5227. *
  5228. * @see dol_escape_htmltag() strip_tags() dol_string_nohtmltag() dol_string_onlythesehtmltags()
  5229. */
  5230. function dol_string_neverthesehtmltags($stringtoclean, $disallowed_tags = array('textarea'), $cleanalsosomestyles = 0)
  5231. {
  5232. $temp = $stringtoclean;
  5233. foreach ($disallowed_tags as $tagtoremove)
  5234. {
  5235. $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
  5236. $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
  5237. }
  5238. if ($cleanalsosomestyles) {
  5239. $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
  5240. }
  5241. return $temp;
  5242. }
  5243. /**
  5244. * Return first line of text. Cut will depends if content is HTML or not.
  5245. *
  5246. * @param string $text Input text
  5247. * @param int $nboflines Nb of lines to get (default is 1 = first line only)
  5248. * @param string $charset Charset of $text string (UTF-8 by default)
  5249. * @return string Output text
  5250. * @see dol_nboflines_bis(), dol_string_nohtmltag(), dol_escape_htmltag()
  5251. */
  5252. function dolGetFirstLineOfText($text, $nboflines = 1, $charset = 'UTF-8')
  5253. {
  5254. if ($nboflines == 1)
  5255. {
  5256. if (dol_textishtml($text))
  5257. {
  5258. $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
  5259. $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
  5260. } else {
  5261. $firstline = preg_replace('/[\n\r].*/', '', $text);
  5262. }
  5263. return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
  5264. } else {
  5265. $ishtml = 0;
  5266. if (dol_textishtml($text))
  5267. {
  5268. $text = preg_replace('/\n/', '', $text);
  5269. $ishtml = 1;
  5270. $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5271. } else {
  5272. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5273. }
  5274. $text = strtr($text, $repTable);
  5275. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5276. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5277. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5278. $firstline = '';
  5279. $i = 0;
  5280. $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
  5281. while (($i < $nba) && ($i < ($nboflines * 2)))
  5282. {
  5283. if ($i % 2 == 0) $firstline .= $a[$i];
  5284. elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) $firstline .= ($ishtml ? "<br>\n" : "\n");
  5285. $i++;
  5286. }
  5287. unset($a);
  5288. return $firstline.(($i < $nba) ? '...' : '');
  5289. }
  5290. }
  5291. /**
  5292. * Replace CRLF in string with a HTML BR tag.
  5293. * 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.
  5294. *
  5295. * @param string $stringtoencode String to encode
  5296. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br
  5297. * @param bool $forxml false=Use <br>, true=Use <br />
  5298. * @return string String encoded
  5299. * @see dol_nboflines(), dolGetFirstLineOfText()
  5300. */
  5301. function dol_nl2br($stringtoencode, $nl2brmode = 0, $forxml = false)
  5302. {
  5303. if (!$nl2brmode) {
  5304. return nl2br($stringtoencode, $forxml);
  5305. } else {
  5306. $ret = preg_replace('/(\r\n|\r|\n)/i', ($forxml ? '<br />' : '<br>'), $stringtoencode);
  5307. return $ret;
  5308. }
  5309. }
  5310. /**
  5311. * This function is called to encode a string into a HTML string but differs from htmlentities because
  5312. * a detection is done before to see if text is already HTML or not. Also, all entities but &,<,>," are converted.
  5313. * This permits to encode special chars to entities with no double encoding for already encoded HTML strings.
  5314. * This function also remove last EOL or BR if $removelasteolbr=1 (default).
  5315. * For PDF usage, you can show text by 2 ways:
  5316. * - writeHTMLCell -> param must be encoded into HTML.
  5317. * - MultiCell -> param must not be encoded into HTML.
  5318. * Because writeHTMLCell convert also \n into <br>, if function
  5319. * is used to build PDF, nl2brmode must be 1.
  5320. *
  5321. * @param string $stringtoencode String to encode
  5322. * @param int $nl2brmode 0=Adding br before \n, 1=Replacing \n by br (for use with FPDF writeHTMLCell function for example)
  5323. * @param string $pagecodefrom Pagecode stringtoencode is encoded
  5324. * @param int $removelasteolbr 1=Remove last br or lasts \n (default), 0=Do nothing
  5325. * @return string String encoded
  5326. */
  5327. function dol_htmlentitiesbr($stringtoencode, $nl2brmode = 0, $pagecodefrom = 'UTF-8', $removelasteolbr = 1)
  5328. {
  5329. $newstring = $stringtoencode;
  5330. if (dol_textishtml($stringtoencode)) // Check if text is already HTML or not
  5331. {
  5332. $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.
  5333. if ($removelasteolbr) $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
  5334. $newstring = strtr($newstring, array('&'=>'__and__', '<'=>'__lt__', '>'=>'__gt__', '"'=>'__dquot__'));
  5335. $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
  5336. $newstring = strtr($newstring, array('__and__'=>'&', '__lt__'=>'<', '__gt__'=>'>', '__dquot__'=>'"'));
  5337. } else {
  5338. if ($removelasteolbr) $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
  5339. $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
  5340. }
  5341. // Other substitutions that htmlentities does not do
  5342. //$newstring=str_replace(chr(128),'&euro;',$newstring); // 128 = 0x80. Not in html entity table. // Seems useles with TCPDF. Make bug with UTF8 languages
  5343. return $newstring;
  5344. }
  5345. /**
  5346. * This function is called to decode a HTML string (it decodes entities and br tags)
  5347. *
  5348. * @param string $stringtodecode String to decode
  5349. * @param string $pagecodeto Page code for result
  5350. * @return string String decoded
  5351. */
  5352. function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
  5353. {
  5354. $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT | ENT_HTML5, $pagecodeto);
  5355. $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
  5356. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
  5357. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
  5358. $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
  5359. return $ret;
  5360. }
  5361. /**
  5362. * This function remove all ending \n and br at end
  5363. *
  5364. * @param string $stringtodecode String to decode
  5365. * @return string String decoded
  5366. */
  5367. function dol_htmlcleanlastbr($stringtodecode)
  5368. {
  5369. $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
  5370. return $ret;
  5371. }
  5372. /**
  5373. * Replace html_entity_decode functions to manage errors
  5374. *
  5375. * @param string $a Operand a
  5376. * @param string $b Operand b (ENT_QUOTES|ENT_HTML5=convert simple, double quotes, colon, e accent, ...)
  5377. * @param string $c Operand c
  5378. * @param string $keepsomeentities Entities but &, <, >, " are not converted.
  5379. * @return string String decoded
  5380. */
  5381. function dol_html_entity_decode($a, $b, $c = 'UTF-8', $keepsomeentities = 0)
  5382. {
  5383. $newstring = $a;
  5384. if ($keepsomeentities) $newstring = strtr($newstring, array('&amp;'=>'__andamp__', '&lt;'=>'__andlt__', '&gt;'=>'__andgt__', '"'=>'__dquot__'));
  5385. $newstring = html_entity_decode($newstring, $b, $c);
  5386. if ($keepsomeentities) $newstring = strtr($newstring, array('__andamp__'=>'&amp;', '__andlt__'=>'&lt;', '__andgt__'=>'&gt;', '__dquot__'=>'"'));
  5387. return $newstring;
  5388. }
  5389. /**
  5390. * Replace htmlentities functions.
  5391. * Goal of this function is to be sure to have default values of htmlentities that match what we need.
  5392. *
  5393. * @param string $string The input string to encode
  5394. * @param int $flags Flags (see PHP doc above)
  5395. * @param string $encoding Encoding page code
  5396. * @param bool $double_encode When double_encode is turned off, PHP will not encode existing html entities
  5397. * @return string $ret Encoded string
  5398. */
  5399. function dol_htmlentities($string, $flags = null, $encoding = 'UTF-8', $double_encode = false)
  5400. {
  5401. return htmlentities($string, $flags, $encoding, $double_encode);
  5402. }
  5403. /**
  5404. * Check if a string is a correct iso string
  5405. * If not, it will we considered not HTML encoded even if it is by FPDF.
  5406. * Example, if string contains euro symbol that has ascii code 128
  5407. *
  5408. * @param string $s String to check
  5409. * @param string $clean Clean if it is not an ISO. Warning, if file is utf8, you will get a bad formated file.
  5410. * @return int|string 0 if bad iso, 1 if good iso, Or the clean string if $clean is 1
  5411. */
  5412. function dol_string_is_good_iso($s, $clean = 0)
  5413. {
  5414. $len = dol_strlen($s);
  5415. $out = '';
  5416. $ok = 1;
  5417. for ($scursor = 0; $scursor < $len; $scursor++)
  5418. {
  5419. $ordchar = ord($s[$scursor]);
  5420. //print $scursor.'-'.$ordchar.'<br>';
  5421. if ($ordchar < 32 && $ordchar != 13 && $ordchar != 10) { $ok = 0; break; } elseif ($ordchar > 126 && $ordchar < 160) { $ok = 0; break; } elseif ($clean) {
  5422. $out .= $s[$scursor];
  5423. }
  5424. }
  5425. if ($clean) return $out;
  5426. return $ok;
  5427. }
  5428. /**
  5429. * Return nb of lines of a clear text
  5430. *
  5431. * @param string $s String to check
  5432. * @param int $maxchar Not yet used
  5433. * @return int Number of lines
  5434. * @see dol_nboflines_bis(), dolGetFirstLineOfText()
  5435. */
  5436. function dol_nboflines($s, $maxchar = 0)
  5437. {
  5438. if ($s == '') return 0;
  5439. $arraystring = explode("\n", $s);
  5440. $nb = count($arraystring);
  5441. return $nb;
  5442. }
  5443. /**
  5444. * Return nb of lines of a formated text with \n and <br> (WARNING: string must not have mixed \n and br separators)
  5445. *
  5446. * @param string $text Text
  5447. * @param int $maxlinesize Largeur de ligne en caracteres (ou 0 si pas de limite - defaut)
  5448. * @param string $charset Give the charset used to encode the $text variable in memory.
  5449. * @return int Number of lines
  5450. * @see dol_nboflines(), dolGetFirstLineOfText()
  5451. */
  5452. function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
  5453. {
  5454. $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5455. if (dol_textishtml($text)) $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
  5456. $text = strtr($text, $repTable);
  5457. if ($charset == 'UTF-8') { $pattern = '/(<br[^>]*>)/Uu'; } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
  5458. else $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
  5459. $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
  5460. $nblines = (int) floor((count($a) + 1) / 2);
  5461. // count possible auto line breaks
  5462. if ($maxlinesize)
  5463. {
  5464. foreach ($a as $line)
  5465. {
  5466. if (dol_strlen($line) > $maxlinesize)
  5467. {
  5468. //$line_dec = html_entity_decode(strip_tags($line));
  5469. $line_dec = html_entity_decode($line);
  5470. if (dol_strlen($line_dec) > $maxlinesize)
  5471. {
  5472. $line_dec = wordwrap($line_dec, $maxlinesize, '\n', true);
  5473. $nblines += substr_count($line_dec, '\n');
  5474. }
  5475. }
  5476. }
  5477. }
  5478. unset($a);
  5479. return $nblines;
  5480. }
  5481. /**
  5482. * Return if a text is a html content
  5483. *
  5484. * @param string $msg Content to check
  5485. * @param int $option 0=Full detection, 1=Fast check
  5486. * @return boolean true/false
  5487. * @see dol_concatdesc()
  5488. */
  5489. function dol_textishtml($msg, $option = 0)
  5490. {
  5491. if ($option == 1)
  5492. {
  5493. if (preg_match('/<html/i', $msg)) return true;
  5494. elseif (preg_match('/<body/i', $msg)) return true;
  5495. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5496. elseif (preg_match('/<br/i', $msg)) return true;
  5497. return false;
  5498. } else {
  5499. if (preg_match('/<html/i', $msg)) return true;
  5500. elseif (preg_match('/<body/i', $msg)) return true;
  5501. elseif (preg_match('/<\/textarea/i', $msg)) return true;
  5502. elseif (preg_match('/<(b|em|i|u)>/i', $msg)) return true;
  5503. elseif (preg_match('/<br\/>/i', $msg)) return true;
  5504. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) return true;
  5505. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg)) return true;
  5506. elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg)) return true;
  5507. elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) return true; // must accept <img src="http://example.com/aaa.png" />
  5508. elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) return true; // must accept <a href="http://example.com/aaa.png" />
  5509. elseif (preg_match('/<h[0-9]>/i', $msg)) return true;
  5510. elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
  5511. elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
  5512. return false;
  5513. }
  5514. }
  5515. /**
  5516. * Concat 2 descriptions with a new line between them (second operand after first one with appropriate new line separator)
  5517. * text1 html + text2 html => text1 + '<br>' + text2
  5518. * text1 html + text2 txt => text1 + '<br>' + dol_nl2br(text2)
  5519. * text1 txt + text2 html => dol_nl2br(text1) + '<br>' + text2
  5520. * text1 txt + text2 txt => text1 + '\n' + text2
  5521. *
  5522. * @param string $text1 Text 1
  5523. * @param string $text2 Text 2
  5524. * @param bool $forxml true=Use <br /> instead of <br> if we have to add a br tag
  5525. * @param bool $invert invert order of description lines (we often use config MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION in this parameter)
  5526. * @return string Text 1 + new line + Text2
  5527. * @see dol_textishtml()
  5528. */
  5529. function dol_concatdesc($text1, $text2, $forxml = false, $invert = false)
  5530. {
  5531. if (!empty($invert))
  5532. {
  5533. $tmp = $text1;
  5534. $text1 = $text2;
  5535. $text2 = $tmp;
  5536. }
  5537. $ret = '';
  5538. $ret .= (!dol_textishtml($text1) && dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text1, 0, 1, '', 1), 0, $forxml) : $text1;
  5539. $ret .= (!empty($text1) && !empty($text2)) ? ((dol_textishtml($text1) || dol_textishtml($text2)) ? ($forxml ? "<br \>\n" : "<br>\n") : "\n") : "";
  5540. $ret .= (dol_textishtml($text1) && !dol_textishtml($text2)) ? dol_nl2br(dol_escape_htmltag($text2, 0, 1, '', 1), 0, $forxml) : $text2;
  5541. return $ret;
  5542. }
  5543. /**
  5544. * Return array of possible common substitutions. This includes several families like: 'system', 'mycompany', 'object', 'objectamount', 'date', 'user'
  5545. *
  5546. * @param Translate $outputlangs Output language
  5547. * @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)
  5548. * @param array $exclude Array of family keys we want to exclude. For example array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...)
  5549. * @param Object $object Object for keys on object
  5550. * @return array Array of substitutions
  5551. * @see setSubstitFromObject()
  5552. */
  5553. function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
  5554. {
  5555. global $db, $conf, $mysoc, $user, $extrafields;
  5556. $substitutionarray = array();
  5557. if (empty($exclude) || !in_array('user', $exclude))
  5558. {
  5559. // Add SIGNATURE into substitutionarray first, so, when we will make the substitution,
  5560. // this will include signature content first and then replace var found into content of signature
  5561. $signature = $user->signature;
  5562. $substitutionarray = array_merge($substitutionarray, array(
  5563. '__USER_SIGNATURE__' => (string) (($signature && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)) ? ($onlykey == 2 ? dol_trunc(dol_string_nohtmltag($signature), 30) : $signature) : '')
  5564. )
  5565. );
  5566. $substitutionarray = array_merge($substitutionarray, array(
  5567. '__USER_ID__' => (string) $user->id,
  5568. '__USER_LOGIN__' => (string) $user->login,
  5569. '__USER_EMAIL__' => (string) $user->email,
  5570. '__USER_LASTNAME__' => (string) $user->lastname,
  5571. '__USER_FIRSTNAME__' => (string) $user->firstname,
  5572. '__USER_FULLNAME__' => (string) $user->getFullName($outputlangs),
  5573. '__USER_SUPERVISOR_ID__' => (string) ($user->fk_user ? $user->fk_user : '0'),
  5574. '__USER_REMOTE_IP__' => (string) getUserRemoteIP()
  5575. )
  5576. );
  5577. }
  5578. if ((empty($exclude) || !in_array('mycompany', $exclude)) && is_object($mysoc))
  5579. {
  5580. $substitutionarray = array_merge($substitutionarray, array(
  5581. '__MYCOMPANY_NAME__' => $mysoc->name,
  5582. '__MYCOMPANY_EMAIL__' => $mysoc->email,
  5583. '__MYCOMPANY_PROFID1__' => $mysoc->idprof1,
  5584. '__MYCOMPANY_PROFID2__' => $mysoc->idprof2,
  5585. '__MYCOMPANY_PROFID3__' => $mysoc->idprof3,
  5586. '__MYCOMPANY_PROFID4__' => $mysoc->idprof4,
  5587. '__MYCOMPANY_PROFID5__' => $mysoc->idprof5,
  5588. '__MYCOMPANY_PROFID6__' => $mysoc->idprof6,
  5589. '__MYCOMPANY_CAPITAL__' => $mysoc->capital,
  5590. '__MYCOMPANY_FULLADDRESS__' => $mysoc->getFullAddress(1, ', '),
  5591. '__MYCOMPANY_ADDRESS__' => $mysoc->address,
  5592. '__MYCOMPANY_ZIP__' => $mysoc->zip,
  5593. '__MYCOMPANY_TOWN__' => $mysoc->town,
  5594. '__MYCOMPANY_COUNTRY__' => $mysoc->country,
  5595. '__MYCOMPANY_COUNTRY_ID__' => $mysoc->country_id,
  5596. '__MYCOMPANY_COUNTRY_CODE__' => $mysoc->country_code,
  5597. '__MYCOMPANY_CURRENCY_CODE__' => $conf->currency
  5598. ));
  5599. }
  5600. if (($onlykey || is_object($object)) && (empty($exclude) || !in_array('object', $exclude)))
  5601. {
  5602. if ($onlykey)
  5603. {
  5604. $substitutionarray['__ID__'] = '__ID__';
  5605. $substitutionarray['__REF__'] = '__REF__';
  5606. $substitutionarray['__REF_CLIENT__'] = '__REF_CLIENT__';
  5607. $substitutionarray['__REF_SUPPLIER__'] = '__REF_SUPPLIER__';
  5608. $substitutionarray['__NOTE_PUBLIC__'] = '__NOTE_PUBLIC__';
  5609. $substitutionarray['__NOTE_PRIVATE__'] = '__NOTE_PRIVATE__';
  5610. $substitutionarray['__EXTRAFIELD_XXX__'] = '__EXTRAFIELD_XXX__';
  5611. if (!empty($conf->societe->enabled)) // Most objects are concerned
  5612. {
  5613. $substitutionarray['__THIRDPARTY_ID__'] = '__THIRDPARTY_ID__';
  5614. $substitutionarray['__THIRDPARTY_NAME__'] = '__THIRDPARTY_NAME__';
  5615. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = '__THIRDPARTY_NAME_ALIAS__';
  5616. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = '__THIRDPARTY_CODE_CLIENT__';
  5617. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = '__THIRDPARTY_CODE_FOURNISSEUR__';
  5618. $substitutionarray['__THIRDPARTY_EMAIL__'] = '__THIRDPARTY_EMAIL__';
  5619. $substitutionarray['__THIRDPARTY_PHONE__'] = '__THIRDPARTY_PHONE__';
  5620. $substitutionarray['__THIRDPARTY_FAX__'] = '__THIRDPARTY_FAX__';
  5621. $substitutionarray['__THIRDPARTY_ADDRESS__'] = '__THIRDPARTY_ADDRESS__';
  5622. $substitutionarray['__THIRDPARTY_ZIP__'] = '__THIRDPARTY_ZIP__';
  5623. $substitutionarray['__THIRDPARTY_TOWN__'] = '__THIRDPARTY_TOWN__';
  5624. $substitutionarray['__THIRDPARTY_IDPROF1__'] = '__THIRDPARTY_IDPROF1__';
  5625. $substitutionarray['__THIRDPARTY_IDPROF2__'] = '__THIRDPARTY_IDPROF2__';
  5626. $substitutionarray['__THIRDPARTY_IDPROF3__'] = '__THIRDPARTY_IDPROF3__';
  5627. $substitutionarray['__THIRDPARTY_IDPROF4__'] = '__THIRDPARTY_IDPROF4__';
  5628. $substitutionarray['__THIRDPARTY_IDPROF5__'] = '__THIRDPARTY_IDPROF5__';
  5629. $substitutionarray['__THIRDPARTY_IDPROF6__'] = '__THIRDPARTY_IDPROF6__';
  5630. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = '__THIRDPARTY_TVAINTRA__';
  5631. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = '__THIRDPARTY_NOTE_PUBLIC__';
  5632. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = '__THIRDPARTY_NOTE_PRIVATE__';
  5633. }
  5634. if (!empty($conf->adherent->enabled) && (!is_object($object) || $object->element == 'adherent'))
  5635. {
  5636. $substitutionarray['__MEMBER_ID__'] = '__MEMBER_ID__';
  5637. $substitutionarray['__MEMBER_CIVILITY__'] = '__MEMBER_CIVILITY__';
  5638. $substitutionarray['__MEMBER_FIRSTNAME__'] = '__MEMBER_FIRSTNAME__';
  5639. $substitutionarray['__MEMBER_LASTNAME__'] = '__MEMBER_LASTNAME__';
  5640. /*$substitutionarray['__MEMBER_NOTE_PUBLIC__'] = '__MEMBER_NOTE_PUBLIC__';
  5641. $substitutionarray['__MEMBER_NOTE_PRIVATE__'] = '__MEMBER_NOTE_PRIVATE__';*/
  5642. }
  5643. if (!empty($conf->recruitment->enabled) && (!is_object($object) || $object->element == 'candidature'))
  5644. {
  5645. $substitutionarray['__CANDIDATE_FULLNAME__'] = '__CANDIDATE_FULLNAME__';
  5646. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = '__CANDIDATE_FIRSTNAME__';
  5647. $substitutionarray['__CANDIDATE_LASTNAME__'] = '__CANDIDATE_LASTNAME__';
  5648. }
  5649. if (!empty($conf->projet->enabled)) // Most objects
  5650. {
  5651. $substitutionarray['__PROJECT_ID__'] = '__PROJECT_ID__';
  5652. $substitutionarray['__PROJECT_REF__'] = '__PROJECT_REF__';
  5653. $substitutionarray['__PROJECT_NAME__'] = '__PROJECT_NAME__';
  5654. /*$substitutionarray['__PROJECT_NOTE_PUBLIC__'] = '__PROJECT_NOTE_PUBLIC__';
  5655. $substitutionarray['__PROJECT_NOTE_PRIVATE__'] = '__PROJECT_NOTE_PRIVATE__';*/
  5656. }
  5657. if (!empty($conf->contrat->enabled) && (!is_object($object) || $object->element == 'contract'))
  5658. {
  5659. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = 'Highest date planned for a service start';
  5660. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = 'Highest date and hour planned for service start';
  5661. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = 'Lowest data for planned expiration of service';
  5662. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = 'Lowest date and hour for planned expiration of service';
  5663. }
  5664. $substitutionarray['__ONLINE_PAYMENT_URL__'] = 'UrlToPayOnlineIfApplicable';
  5665. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = 'TextAndUrlToPayOnlineIfApplicable';
  5666. $substitutionarray['__SECUREKEYPAYMENT__'] = 'Security key (if key is not unique per record)';
  5667. $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = 'Security key for payment on a member subscription (one key per member)';
  5668. $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = 'Security key for payment on an order';
  5669. $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = 'Security key for payment on an invoice';
  5670. $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'Security key for payment on a a service';
  5671. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = 'Direct download url of a proposal';
  5672. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = 'Direct download url of an order';
  5673. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = 'Direct download url of an invoice';
  5674. if (!empty($conf->expedition->enabled) && (!is_object($object) || $object->element == 'shipping'))
  5675. {
  5676. $substitutionarray['__SHIPPINGTRACKNUM__'] = 'Shipping tracking number';
  5677. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = 'Shipping tracking url';
  5678. }
  5679. if (!empty($conf->reception->enabled) && (!is_object($object) || $object->element == 'reception'))
  5680. {
  5681. $substitutionarray['__RECEPTIONTRACKNUM__'] = 'Shippin tracking number of shipment';
  5682. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = 'Shipping tracking url';
  5683. }
  5684. } else {
  5685. $substitutionarray['__ID__'] = $object->id;
  5686. $substitutionarray['__REF__'] = $object->ref;
  5687. $substitutionarray['__REF_CLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5688. $substitutionarray['__REF_SUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5689. $substitutionarray['__NOTE_PUBLIC__'] = (isset($object->note_public) ? $object->note_public : null);
  5690. $substitutionarray['__NOTE_PRIVATE__'] = (isset($object->note_private) ? $object->note_private : null);
  5691. $substitutionarray['__DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5692. // For backward compatibility
  5693. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5694. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5695. $substitutionarray['__REFCLIENT__'] = (isset($object->ref_client) ? $object->ref_client : (isset($object->ref_customer) ? $object->ref_customer : null));
  5696. $substitutionarray['__REFSUPPLIER__'] = (isset($object->ref_supplier) ? $object->ref_supplier : null);
  5697. $substitutionarray['__SUPPLIER_ORDER_DATE_DELIVERY__'] = (isset($object->date_livraison) ? dol_print_date($object->date_livraison, 'day', 0, $outputlangs) : '');
  5698. $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 : '')) : '');
  5699. if (is_object($object) && ($object->element == 'adherent' || $object->element == 'member') && $object->id > 0)
  5700. {
  5701. $birthday = (empty($object->birth) ? '': dol_print_date($object->birth, 'day'));
  5702. $substitutionarray['__MEMBER_ID__'] = (isset($object->id) ? $object->id : '');
  5703. if (method_exists($object, 'getCivilityLabel')) $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
  5704. $substitutionarray['__MEMBER_FIRSTNAME__'] = (isset($object->firstname) ? $object->firstname : '');
  5705. $substitutionarray['__MEMBER_LASTNAME__'] = (isset($object->lastname) ? $object->lastname : '');
  5706. if (method_exists($object, 'getFullName')) $substitutionarray['__MEMBER_FULLNAME__'] = $object->getFullName($outputlangs);
  5707. $substitutionarray['__MEMBER_COMPANY__'] = (isset($object->societe) ? $object->societe : '');
  5708. $substitutionarray['__MEMBER_ADDRESS__'] = (isset($object->address) ? $object->address : '');
  5709. $substitutionarray['__MEMBER_ZIP__'] = (isset($object->zip) ? $object->zip : '');
  5710. $substitutionarray['__MEMBER_TOWN__'] = (isset($object->town) ? $object->town : '');
  5711. $substitutionarray['__MEMBER_COUNTRY__'] = (isset($object->country) ? $object->country : '');
  5712. $substitutionarray['__MEMBER_EMAIL__'] = (isset($object->email) ? $object->email : '');
  5713. $substitutionarray['__MEMBER_BIRTH__'] = (isset($birthday) ? $birthday : '');
  5714. $substitutionarray['__MEMBER_PHOTO__'] = (isset($object->photo) ? $object->photo : '');
  5715. $substitutionarray['__MEMBER_LOGIN__'] = (isset($object->login) ? $object->login : '');
  5716. $substitutionarray['__MEMBER_PASSWORD__'] = (isset($object->pass) ? $object->pass : '');
  5717. $substitutionarray['__MEMBER_PHONE__'] = (isset($object->phone) ? $object->phone : '');
  5718. $substitutionarray['__MEMBER_PHONEPRO__'] = (isset($object->phone_perso) ? $object->phone_perso : '');
  5719. $substitutionarray['__MEMBER_PHONEMOBILE__'] = (isset($object->phone_mobile) ? $object->phone_mobile : '');
  5720. $substitutionarray['__MEMBER_TYPE__'] = (isset($object->type) ? $object->type : '');
  5721. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE__'] = dol_print_date($object->first_subscription_date, 'dayrfc');
  5722. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->first_subscription_date_start, 'dayrfc');
  5723. $substitutionarray['__MEMBER_FIRST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->first_subscription_date_end, 'dayrfc');
  5724. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE__'] = dol_print_date($object->last_subscription_date, 'dayrfc');
  5725. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_START__'] = dol_print_date($object->last_subscription_date_start, 'dayrfc');
  5726. $substitutionarray['__MEMBER_LAST_SUBSCRIPTION_DATE_END__'] = dol_print_date($object->last_subscription_date_end, 'dayrfc');
  5727. }
  5728. if (is_object($object) && $object->element == 'societe') {
  5729. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object) ? $object->id : '');
  5730. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object) ? $object->name : '');
  5731. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object) ? $object->name_alias : '');
  5732. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object) ? $object->code_client : '');
  5733. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object) ? $object->code_fournisseur : '');
  5734. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object) ? $object->email : '');
  5735. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object) ? $object->phone : '');
  5736. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object) ? $object->fax : '');
  5737. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object) ? $object->address : '');
  5738. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object) ? $object->zip : '');
  5739. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object) ? $object->town : '');
  5740. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object) ? $object->country_id : '');
  5741. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object) ? $object->country_code : '');
  5742. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object) ? $object->idprof1 : '');
  5743. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object) ? $object->idprof2 : '');
  5744. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object) ? $object->idprof3 : '');
  5745. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object) ? $object->idprof4 : '');
  5746. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object) ? $object->idprof5 : '');
  5747. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object) ? $object->idprof6 : '');
  5748. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object) ? $object->tva_intra : '');
  5749. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_public) : '');
  5750. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object) ? dol_htmlentitiesbr($object->note_private) : '');
  5751. } elseif (is_object($object->thirdparty)) {
  5752. $substitutionarray['__THIRDPARTY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->id : '');
  5753. $substitutionarray['__THIRDPARTY_NAME__'] = (is_object($object->thirdparty) ? $object->thirdparty->name : '');
  5754. $substitutionarray['__THIRDPARTY_NAME_ALIAS__'] = (is_object($object->thirdparty) ? $object->thirdparty->name_alias : '');
  5755. $substitutionarray['__THIRDPARTY_CODE_CLIENT__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_client : '');
  5756. $substitutionarray['__THIRDPARTY_CODE_FOURNISSEUR__'] = (is_object($object->thirdparty) ? $object->thirdparty->code_fournisseur : '');
  5757. $substitutionarray['__THIRDPARTY_EMAIL__'] = (is_object($object->thirdparty) ? $object->thirdparty->email : '');
  5758. $substitutionarray['__THIRDPARTY_PHONE__'] = (is_object($object->thirdparty) ? $object->thirdparty->phone : '');
  5759. $substitutionarray['__THIRDPARTY_FAX__'] = (is_object($object->thirdparty) ? $object->thirdparty->fax : '');
  5760. $substitutionarray['__THIRDPARTY_ADDRESS__'] = (is_object($object->thirdparty) ? $object->thirdparty->address : '');
  5761. $substitutionarray['__THIRDPARTY_ZIP__'] = (is_object($object->thirdparty) ? $object->thirdparty->zip : '');
  5762. $substitutionarray['__THIRDPARTY_TOWN__'] = (is_object($object->thirdparty) ? $object->thirdparty->town : '');
  5763. $substitutionarray['__THIRDPARTY_COUNTRY_ID__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_id : '');
  5764. $substitutionarray['__THIRDPARTY_COUNTRY_CODE__'] = (is_object($object->thirdparty) ? $object->thirdparty->country_code : '');
  5765. $substitutionarray['__THIRDPARTY_IDPROF1__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof1 : '');
  5766. $substitutionarray['__THIRDPARTY_IDPROF2__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof2 : '');
  5767. $substitutionarray['__THIRDPARTY_IDPROF3__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof3 : '');
  5768. $substitutionarray['__THIRDPARTY_IDPROF4__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof4 : '');
  5769. $substitutionarray['__THIRDPARTY_IDPROF5__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof5 : '');
  5770. $substitutionarray['__THIRDPARTY_IDPROF6__'] = (is_object($object->thirdparty) ? $object->thirdparty->idprof6 : '');
  5771. $substitutionarray['__THIRDPARTY_TVAINTRA__'] = (is_object($object->thirdparty) ? $object->thirdparty->tva_intra : '');
  5772. $substitutionarray['__THIRDPARTY_NOTE_PUBLIC__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_public) : '');
  5773. $substitutionarray['__THIRDPARTY_NOTE_PRIVATE__'] = (is_object($object->thirdparty) ? dol_htmlentitiesbr($object->thirdparty->note_private) : '');
  5774. }
  5775. if (is_object($object) && $object->element == 'recruitmentcandidature') {
  5776. $substitutionarray['__CANDIDATE_FULLNAME__'] = $object->getFullName($outputlangs);
  5777. $substitutionarray['__CANDIDATE_FIRSTNAME__'] = $object->firstname;
  5778. $substitutionarray['__CANDIDATE_LASTNAME__'] = $object->lastname;
  5779. }
  5780. if (is_object($object->project))
  5781. {
  5782. $substitutionarray['__PROJECT_ID__'] = (is_object($object->project) ? $object->project->id : '');
  5783. $substitutionarray['__PROJECT_REF__'] = (is_object($object->project) ? $object->project->ref : '');
  5784. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->project) ? $object->project->title : '');
  5785. }
  5786. if (is_object($object->projet)) // Deprecated, for backward compatibility
  5787. {
  5788. $substitutionarray['__PROJECT_ID__'] = (is_object($object->projet) ? $object->projet->id : '');
  5789. $substitutionarray['__PROJECT_REF__'] = (is_object($object->projet) ? $object->projet->ref : '');
  5790. $substitutionarray['__PROJECT_NAME__'] = (is_object($object->projet) ? $object->projet->title : '');
  5791. }
  5792. if (is_object($object) && $object->element == 'shipping')
  5793. {
  5794. $substitutionarray['__SHIPPINGTRACKNUM__'] = $object->tracking_number;
  5795. $substitutionarray['__SHIPPINGTRACKNUMURL__'] = $object->tracking_url;
  5796. }
  5797. if (is_object($object) && $object->element == 'reception')
  5798. {
  5799. $substitutionarray['__RECEPTIONTRACKNUM__'] = $object->tracking_number;
  5800. $substitutionarray['__RECEPTIONTRACKNUMURL__'] = $object->tracking_url;
  5801. }
  5802. if (is_object($object) && $object->element == 'contrat' && $object->id > 0 && is_array($object->lines))
  5803. {
  5804. $dateplannedstart = '';
  5805. $datenextexpiration = '';
  5806. foreach ($object->lines as $line)
  5807. {
  5808. if ($line->date_ouverture_prevue > $dateplannedstart) $dateplannedstart = $line->date_ouverture_prevue;
  5809. if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) $datenextexpiration = $line->date_fin_prevue;
  5810. }
  5811. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
  5812. $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
  5813. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATE__'] = dol_print_date($datenextexpiration, 'dayrfc');
  5814. $substitutionarray['__CONTRACT_LOWEST_EXPIRATION_DATETIME__'] = dol_print_date($datenextexpiration, 'standard');
  5815. }
  5816. // Create dynamic tags for __EXTRAFIELD_FIELD__
  5817. if ($object->table_element && $object->id > 0)
  5818. {
  5819. if (!is_object($extrafields)) $extrafields = new ExtraFields($db);
  5820. $extrafields->fetch_name_optionals_label($object->table_element, true);
  5821. if ($object->fetch_optionals() > 0)
  5822. {
  5823. if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
  5824. {
  5825. foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
  5826. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
  5827. if ($extrafields->attributes[$object->table_element]['type'][$key] == 'date') {
  5828. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = dol_print_date($object->array_options['options_'.$key], 'day');
  5829. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = dol_print_date($object->array_options['options_'.$key], 'day', 'tzserver', $outputlangs);
  5830. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = dol_print_date($object->array_options['options_'.$key], 'dayrfc');
  5831. } elseif ($extrafields->attributes[$object->table_element]['type'][$key] == 'datetime') {
  5832. $datetime = $object->array_options['options_'.$key];
  5833. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour') : '');
  5834. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhour', 'tzserver', $outputlangs) : '');
  5835. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_DAY_LOCALE__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'day', 'tzserver', $outputlangs) : '');
  5836. $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'_RFC__'] = ($datetime != "0000-00-00 00:00:00" ? dol_print_date($datetime, 'dayhourrfc') : '');
  5837. }
  5838. }
  5839. }
  5840. }
  5841. }
  5842. // Complete substitution array with the url to make online payment
  5843. $paymenturl = '';
  5844. if (empty($substitutionarray['__REF__']))
  5845. {
  5846. $paymenturl = '';
  5847. } else {
  5848. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  5849. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  5850. $outputlangs->loadLangs(array('paypal', 'other'));
  5851. $typeforonlinepayment = 'free';
  5852. if (is_object($object) && $object->element == 'commande') $typeforonlinepayment = 'order';
  5853. if (is_object($object) && $object->element == 'facture') $typeforonlinepayment = 'invoice';
  5854. if (is_object($object) && $object->element == 'member') $typeforonlinepayment = 'member';
  5855. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
  5856. $paymenturl = $url;
  5857. }
  5858. if ($object->id > 0)
  5859. {
  5860. $substitutionarray['__ONLINE_PAYMENT_TEXT_AND_URL__'] = ($paymenturl ?str_replace('\n', "\n", $outputlangs->trans("PredefinedMailContentLink", $paymenturl)) : '');
  5861. $substitutionarray['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  5862. if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal')
  5863. {
  5864. $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
  5865. } else $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
  5866. if (!empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande')
  5867. {
  5868. $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
  5869. } else $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
  5870. if (!empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture')
  5871. {
  5872. $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
  5873. } else $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
  5874. if (is_object($object) && $object->element == 'propal') $substitutionarray['__URL_PROPOSAL__'] = DOL_MAIN_URL_ROOT."/comm/propal/card.php?id=".$object->id;
  5875. if (is_object($object) && $object->element == 'commande') $substitutionarray['__URL_ORDER__'] = DOL_MAIN_URL_ROOT."/commande/card.php?id=".$object->id;
  5876. if (is_object($object) && $object->element == 'facture') $substitutionarray['__URL_INVOICE__'] = DOL_MAIN_URL_ROOT."/compta/facture/card.php?id=".$object->id;
  5877. }
  5878. if (is_object($object) && $object->element == 'action')
  5879. {
  5880. $substitutionarray['__EVENT_LABEL__'] = $object->label;
  5881. $substitutionarray['__EVENT_DATE__'] = dol_print_date($object->datep, '%A %d %b %Y');
  5882. $substitutionarray['__EVENT_TIME__'] = dol_print_date($object->datep, '%H:%M:%S');
  5883. }
  5884. }
  5885. }
  5886. if (empty($exclude) || !in_array('objectamount', $exclude))
  5887. {
  5888. $substitutionarray['__DATE_YMD__'] = is_object($object) ? (isset($object->date) ? dol_print_date($object->date, 'day', 0, $outputlangs) : null) : '';
  5889. $substitutionarray['__DATE_DUE_YMD__'] = is_object($object) ? (isset($object->date_lim_reglement) ? dol_print_date($object->date_lim_reglement, 'day', 0, $outputlangs) : null) : '';
  5890. $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
  5891. $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
  5892. $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  5893. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
  5894. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
  5895. $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? ($object->total_ttc ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5896. $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? ($object->total_ht ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5897. $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? (isset($object->total_vat) ? price($object->total_vat, 0, $outputlangs, 0, 0, -1, $conf->currency) : ($object->total_tva ? price($object->total_tva, 0, $outputlangs, 0, 0, -1, $conf->currency) : null)) : '';
  5898. if ($onlykey != 2 || $mysoc->useLocalTax(1)) $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? ($object->total_localtax1 ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5899. if ($onlykey != 2 || $mysoc->useLocalTax(2)) $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? ($object->total_localtax2 ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, $conf->currency) : null) : '';
  5900. // TODO Add keys for foreign multicurrency
  5901. // For backward compatibility
  5902. if ($onlykey != 2)
  5903. {
  5904. $substitutionarray['__TOTAL_TTC__'] = is_object($object) ? $object->total_ttc : '';
  5905. $substitutionarray['__TOTAL_HT__'] = is_object($object) ? $object->total_ht : '';
  5906. $substitutionarray['__TOTAL_VAT__'] = is_object($object) ? (isset($object->total_vat) ? $object->total_vat : $object->total_tva) : '';
  5907. }
  5908. }
  5909. //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
  5910. if (empty($exclude) || !in_array('date', $exclude))
  5911. {
  5912. include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  5913. $tmp = dol_getdate(dol_now(), true);
  5914. $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5915. $tmp3 = dol_get_prev_month($tmp['mon'], $tmp['year']);
  5916. $tmp4 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
  5917. $tmp5 = dol_get_next_month($tmp['mon'], $tmp['year']);
  5918. $daytext = $outputlangs->trans('Day'.$tmp['wday']);
  5919. $substitutionarray = array_merge($substitutionarray, array(
  5920. '__DAY__' => (string) $tmp['mday'],
  5921. '__DAY_TEXT__' => $daytext, // Monday
  5922. '__DAY_TEXT_SHORT__' => dol_trunc($daytext, 3, 'right', 'UTF-8', 1), // Mon
  5923. '__DAY_TEXT_MIN__' => dol_trunc($daytext, 1, 'right', 'UTF-8', 1), // M
  5924. '__MONTH__' => (string) $tmp['mon'],
  5925. '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
  5926. '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
  5927. '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
  5928. '__YEAR__' => (string) $tmp['year'],
  5929. '__PREVIOUS_DAY__' => (string) $tmp2['day'],
  5930. '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
  5931. '__PREVIOUS_YEAR__' => (string) ($tmp['year'] - 1),
  5932. '__NEXT_DAY__' => (string) $tmp4['day'],
  5933. '__NEXT_MONTH__' => (string) $tmp5['month'],
  5934. '__NEXT_YEAR__' => (string) ($tmp['year'] + 1),
  5935. ));
  5936. }
  5937. if (!empty($conf->multicompany->enabled))
  5938. {
  5939. $substitutionarray = array_merge($substitutionarray, array('__ENTITY_ID__' => $conf->entity));
  5940. }
  5941. if (empty($exclude) || !in_array('system', $exclude))
  5942. {
  5943. $substitutionarray['__DOL_MAIN_URL_ROOT__'] = DOL_MAIN_URL_ROOT;
  5944. $substitutionarray['__(AnyTranslationKey)__'] = $outputlangs->trans('TranslationOfKey');
  5945. $substitutionarray['__(AnyTranslationKey|langfile)__'] = $outputlangs->trans('TranslationOfKey').' (load also language file before)';
  5946. $substitutionarray['__[AnyConstantKey]__'] = $outputlangs->trans('ValueOfConstantKey');
  5947. }
  5948. return $substitutionarray;
  5949. }
  5950. /**
  5951. * Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newval),
  5952. * and texts like __(TranslationKey|langfile)__ and __[ConstantKey]__ are also replaced.
  5953. * Example of usage:
  5954. * $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $thirdparty);
  5955. * complete_substitutions_array($substitutionarray, $langs, $thirdparty);
  5956. * $mesg = make_substitutions($mesg, $substitutionarray, $langs);
  5957. *
  5958. * @param string $text Source string in which we must do substitution
  5959. * @param array $substitutionarray Array with key->val to substitute. Example: array('__MYKEY__' => 'MyVal', ...)
  5960. * @param Translate $outputlangs Output language
  5961. * @return string Output string after substitutions
  5962. * @see complete_substitutions_array(), getCommonSubstitutionArray()
  5963. */
  5964. function make_substitutions($text, $substitutionarray, $outputlangs = null)
  5965. {
  5966. global $conf, $langs;
  5967. if (!is_array($substitutionarray)) return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
  5968. if (empty($outputlangs)) $outputlangs = $langs;
  5969. // Make substitution for language keys: __(AnyTranslationKey)__ or __(AnyTranslationKey|langfile)__
  5970. if (is_object($outputlangs))
  5971. {
  5972. $reg = array();
  5973. while (preg_match('/__\(([^\)]+)\)__/', $text, $reg))
  5974. {
  5975. $msgishtml = 0;
  5976. if (dol_textishtml($text, 1)) $msgishtml = 1;
  5977. // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
  5978. $tmp = explode('|', $reg[1]);
  5979. if (!empty($tmp[1])) $outputlangs->load($tmp[1]);
  5980. $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ?dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
  5981. }
  5982. }
  5983. // Make substitution for constant keys.
  5984. // Must be after the substitution of translation, so if the text of translation contains a string __[xxx]__, it is also converted.
  5985. $reg = array();
  5986. while (preg_match('/__\[([^\]]+)\]__/', $text, $reg))
  5987. {
  5988. $msgishtml = 0;
  5989. if (dol_textishtml($text, 1)) $msgishtml = 1;
  5990. $keyfound = $reg[1];
  5991. if (isASecretKey($keyfound)) $newval = '*****forbidden*****';
  5992. else $newval = empty($conf->global->$keyfound) ? '' : $conf->global->$keyfound;
  5993. $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ?dol_htmlentitiesbr($newval) : $newval, $text);
  5994. }
  5995. // Make substitition for array $substitutionarray
  5996. foreach ($substitutionarray as $key => $value)
  5997. {
  5998. if (!isset($value)) continue; // If value is null, it same than not having substitution key at all into array, we do not replace.
  5999. if ($key == '__USER_SIGNATURE__' && (!empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) $value = ''; // Protection
  6000. $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
  6001. }
  6002. return $text;
  6003. }
  6004. /**
  6005. * Complete the $substitutionarray with more entries coming from external module that had set the "substitutions=1" into module_part array.
  6006. * In this case, method completesubstitutionarray provided by module is called.
  6007. *
  6008. * @param array $substitutionarray Array substitution old value => new value value
  6009. * @param Translate $outputlangs Output language
  6010. * @param Object $object Source object
  6011. * @param mixed $parameters Add more parameters (useful to pass product lines)
  6012. * @param string $callfunc What is the name of the custom function that will be called? (default: completesubstitutionarray)
  6013. * @return void
  6014. * @see make_substitutions()
  6015. */
  6016. function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
  6017. {
  6018. global $conf, $user;
  6019. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  6020. // Add a substitution key for each extrafields, using key __EXTRA_XXX__
  6021. // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
  6022. /*if (is_object($object) && is_array($object->array_options))
  6023. {
  6024. foreach($object->array_options as $key => $val)
  6025. {
  6026. $keyshort=preg_replace('/^(options|extra)_/','',$key);
  6027. $substitutionarray['__EXTRAFIELD_'.$keyshort.'__']=$val;
  6028. // For backward compatibiliy
  6029. $substitutionarray['%EXTRA_'.$keyshort.'%']=$val;
  6030. }
  6031. }*/
  6032. // Check if there is external substitution to do, requested by plugins
  6033. $dirsubstitutions = array_merge(array(), (array) $conf->modules_parts['substitutions']);
  6034. foreach ($dirsubstitutions as $reldir)
  6035. {
  6036. $dir = dol_buildpath($reldir, 0);
  6037. // Check if directory exists
  6038. if (!dol_is_dir($dir)) continue;
  6039. $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
  6040. foreach ($substitfiles as $substitfile)
  6041. {
  6042. if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg))
  6043. {
  6044. $module = $reg[1];
  6045. dol_syslog("Library ".$substitfile['name']." found into ".$dir);
  6046. // Include the user's functions file
  6047. require_once $dir.$substitfile['name'];
  6048. // Call the user's function, and only if it is defined
  6049. $function_name = $module."_".$callfunc;
  6050. if (function_exists($function_name)) $function_name($substitutionarray, $outputlangs, $object, $parameters);
  6051. }
  6052. }
  6053. }
  6054. if (!empty($conf->global->ODT_ENABLE_ALL_TAGS_IN_SUBSTITUTIONS)) {
  6055. // to list all tags in odt template
  6056. $tags = '';
  6057. foreach ($substitutionarray as $key => $value) {
  6058. $tags .= '{' . $key . '} => ' . $value ."\n";
  6059. }
  6060. $substitutionarray = array_merge($substitutionarray, array('__ALL_TAGS__' => $tags));
  6061. }
  6062. }
  6063. /**
  6064. * Format output for start and end date
  6065. *
  6066. * @param int $date_start Start date
  6067. * @param int $date_end End date
  6068. * @param string $format Output format
  6069. * @param Translate $outputlangs Output language
  6070. * @return void
  6071. */
  6072. function print_date_range($date_start, $date_end, $format = '', $outputlangs = '')
  6073. {
  6074. print get_date_range($date_start, $date_end, $format, $outputlangs);
  6075. }
  6076. /**
  6077. * Format output for start and end date
  6078. *
  6079. * @param int $date_start Start date
  6080. * @param int $date_end End date
  6081. * @param string $format Output format
  6082. * @param Translate $outputlangs Output language
  6083. * @param integer $withparenthesis 1=Add parenthesis, 0=non parenthesis
  6084. * @return string String
  6085. */
  6086. function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
  6087. {
  6088. global $langs;
  6089. $out = '';
  6090. if (!is_object($outputlangs)) $outputlangs = $langs;
  6091. if ($date_start && $date_end)
  6092. {
  6093. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6094. }
  6095. if ($date_start && !$date_end)
  6096. {
  6097. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6098. }
  6099. if (!$date_start && $date_end)
  6100. {
  6101. $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
  6102. }
  6103. return $out;
  6104. }
  6105. /**
  6106. * Return firstname and lastname in correct order
  6107. *
  6108. * @param string $firstname Firstname
  6109. * @param string $lastname Lastname
  6110. * @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
  6111. * @return string Firstname + lastname or Lastname + firstname
  6112. */
  6113. function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
  6114. {
  6115. global $conf;
  6116. $ret = '';
  6117. // If order not defined, we use the setup
  6118. if ($nameorder < 0) $nameorder = (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
  6119. if ($nameorder == 1) {
  6120. $ret .= $firstname;
  6121. if ($firstname && $lastname) $ret .= ' ';
  6122. $ret .= $lastname;
  6123. } elseif ($nameorder == 2 || $nameorder == 3) {
  6124. $ret .= $firstname;
  6125. if (empty($ret) && $nameorder == 3) {
  6126. $ret .= $lastname;
  6127. }
  6128. } else { // 0, 4 or 5
  6129. $ret .= $lastname;
  6130. if (empty($ret) && $nameorder == 5) {
  6131. $ret .= $firstname;
  6132. }
  6133. if ($nameorder == 0) {
  6134. if ($firstname && $lastname) $ret .= ' ';
  6135. $ret .= $firstname;
  6136. }
  6137. }
  6138. return $ret;
  6139. }
  6140. /**
  6141. * Set event message in dol_events session object. Will be output by calling dol_htmloutput_events.
  6142. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6143. * Note: Prefer to use setEventMessages instead.
  6144. *
  6145. * @param string|string[] $mesgs Message string or array
  6146. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6147. * @return void
  6148. * @see dol_htmloutput_events()
  6149. */
  6150. function setEventMessage($mesgs, $style = 'mesgs')
  6151. {
  6152. //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING); This is not deprecated, it is used by setEventMessages function
  6153. if (!is_array($mesgs)) {
  6154. // If mesgs is a string
  6155. if ($mesgs) $_SESSION['dol_events'][$style][] = $mesgs;
  6156. } else {
  6157. // If mesgs is an array
  6158. foreach ($mesgs as $mesg)
  6159. {
  6160. if ($mesg) $_SESSION['dol_events'][$style][] = $mesg;
  6161. }
  6162. }
  6163. }
  6164. /**
  6165. * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
  6166. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
  6167. *
  6168. * @param string $mesg Message string
  6169. * @param array $mesgs Message array
  6170. * @param string $style Which style to use ('mesgs' by default, 'warnings', 'errors')
  6171. * @param string $messagekey A key to be used to allow the feature "Never show this message again"
  6172. * @return void
  6173. * @see dol_htmloutput_events()
  6174. */
  6175. function setEventMessages($mesg, $mesgs, $style = 'mesgs', $messagekey = '')
  6176. {
  6177. if (empty($mesg) && empty($mesgs))
  6178. {
  6179. dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
  6180. } else {
  6181. if ($messagekey)
  6182. {
  6183. // Complete message with a js link to set a cookie "DOLHIDEMESSAGE".$messagekey;
  6184. // TODO
  6185. $mesg .= '';
  6186. }
  6187. if (empty($messagekey) || empty($_COOKIE["DOLHIDEMESSAGE".$messagekey]))
  6188. {
  6189. if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
  6190. if (empty($mesgs)) setEventMessage($mesg, $style);
  6191. else {
  6192. if (!empty($mesg) && !in_array($mesg, $mesgs)) setEventMessage($mesg, $style); // Add message string if not already into array
  6193. setEventMessage($mesgs, $style);
  6194. }
  6195. }
  6196. }
  6197. }
  6198. /**
  6199. * Print formated messages to output (Used to show messages on html output).
  6200. * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function, so there is
  6201. * no need to call it explicitely.
  6202. *
  6203. * @param int $disabledoutputofmessages Clear all messages stored into session without diplaying them
  6204. * @return void
  6205. * @see dol_htmloutput_mesg()
  6206. */
  6207. function dol_htmloutput_events($disabledoutputofmessages = 0)
  6208. {
  6209. // Show mesgs
  6210. if (isset($_SESSION['dol_events']['mesgs'])) {
  6211. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
  6212. unset($_SESSION['dol_events']['mesgs']);
  6213. }
  6214. // Show errors
  6215. if (isset($_SESSION['dol_events']['errors'])) {
  6216. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
  6217. unset($_SESSION['dol_events']['errors']);
  6218. }
  6219. // Show warnings
  6220. if (isset($_SESSION['dol_events']['warnings'])) {
  6221. if (empty($disabledoutputofmessages)) dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
  6222. unset($_SESSION['dol_events']['warnings']);
  6223. }
  6224. }
  6225. /**
  6226. * Get formated messages to output (Used to show messages on html output).
  6227. * This include also the translation of the message key.
  6228. *
  6229. * @param string $mesgstring Message string or message key
  6230. * @param string[] $mesgarray Array of message strings or message keys
  6231. * @param string $style Style of message output ('ok' or 'error')
  6232. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6233. * @return string Return html output
  6234. *
  6235. * @see dol_print_error()
  6236. * @see dol_htmloutput_errors()
  6237. * @see setEventMessages()
  6238. */
  6239. function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
  6240. {
  6241. global $conf, $langs;
  6242. $ret = 0; $return = '';
  6243. $out = '';
  6244. $divstart = $divend = '';
  6245. // If inline message with no format, we add it.
  6246. if ((empty($conf->use_javascript_ajax) || !empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out))
  6247. {
  6248. $divstart = '<div class="'.$style.' clearboth">';
  6249. $divend = '</div>';
  6250. }
  6251. if ((is_array($mesgarray) && count($mesgarray)) || $mesgstring)
  6252. {
  6253. $langs->load("errors");
  6254. $out .= $divstart;
  6255. if (is_array($mesgarray) && count($mesgarray))
  6256. {
  6257. foreach ($mesgarray as $message)
  6258. {
  6259. $ret++;
  6260. $out .= $langs->trans($message);
  6261. if ($ret < count($mesgarray)) $out .= "<br>\n";
  6262. }
  6263. }
  6264. if ($mesgstring)
  6265. {
  6266. $langs->load("errors");
  6267. $ret++;
  6268. $out .= $langs->trans($mesgstring);
  6269. }
  6270. $out .= $divend;
  6271. }
  6272. if ($out)
  6273. {
  6274. if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded))
  6275. {
  6276. $return = '<script>
  6277. $(document).ready(function() {
  6278. var block = '.(!empty($conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
  6279. if (block) {
  6280. $.dolEventValid("","'.dol_escape_js($out).'");
  6281. } else {
  6282. /* jnotify(message, preset of message type, keepmessage) */
  6283. $.jnotify("'.dol_escape_js($out).'",
  6284. "'.($style == "ok" ? 3000 : $style).'",
  6285. '.($style == "ok" ? "false" : "true").',
  6286. { remove: function (){} } );
  6287. }
  6288. });
  6289. </script>';
  6290. } else {
  6291. $return = $out;
  6292. }
  6293. }
  6294. return $return;
  6295. }
  6296. /**
  6297. * Get formated error messages to output (Used to show messages on html output).
  6298. *
  6299. * @param string $mesgstring Error message
  6300. * @param array $mesgarray Error messages array
  6301. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6302. * @return string Return html output
  6303. *
  6304. * @see dol_print_error()
  6305. * @see dol_htmloutput_mesg()
  6306. */
  6307. function get_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6308. {
  6309. return get_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6310. }
  6311. /**
  6312. * Print formated messages to output (Used to show messages on html output).
  6313. *
  6314. * @param string $mesgstring Message string or message key
  6315. * @param string[] $mesgarray Array of message strings or message keys
  6316. * @param string $style Which style to use ('ok', 'warning', 'error')
  6317. * @param int $keepembedded Set to 1 if message must be kept embedded into its html place (this disable jnotify)
  6318. * @return void
  6319. *
  6320. * @see dol_print_error()
  6321. * @see dol_htmloutput_errors()
  6322. * @see setEventMessages()
  6323. */
  6324. function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
  6325. {
  6326. if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) return;
  6327. $iserror = 0;
  6328. $iswarning = 0;
  6329. if (is_array($mesgarray))
  6330. {
  6331. foreach ($mesgarray as $val)
  6332. {
  6333. if ($val && preg_match('/class="error"/i', $val)) { $iserror++; break; }
  6334. if ($val && preg_match('/class="warning"/i', $val)) { $iswarning++; break; }
  6335. }
  6336. } elseif ($mesgstring && preg_match('/class="error"/i', $mesgstring)) $iserror++;
  6337. elseif ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) $iswarning++;
  6338. if ($style == 'error') $iserror++;
  6339. if ($style == 'warning') $iswarning++;
  6340. if ($iserror || $iswarning)
  6341. {
  6342. // Remove div from texts
  6343. $mesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $mesgstring);
  6344. $mesgstring = preg_replace('/<div class="(error|warning)">/', '', $mesgstring);
  6345. $mesgstring = preg_replace('/<\/div>/', '', $mesgstring);
  6346. // Remove div from texts array
  6347. if (is_array($mesgarray))
  6348. {
  6349. $newmesgarray = array();
  6350. foreach ($mesgarray as $val)
  6351. {
  6352. if (is_string($val))
  6353. {
  6354. $tmpmesgstring = preg_replace('/<\/div><div class="(error|warning)">/', '<br>', $val);
  6355. $tmpmesgstring = preg_replace('/<div class="(error|warning)">/', '', $tmpmesgstring);
  6356. $tmpmesgstring = preg_replace('/<\/div>/', '', $tmpmesgstring);
  6357. $newmesgarray[] = $tmpmesgstring;
  6358. } else {
  6359. dol_syslog("Error call of dol_htmloutput_mesg with an array with a value that is not a string", LOG_WARNING);
  6360. }
  6361. }
  6362. $mesgarray = $newmesgarray;
  6363. }
  6364. print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
  6365. } else print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
  6366. }
  6367. /**
  6368. * Print formated error messages to output (Used to show messages on html output).
  6369. *
  6370. * @param string $mesgstring Error message
  6371. * @param array $mesgarray Error messages array
  6372. * @param int $keepembedded Set to 1 in error message must be kept embedded into its html place (this disable jnotify)
  6373. * @return void
  6374. *
  6375. * @see dol_print_error()
  6376. * @see dol_htmloutput_mesg()
  6377. */
  6378. function dol_htmloutput_errors($mesgstring = '', $mesgarray = array(), $keepembedded = 0)
  6379. {
  6380. dol_htmloutput_mesg($mesgstring, $mesgarray, 'error', $keepembedded);
  6381. }
  6382. /**
  6383. * Advanced sort array by second index function, which produces ascending (default)
  6384. * or descending output and uses optionally natural case insensitive sorting (which
  6385. * can be optionally case sensitive as well).
  6386. *
  6387. * @param array $array Array to sort (array of array('key1'=>val1,'key2'=>val2,'key3'...) or array of objects)
  6388. * @param string $index Key in array to use for sorting criteria
  6389. * @param int $order Sort order ('asc' or 'desc')
  6390. * @param int $natsort 1=use "natural" sort (natsort), 0=use "standard" sort (asort)
  6391. * @param int $case_sensitive 1=sort is case sensitive, 0=not case sensitive
  6392. * @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.
  6393. * @return array Sorted array
  6394. */
  6395. function dol_sort_array(&$array, $index, $order = 'asc', $natsort = 0, $case_sensitive = 0, $keepindex = 0)
  6396. {
  6397. // Clean parameters
  6398. $order = strtolower($order);
  6399. if (is_array($array))
  6400. {
  6401. $sizearray = count($array);
  6402. if ($sizearray > 0)
  6403. {
  6404. $temp = array();
  6405. foreach (array_keys($array) as $key)
  6406. {
  6407. if (is_object($array[$key]))
  6408. {
  6409. $temp[$key] = $array[$key]->$index;
  6410. } else {
  6411. $temp[$key] = $array[$key][$index];
  6412. }
  6413. }
  6414. if (!$natsort) {
  6415. ($order == 'asc') ? asort($temp) : arsort($temp);
  6416. } else {
  6417. ($case_sensitive) ? natsort($temp) : natcasesort($temp);
  6418. if ($order != 'asc') $temp = array_reverse($temp, true);
  6419. }
  6420. $sorted = array();
  6421. foreach (array_keys($temp) as $key)
  6422. {
  6423. (is_numeric($key) && empty($keepindex)) ? $sorted[] = $array[$key] : $sorted[$key] = $array[$key];
  6424. }
  6425. return $sorted;
  6426. }
  6427. }
  6428. return $array;
  6429. }
  6430. /**
  6431. * Check if a string is in UTF8
  6432. *
  6433. * @param string $str String to check
  6434. * @return boolean True if string is UTF8 or ISO compatible with UTF8, False if not (ISO with special char or Binary)
  6435. */
  6436. function utf8_check($str)
  6437. {
  6438. // We must use here a binary strlen function (so not dol_strlen)
  6439. $strLength = dol_strlen($str);
  6440. for ($i = 0; $i < $strLength; $i++)
  6441. {
  6442. if (ord($str[$i]) < 0x80) continue; // 0bbbbbbb
  6443. elseif ((ord($str[$i]) & 0xE0) == 0xC0) $n = 1; // 110bbbbb
  6444. elseif ((ord($str[$i]) & 0xF0) == 0xE0) $n = 2; // 1110bbbb
  6445. elseif ((ord($str[$i]) & 0xF8) == 0xF0) $n = 3; // 11110bbb
  6446. elseif ((ord($str[$i]) & 0xFC) == 0xF8) $n = 4; // 111110bb
  6447. elseif ((ord($str[$i]) & 0xFE) == 0xFC) $n = 5; // 1111110b
  6448. else return false; // Does not match any model
  6449. for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
  6450. if ((++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
  6451. return false;
  6452. }
  6453. }
  6454. return true;
  6455. }
  6456. /**
  6457. * Check if a string is in ASCII
  6458. *
  6459. * @param string $str String to check
  6460. * @return boolean True if string is ASCII, False if not (byte value > 0x7F)
  6461. */
  6462. function ascii_check($str)
  6463. {
  6464. if (function_exists('mb_check_encoding')) {
  6465. //if (mb_detect_encoding($str, 'ASCII', true) return false;
  6466. if (!mb_check_encoding($str, 'ASCII')) return false;
  6467. } else {
  6468. if (preg_match('/[^\x00-\x7f]/', $str)) return false; // Contains a byte > 7f
  6469. }
  6470. return true;
  6471. }
  6472. /**
  6473. * Return a string encoded into OS filesystem encoding. This function is used to define
  6474. * value to pass to filesystem PHP functions.
  6475. *
  6476. * @param string $str String to encode (UTF-8)
  6477. * @return string Encoded string (UTF-8, ISO-8859-1)
  6478. */
  6479. function dol_osencode($str)
  6480. {
  6481. global $conf;
  6482. $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
  6483. if (empty($tmp) && !empty($_SERVER["WINDIR"])) $tmp = 'iso-8859-1'; // By default for windows
  6484. if (empty($tmp)) $tmp = 'utf-8'; // By default for other
  6485. if (!empty($conf->global->MAIN_FILESYSTEM_ENCODING)) $tmp = $conf->global->MAIN_FILESYSTEM_ENCODING;
  6486. if ($tmp == 'iso-8859-1') return utf8_decode($str);
  6487. return $str;
  6488. }
  6489. /**
  6490. * Return an id or code from a code or id.
  6491. * Store also Code-Id into a cache to speed up next request on same key.
  6492. *
  6493. * @param DoliDB $db Database handler
  6494. * @param string $key Code or Id to get Id or Code
  6495. * @param string $tablename Table name without prefix
  6496. * @param string $fieldkey Field to search the key into
  6497. * @param string $fieldid Field to get
  6498. * @param int $entityfilter Filter by entity
  6499. * @return int <0 if KO, Id of code if OK
  6500. * @see $langs->getLabelFromKey
  6501. */
  6502. function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
  6503. {
  6504. global $cache_codes;
  6505. // If key empty
  6506. if ($key == '') return '';
  6507. // Check in cache
  6508. if (isset($cache_codes[$tablename][$key][$fieldid])) // Can be defined to 0 or ''
  6509. {
  6510. return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
  6511. }
  6512. dol_syslog('dol_getIdFromCode (value for field '.$fieldid.' from key '.$key.' not found into cache)', LOG_DEBUG);
  6513. $sql = "SELECT ".$fieldid." as valuetoget";
  6514. $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
  6515. $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
  6516. if (!empty($entityfilter))
  6517. $sql .= " AND entity IN (".getEntity($tablename).")";
  6518. $resql = $db->query($sql);
  6519. if ($resql)
  6520. {
  6521. $obj = $db->fetch_object($resql);
  6522. if ($obj) $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
  6523. else $cache_codes[$tablename][$key][$fieldid] = '';
  6524. $db->free($resql);
  6525. return $cache_codes[$tablename][$key][$fieldid];
  6526. } else {
  6527. return -1;
  6528. }
  6529. }
  6530. /**
  6531. * Verify if condition in string is ok or not
  6532. *
  6533. * @param string $strRights String with condition to check
  6534. * @return boolean True or False. Return True if strRights is ''
  6535. */
  6536. function verifCond($strRights)
  6537. {
  6538. global $user, $conf, $langs;
  6539. global $leftmenu;
  6540. global $rights; // To export to dol_eval function
  6541. //print $strRights."<br>\n";
  6542. $rights = true;
  6543. if ($strRights != '')
  6544. {
  6545. $str = 'if(!('.$strRights.')) { $rights = false; }';
  6546. dol_eval($str); // The dol_eval must contains all the global $xxx used into a condition
  6547. }
  6548. return $rights;
  6549. }
  6550. /**
  6551. * Replace eval function to add more security.
  6552. * This function is called by verifCond() or trans() and transnoentitiesnoconv().
  6553. *
  6554. * @param string $s String to evaluate
  6555. * @param int $returnvalue 0=No return (used to execute eval($a=something)). 1=Value of eval is returned (used to eval($something)).
  6556. * @param int $hideerrors 1=Hide errors
  6557. * @return mixed Nothing or return result of eval
  6558. */
  6559. function dol_eval($s, $returnvalue = 0, $hideerrors = 1)
  6560. {
  6561. // Only global variables can be changed by eval function and returned to caller
  6562. global $db, $langs, $user, $conf, $website, $websitepage;
  6563. global $action, $mainmenu, $leftmenu;
  6564. global $rights;
  6565. global $object;
  6566. global $mysoc;
  6567. global $obj; // To get $obj used into list when dol_eval is used for computed fields and $obj is not yet $object
  6568. global $soc; // For backward compatibility
  6569. //print $s."<br>\n";
  6570. if ($returnvalue) {
  6571. if ($hideerrors) return @eval('return '.$s.';');
  6572. else return eval('return '.$s.';');
  6573. } else {
  6574. if ($hideerrors) @eval($s);
  6575. else eval($s);
  6576. }
  6577. }
  6578. /**
  6579. * Return if var element is ok
  6580. *
  6581. * @param string $element Variable to check
  6582. * @return boolean Return true of variable is not empty
  6583. */
  6584. function dol_validElement($element)
  6585. {
  6586. return (trim($element) != '');
  6587. }
  6588. /**
  6589. * Return img flag of country for a language code or country code
  6590. *
  6591. * @param string $codelang Language code ('en_IN', 'fr_CA', ...) or ISO Country code on 2 characters in uppercase ('IN', 'FR')
  6592. * @param string $moreatt Add more attribute on img tag (For example 'style="float: right"' or 'class="saturatemedium"')
  6593. * @return string HTML img string with flag.
  6594. */
  6595. function picto_from_langcode($codelang, $moreatt = '')
  6596. {
  6597. if (empty($codelang)) return '';
  6598. if ($codelang == 'auto')
  6599. {
  6600. return '<span class="fa fa-globe"></span>';
  6601. }
  6602. $langtocountryflag = array(
  6603. 'ar_AR' => '',
  6604. 'ca_ES' => 'catalonia',
  6605. 'da_DA' => 'dk',
  6606. 'fr_CA' => 'mq',
  6607. 'sv_SV' => 'se',
  6608. 'AQ' => 'unknown',
  6609. 'CW' => 'unknown',
  6610. 'IM' => 'unknown',
  6611. 'JE' => 'unknown',
  6612. 'MF' => 'unknown',
  6613. 'BL' => 'unknown',
  6614. 'SX' => 'unknown'
  6615. );
  6616. if (isset($langtocountryflag[$codelang])) $flagImage = $langtocountryflag[$codelang];
  6617. else {
  6618. $tmparray = explode('_', $codelang);
  6619. $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
  6620. }
  6621. return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
  6622. }
  6623. /**
  6624. * Return default language from country code.
  6625. * Return null if not found.
  6626. *
  6627. * @param string $countrycode Country code like 'US', 'FR', 'CA', ...
  6628. * @return string Value of locale like 'en_US', 'fr_FR', ...
  6629. */
  6630. function getLanguageCodeFromCountryCode($countrycode)
  6631. {
  6632. global $mysoc;
  6633. if (empty($countrycode)) return null;
  6634. if (strtoupper($countrycode) == 'MQ') return 'fr_CA';
  6635. if (strtoupper($countrycode) == 'SE') return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
  6636. if (strtoupper($countrycode) == 'CH')
  6637. {
  6638. if ($mysoc->country_code == 'FR') return 'fr_CH';
  6639. if ($mysoc->country_code == 'DE') return 'de_CH';
  6640. }
  6641. // Locale list taken from:
  6642. // http://stackoverflow.com/questions/3191664/
  6643. // list-of-all-locales-and-their-short-codes
  6644. $locales = array(
  6645. 'af-ZA',
  6646. 'am-ET',
  6647. 'ar-AE',
  6648. 'ar-BH',
  6649. 'ar-DZ',
  6650. 'ar-EG',
  6651. 'ar-IQ',
  6652. 'ar-JO',
  6653. 'ar-KW',
  6654. 'ar-LB',
  6655. 'ar-LY',
  6656. 'ar-MA',
  6657. 'ar-OM',
  6658. 'ar-QA',
  6659. 'ar-SA',
  6660. 'ar-SY',
  6661. 'ar-TN',
  6662. 'ar-YE',
  6663. 'as-IN',
  6664. 'ba-RU',
  6665. 'be-BY',
  6666. 'bg-BG',
  6667. 'bn-BD',
  6668. 'bn-IN',
  6669. 'bo-CN',
  6670. 'br-FR',
  6671. 'ca-ES',
  6672. 'co-FR',
  6673. 'cs-CZ',
  6674. 'cy-GB',
  6675. 'da-DK',
  6676. 'de-AT',
  6677. 'de-CH',
  6678. 'de-DE',
  6679. 'de-LI',
  6680. 'de-LU',
  6681. 'dv-MV',
  6682. 'el-GR',
  6683. 'en-AU',
  6684. 'en-BZ',
  6685. 'en-CA',
  6686. 'en-GB',
  6687. 'en-IE',
  6688. 'en-IN',
  6689. 'en-JM',
  6690. 'en-MY',
  6691. 'en-NZ',
  6692. 'en-PH',
  6693. 'en-SG',
  6694. 'en-TT',
  6695. 'en-US',
  6696. 'en-ZA',
  6697. 'en-ZW',
  6698. 'es-AR',
  6699. 'es-BO',
  6700. 'es-CL',
  6701. 'es-CO',
  6702. 'es-CR',
  6703. 'es-DO',
  6704. 'es-EC',
  6705. 'es-ES',
  6706. 'es-GT',
  6707. 'es-HN',
  6708. 'es-MX',
  6709. 'es-NI',
  6710. 'es-PA',
  6711. 'es-PE',
  6712. 'es-PR',
  6713. 'es-PY',
  6714. 'es-SV',
  6715. 'es-US',
  6716. 'es-UY',
  6717. 'es-VE',
  6718. 'et-EE',
  6719. 'eu-ES',
  6720. 'fa-IR',
  6721. 'fi-FI',
  6722. 'fo-FO',
  6723. 'fr-BE',
  6724. 'fr-CA',
  6725. 'fr-CH',
  6726. 'fr-FR',
  6727. 'fr-LU',
  6728. 'fr-MC',
  6729. 'fy-NL',
  6730. 'ga-IE',
  6731. 'gd-GB',
  6732. 'gl-ES',
  6733. 'gu-IN',
  6734. 'he-IL',
  6735. 'hi-IN',
  6736. 'hr-BA',
  6737. 'hr-HR',
  6738. 'hu-HU',
  6739. 'hy-AM',
  6740. 'id-ID',
  6741. 'ig-NG',
  6742. 'ii-CN',
  6743. 'is-IS',
  6744. 'it-CH',
  6745. 'it-IT',
  6746. 'ja-JP',
  6747. 'ka-GE',
  6748. 'kk-KZ',
  6749. 'kl-GL',
  6750. 'km-KH',
  6751. 'kn-IN',
  6752. 'ko-KR',
  6753. 'ky-KG',
  6754. 'lb-LU',
  6755. 'lo-LA',
  6756. 'lt-LT',
  6757. 'lv-LV',
  6758. 'mi-NZ',
  6759. 'mk-MK',
  6760. 'ml-IN',
  6761. 'mn-MN',
  6762. 'mr-IN',
  6763. 'ms-BN',
  6764. 'ms-MY',
  6765. 'mt-MT',
  6766. 'nb-NO',
  6767. 'ne-NP',
  6768. 'nl-BE',
  6769. 'nl-NL',
  6770. 'nn-NO',
  6771. 'oc-FR',
  6772. 'or-IN',
  6773. 'pa-IN',
  6774. 'pl-PL',
  6775. 'ps-AF',
  6776. 'pt-BR',
  6777. 'pt-PT',
  6778. 'rm-CH',
  6779. 'ro-RO',
  6780. 'ru-RU',
  6781. 'rw-RW',
  6782. 'sa-IN',
  6783. 'se-FI',
  6784. 'se-NO',
  6785. 'se-SE',
  6786. 'si-LK',
  6787. 'sk-SK',
  6788. 'sl-SI',
  6789. 'sq-AL',
  6790. 'sv-FI',
  6791. 'sv-SE',
  6792. 'sw-KE',
  6793. 'ta-IN',
  6794. 'te-IN',
  6795. 'th-TH',
  6796. 'tk-TM',
  6797. 'tn-ZA',
  6798. 'tr-TR',
  6799. 'tt-RU',
  6800. 'ug-CN',
  6801. 'uk-UA',
  6802. 'ur-PK',
  6803. 'vi-VN',
  6804. 'wo-SN',
  6805. 'xh-ZA',
  6806. 'yo-NG',
  6807. 'zh-CN',
  6808. 'zh-HK',
  6809. 'zh-MO',
  6810. 'zh-SG',
  6811. 'zh-TW',
  6812. 'zu-ZA',
  6813. );
  6814. $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
  6815. if (in_array($buildprimarykeytotest, $locales)) return strtolower($countrycode).'_'.strtoupper($countrycode);
  6816. if (function_exists('locale_get_primary_language') && function_exists('locale_get_region')) // Need extension php-intl
  6817. {
  6818. foreach ($locales as $locale)
  6819. {
  6820. $locale_language = locale_get_primary_language($locale);
  6821. $locale_region = locale_get_region($locale);
  6822. if (strtoupper($countrycode) == $locale_region)
  6823. {
  6824. //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
  6825. return strtolower($locale_language).'_'.strtoupper($locale_region);
  6826. }
  6827. }
  6828. } else {
  6829. dol_syslog("Warning Exention php-intl is not available", LOG_WARNING);
  6830. }
  6831. return null;
  6832. }
  6833. /**
  6834. * Complete or removed entries into a head array (used to build tabs).
  6835. * For example, with value added by external modules. Such values are declared into $conf->modules_parts['tab'].
  6836. * Or by change using hook completeTabsHead
  6837. *
  6838. * @param Conf $conf Object conf
  6839. * @param Translate $langs Object langs
  6840. * @param object|null $object Object object
  6841. * @param array $head Object head
  6842. * @param int $h New position to fill
  6843. * @param string $type Value for object where objectvalue can be
  6844. * 'thirdparty' to add a tab in third party view
  6845. * 'intervention' to add a tab in intervention view
  6846. * 'supplier_order' to add a tab in supplier order view
  6847. * 'supplier_invoice' to add a tab in supplier invoice view
  6848. * 'invoice' to add a tab in customer invoice view
  6849. * 'order' to add a tab in customer order view
  6850. * 'contract' to add a tabl in contract view
  6851. * 'product' to add a tab in product view
  6852. * 'propal' to add a tab in propal view
  6853. * 'user' to add a tab in user view
  6854. * 'group' to add a tab in group view
  6855. * 'member' to add a tab in fundation member view
  6856. * 'categories_x' to add a tab in category view ('x': type of category (0=product, 1=supplier, 2=customer, 3=member)
  6857. * 'ecm' to add a tab for another ecm view
  6858. * 'stock' to add a tab for warehouse view
  6859. * @param string $mode 'add' to complete head, 'remove' to remove entries
  6860. * @return void
  6861. */
  6862. function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
  6863. {
  6864. global $hookmanager;
  6865. if (isset($conf->modules_parts['tabs'][$type]) && is_array($conf->modules_parts['tabs'][$type]))
  6866. {
  6867. foreach ($conf->modules_parts['tabs'][$type] as $value)
  6868. {
  6869. $values = explode(':', $value);
  6870. if ($mode == 'add' && !preg_match('/^\-/', $values[1]))
  6871. {
  6872. if (count($values) == 6) // new declaration with permissions: $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
  6873. {
  6874. if ($values[0] != $type) continue;
  6875. if (verifCond($values[4]))
  6876. {
  6877. if ($values[3]) $langs->load($values[3]);
  6878. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6879. {
  6880. $substitutionarray = array();
  6881. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6882. $label = make_substitutions($reg[1], $substitutionarray);
  6883. } else $label = $langs->trans($values[2]);
  6884. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
  6885. $head[$h][1] = $label;
  6886. $head[$h][2] = str_replace('+', '', $values[1]);
  6887. $h++;
  6888. }
  6889. } elseif (count($values) == 5) // deprecated
  6890. {
  6891. dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
  6892. if ($values[0] != $type) continue;
  6893. if ($values[3]) $langs->load($values[3]);
  6894. if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg))
  6895. {
  6896. $substitutionarray = array();
  6897. complete_substitutions_array($substitutionarray, $langs, $object, array('needforkey'=>$values[2]));
  6898. $label = make_substitutions($reg[1], $substitutionarray);
  6899. } else $label = $langs->trans($values[2]);
  6900. $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
  6901. $head[$h][1] = $label;
  6902. $head[$h][2] = str_replace('+', '', $values[1]);
  6903. $h++;
  6904. }
  6905. } elseif ($mode == 'remove' && preg_match('/^\-/', $values[1]))
  6906. {
  6907. if ($values[0] != $type) continue;
  6908. $tabname = str_replace('-', '', $values[1]);
  6909. foreach ($head as $key => $val)
  6910. {
  6911. $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
  6912. //var_dump($key.' - '.$tabname.' - '.$head[$key][2].' - '.$values[3].' - '.$condition);
  6913. if ($head[$key][2] == $tabname && $condition)
  6914. {
  6915. unset($head[$key]);
  6916. break;
  6917. }
  6918. }
  6919. }
  6920. }
  6921. }
  6922. // No need to make a return $head. Var is modified as a reference
  6923. if (!empty($hookmanager))
  6924. {
  6925. $parameters = array('object' => $object, 'mode' => $mode, 'head' => $head);
  6926. $reshook = $hookmanager->executeHooks('completeTabsHead', $parameters);
  6927. if ($reshook > 0)
  6928. {
  6929. $head = $hookmanager->resArray;
  6930. $h = count($head);
  6931. }
  6932. }
  6933. }
  6934. /**
  6935. * Print common footer :
  6936. * conf->global->MAIN_HTML_FOOTER
  6937. * js for switch of menu hider
  6938. * js for conf->global->MAIN_GOOGLE_AN_ID
  6939. * js for conf->global->MAIN_SHOW_TUNING_INFO or $_SERVER["MAIN_SHOW_TUNING_INFO"]
  6940. * js for conf->logbuffer
  6941. *
  6942. * @param string $zone 'private' (for private pages) or 'public' (for public pages)
  6943. * @return void
  6944. */
  6945. function printCommonFooter($zone = 'private')
  6946. {
  6947. global $conf, $hookmanager, $user, $debugbar;
  6948. global $action;
  6949. global $micro_start_time;
  6950. if ($zone == 'private') print "\n".'<!-- Common footer for private page -->'."\n";
  6951. else print "\n".'<!-- Common footer for public page -->'."\n";
  6952. // A div to store page_y POST parameter so we can read it using javascript
  6953. print "\n<!-- A div to store page_y POST parameter -->\n";
  6954. print '<div id="page_y" style="display: none;">'.(empty($_POST['page_y']) ? '' : $_POST['page_y']).'</div>'."\n";
  6955. $parameters = array();
  6956. $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
  6957. if (empty($reshook))
  6958. {
  6959. if (!empty($conf->global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER."\n";
  6960. print "\n";
  6961. if (!empty($conf->use_javascript_ajax))
  6962. {
  6963. print '<script>'."\n";
  6964. print 'jQuery(document).ready(function() {'."\n";
  6965. if ($zone == 'private' && empty($conf->dol_use_jmobile))
  6966. {
  6967. print "\n";
  6968. print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
  6969. print 'jQuery("li.menuhider").click(function(event) {';
  6970. print ' if (!$( "body" ).hasClass( "sidebar-collapse" )){ event.preventDefault(); }'."\n";
  6971. print ' console.log("We click on .menuhider");'."\n";
  6972. print ' $("body").toggleClass("sidebar-collapse")'."\n";
  6973. print '});'."\n";
  6974. }
  6975. // Management of focus and mandatory for fields
  6976. if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"]))))
  6977. {
  6978. print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
  6979. $relativepathstring = $_SERVER["PHP_SELF"];
  6980. // Clean $relativepathstring
  6981. if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
  6982. $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
  6983. $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
  6984. //$tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
  6985. if (!empty($user->default_values[$relativepathstring]['focus']))
  6986. {
  6987. foreach ($user->default_values[$relativepathstring]['focus'] as $defkey => $defval)
  6988. {
  6989. $qualified = 0;
  6990. if ($defkey != '_noquery_')
  6991. {
  6992. $tmpqueryarraytohave = explode('&', $defkey);
  6993. $foundintru = 0;
  6994. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  6995. {
  6996. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  6997. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  6998. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  6999. }
  7000. if (!$foundintru) $qualified = 1;
  7001. //var_dump($defkey.'-'.$qualified);
  7002. } else $qualified = 1;
  7003. if ($qualified)
  7004. {
  7005. foreach ($defval as $paramkey => $paramval)
  7006. {
  7007. // Set focus on field
  7008. print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
  7009. print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
  7010. print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
  7011. }
  7012. }
  7013. }
  7014. }
  7015. if (!empty($user->default_values[$relativepathstring]['mandatory']))
  7016. {
  7017. foreach ($user->default_values[$relativepathstring]['mandatory'] as $defkey => $defval)
  7018. {
  7019. $qualified = 0;
  7020. if ($defkey != '_noquery_')
  7021. {
  7022. $tmpqueryarraytohave = explode('&', $defkey);
  7023. $foundintru = 0;
  7024. foreach ($tmpqueryarraytohave as $tmpquerytohave)
  7025. {
  7026. $tmpquerytohaveparam = explode('=', $tmpquerytohave);
  7027. //print "console.log('".$tmpquerytohaveparam[0]." ".$tmpquerytohaveparam[1]." ".GETPOST($tmpquerytohaveparam[0])."');";
  7028. if (!GETPOSTISSET($tmpquerytohaveparam[0]) || ($tmpquerytohaveparam[1] != GETPOST($tmpquerytohaveparam[0]))) $foundintru = 1;
  7029. }
  7030. if (!$foundintru) $qualified = 1;
  7031. //var_dump($defkey.'-'.$qualified);
  7032. } else $qualified = 1;
  7033. if ($qualified)
  7034. {
  7035. foreach ($defval as $paramkey => $paramval)
  7036. {
  7037. // Add property 'required' on input
  7038. print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7039. print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
  7040. print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
  7041. }
  7042. }
  7043. }
  7044. }
  7045. }
  7046. print '});'."\n";
  7047. // End of tuning
  7048. if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']) || !empty($conf->global->MAIN_SHOW_TUNING_INFO))
  7049. {
  7050. print "\n";
  7051. print "/* JS CODE TO ENABLE to add memory info */\n";
  7052. print 'window.console && console.log("';
  7053. if (!empty($conf->global->MEMCACHED_SERVER)) print 'MEMCACHED_SERVER='.$conf->global->MEMCACHED_SERVER.' - ';
  7054. print 'MAIN_OPTIMIZE_SPEED='.(isset($conf->global->MAIN_OPTIMIZE_SPEED) ? $conf->global->MAIN_OPTIMIZE_SPEED : 'off');
  7055. if (!empty($micro_start_time)) // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in global variable.
  7056. {
  7057. $micro_end_time = microtime(true);
  7058. print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
  7059. }
  7060. if (function_exists("memory_get_usage")) {
  7061. print ' - Mem: '.memory_get_usage(); // Do not use true here, it seems it takes the peak amount
  7062. }
  7063. if (function_exists("memory_get_peak_usage")) {
  7064. print ' - Real mem peak: '.memory_get_peak_usage(true);
  7065. }
  7066. if (function_exists("zend_loader_file_encoded"))
  7067. {
  7068. print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
  7069. }
  7070. print '");'."\n";
  7071. }
  7072. print "\n".'</script>'."\n";
  7073. // Google Analytics
  7074. // TODO Add a hook here
  7075. if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID))
  7076. {
  7077. $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID);
  7078. foreach ($tmptagarray as $tmptag) {
  7079. print "\n";
  7080. print "<!-- JS CODE TO ENABLE for google analtics tag -->\n";
  7081. print "
  7082. <!-- Global site tag (gtag.js) - Google Analytics -->
  7083. <script async src=\"https://www.googletagmanager.com/gtag/js?id=".trim($tmptag)."\"></script>
  7084. <script>
  7085. window.dataLayer = window.dataLayer || [];
  7086. function gtag(){dataLayer.push(arguments);}
  7087. gtag('js', new Date());
  7088. gtag('config', '".trim($tmptag)."');
  7089. </script>";
  7090. print "\n";
  7091. }
  7092. }
  7093. }
  7094. // Add Xdebug coverage of code
  7095. if (defined('XDEBUGCOVERAGE'))
  7096. {
  7097. print_r(xdebug_get_code_coverage());
  7098. }
  7099. // Add DebugBar data
  7100. if (!empty($user->rights->debugbar->read) && is_object($debugbar))
  7101. {
  7102. $debugbar['time']->stopMeasure('pageaftermaster');
  7103. print '<!-- Output debugbar data -->'."\n";
  7104. $renderer = $debugbar->getRenderer();
  7105. print $debugbar->getRenderer()->render();
  7106. } elseif (count($conf->logbuffer)) // If there is some logs in buffer to show
  7107. {
  7108. print "\n";
  7109. print "<!-- Start of log output\n";
  7110. //print '<div class="hidden">'."\n";
  7111. foreach ($conf->logbuffer as $logline)
  7112. {
  7113. print $logline."<br>\n";
  7114. }
  7115. //print '</div>'."\n";
  7116. print "End of log output -->\n";
  7117. }
  7118. }
  7119. }
  7120. /**
  7121. * Split a string with 2 keys into key array.
  7122. * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
  7123. *
  7124. * @param string $string String to explode
  7125. * @param string $delimiter Delimiter between each couple of data
  7126. * @param string $kv Delimiter between key and value
  7127. * @return array Array of data exploded
  7128. */
  7129. function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
  7130. {
  7131. if ($a = explode($delimiter, $string))
  7132. {
  7133. $ka = array();
  7134. foreach ($a as $s) { // each part
  7135. if ($s) {
  7136. if ($pos = strpos($s, $kv)) { // key/value delimiter
  7137. $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
  7138. } else { // key delimiter not found
  7139. $ka[] = trim($s);
  7140. }
  7141. }
  7142. }
  7143. return $ka;
  7144. }
  7145. return array();
  7146. }
  7147. /**
  7148. * Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
  7149. *
  7150. * @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.
  7151. * @return string HTML code to set focus
  7152. */
  7153. function dol_set_focus($selector)
  7154. {
  7155. print "\n".'<!-- Set focus onto a specific field -->'."\n";
  7156. print '<script>jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
  7157. }
  7158. /**
  7159. * Return getmypid() or random PID when function is disabled
  7160. * Some web hosts disable this php function for security reasons
  7161. * and sometimes we can't redeclare function
  7162. *
  7163. * @return int
  7164. */
  7165. function dol_getmypid()
  7166. {
  7167. if (!function_exists('getmypid')) {
  7168. return mt_rand(1, 32768);
  7169. } else {
  7170. return getmypid();
  7171. }
  7172. }
  7173. /**
  7174. * Generate natural SQL search string for a criteria (this criteria can be tested on one or several fields)
  7175. *
  7176. * @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")
  7177. * @param string $value The value to look for.
  7178. * If param $mode is 0, can contains several keywords separated with a space or |
  7179. * like "keyword1 keyword2" = We want record field like keyword1 AND field like keyword2
  7180. * or like "keyword1|keyword2" = We want record field like keyword1 OR field like keyword2
  7181. * If param $mode is 1, can contains an operator <, > or = like "<10" or ">=100.5 < 1000"
  7182. * If param $mode is 2, can contains a list of int id separated by comma like "1,3,4"
  7183. * If param $mode is 3, can contains a list of string separated by comma like "a,b,c"
  7184. * @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')
  7185. * 3=value is list of string separated with comma (Example 'text 1,text 2'), 4=value is a list of ID separated with comma (Example '2,7') to be used to search into a multiselect string '1,2,3,4'
  7186. * @param integer $nofirstand 1=Do not output the first 'AND'
  7187. * @return string $res The statement to append to the SQL query
  7188. */
  7189. function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
  7190. {
  7191. global $db, $langs;
  7192. $value = trim($value);
  7193. if ($mode == 0)
  7194. {
  7195. $value = preg_replace('/\*/', '%', $value); // Replace * with %
  7196. }
  7197. if ($mode == 1)
  7198. {
  7199. $value = preg_replace('/([<>=]+)\s+([0-9'.preg_quote($langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do
  7200. }
  7201. $value = preg_replace('/\s*\|\s*/', '|', $value);
  7202. $crits = explode(' ', $value);
  7203. $res = '';
  7204. if (!is_array($fields)) $fields = array($fields);
  7205. $j = 0;
  7206. foreach ($crits as $crit)
  7207. {
  7208. $crit = trim($crit);
  7209. $i = 0; $i2 = 0;
  7210. $newres = '';
  7211. foreach ($fields as $field)
  7212. {
  7213. if ($mode == 1)
  7214. {
  7215. $operator = '=';
  7216. $newcrit = preg_replace('/([<>=]+)/', '', $crit);
  7217. $reg = array();
  7218. preg_match('/([<>=]+)/', $crit, $reg);
  7219. if ($reg[1])
  7220. {
  7221. $operator = $reg[1];
  7222. }
  7223. if ($newcrit != '')
  7224. {
  7225. $numnewcrit = price2num($newcrit);
  7226. if (is_numeric($numnewcrit))
  7227. {
  7228. $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric
  7229. } else {
  7230. $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
  7231. }
  7232. $i2++; // a criteria was added to string
  7233. }
  7234. } elseif ($mode == 2 || $mode == -2)
  7235. {
  7236. $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer
  7237. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : '');
  7238. $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)";
  7239. if ($mode == -2) $newres .= ' OR '.$field.' IS NULL';
  7240. $i2++; // a criteria was added to string
  7241. } elseif ($mode == 3 || $mode == -3)
  7242. {
  7243. $tmparray = explode(',', $crit);
  7244. if (count($tmparray))
  7245. {
  7246. $listofcodes = '';
  7247. foreach ($tmparray as $val)
  7248. {
  7249. $val = trim($val);
  7250. if ($val)
  7251. {
  7252. $listofcodes .= ($listofcodes ? ',' : '');
  7253. $listofcodes .= "'".$db->escape($val)."'";
  7254. }
  7255. }
  7256. $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -3 ? 'NOT ' : '')."IN (".$db->sanitize($listofcodes, 1).")";
  7257. $i2++; // a criteria was added to string
  7258. }
  7259. if ($mode == -3) $newres .= ' OR '.$field.' IS NULL';
  7260. } elseif ($mode == 4)
  7261. {
  7262. $tmparray = explode(',', $crit);
  7263. if (count($tmparray))
  7264. {
  7265. $listofcodes = '';
  7266. foreach ($tmparray as $val)
  7267. {
  7268. $val = trim($val);
  7269. if ($val)
  7270. {
  7271. $newres .= ($i2 > 0 ? ' OR (' : '(').$field.' LIKE \''.$db->escape($val).',%\'';
  7272. $newres .= ' OR '.$field.' = \''.$db->escape($val).'\'';
  7273. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).'\'';
  7274. $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape($val).',%\'';
  7275. $newres .= ')';
  7276. $i2++;
  7277. }
  7278. }
  7279. }
  7280. } else // $mode=0
  7281. {
  7282. $tmpcrits = explode('|', $crit);
  7283. $i3 = 0;
  7284. foreach ($tmpcrits as $tmpcrit)
  7285. {
  7286. if ($tmpcrit !== '0' && empty($tmpcrit)) continue;
  7287. $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
  7288. if (preg_match('/\.(id|rowid)$/', $field)) // Special case for rowid that is sometimes a ref so used as a search field
  7289. {
  7290. $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ?trim($tmpcrit) : '0');
  7291. } else {
  7292. $newres .= $field." LIKE '";
  7293. $tmpcrit = trim($tmpcrit);
  7294. $tmpcrit2 = $tmpcrit;
  7295. $tmpbefore = '%'; $tmpafter = '%';
  7296. if (preg_match('/^[\^\$]/', $tmpcrit))
  7297. {
  7298. $tmpbefore = '';
  7299. $tmpcrit2 = preg_replace('/^[\^\$]/', '', $tmpcrit2);
  7300. }
  7301. if (preg_match('/[\^\$]$/', $tmpcrit))
  7302. {
  7303. $tmpafter = '';
  7304. $tmpcrit2 = preg_replace('/[\^\$]$/', '', $tmpcrit2);
  7305. }
  7306. $newres .= $tmpbefore;
  7307. $newres .= $db->escape($tmpcrit2);
  7308. $newres .= $tmpafter;
  7309. $newres .= "'";
  7310. if ($tmpcrit2 == '')
  7311. {
  7312. $newres .= ' OR '.$field." IS NULL";
  7313. }
  7314. }
  7315. $i3++;
  7316. }
  7317. $i2++; // a criteria was added to string
  7318. }
  7319. $i++;
  7320. }
  7321. if ($newres) $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
  7322. $j++;
  7323. }
  7324. $res = ($nofirstand ? "" : " AND ")."(".$res.")";
  7325. //print 'xx'.$res.'yy';
  7326. return $res;
  7327. }
  7328. /**
  7329. * Return string with full Url. The file qualified is the one defined by relative path in $object->last_main_doc
  7330. *
  7331. * @param Object $object Object
  7332. * @return string Url string
  7333. */
  7334. function showDirectDownloadLink($object)
  7335. {
  7336. global $conf, $langs;
  7337. $out = '';
  7338. $url = $object->getLastMainDocLink($object->element);
  7339. if ($url)
  7340. {
  7341. $out .= img_picto('', 'globe').' '.$langs->trans("DirectDownloadLink").'<br>';
  7342. $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
  7343. $out .= ajax_autoselect("directdownloadlink", 0);
  7344. }
  7345. return $out;
  7346. }
  7347. /**
  7348. * Return the filename of file to get the thumbs
  7349. *
  7350. * @param string $file Original filename (full or relative path)
  7351. * @param string $extName Extension to differenciate thumb file name ('', '_small', '_mini')
  7352. * @param string $extImgTarget Force image extension for thumbs. Use '' to keep same extension than original image (default).
  7353. * @return string New file name (full or relative path, including the thumbs/)
  7354. */
  7355. function getImageFileNameForSize($file, $extName, $extImgTarget = '')
  7356. {
  7357. $dirName = dirname($file);
  7358. if ($dirName == '.') $dirName = '';
  7359. $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp|\.webp)$/i', '', $file); // We remove extension, whatever is its case
  7360. $fileName = basename($fileName);
  7361. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
  7362. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
  7363. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
  7364. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
  7365. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
  7366. if (empty($extImgTarget)) $extImgTarget = (preg_match('/\.webp$/i', $file) ? '.webp' : '');
  7367. if (!$extImgTarget) return $file;
  7368. $subdir = '';
  7369. if ($extName) $subdir = 'thumbs/';
  7370. return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
  7371. }
  7372. /**
  7373. * Return URL we can use for advanced preview links
  7374. *
  7375. * @param string $modulepart propal, facture, facture_fourn, ...
  7376. * @param string $relativepath Relative path of docs.
  7377. * @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)
  7378. * @param string $param More param on http links
  7379. * @return string|array Output string with href link or array with all components of link
  7380. */
  7381. function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
  7382. {
  7383. global $conf, $langs;
  7384. if (empty($conf->use_javascript_ajax)) return '';
  7385. $isAllowedForPreview = dolIsAllowedForPreview($relativepath);
  7386. if ($alldata == 1)
  7387. {
  7388. if ($isAllowedForPreview) 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));
  7389. else return array();
  7390. }
  7391. // old behavior, return a string
  7392. if ($isAllowedForPreview) 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')).'\')';
  7393. else return '';
  7394. }
  7395. /**
  7396. * Make content of an input box selected when we click into input field.
  7397. *
  7398. * @param string $htmlname Id of html object ('#idvalue' or '.classvalue')
  7399. * @param string $addlink Add a 'link to' after
  7400. * @return string
  7401. */
  7402. function ajax_autoselect($htmlname, $addlink = '')
  7403. {
  7404. global $langs;
  7405. $out = '<script>
  7406. jQuery(document).ready(function () {
  7407. jQuery("'.((strpos($htmlname, '.') === 0 ? '' : '#').$htmlname).'").click(function() { jQuery(this).select(); } );
  7408. });
  7409. </script>';
  7410. if ($addlink) $out .= ' <a href="'.$addlink.'" target="_blank">'.$langs->trans("Link").'</a>';
  7411. return $out;
  7412. }
  7413. /**
  7414. * Return if a file is qualified for preview
  7415. *
  7416. * @param string $file Filename we looking for information
  7417. * @return int 1 If allowed, 0 otherwise
  7418. * @see dol_mimetype(), image_format_supported() from images.lib.php
  7419. */
  7420. function dolIsAllowedForPreview($file)
  7421. {
  7422. global $conf;
  7423. // Check .noexe extension in filename
  7424. if (preg_match('/\.noexe$/i', $file)) return 0;
  7425. // Check mime types
  7426. $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'webp');
  7427. if (!empty($conf->global->MAIN_ALLOW_SVG_FILES_AS_IMAGES)) $mime_preview[] = 'svg+xml';
  7428. //$mime_preview[]='vnd.oasis.opendocument.presentation';
  7429. //$mime_preview[]='archive';
  7430. $num_mime = array_search(dol_mimetype($file, '', 1), $mime_preview);
  7431. if ($num_mime !== false) return 1;
  7432. // By default, not allowed for preview
  7433. return 0;
  7434. }
  7435. /**
  7436. * Return mime type of a file
  7437. *
  7438. * @param string $file Filename we looking for MIME type
  7439. * @param string $default Default mime type if extension not found in known list
  7440. * @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
  7441. * @return string Return a mime type family (text/xxx, application/xxx, image/xxx, audio, video, archive)
  7442. * @see dolIsAllowedForPreview(), image_format_supported() from images.lib.php
  7443. */
  7444. function dol_mimetype($file, $default = 'application/octet-stream', $mode = 0)
  7445. {
  7446. $mime = $default;
  7447. $imgmime = 'other.png';
  7448. $famime = 'file-o';
  7449. $srclang = '';
  7450. $tmpfile = preg_replace('/\.noexe$/', '', $file);
  7451. // Plain text files
  7452. if (preg_match('/\.txt$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7453. if (preg_match('/\.rtx$/i', $tmpfile)) { $mime = 'text/richtext'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7454. if (preg_match('/\.csv$/i', $tmpfile)) { $mime = 'text/csv'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7455. if (preg_match('/\.tsv$/i', $tmpfile)) { $mime = 'text/tab-separated-values'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7456. if (preg_match('/\.(cf|conf|log)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7457. if (preg_match('/\.ini$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'ini'; $famime = 'file-text-o'; }
  7458. if (preg_match('/\.md$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'md'; $famime = 'file-text-o'; }
  7459. if (preg_match('/\.css$/i', $tmpfile)) { $mime = 'text/css'; $imgmime = 'css.png'; $srclang = 'css'; $famime = 'file-text-o'; }
  7460. if (preg_match('/\.lang$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'lang'; $famime = 'file-text-o'; }
  7461. // Certificate files
  7462. if (preg_match('/\.(crt|cer|key|pub)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $famime = 'file-text-o'; }
  7463. // XML based (HTML/XML/XAML)
  7464. if (preg_match('/\.(html|htm|shtml)$/i', $tmpfile)) { $mime = 'text/html'; $imgmime = 'html.png'; $srclang = 'html'; $famime = 'file-text-o'; }
  7465. if (preg_match('/\.(xml|xhtml)$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xml'; $famime = 'file-text-o'; }
  7466. if (preg_match('/\.xaml$/i', $tmpfile)) { $mime = 'text/xml'; $imgmime = 'other.png'; $srclang = 'xaml'; $famime = 'file-text-o'; }
  7467. // Languages
  7468. if (preg_match('/\.bas$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'bas'; $famime = 'file-code-o'; }
  7469. if (preg_match('/\.(c)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'c'; $famime = 'file-code-o'; }
  7470. if (preg_match('/\.(cpp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cpp'; $famime = 'file-code-o'; }
  7471. if (preg_match('/\.cs$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'cs'; $famime = 'file-code-o'; }
  7472. if (preg_match('/\.(h)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'h'; $famime = 'file-code-o'; }
  7473. if (preg_match('/\.(java|jsp)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'java'; $famime = 'file-code-o'; }
  7474. if (preg_match('/\.php([0-9]{1})?$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7475. if (preg_match('/\.phtml$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'php.png'; $srclang = 'php'; $famime = 'file-code-o'; }
  7476. if (preg_match('/\.(pl|pm)$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'pl.png'; $srclang = 'perl'; $famime = 'file-code-o'; }
  7477. if (preg_match('/\.sql$/i', $tmpfile)) { $mime = 'text/plain'; $imgmime = 'text.png'; $srclang = 'sql'; $famime = 'file-code-o'; }
  7478. if (preg_match('/\.js$/i', $tmpfile)) { $mime = 'text/x-javascript'; $imgmime = 'jscript.png'; $srclang = 'js'; $famime = 'file-code-o'; }
  7479. // Open office
  7480. if (preg_match('/\.odp$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.presentation'; $imgmime = 'ooffice.png'; $famime = 'file-powerpoint-o'; }
  7481. if (preg_match('/\.ods$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.spreadsheet'; $imgmime = 'ooffice.png'; $famime = 'file-excel-o'; }
  7482. if (preg_match('/\.odt$/i', $tmpfile)) { $mime = 'application/vnd.oasis.opendocument.text'; $imgmime = 'ooffice.png'; $famime = 'file-word-o'; }
  7483. // MS Office
  7484. if (preg_match('/\.mdb$/i', $tmpfile)) { $mime = 'application/msaccess'; $imgmime = 'mdb.png'; $famime = 'file-o'; }
  7485. if (preg_match('/\.doc(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7486. if (preg_match('/\.dot(x|m)?$/i', $tmpfile)) { $mime = 'application/msword'; $imgmime = 'doc.png'; $famime = 'file-word-o'; }
  7487. if (preg_match('/\.xlt(x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7488. if (preg_match('/\.xla(m)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7489. if (preg_match('/\.xls$/i', $tmpfile)) { $mime = 'application/vnd.ms-excel'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7490. if (preg_match('/\.xls(b|m|x)$/i', $tmpfile)) { $mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; $imgmime = 'xls.png'; $famime = 'file-excel-o'; }
  7491. if (preg_match('/\.pps(m|x)?$/i', $tmpfile)) { $mime = 'application/vnd.ms-powerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7492. if (preg_match('/\.ppt(m|x)?$/i', $tmpfile)) { $mime = 'application/x-mspowerpoint'; $imgmime = 'ppt.png'; $famime = 'file-powerpoint-o'; }
  7493. // Other
  7494. if (preg_match('/\.pdf$/i', $tmpfile)) { $mime = 'application/pdf'; $imgmime = 'pdf.png'; $famime = 'file-pdf-o'; }
  7495. // Scripts
  7496. if (preg_match('/\.bat$/i', $tmpfile)) { $mime = 'text/x-bat'; $imgmime = 'script.png'; $srclang = 'dos'; $famime = 'file-code-o'; }
  7497. if (preg_match('/\.sh$/i', $tmpfile)) { $mime = 'text/x-sh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7498. if (preg_match('/\.ksh$/i', $tmpfile)) { $mime = 'text/x-ksh'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7499. if (preg_match('/\.bash$/i', $tmpfile)) { $mime = 'text/x-bash'; $imgmime = 'script.png'; $srclang = 'bash'; $famime = 'file-code-o'; }
  7500. // Images
  7501. if (preg_match('/\.ico$/i', $tmpfile)) { $mime = 'image/x-icon'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7502. if (preg_match('/\.(jpg|jpeg)$/i', $tmpfile)) { $mime = 'image/jpeg'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7503. if (preg_match('/\.png$/i', $tmpfile)) { $mime = 'image/png'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7504. if (preg_match('/\.gif$/i', $tmpfile)) { $mime = 'image/gif'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7505. if (preg_match('/\.bmp$/i', $tmpfile)) { $mime = 'image/bmp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7506. if (preg_match('/\.(tif|tiff)$/i', $tmpfile)) { $mime = 'image/tiff'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7507. if (preg_match('/\.svg$/i', $tmpfile)) { $mime = 'image/svg+xml'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7508. if (preg_match('/\.webp$/i', $tmpfile)) { $mime = 'image/webp'; $imgmime = 'image.png'; $famime = 'file-image-o'; }
  7509. // Calendar
  7510. if (preg_match('/\.vcs$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7511. if (preg_match('/\.ics$/i', $tmpfile)) { $mime = 'text/calendar'; $imgmime = 'other.png'; $famime = 'file-text-o'; }
  7512. // Other
  7513. if (preg_match('/\.torrent$/i', $tmpfile)) { $mime = 'application/x-bittorrent'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7514. // Audio
  7515. if (preg_match('/\.(mp3|ogg|au|wav|wma|mid)$/i', $tmpfile)) { $mime = 'audio'; $imgmime = 'audio.png'; $famime = 'file-audio-o'; }
  7516. // Video
  7517. if (preg_match('/\.ogv$/i', $tmpfile)) { $mime = 'video/ogg'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7518. if (preg_match('/\.webm$/i', $tmpfile)) { $mime = 'video/webm'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7519. if (preg_match('/\.avi$/i', $tmpfile)) { $mime = 'video/x-msvideo'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7520. if (preg_match('/\.divx$/i', $tmpfile)) { $mime = 'video/divx'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7521. if (preg_match('/\.xvid$/i', $tmpfile)) { $mime = 'video/xvid'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7522. if (preg_match('/\.(wmv|mpg|mpeg)$/i', $tmpfile)) { $mime = 'video'; $imgmime = 'video.png'; $famime = 'file-video-o'; }
  7523. // Archive
  7524. if (preg_match('/\.(zip|rar|gz|tgz|z|cab|bz2|7z|tar|lzh)$/i', $tmpfile)) { $mime = 'archive'; $imgmime = 'archive.png'; $famime = 'file-archive-o'; } // application/xxx where zzz is zip, ...
  7525. // Exe
  7526. if (preg_match('/\.(exe|com)$/i', $tmpfile)) { $mime = 'application/octet-stream'; $imgmime = 'other.png'; $famime = 'file-o'; }
  7527. // Lib
  7528. if (preg_match('/\.(dll|lib|o|so|a)$/i', $tmpfile)) { $mime = 'library'; $imgmime = 'library.png'; $famime = 'file-o'; }
  7529. // Err
  7530. if (preg_match('/\.err$/i', $tmpfile)) { $mime = 'error'; $imgmime = 'error.png'; $famime = 'file-text-o'; }
  7531. // Return string
  7532. if ($mode == 1)
  7533. {
  7534. $tmp = explode('/', $mime);
  7535. return (!empty($tmp[1]) ? $tmp[1] : $tmp[0]);
  7536. }
  7537. if ($mode == 2)
  7538. {
  7539. return $imgmime;
  7540. }
  7541. if ($mode == 3)
  7542. {
  7543. return $srclang;
  7544. }
  7545. if ($mode == 4)
  7546. {
  7547. return $famime;
  7548. }
  7549. return $mime;
  7550. }
  7551. /**
  7552. * Return value from dictionary
  7553. *
  7554. * @param string $tablename name of dictionary
  7555. * @param string $field the value to return
  7556. * @param int $id id of line
  7557. * @param bool $checkentity add filter on entity
  7558. * @param string $rowidfield name of the column rowid
  7559. * @return string
  7560. */
  7561. function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
  7562. {
  7563. global $dictvalues, $db, $langs;
  7564. if (!isset($dictvalues[$tablename]))
  7565. {
  7566. $dictvalues[$tablename] = array();
  7567. $sql = 'SELECT * FROM '.$tablename.' WHERE 1'; // Here select * is allowed as it is generic code and we don't have list of fields
  7568. if ($checkentity) $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
  7569. $resql = $db->query($sql);
  7570. if ($resql)
  7571. {
  7572. while ($obj = $db->fetch_object($resql))
  7573. {
  7574. $dictvalues[$tablename][$obj->{$rowidfield}] = $obj;
  7575. }
  7576. } else {
  7577. dol_print_error($db);
  7578. }
  7579. }
  7580. if (!empty($dictvalues[$tablename][$id])) return $dictvalues[$tablename][$id]->{$field}; // Found
  7581. else // Not found
  7582. {
  7583. if ($id > 0) return $id;
  7584. return '';
  7585. }
  7586. }
  7587. /**
  7588. * Return true if the color is light
  7589. *
  7590. * @param string $stringcolor String with hex (FFFFFF) or comma RGB ('255,255,255')
  7591. * @return int -1 : Error with argument passed |0 : color is dark | 1 : color is light
  7592. */
  7593. function colorIsLight($stringcolor)
  7594. {
  7595. $stringcolor = str_replace('#', '', $stringcolor);
  7596. $res = -1;
  7597. if (!empty($stringcolor))
  7598. {
  7599. $res = 0;
  7600. $tmp = explode(',', $stringcolor);
  7601. if (count($tmp) > 1) // This is a comma RGB ('255','255','255')
  7602. {
  7603. $r = $tmp[0];
  7604. $g = $tmp[1];
  7605. $b = $tmp[2];
  7606. } else {
  7607. $hexr = $stringcolor[0].$stringcolor[1];
  7608. $hexg = $stringcolor[2].$stringcolor[3];
  7609. $hexb = $stringcolor[4].$stringcolor[5];
  7610. $r = hexdec($hexr);
  7611. $g = hexdec($hexg);
  7612. $b = hexdec($hexb);
  7613. }
  7614. $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
  7615. if ($bright > 0.6) $res = 1;
  7616. }
  7617. return $res;
  7618. }
  7619. /**
  7620. * Function to test if an entry is enabled or not
  7621. *
  7622. * @param string $type_user 0=We test for internal user, 1=We test for external user
  7623. * @param array $menuentry Array for feature entry to test
  7624. * @param array $listofmodulesforexternal Array with list of modules allowed to external users
  7625. * @return int 0=Hide, 1=Show, 2=Show gray
  7626. */
  7627. function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
  7628. {
  7629. global $conf;
  7630. //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
  7631. //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
  7632. if (empty($menuentry['enabled'])) return 0; // Entry disabled by condition
  7633. if ($type_user && $menuentry['module'])
  7634. {
  7635. $tmploops = explode('|', $menuentry['module']);
  7636. $found = 0;
  7637. foreach ($tmploops as $tmploop)
  7638. {
  7639. if (in_array($tmploop, $listofmodulesforexternal)) {
  7640. $found++; break;
  7641. }
  7642. }
  7643. if (!$found) return 0; // Entry is for menus all excluded to external users
  7644. }
  7645. if (!$menuentry['perms'] && $type_user) return 0; // No permissions and user is external
  7646. if (!$menuentry['perms'] && !empty($conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) return 0; // No permissions and option to hide when not allowed, even for internal user, is on
  7647. if (!$menuentry['perms']) return 2; // No permissions and user is external
  7648. return 1;
  7649. }
  7650. /**
  7651. * Round to next multiple.
  7652. *
  7653. * @param double $n Number to round up
  7654. * @param integer $x Multiple. For example 60 to round up to nearest exact minute for a date with seconds.
  7655. * @return integer Value rounded.
  7656. */
  7657. function roundUpToNextMultiple($n, $x = 5)
  7658. {
  7659. return (ceil($n) % $x === 0) ? ceil($n) : round(($n + $x / 2) / $x) * $x;
  7660. }
  7661. /**
  7662. * Function dolGetBadge
  7663. *
  7664. * @param string $label label of badge no html : use in alt attribute for accessibility
  7665. * @param string $html optional : label of badge with html
  7666. * @param string $type type of badge : Primary Secondary Success Danger Warning Info Light Dark status0 status1 status2 status3 status4 status5 status6 status7 status8 status9
  7667. * @param string $mode default '' , 'pill', 'dot'
  7668. * @param string $url the url for link
  7669. * @param array $params various params for future : recommended rather than adding more fuction arguments. array('attr'=>array('title'=>'abc'))
  7670. * @return string Html badge
  7671. */
  7672. function dolGetBadge($label, $html = '', $type = 'primary', $mode = '', $url = '', $params = array())
  7673. {
  7674. $attr = array(
  7675. 'class'=>'badge '.(!empty($mode) ? ' badge-'.$mode : '').(!empty($type) ? ' badge-'.$type : '').(empty($params['css']) ? '' : ' '.$params['css'])
  7676. );
  7677. if (empty($html)) {
  7678. $html = $label;
  7679. }
  7680. if (!empty($url)) {
  7681. $attr['href'] = $url;
  7682. }
  7683. if ($mode === 'dot') {
  7684. $attr['class'] .= ' classfortooltip';
  7685. $attr['title'] = $html;
  7686. $attr['aria-label'] = $label;
  7687. $html = '';
  7688. }
  7689. // Override attr
  7690. if (!empty($params['attr']) && is_array($params['attr'])) {
  7691. foreach ($params['attr']as $key => $value) {
  7692. if ($key == 'class') {
  7693. $attr['class'] .= ' '.$value;
  7694. } elseif ($key == 'classOverride') {
  7695. $attr['class'] = $value;
  7696. } else {
  7697. $attr[$key] = $value;
  7698. }
  7699. }
  7700. }
  7701. // TODO: add hook
  7702. // escape all attribute
  7703. $attr = array_map('dol_escape_htmltag', $attr);
  7704. $TCompiledAttr = array();
  7705. foreach ($attr as $key => $value) {
  7706. $TCompiledAttr[] = $key.'="'.$value.'"';
  7707. }
  7708. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7709. $tag = !empty($url) ? 'a' : 'span';
  7710. return '<'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'>';
  7711. }
  7712. /**
  7713. * Output the badge of a status.
  7714. *
  7715. * @param string $statusLabel Label of badge no html : use in alt attribute for accessibility
  7716. * @param string $statusLabelShort Short label of badge no html
  7717. * @param string $html Optional : label of badge with html
  7718. * @param string $statusType status0 status1 status2 status3 status4 status5 status6 status7 status8 status9 : image name or badge name
  7719. * @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
  7720. * @param string $url The url for link
  7721. * @param array $params Various params. Example: array('tooltip'=>'...', 'badgeParams'=>...)
  7722. * @return string Html status string
  7723. */
  7724. function dolGetStatus($statusLabel = '', $statusLabelShort = '', $html = '', $statusType = 'status0', $displayMode = 0, $url = '', $params = array())
  7725. {
  7726. global $conf;
  7727. $return = '';
  7728. $dolGetBadgeParams = array();
  7729. if (!empty($params['badgeParams'])) {
  7730. $dolGetBadgeParams = $params['badgeParams'];
  7731. }
  7732. // TODO : add a hook
  7733. if ($displayMode == 0) {
  7734. $return = !empty($html) ? $html : (empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort));
  7735. } elseif ($displayMode == 1) {
  7736. $return = !empty($html) ? $html : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7737. } // Use status with images (for backward compatibility)
  7738. elseif (!empty($conf->global->MAIN_STATUS_USES_IMAGES)) {
  7739. $return = '';
  7740. $htmlLabel = (in_array($displayMode, array(1, 2, 5)) ? '<span class="hideonsmartphone">' : '').(!empty($html) ? $html : $statusLabel).(in_array($displayMode, array(1, 2, 5)) ? '</span>' : '');
  7741. $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>' : '');
  7742. // For small screen, we always use the short label instead of long label.
  7743. if (!empty($conf->dol_optimize_smallscreen))
  7744. {
  7745. if ($displayMode == 0) $displayMode = 1;
  7746. elseif ($displayMode == 4) $displayMode = 2;
  7747. elseif ($displayMode == 6) $displayMode = 5;
  7748. }
  7749. // For backward compatibility. Image's filename are still in French, so we use this array to convert
  7750. $statusImg = array(
  7751. 'status0' => 'statut0',
  7752. 'status1' => 'statut1',
  7753. 'status2' => 'statut2',
  7754. 'status3' => 'statut3',
  7755. 'status4' => 'statut4',
  7756. 'status5' => 'statut5',
  7757. 'status6' => 'statut6',
  7758. 'status7' => 'statut7',
  7759. 'status8' => 'statut8',
  7760. 'status9' => 'statut9'
  7761. );
  7762. if (!empty($statusImg[$statusType])) {
  7763. $htmlImg = img_picto($statusLabel, $statusImg[$statusType]);
  7764. } else {
  7765. $htmlImg = img_picto($statusLabel, $statusType);
  7766. }
  7767. if ($displayMode === 2) {
  7768. $return = $htmlImg.' '.$htmlLabelShort;
  7769. } elseif ($displayMode === 3) {
  7770. $return = $htmlImg;
  7771. } elseif ($displayMode === 4) {
  7772. $return = $htmlImg.' '.$htmlLabel;
  7773. } elseif ($displayMode === 5) {
  7774. $return = $htmlLabelShort.' '.$htmlImg;
  7775. } else { // $displayMode >= 6
  7776. $return = $htmlLabel.' '.$htmlImg;
  7777. }
  7778. } // Use new badge
  7779. elseif (empty($conf->global->MAIN_STATUS_USES_IMAGES) && !empty($displayMode)) {
  7780. $statusLabelShort = (empty($statusLabelShort) ? $statusLabel : $statusLabelShort);
  7781. $dolGetBadgeParams['attr']['class'] = 'badge-status';
  7782. $dolGetBadgeParams['attr']['title'] = empty($params['tooltip']) ? $statusLabel : $params['tooltip'];
  7783. if ($displayMode == 3) {
  7784. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), '', $statusType, 'dot', $url, $dolGetBadgeParams);
  7785. } elseif ($displayMode === 5) {
  7786. $return = dolGetBadge($statusLabelShort, $html, $statusType, '', $url, $dolGetBadgeParams);
  7787. } else {
  7788. $return = dolGetBadge((empty($conf->dol_optimize_smallscreen) ? $statusLabel : (empty($statusLabelShort) ? $statusLabel : $statusLabelShort)), $html, $statusType, '', $url, $dolGetBadgeParams);
  7789. }
  7790. }
  7791. return $return;
  7792. }
  7793. /**
  7794. * Function dolGetButtonAction
  7795. *
  7796. * @param string $label label of button no html : use in alt attribute for accessibility $html is not empty
  7797. * @param string $html optional : content with html
  7798. * @param string $actionType default, delete, danger
  7799. * @param string $url the url for link
  7800. * @param string $id attribute id of button
  7801. * @param int $userRight user action right
  7802. * @param array $params various params for future : recommended rather than adding more function arguments
  7803. * @return string html button
  7804. */
  7805. function dolGetButtonAction($label, $html = '', $actionType = 'default', $url = '', $id = '', $userRight = 1, $params = array())
  7806. {
  7807. $class = 'butAction';
  7808. if ($actionType == 'danger' || $actionType == 'delete') {
  7809. $class = 'butActionDelete';
  7810. }
  7811. $attr = array(
  7812. 'class' => $class
  7813. ,'href' => empty($url) ? '' : $url
  7814. );
  7815. if (empty($html)) {
  7816. $html = $label;
  7817. } else {
  7818. $attr['aria-label'] = $label;
  7819. }
  7820. if (empty($userRight)) {
  7821. $attr['class'] = 'butActionRefused';
  7822. $attr['href'] = '';
  7823. }
  7824. if (!empty($id)) {
  7825. $attr['id'] = $id;
  7826. }
  7827. // Override attr
  7828. if (!empty($params['attr']) && is_array($params['attr'])) {
  7829. foreach ($params['attr'] as $key => $value) {
  7830. if ($key == 'class') {
  7831. $attr['class'] .= ' '.$value;
  7832. } elseif ($key == 'classOverride') {
  7833. $attr['class'] = $value;
  7834. } else {
  7835. $attr[$key] = $value;
  7836. }
  7837. }
  7838. }
  7839. if (isset($attr['href']) && empty($attr['href'])) {
  7840. unset($attr['href']);
  7841. }
  7842. // TODO : add a hook
  7843. // escape all attribute
  7844. $attr = array_map('dol_escape_htmltag', $attr);
  7845. $TCompiledAttr = array();
  7846. foreach ($attr as $key => $value) {
  7847. $TCompiledAttr[] = $key.'="'.$value.'"';
  7848. }
  7849. $compiledAttributes = !empty($TCompiledAttr) ?implode(' ', $TCompiledAttr) : '';
  7850. $tag = !empty($attr['href']) ? 'a' : 'span';
  7851. return '<div class="inline-block divButAction"><'.$tag.' '.$compiledAttributes.'>'.$html.'</'.$tag.'></div>';
  7852. }
  7853. /**
  7854. * Function dolGetButtonTitle : this kind of buttons are used in title in list
  7855. *
  7856. * @param string $label label of button
  7857. * @param string $helpText optional : content for help tooltip
  7858. * @param string $iconClass class for icon element (Example: 'fa fa-file')
  7859. * @param string $url the url for link
  7860. * @param string $id attribute id of button
  7861. * @param int $status 0 no user rights, 1 active, -1 Feature Disabled, -2 disable Other reason use helpText as tooltip
  7862. * @param array $params various params for future : recommended rather than adding more function arguments
  7863. * @return string html button
  7864. */
  7865. function dolGetButtonTitle($label, $helpText = '', $iconClass = 'fa fa-file', $url = '', $id = '', $status = 1, $params = array())
  7866. {
  7867. global $langs, $conf, $user;
  7868. // Actually this conf is used in css too for external module compatibility and smooth transition to this function
  7869. if (!empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED) && (!$user->admin) && $status <= 0) {
  7870. return '';
  7871. }
  7872. $class = 'btnTitle';
  7873. if ($iconClass == 'fa fa-plus-circle') $class .= ' btnTitlePlus';
  7874. $useclassfortooltip = 1;
  7875. if (!empty($params['morecss'])) $class .= ' '.$params['morecss'];
  7876. $attr = array(
  7877. 'class' => $class,
  7878. 'href' => empty($url) ? '' : $url
  7879. );
  7880. if (!empty($helpText)) {
  7881. $attr['title'] = dol_escape_htmltag($helpText);
  7882. } elseif (empty($attr['title']) && $label) {
  7883. $attr['title'] = $label;
  7884. $useclassfortooltip = 0;
  7885. }
  7886. if ($status <= 0) {
  7887. $attr['class'] .= ' refused';
  7888. $attr['href'] = '';
  7889. if ($status == -1) { // disable
  7890. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("FeatureDisabled"));
  7891. } elseif ($status == 0) { // Not enough permissions
  7892. $attr['title'] = dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions"));
  7893. }
  7894. }
  7895. if (!empty($attr['title']) && $useclassfortooltip) {
  7896. $attr['class'] .= ' classfortooltip';
  7897. }
  7898. if (!empty($id)) {
  7899. $attr['id'] = $id;
  7900. }
  7901. // Override attr
  7902. if (!empty($params['attr']) && is_array($params['attr'])) {
  7903. foreach ($params['attr'] as $key => $value) {
  7904. if ($key == 'class') {
  7905. $attr['class'] .= ' '.$value;
  7906. } elseif ($key == 'classOverride') {
  7907. $attr['class'] = $value;
  7908. } else {
  7909. $attr[$key] = $value;
  7910. }
  7911. }
  7912. }
  7913. if (isset($attr['href']) && empty($attr['href'])) {
  7914. unset($attr['href']);
  7915. }
  7916. // TODO : add a hook
  7917. // escape all attribute
  7918. $attr = array_map('dol_escape_htmltag', $attr);
  7919. $TCompiledAttr = array();
  7920. foreach ($attr as $key => $value) {
  7921. $TCompiledAttr[] = $key.'="'.$value.'"';
  7922. }
  7923. $compiledAttributes = (empty($TCompiledAttr) ? '' : implode(' ', $TCompiledAttr));
  7924. $tag = (empty($attr['href']) ? 'span' : 'a');
  7925. $button = '<'.$tag.' '.$compiledAttributes.'>';
  7926. $button .= '<span class="'.$iconClass.' valignmiddle btnTitle-icon"></span>';
  7927. if (!empty($params['forcenohideoftext'])) {
  7928. $button .= '<span class="valignmiddle text-plus-circle btnTitle-label'.(empty($params['forcenohideoftext']) ? ' hideonsmartphone' : '').'">'.$label.'</span>';
  7929. }
  7930. $button .= '</'.$tag.'>';
  7931. return $button;
  7932. }
  7933. /**
  7934. * Get an array with properties of an element.
  7935. * Called by fetchObjectByElement.
  7936. *
  7937. * @param string $element_type Element type (Value of $object->element). Example: 'action', 'facture', 'project_task' or 'object@mymodule'...
  7938. * @return array (module, classpath, element, subelement, classfile, classname)
  7939. */
  7940. function getElementProperties($element_type)
  7941. {
  7942. $regs = array();
  7943. $classfile = $classname = $classpath = '';
  7944. // Parse element/subelement (ex: project_task)
  7945. $module = $element_type;
  7946. $element = $element_type;
  7947. $subelement = $element_type;
  7948. // If we ask an resource form external module (instead of default path)
  7949. if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs)) {
  7950. $element = $subelement = $regs[1];
  7951. $module = $regs[2];
  7952. }
  7953. //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
  7954. if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs)) {
  7955. $module = $element = $regs[1];
  7956. $subelement = $regs[2];
  7957. }
  7958. // For compat
  7959. if ($element_type == "action") {
  7960. $classpath = 'comm/action/class';
  7961. $subelement = 'Actioncomm';
  7962. $module = 'agenda';
  7963. }
  7964. // To work with non standard path
  7965. if ($element_type == 'facture' || $element_type == 'invoice') {
  7966. $classpath = 'compta/facture/class';
  7967. $module = 'facture';
  7968. $subelement = 'facture';
  7969. }
  7970. if ($element_type == 'commande' || $element_type == 'order') {
  7971. $classpath = 'commande/class';
  7972. $module = 'commande';
  7973. $subelement = 'commande';
  7974. }
  7975. if ($element_type == 'propal') {
  7976. $classpath = 'comm/propal/class';
  7977. }
  7978. if ($element_type == 'supplier_proposal') {
  7979. $classpath = 'supplier_proposal/class';
  7980. }
  7981. if ($element_type == 'shipping') {
  7982. $classpath = 'expedition/class';
  7983. $subelement = 'expedition';
  7984. $module = 'expedition_bon';
  7985. }
  7986. if ($element_type == 'delivery') {
  7987. $classpath = 'delivery/class';
  7988. $subelement = 'delivery';
  7989. $module = 'delivery_note';
  7990. }
  7991. if ($element_type == 'contract') {
  7992. $classpath = 'contrat/class';
  7993. $module = 'contrat';
  7994. $subelement = 'contrat';
  7995. }
  7996. if ($element_type == 'member') {
  7997. $classpath = 'adherents/class';
  7998. $module = 'adherent';
  7999. $subelement = 'adherent';
  8000. }
  8001. if ($element_type == 'cabinetmed_cons') {
  8002. $classpath = 'cabinetmed/class';
  8003. $module = 'cabinetmed';
  8004. $subelement = 'cabinetmedcons';
  8005. }
  8006. if ($element_type == 'fichinter') {
  8007. $classpath = 'fichinter/class';
  8008. $module = 'ficheinter';
  8009. $subelement = 'fichinter';
  8010. }
  8011. if ($element_type == 'dolresource' || $element_type == 'resource') {
  8012. $classpath = 'resource/class';
  8013. $module = 'resource';
  8014. $subelement = 'dolresource';
  8015. }
  8016. if ($element_type == 'propaldet') {
  8017. $classpath = 'comm/propal/class';
  8018. $module = 'propal';
  8019. $subelement = 'propaleligne';
  8020. }
  8021. if ($element_type == 'order_supplier') {
  8022. $classpath = 'fourn/class';
  8023. $module = 'fournisseur';
  8024. $subelement = 'commandefournisseur';
  8025. $classfile = 'fournisseur.commande';
  8026. }
  8027. if ($element_type == 'invoice_supplier') {
  8028. $classpath = 'fourn/class';
  8029. $module = 'fournisseur';
  8030. $subelement = 'facturefournisseur';
  8031. $classfile = 'fournisseur.facture';
  8032. }
  8033. if ($element_type == "service") {
  8034. $classpath = 'product/class';
  8035. $subelement = 'product';
  8036. }
  8037. if (empty($classfile)) $classfile = strtolower($subelement);
  8038. if (empty($classname)) $classname = ucfirst($subelement);
  8039. if (empty($classpath)) $classpath = $module.'/class';
  8040. $element_properties = array(
  8041. 'module' => $module,
  8042. 'classpath' => $classpath,
  8043. 'element' => $element,
  8044. 'subelement' => $subelement,
  8045. 'classfile' => $classfile,
  8046. 'classname' => $classname
  8047. );
  8048. return $element_properties;
  8049. }
  8050. /**
  8051. * Fetch an object from its id and element_type
  8052. * Inclusion of classes is automatic
  8053. *
  8054. * @param int $element_id Element id
  8055. * @param string $element_type Element type
  8056. * @param string $element_ref Element ref (Use this or element_id but not both)
  8057. * @return int|object object || 0 || -1 if error
  8058. */
  8059. function fetchObjectByElement($element_id, $element_type, $element_ref = '')
  8060. {
  8061. global $conf, $db;
  8062. $element_prop = getElementProperties($element_type);
  8063. if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
  8064. {
  8065. dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
  8066. $objecttmp = new $element_prop['classname']($db);
  8067. $ret = $objecttmp->fetch($element_id, $element_ref);
  8068. if ($ret >= 0)
  8069. {
  8070. return $objecttmp;
  8071. }
  8072. }
  8073. return 0;
  8074. }
  8075. /**
  8076. * Return if a file can contains executable content
  8077. *
  8078. * @param string $filename File name to test
  8079. * @return boolean True if yes, False if no
  8080. */
  8081. function isAFileWithExecutableContent($filename)
  8082. {
  8083. 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))
  8084. {
  8085. return true;
  8086. }
  8087. return false;
  8088. }
  8089. /**
  8090. * Return the value of token currently saved into session with name 'newtoken'.
  8091. * This token must be send by any POST as it will be used by next page for comparison with value in session.
  8092. *
  8093. * @return string
  8094. */
  8095. function newToken()
  8096. {
  8097. return $_SESSION['newtoken'];
  8098. }
  8099. /**
  8100. * Return the value of token currently saved into session with name 'token'.
  8101. *
  8102. * @return string
  8103. */
  8104. function currentToken()
  8105. {
  8106. return $_SESSION['token'];
  8107. }
  8108. /**
  8109. * Start a table with headers and a optinal clickable number (don't forget to use "finishSimpleTable()" after the last table row)
  8110. *
  8111. * @param string $header The first left header of the table (automatic translated)
  8112. * @param string $link (optional) The link to a internal dolibarr page, when click on the number (without the first "/")
  8113. * @param string $arguments (optional) Additional arguments for the link (e.g. "search_status=0")
  8114. * @param integer $emptyRows (optional) The count of empty rows after the first header
  8115. * @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"
  8116. * @return void
  8117. *
  8118. * @see finishSimpleTable()
  8119. */
  8120. function startSimpleTable($header, $link = "", $arguments = "", $emptyRows = 0, $number = -1)
  8121. {
  8122. global $langs;
  8123. print '<div class="div-table-responsive-no-min">';
  8124. print '<table class="noborder centpercent">';
  8125. print '<tr class="liste_titre">';
  8126. print $emptyRows < 1 ? '<th>' : '<th colspan="'.($emptyRows + 1).'">';
  8127. print $langs->trans($header);
  8128. // extra space between the first header and the number
  8129. if ($number > -1) {
  8130. print ' ';
  8131. }
  8132. if (!empty($link)) {
  8133. if (!empty($arguments)) {
  8134. print '<a href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  8135. } else {
  8136. print '<a href="'.DOL_URL_ROOT.'/'.$link.'">';
  8137. }
  8138. }
  8139. if ($number > -1) {
  8140. print '<span class="badge">'.$number.'</span>';
  8141. }
  8142. if (!empty($link)) {
  8143. print '</a>';
  8144. }
  8145. print '</th>';
  8146. if ($number < 0 && !empty($link)) {
  8147. print '<th class="right">';
  8148. if (!empty($arguments)) {
  8149. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'?'.$arguments.'">';
  8150. } else {
  8151. print '<a class="commonlink" href="'.DOL_URL_ROOT.'/'.$link.'">';
  8152. }
  8153. print $langs->trans("FullList");
  8154. print '</a>';
  8155. print '</th>';
  8156. }
  8157. print '</tr>';
  8158. }
  8159. /**
  8160. * Add the correct HTML close tags for "startSimpleTable(...)" (use after the last table line)
  8161. *
  8162. * @param bool $addLineBreak (optional) Add a extra line break after the complete table (\<br\>)
  8163. * @return void
  8164. *
  8165. * @see startSimpleTable()
  8166. */
  8167. function finishSimpleTable($addLineBreak = false)
  8168. {
  8169. print '</table>';
  8170. print '</div>';
  8171. if ($addLineBreak) {
  8172. print '<br>';
  8173. }
  8174. }
  8175. /**
  8176. * Add a summary line to the current open table ("None", "XMoreLines" or "Total xxx")
  8177. *
  8178. * @param integer $tableColumnCount The complete count columns of the table
  8179. * @param integer $num The count of the rows of the table, when it is zero (0) the "$noneWord" is shown instead
  8180. * @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)
  8181. * @param integer $total (optional) The total value thaht is shown after when the table has minimum of one entire
  8182. * @param string $noneWord (optional) The word that is shown when the table has no entires ($num === 0)
  8183. * @param boolean $extraRightColumn (optional) Add a addtional column after the summary word and total number
  8184. * @return void
  8185. */
  8186. function addSummaryTableLine($tableColumnCount, $num, $nbofloop = 0, $total = 0, $noneWord = "None", $extraRightColumn = false)
  8187. {
  8188. global $langs;
  8189. if ($num === 0) {
  8190. print '<tr class="oddeven">';
  8191. print '<td colspan="'.$tableColumnCount.'" class="opacitymedium">'.$langs->trans($noneWord).'</td>';
  8192. print '</tr>';
  8193. return;
  8194. }
  8195. if ($nbofloop === 0)
  8196. {
  8197. // don't show a summary line
  8198. return;
  8199. }
  8200. if ($num === 0) {
  8201. $colspan = $tableColumnCount;
  8202. }
  8203. elseif ($num > $nbofloop) {
  8204. $colspan = $tableColumnCount;
  8205. } else {
  8206. $colspan = $tableColumnCount - 1;
  8207. }
  8208. if ($extraRightColumn) {
  8209. $colspan--;
  8210. }
  8211. print '<tr class="liste_total">';
  8212. if ($nbofloop > 0 && $num > $nbofloop) {
  8213. print '<td colspan="'.$colspan.'" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>';
  8214. } else {
  8215. print '<td colspan="'.$colspan.'" class="right"> '.$langs->trans("Total").'</td>';
  8216. print '<td class="right" width="100">'.price($total).'</td>';
  8217. }
  8218. if ($extraRightColumn) {
  8219. print '<td></td>';
  8220. }
  8221. print '</tr>';
  8222. }
  8223. /**
  8224. * Return a file on output using a low memory. It can return very large files with no need of memory.
  8225. * WARNING: This close output buffers.
  8226. *
  8227. * @param string $fullpath_original_file_osencoded Full path of file to return.
  8228. * @param int $method -1 automatic, 0=readfile, 1=fread, 2=stream_copy_to_stream
  8229. * @return void
  8230. */
  8231. function readfileLowMemory($fullpath_original_file_osencoded, $method = -1)
  8232. {
  8233. global $conf;
  8234. if ($method == -1) {
  8235. $method = 0;
  8236. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1;
  8237. if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2;
  8238. }
  8239. // Be sure we don't have output buffering enabled to have readfile working correctly
  8240. while (ob_get_level()) ob_end_flush();
  8241. // Solution 0
  8242. if ($method == 0) {
  8243. readfile($fullpath_original_file_osencoded);
  8244. }
  8245. // Solution 1
  8246. elseif ($method == 1) {
  8247. $handle = fopen($fullpath_original_file_osencoded, "rb");
  8248. while (!feof($handle)) {
  8249. print fread($handle, 8192);
  8250. }
  8251. fclose($handle);
  8252. }
  8253. // Solution 2
  8254. elseif ($method == 2) {
  8255. $handle1 = fopen($fullpath_original_file_osencoded, "rb");
  8256. $handle2 = fopen("php://output", "wb");
  8257. stream_copy_to_stream($handle1, $handle2);
  8258. fclose($handle1);
  8259. fclose($handle2);
  8260. }
  8261. }